{"text": "function testModel(downsample,model,trainNum,warpsize,cdim,ndim,seed,RoIRoD)\n\nswitch model\n case 'vgg16'\n Epoches = 40;\n case 'resnet50'\n Epoches = 20;\nend\n\nmodelDir = fullfile('data','GAIC',model,RoIRoD,[num2str(trainNum) '_down' num2str(downsample)...\n '_warp' num2str(warpsize) 'cdim' num2str(cdim) 'ndim' num2str(ndim) 'seed' num2str(seed)]);\n\nload(['imdb_GAIC',num2str(trainNum),'.mat'],'imdb');\ngt_scores = cat(2,imdb.bbox.gt_scores{imdb.images.set==1});\ngt_scores_means = mean(gt_scores);\ngt_scores_stds = std(gt_scores);\n\nfor epoch = 1:Epoches\n acc5 = zeros(200,4);\n acc10 = zeros(200,4);\n fprintf('processing epoch %d\\n',epoch);\n netStruct = load(fullfile(modelDir,['net-epoch-',num2str(epoch) '.mat']),'net');\n net = dagnn.DagNN.loadobj(netStruct.net) ;\n net.mode = 'test' ;\n net.move('gpu') ;\n probVarI = net.getVarIndex('predcls');\n net.vars(probVarI).precious = 1;\n minScale = net.meta.minScale;\n \n testID = imdb.images.testSet;\n tic;\n for i = 1:numel(testID)\n img = imread(imdb.meta.img_path{testID(i)});\n [x1,x2,x3] = size(img);\n boxes = imdb.bbox.boxes{testID(i)};\n ss = (boxes(3,:)-boxes(1,:)).*(boxes(4,:)-boxes(2,:));\n\n imre = single(imresize(img,minScale/min([x1,x2]),'bilinear'));\n imre = bsxfun(@minus,imre,net.meta.normalization.averageImage);\n \n [r1,r2,r3] = size(imre); \n r1 = 32*round(r1/32);\n r2 = 32*round(r2/32);\n imre = imresize(imre,[r1,r2],'bilinear');\n\n scale1 = r1/x1;\n scale2 = r2/x2;\n boxes_s = [];\n boxes_s(1,:) = max(floor(boxes(1,:) * scale1),1);\n boxes_s(2,:) = max(floor(boxes(2,:) * scale2),1);\n boxes_s(3,:) = min(ceil(boxes(3,:) * scale1),r1);\n boxes_s(4,:) = min(ceil(boxes(4,:) * scale2),r2);\n \n \n inputs = {'input', gpuArray(imre), 'rois', gpuArray(single([ones(1,size(boxes_s,2));boxes_s]))} ;\n \n net.eval(inputs) ;\n preds{i} = squeeze(gather(net.vars(probVarI).value)) ;\n preds{i} = preds{i} * gt_scores_stds + gt_scores_means;\n gts = imdb.bbox.gt_scores{testID(i)};\n \n srcc(i) = corr(preds{i}, gts', 'type', 'Spearman');\n \n [gts_sorted,id_gts] = sort(gts,'descend');\n [~,id_preds] = sort(preds{i},'descend');\n [~,id_baseline] = sort(ss,'descend');\n\n for k = 1:4\n for j = 1:k\n if gts(id_preds(j)) >= gts_sorted(5)\n acc5(i,k) = acc5(i,k) + 1;\n end\n end\n acc5(i,k) = acc5(i,k) / k;\n end\n \n for k = 1:4\n for j = 1:k\n if gts(id_preds(j)) >= gts_sorted(10)\n acc10(i,k) = acc10(i,k) + 1;\n end\n end\n acc10(i,k) = acc10(i,k) / k;\n end\n end\n toc;\n Acc5(epoch,:) = sum(acc5)/numel(testID);\n Acc10(epoch,:) = sum(acc10)/numel(testID);\n SRCC(epoch) = mean(srcc);\nend\nAllRes = cat(2,Acc5,mean(Acc5,2),Acc10,mean(Acc10,2),SRCC');\nsave(fullfile(modelDir,'Result.mat'),'Acc5','Acc10','SRCC','AllRes');\n\nend\n\n", "meta": {"author": "HuiZeng", "repo": "Grid-Anchor-based-Image-Cropping", "sha": "d3262a1bc840cd998cdff4bee0c712b4ad0787b7", "save_path": "github-repos/MATLAB/HuiZeng-Grid-Anchor-based-Image-Cropping", "path": "github-repos/MATLAB/HuiZeng-Grid-Anchor-based-Image-Cropping/Grid-Anchor-based-Image-Cropping-d3262a1bc840cd998cdff4bee0c712b4ad0787b7/testModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.199860318598717}} {"text": "function [P, J] = regionGrowing(cIM, initPos, thresVal, maxDist, tfMean, tfFillHoles, tfSimplify)\n% REGIONGROWING Region growing algorithm for 2D/3D grayscale images\n%\n% Syntax:\n% P = regionGrowing();\n% P = regionGrowing(cIM);\n% P = regionGrowing(cIM, initPos)\n% P = regionGrowing(..., thresVal, maxDist, tfMean, tfFillHoles, tfSimpl)\n% [P, J] = regionGrowing(...);\n%\n% Inputs:\n% cIM: 2D/3D grayscale matrix {current image}\n% initPos: Coordinates for initial seed position {ginput position}\n% thresVal: Absolute threshold level to be included {5% of max-min}\n% maxDist: Maximum distance to the initial position in [px] {Inf}\n% tfMean: Updates the initial value to the region mean (slow) {false}\n% tfFillHoles: Fills enclosed holes in the binary mask {true}\n% tfSimplify: Reduces the number of vertices {true, if dpsimplify exists}\n%\n% Outputs:\n% P: VxN array (with V number of vertices, N number of dimensions)\n% P is the enclosing polygon for all associated pixel/voxel\n% J: Binary mask (with the same size as the input image) indicating\n% 1 (true) for associated pixel/voxel and 0 (false) for outside\n% \n% Examples:\n% % 2D Example\n% load example\n% figure, imshow(cIM, [0 1500]), hold all\n% poly = regionGrowing(cIM, [], 300); % click somewhere inside the lungs\n% plot(poly(:,1), poly(:,2), 'LineWidth', 2)\n% \n% % 3D Example\n% load mri\n% poly = regionGrowing(squeeze(D), [66,55,13], 60, Inf, [], true, false);\n% plot3(poly(:,1), poly(:,2), poly(:,3), 'x', 'LineWidth', 2)\n%\n% Requirements:\n% TheMathWorks Image Processing Toolbox for bwboundaries() and axes2pix()\n% Optional: Line Simplification by Wolfgang Schwanghart to reduce the \n% number of polygon vertices (see the MATLAB FileExchange)\n%\n% Remarks:\n% The queue is not preallocated and the region mean computation is slow.\n% I haven't implemented a preallocation nor a queue counter yet for the\n% sake of clarity, however this would be of course more efficient.\n%\n% Author:\n% Daniel Kellner, 2011, braggpeaks{}googlemail.com\n% History: v1.00: 2011/08/14\n\n\n% error checking on input arguments\nif nargin > 7\n error('Wrong number of input arguments!')\nend\n\nif ~exist('cIM', 'var')\n himage = findobj('Type', 'image');\n if isempty(himage) || length(himage) > 1\n error('Please define one of the current images!')\n end\n \n cIM = get(himage, 'CData');\nend\n\nif ~exist('initPos', 'var') || isempty(initPos)\n himage = findobj('Type', 'image');\n if isempty(himage)\n himage = imshow(cIM, []);\n end\n \n % graphical user input for the initial position\n p = ginput(1);\n \n % get the pixel position concerning to the current axes coordinates\n initPos(1) = round(axes2pix(size(cIM, 2), get(himage, 'XData'), p(2)));\n initPos(2) = round(axes2pix(size(cIM, 1), get(himage, 'YData'), p(1)));\nend\n\nif ~exist('thresVal', 'var') || isempty(thresVal)\n thresVal = double((max(cIM(:)) - min(cIM(:)))) * 0.05;\nend\n\nif ~exist('maxDist', 'var') || isempty(maxDist)\n maxDist = Inf;\nend\n\nif ~exist('tfMean', 'var') || isempty(tfMean)\n tfMean = false;\nend\n\nif ~exist('tfFillHoles', 'var')\n tfFillHoles = true;\nend\n\nif isequal(ndims(cIM), 2)\n initPos(3) = 1;\nelseif isequal(ndims(cIM),1) || ndims(cIM) > 3\n error('There are only 2D images and 3D image sets allowed!')\nend\n\n[nRow, nCol, nSli] = size(cIM);\n\nif initPos(1) < 1 || initPos(2) < 1 ||...\n initPos(1) > nRow || initPos(2) > nCol\n error('Initial position out of bounds, please try again!')\nend\n\nif thresVal < 0 || maxDist < 0\n error('Threshold and maximum distance values must be positive!')\nend\n\nif ~isempty(which('dpsimplify.m'))\n if ~exist('tfSimplify', 'var')\n tfSimplify = true;\n end\n simplifyTolerance = 1;\nelse\n tfSimplify = false;\nend\n\n\n% initial pixel value\nregVal = double(cIM(initPos(1), initPos(2), initPos(3)));\n\n% text output with initial parameters\ndisp(['RegionGrowing Opening: Initial position (' num2str(initPos(1))...\n '|' num2str(initPos(2)) '|' num2str(initPos(3)) ') with '...\n num2str(regVal) ' as initial pixel value!'])\n\n% preallocate array\nJ = false(nRow, nCol, nSli);\n\n% add the initial pixel to the queue\nqueue = [initPos(1), initPos(2), initPos(3)];\n\n\n%%% START OF REGION GROWING ALGORITHM\nwhile size(queue, 1)\n % the first queue position determines the new values\n xv = queue(1,1);\n yv = queue(1,2);\n zv = queue(1,3);\n \n % .. and delete the first queue position\n queue(1,:) = [];\n \n % check the neighbors for the current position\n for i = -1:1\n for j = -1:1\n for k = -1:1\n \n if xv+i > 0 && xv+i <= nRow &&... % within the x-bounds?\n yv+j > 0 && yv+j <= nCol &&... % within the y-bounds? \n zv+k > 0 && zv+k <= nSli &&... % within the z-bounds?\n any([i, j, k]) &&... % i/j/k of (0/0/0) is redundant!\n ~J(xv+i, yv+j, zv+k) &&... % pixelposition already set?\n sqrt( (xv+i-initPos(1))^2 +...\n (yv+j-initPos(2))^2 +...\n (zv+k-initPos(3))^2 ) < maxDist &&... % within distance?\n cIM(xv+i, yv+j, zv+k) <= (regVal + thresVal) &&...% within range\n cIM(xv+i, yv+j, zv+k) >= (regVal - thresVal) % of the threshold?\n\n % current pixel is true, if all properties are fullfilled\n J(xv+i, yv+j, zv+k) = true; \n\n % add the current pixel to the computation queue (recursive)\n queue(end+1,:) = [xv+i, yv+j, zv+k];\n\n if tfMean\n regVal = mean(mean(cIM(J > 0))); % --> slow!\n end\n \n end \n end\n end \n end\nend\n%%% END OF REGION GROWING ALGORITHM\n\n\n% loop through each slice, fill holes and extract the polygon vertices\nP = [];\nfor cSli = 1:nSli\n if ~any(J(:,:,cSli))\n continue\n end\n \n\t% use bwboundaries() to extract the enclosing polygon\n if tfFillHoles\n % fill the holes inside the mask\n J(:,:,cSli) = imfill(J(:,:,cSli), 'holes'); \n B = bwboundaries(J(:,:,cSli), 8, 'noholes');\n else\n B = bwboundaries(J(:,:,cSli));\n end\n \n\tnewVertices = [B{1}(:,2), B{1}(:,1)];\n\t\n % simplify the polygon via Line Simplification\n if tfSimplify\n newVertices = dpsimplify(newVertices, simplifyTolerance); \n end\n \n % number of new vertices to be added\n nNew = size(newVertices, 1);\n \n % append the new vertices to the existing polygon matrix\n if isequal(nSli, 1) % 2D\n P(end+1:end+nNew, :) = newVertices;\n else % 3D\n P(end+1:end+nNew, :) = [newVertices, repmat(cSli, nNew, 1)];\n end\nend\n\n% text output with final number of vertices\ndisp(['RegionGrowing Ending: Found ' num2str(length(find(J)))...\n ' pixels within the threshold range (' num2str(size(P, 1))...\n ' polygon vertices)!'])", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32532-region-growing-2d3d-grayscale/regionGrowing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19985352337482945}} {"text": "% -*- INTERNAL UNDOCUMENTED FUNCTION -*-\nfunction [spv, spp] = sp_bspline_fluid_3d (element_name, ...\n knots, nsub_p, degree_p, regularity_p, msh)\n\nwarning ('geopdes:obsolete', 'Function SP_BSPLINE_FLUID_3D is obsolete. Using SP_BSPLINE_FLUID instead')\n\n[spv, spp] = sp_bspline_fluid (element_name, knots, nsub_p, degree_p, regularity_p, msh);\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/obsolete/sp_bspline_fluid_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3629692124105861, "lm_q1q2_score": 0.19985351646253977}} {"text": "function [sFile, ChannelMat] = in_fopen_eeglab(DataFile, ImportOptions)\n% IN_FOPEN_EEGLAB: Open an EEGLAB .set file (continuous recordings).\n%\n% FORMAT:\n% EEGLAB datasets can have two forms : one file (.SET) or two files (.SET/.DAT).\n% In both cases, .SET file is a Matlab matrix with the dataset header in 'EEG' field.\n% 1) .SET : Recordings are stored in the 'EEGDATA' field of the .SET matrix\n% 2) .SET/.DAT : Recordings are stored in binary mode in a separate .DAT file,\n% whose file name is stored in field 'EEG.datfile' of the .SET matrix.\n% Format : [nbChan, nbTime*nbTrials] float32 binary matrix (Little-Endian)\n% Channel locations may be stored in the .SET file, in field 'EEG.chanlocs'\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2008-2023\n\n% ===== PARSE INPUTS =====\nif (nargin < 2) || isempty(ImportOptions)\n ImportOptions = db_template('ImportOptions');\nend\n\n\n%% ===== READER HEADER =====\n% Load .set file\nif isstruct(DataFile)\n hdr = DataFile;\n DataFile = hdr.filename;\nelse\n hdr = load(DataFile, '-mat');\nend\n% If there is no EEG field\nif ~isfield(hdr, 'EEG')\n if isfield(hdr, 'nbchan') && isfield(hdr, 'pnts') && isfield(hdr, 'trials')\n hdr = struct('EEG', hdr);\n else\n error('Invalid EEGLAB .set file: missing EEG structure.');\n end\nend\n% Add some information\nhdr.isRaw = (~isfield(hdr.EEG, 'epoch') || isempty(hdr.EEG.epoch)) && (isfield(hdr.EEG, 'data') && ~isempty(hdr.EEG.data));\nnChannels = hdr.EEG.nbchan;\nnTime = hdr.EEG.pnts;\nnEpochs = hdr.EEG.trials;\n\n% === GET TIME ===\n% if isfield(hdr.EEG, 'times') && ~isempty(hdr.EEG.times) % Disabled the use of \"times\" because it was not always in milliseconds (2-Nov-2022)\n% hdr.Time = hdr.EEG.times ./ 1000;\nif isfield(hdr.EEG, 'srate') && ~isempty(hdr.EEG.srate)\n hdr.Time = hdr.EEG.xmin + (0:nTime-1) ./ hdr.EEG.srate;\nelse\n hdr.Time = linspace(hdr.EEG.xmin, hdr.EEG.xmax, nTime);\n if (nTime > 1)\n hdr.EEG.srate = 1 ./ (hdr.Time(2) - hdr.Time(1));\n else\n hdr.EEG.srate = 1000;\n end\nend\n\n% ===== LIST BAD TRIALS =====\nif ~hdr.isRaw\n % Get accepted/rejected trials (with methods ICA, SIG, ELEC)\n iRejectedTrials = [];\n if isfield(hdr.EEG, 'reject')\n % Epochs rejected by ICA criteria\n if isfield(hdr.EEG.reject, 'icareject')\n iRejectedTrials = [iRejectedTrials, hdr.EEG.reject.icareject];\n end\n % Epochs rejected by single-channel criteria\n if isfield(hdr.EEG.reject, 'sigreject')\n iRejectedTrials = [iRejectedTrials, hdr.EEG.reject.sigreject];\n end\n % Epochs rejected by single-channel criteria\n if isfield(hdr.EEG.reject, 'elecreject')\n iRejectedTrials = [iRejectedTrials, hdr.EEG.reject.elecreject];\n end\n end\n iGoodTrials = setdiff(1:nEpochs, iRejectedTrials);\n\n % Remove trials that have at least one 'bad' value in its events list\n iBadTrials = [];\n if isfield(hdr.EEG.epoch(1), 'eventbad')\n for iTrial = 1:length(hdr.EEG.epoch)\n if (iscell(hdr.EEG.epoch(iTrial).eventbad) && any([hdr.EEG.epoch(iTrial).eventbad{:}])) || ...\n (~iscell(hdr.EEG.epoch(iTrial).eventbad) && hdr.EEG.epoch(iTrial).eventbad) \n iBadTrials(end+1) = iTrial;\n end\n end\n iGoodTrials = setdiff(iGoodTrials, iBadTrials);\n end\nelse\n iGoodTrials = 1;\nend\n\n\n% ===== GET RELEVANT CONDITIONS =====\nepochNames = [];\nisAllEmpty = 1;\nif ~hdr.isRaw && isfield(hdr.EEG, 'event') && ~isempty(hdr.EEG.event)\n % Each trial is classified with many criteria\n % Need to ask the user along which creteria the trials should be classified\n % Get all fields of the 'event' structure\n listParam = fieldnames(hdr.EEG.event(1));\n % Remove entries that are not conditions of the events\n %listParam = setdiff(listParam, {'type','latency','urevent','obs','bad','badChan','epoch'});\n listParam = setdiff(listParam, {'urevent','obs','bad','badChan','epoch'});\n % Convert all the events to strings\n for iParam = 1:length(listParam)\n hdr.EEG.event = ConvertEventToStr(hdr.EEG.event, listParam{iParam});\n hdr.EEG.epoch = ConvertEventToStr(hdr.EEG.epoch, ['event' listParam{iParam}]);\n end\n % Keep only parameters for which the value varies in the valid trials\n iParam = 1;\n paramValues = {};\n while (iParam <= length(listParam))\n % Get all the unique values\n tmpValues = {hdr.EEG.event.(listParam{iParam})};\n % If char and not all the values are the same\n% if ~iscell(tmpValues{1}) && ~all(cellfun(@(c)isequal(c,tmpValues{1}), tmpValues))\n if ischar(tmpValues{1}) && ~all(cellfun(@(c)isequal(c,tmpValues{1}), tmpValues))\n % Latency: keep the native order\n if isequal(listParam{iParam}, 'latency')\n [tmp,I,J] = unique(tmpValues);\n paramValues{end + 1} = tmpValues(sort(I));\n % Else: sort in alphabetical/numerical order\n else\n paramValues{end + 1} = unique(tmpValues);\n end\n iParam = iParam + 1;\n % Else remove parameter \n else\n listParam(iParam) = [];\n end\n end\n\n % If there are different types of events that can be used to classify the epochs\n if (length(listParam) >= 1) && (ImportOptions.DisplayMessages || ~isempty(ImportOptions.EventsTypes))\n % Ask the user to select the parameters to be compared\n if ImportOptions.DisplayMessages\n ParamSelected = gui_show_dialog('Conditions selection', @panel_eeglab_cond, 1, [], listParam, paramValues);\n % Use the list of event types passed in input\n else\n % Get the list of parameters in input\n evtSplit = strtrim(str_split(ImportOptions.EventsTypes, ','));\n % Check that the types are available in the file\n iNotFound = find(~ismember(evtSplit, listParam));\n if ~isempty(iNotFound)\n disp(['BST> Error: Some of the event types in input where not found in the file: ', sprintf('%s ', evtSplit{iNotFound})]);\n evtSplit(iNotFound) = [];\n end\n % Get the condition name for each epoch\n ParamSelected = [];\n if ~isempty(evtSplit)\n % Find the selected event types\n [tmp, I, J] = intersect(evtSplit, listParam);\n % Get the possible combinations of values\n ParamSelected = panel_eeglab_cond('GetConditionCombinations', listParam(J), paramValues(J));\n params = listParam(J);\n % Build the condition name for each epoch (see panel_eeglab_cond.m)\n for iCond = 1:length(ParamSelected)\n strCondName = '';\n for iParam = 1:length(params)\n if (iParam ~= 1)\n strCondName = [strCondName '_'];\n end\n if ischar(ParamSelected(iCond).(params{iParam}))\n tmpStr = strrep(file_standardize(ParamSelected(iCond).(params{iParam})), '_', '-');\n strCondName = [strCondName, params{iParam}, tmpStr];\n else\n strCondName = [strCondName, params{iParam}, sprintf('%d', ParamSelected(iCond).(params{iParam}))];\n end\n end\n ParamSelected(iCond).Name = file_standardize(strCondName);\n end\n end\n end\n % Build the epochs names\n epochNames = cell(1, nEpochs);\n % Process parameters selection\n if ~isempty(ParamSelected)\n paramsList = setdiff(fieldnames(ParamSelected), 'Name');\n % Create FileName in which this file should be saved\n for iTrial = 1:nEpochs\n epoch = hdr.EEG.epoch(iTrial);\n % Find in which condition should be classified this epoch\n isCondFound = 0;\n iCond = 1;\n while ~isCondFound && (iCond <= length(ParamSelected))\n isOk = 1;\n iParam = 1;\n while (isOk && (iParam <= length(paramsList)))\n % If value for targ parameter does not match\n if isequal(paramsList{iParam}, 'latency')\n isMatch = isequal(hdr.EEG.event(epoch.event(1)).latency, ParamSelected(iCond).(paramsList{iParam}));\n elseif iscell(epoch.(['event', paramsList{iParam}]))\n isMatch = any(cellfun(@(c)isequal(c,ParamSelected(iCond).(paramsList{iParam})), epoch.(['event', paramsList{iParam}])));\n else\n isMatch = isequal(epoch.(['event', paramsList{iParam}]), ParamSelected(iCond).(paramsList{iParam}));\n end\n if isMatch\n iParam = iParam + 1;\n else\n isOk = 0;\n end\n end\n if isOk\n isCondFound = 1;\n else\n iCond = iCond + 1;\n end\n end\n % Build new filename with the found condition\n if isCondFound\n epochNames{iTrial} = ParamSelected(iCond).Name;\n else\n epochNames{iTrial} = '';\n end\n end\n isAllEmpty = all(cellfun(@isempty, epochNames));\n % If no parameters were selected\n else\n epochNames = repmat({''}, 1, nEpochs);\n isAllEmpty = 1;\n end\n end\nend\n\n\n%% ===== GET DATA SOURCE =====\n% EEG.data\nif isfield(hdr.EEG, 'data') && ~isempty(hdr.EEG.data)\n if isfield(hdr, hdr.EEG.data)\n EEGDATA = hdr.(hdr.EEG.data);\n else\n EEGDATA = hdr.EEG.data;\n end\n% EEGDATA\nelseif isfield(hdr, 'EEGDATA') && ~isempty(hdr.EEGDATA)\n EEGDATA = hdr.EEGDATA;\n% EEGDATA.datfile\nelseif isfield(hdr.EEG, 'datfile') && ~isempty(hdr.EEG.datfile)\n EEGDATA = hdr.EEG.datfile;\n% Default data file: use the same file name than for .SET file, with .DAT/.FDT extension\nelse\n [fPath, fBase, fExt] = bst_fileparts(DataFile);\n EEGDATA = bst_fullfile(fPath, [fBase, '.dat']);\n if ~file_exist(EEGDATA)\n EEGDATA = bst_fullfile(fPath, [fBase, '.fdt']);\n end\nend\n% In case of attached binary file\nif ischar(EEGDATA) \n % Check binary file existence\n if ~file_exist(EEGDATA)\n % Try with the same name as the .set file\n if file_exist(strrep(DataFile, '.set', '.fdt'))\n EEGDATA = strrep(DataFile, '.set', '.fdt');\n else\n % Try with adding a full path\n [fPath, fBase, fExt] = bst_fileparts(EEGDATA);\n EEGDATA = bst_fullfile(bst_fileparts(DataFile), [fBase, fExt]);\n % File is not accessible\n if ~file_exist(EEGDATA)\n error(['EEGLAB binary file does not exist: ', EEGDATA]);\n end\n end\n end\n % Save correct filename\n hdr.EEG.data = EEGDATA;\n % Remove EEGDATA field\n if isfield(hdr, 'EEGDATA')\n hdr = rmfield(hdr, 'EEGDATA');\n end\nelse\n hdr.EEGDATA = EEGDATA;\nend\n\n\n%% ===== FILL STRUCTURE =====\n% Initialize returned file structure \nsFile = db_template('sfile'); \n% Add information read from header\nsFile.filename = DataFile;\nsFile.fid = []; \nsFile.format = 'EEG-EEGLAB';\nsFile.device = 'EEGLAB';\nsFile.byteorder = 'l';\n% Properties of the recordings\nif (nTime == 1)\n sFile.prop.times = hdr.Time(1) + [0, 1./hdr.EEG.srate];\nelse\n sFile.prop.times = [hdr.Time(1), hdr.Time(end)];\nend\nsFile.prop.sfreq = hdr.EEG.srate;\nsFile.prop.nAvg = 1;\nsFile.header = hdr;\n% Channel file\nif ImportOptions.DisplayMessages\n isFixUnits = [];\nelseif (ImportOptions.ChannelAlign >= 1)\n isFixUnits = 1;\nelse\n isFixUnits = 0;\nend\nChannelMat = in_channel_eeglab_set(hdr, isFixUnits);\n\n% === EPOCHS ===\nfor i = 1:nEpochs\n if ~isempty(epochNames) && ~isempty(epochNames{i})\n sFile.epochs(i).label = epochNames{i};\n sFile.epochs(i).select = 1;\n elseif isAllEmpty\n sFile.epochs(i).label = sprintf('%s (#%d)', hdr.EEG.setname, i);\n sFile.epochs(i).select = 1;\n else\n sFile.epochs(i).select = 0;\n end\n sFile.epochs(i).times = sFile.prop.times;\n sFile.epochs(i).nAvg = 1;\n sFile.epochs(i).bad = ~ismember(i, iGoodTrials);\n % Bad channels\n sFile.epochs(i).channelflag = ones(nChannels, 1);\n if ~hdr.isRaw && isfield(hdr.EEG, 'epoch') && ~isempty(hdr.EEG.epoch) && isfield(hdr.EEG.epoch(1), 'eventbadChan')\n % Get all the bad channels for that epoch\n eventbadChan = hdr.EEG.epoch(iTrial).eventbadChan;\n if iscell(eventbadChan)\n iBadChan = [];\n for j = 1:length(eventbadChan)\n if ~isempty(eventbadChan{j})\n iBadChan = [iBadChan, str2num(eventbadChan{j})];\n end\n end\n else\n iBadChan = str2num(eventbadChan);\n end\n % Report the bad channels in the ChannelFlag array\n sFile.epochs(i).channelflag(iBadChan) = -1;\n end\nend\n% Global channel flag\nif (nEpochs == 1)\n sFile.channelflag = sFile.epochs(1).channelflag;\n sFile.epochs = [];\nelse\n sFile.channelflag = ones(nChannels, 1);\nend\n\n% === EVENTS ====\nif isfield(hdr.EEG, 'event') && ~isempty(hdr.EEG.event) && isfield(hdr.EEG.event, 'type') % && hdr.isRaw\n % Get event types\n intTypes = [];\n if ischar(hdr.EEG.event(1).type)\n listTypes = unique({hdr.EEG.event.type});\n elseif isnumeric(hdr.EEG.event(1).type)\n intTypes = unique([hdr.EEG.event.type]);\n listTypes = cell(1, length(intTypes));\n for iType = 1:length(intTypes)\n listTypes{iType} = num2str(intTypes(iType));\n end\n else\n return;\n end\n % Initialize structure\n events = repmat(db_template('event'), [1, length(listTypes)]);\n % Process each event type\n for iEvt = 1:length(listTypes) \n % Get all the event occurrences\n if ~isempty(intTypes)\n listOcc = find([hdr.EEG.event.type] == intTypes(iEvt));\n else\n listOcc = find(strcmpi({hdr.EEG.event.type}, listTypes{iEvt}));\n end\n % Get event label \n events(iEvt).label = listTypes{iEvt};\n % If no occurrences: skip\n if isempty(listOcc)\n continue;\n end\n % Get epochs indices\n if ~hdr.isRaw && (isfield(hdr.EEG.event(listOcc(1)), 'epoch') && ~isempty(hdr.EEG.event(listOcc(1)).epoch))\n events(iEvt).epochs = [hdr.EEG.event(listOcc).epoch];\n else\n events(iEvt).epochs = ones(1, length(listOcc));\n end\n % Get samples\n if isfield(hdr.EEG.event(listOcc(1)), 'latency')\n allSmp = {hdr.EEG.event(listOcc).latency};\n elseif isfield(hdr.EEG.event(listOcc(1)), 'sample')\n allSmp = {hdr.EEG.event(listOcc).sample};\n else\n disp(['EEGLAB> Missing fields \"latency\" or \"sample\" in event \"', hdr.EEG.event(listOcc(1)).type, '\".']);\n end\n % Convert to values if available as strings\n iChar = find(cellfun(@ischar, allSmp));\n if ~isempty(iChar)\n allSmp(iChar) = cellfun(@str2num, allSmp(iChar), 'UniformOutput', 0);\n end\n % Remove empty latencies\n iEmpty = find(cellfun(@isempty, allSmp));\n if ~isempty(iEmpty)\n [allSmp{iEmpty}] = deal(1);\n end\n samples = round([allSmp{:}]);\n % Add durations if there are more than one sample\n if isfield(hdr.EEG.event(listOcc), 'duration') && ~ischar(hdr.EEG.event(listOcc(1)).duration)\n allDur = [hdr.EEG.event(listOcc).duration];\n if any(allDur > 1) && (length(samples) == length(allDur))\n samples(2,:) = samples + allDur; \n end\n end\n % For epoched files: convert events to samples local to each epoch \n if ~hdr.isRaw\n nSamples = round((sFile.prop.times(2) - sFile.prop.times(1)) .* sFile.prop.sfreq) + 1;\n samples = samples - (events(iEvt).epochs - 1) * nSamples + sFile.prop.times(1) * sFile.prop.sfreq - 1;\n end\n % Compute times\n events(iEvt).times = samples ./ sFile.prop.sfreq;\n % Additional fields\n events(iEvt).channels = [];\n events(iEvt).notes = [];\n end\n % Save structure\n sFile.events = events;\nend\n\nend\n\n\n%% ===== CONVERT EVENTS TO STRING =====\nfunction s = ConvertEventToStr(s, param)\n % For each event\n for i = 1:length(s)\n % Double values: convert to strings\n if isnumeric(s(i).(param))\n s(i).(param) = val2str(s(i).(param));\n % Cell array of doubles\n elseif iscell(s(i).(param))\n for iCell = 1:length(s(i).(param))\n if isnumeric(s(i).(param){iCell})\n s(i).(param){iCell} = val2str(s(i).(param){iCell});\n end\n end\n end\n end\nend\n\nfunction str = val2str(val)\n str = '';\n for iVal = 1:length(val)\n if (str > 1)\n str = [str ' '];\n end\n str = [str, num2str(val(iVal))];\n end\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fopen_eeglab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19954527996478455}} {"text": "function feature_map = get_cnn_layers(im, fparams, gparams)\n\n% Get layers from a cnn.\n\nif size(im,3) == 1\n im = repmat(im, [1 1 3]);\nend\n\nim_sample_size = size(im);\n\n%preprocess the image\nif ~isequal(im_sample_size(1:2), fparams.net.meta.normalization.imageSize(1:2))\n im = imresize(single(im), fparams.net.meta.normalization.imageSize(1:2));\nelse\n im = single(im);\nend\n\n% Normalize with average image\nim = bsxfun(@minus, im, fparams.net.meta.normalization.averageImage);\n\nif fparams.use_gpu\n cnn_feat = vl_simplenn(fparams.net,im,[],[],'CuDNN',true, 'Mode', 'test');\nelse\n cnn_feat = vl_simplenn(fparams.net, im, [], [], 'Mode', 'test');\nend\n\nfeature_map = cell(1,1,length(fparams.output_layer));\n\nfor k = 1:length(fparams.output_layer)\n % Move data to CPU if using GPU\n% if fparams.use_gpu\n% cnn_feat(fparams.output_layer(k) + 1).x = gather(cnn_feat(fparams.output_layer(k) + 1).x);\n% end\n \n if fparams.use_gpu\n if fparams.downsample_factor(k) == 1\n temp_feat = cnn_feat(fparams.output_layer(k) + 1).x(fparams.start_ind(k,1):fparams.end_ind(k,1), fparams.start_ind(k,2):fparams.end_ind(k,2), :, :);\n if fparams.return_gpu\n feature_map{k} = temp_feat;\n else\n feature_map{k} = gather(temp_feat);\n end\n else\n temp_feat = average_feature_region(cnn_feat(fparams.output_layer(k) + 1).x(fparams.start_ind(k,1):fparams.end_ind(k,1), fparams.start_ind(k,2):fparams.end_ind(k,2), :, :), fparams.downsample_factor(k));\n if fparams.return_gpu\n feature_map{k} = temp_feat;\n else\n feature_map{k} = gather(temp_feat);\n end\n end\n else\n if fparams.downsample_factor(k) == 1\n feature_map{k} = cnn_feat(fparams.output_layer(k) + 1).x(fparams.start_ind(k,1):fparams.end_ind(k,1), fparams.start_ind(k,2):fparams.end_ind(k,2), :, :);\n else\n feature_map{k} = average_feature_region(cnn_feat(fparams.output_layer(k) + 1).x(fparams.start_ind(k,1):fparams.end_ind(k,1), fparams.start_ind(k,2):fparams.end_ind(k,2), :, :), fparams.downsample_factor(k));\n end\n end\nend\n\n", "meta": {"author": "jizhu1023", "repo": "DMAN_MOT", "sha": "b522fc5ae8d8152c43be14126c4d6160fdf289f8", "save_path": "github-repos/MATLAB/jizhu1023-DMAN_MOT", "path": "github-repos/MATLAB/jizhu1023-DMAN_MOT/DMAN_MOT-b522fc5ae8d8152c43be14126c4d6160fdf289f8/ECO/feature_extraction/get_cnn_layers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}} {"text": "function [E, wE] = nfgCompareVolumeTrueError(fgGS, fgSS, g_radius,vR,phantomDir)\n%Compare volume of two fiber groups using trueError program\n%\n% [E, wE] = nfgCompareVolumeTrueError(fgGS, fgSS, g_radius,vR,phantomDir)\n%\n% Assumes that fgGS is the gold standard group and fgSS is the selected\n% fibers that match the gold standard from the test group. g_radius is the\n% radius of the gold standard fibers and vR is a vector of radii that might\n% be the thickness of the test fibers.\n%\n%\n% NOTES: \n\n\n% Let's see how trueError compares these fibers\ntempFiberDir = nfgGetName('tempFiberDir',phantomDir);\nctrparamsFile = nfgGetName('ctrparamsFile',phantomDir);\nnoisyImg = nfgGetName('noisyImg',phantomDir);\nbvalsFile = nfgGetName('bvalsFile',phantomDir);\nbvecsFile = nfgGetName('bvecsFile',phantomDir);\nb0File = nfgGetName('b0File',phantomDir);\ntensorsFile = nfgGetName('tensorsFile',phantomDir);\nwmROIFile = nfgGetName('wmROIFile',phantomDir);\ngmROIFile = nfgGetName('gmROIFile',phantomDir);\n\n% XXX special check to find fibers less than 5 points in gold standard\nfiberLen = cellfun('size',fgGS.fibers,2);\nlt5 = fiberLen<5;\nif sum(lt5)>0\n disp(['Warning there are ' num2str(sum(lt5)) ' fibers with less than 5 pts.']);\n fgGS.fibers = fgGS.fibers(~lt5);\nend\n\nmkdir(tempFiberDir);\nmtrExportFibers(fgSS,fullfile(tempFiberDir,'ss.pdb'));\nmtrExportFibers(fgGS,fullfile(tempFiberDir,'gs.pdb'));\n\n% Convert to SBfloat\nargParams = [' -i ' ctrparamsFile];\nargD_SS = [' -p ' fullfile(tempFiberDir,'ss_0.SBfloat')];\nargInput = [' ' fullfile(tempFiberDir,'ss.pdb')];\nargThresh = [' --thresh ' num2str(length(fgSS.fibers)) ' --seq '];\ncmd = ['contrack_score' argParams argD_SS argThresh argInput];\n%disp(cmd);\n[s,r] = system(cmd);\nargD_GS = [' -p ' fullfile(tempFiberDir,'gs_0.SBfloat')];\nargInput = [' ' fullfile(tempFiberDir,'gs.pdb')];\nargThresh = [' --thresh ' num2str(length(fgGS.fibers)) ' --seq '];\ncmd = ['contrack_score' argParams argD_GS argThresh argInput];\n%disp(cmd);\n[s,r] = system(cmd);\n% Run true error on gold\nargD_GS = [' -d ' fullfile(tempFiberDir,'gs_0.SBfloat')];\nargR = [' -r ' noisyImg];\nargVal = [' --val ' bvalsFile];\nargVec = [' --vec ' bvecsFile];\narg0 = [' -0 ' b0File];\nargG = [' -g ' gmROIFile];\nargM = [' -m ' wmROIFile];\nargT = [' --ten ' tensorsFile];\nargGroupSize = ' -v 2';\nb0 = niftiRead(b0File);\nargSubSize = [' -s 0,' num2str(b0.dim(1)-1) ',0,' num2str(b0.dim(2)-1) ',0,' num2str(b0.dim(3)-1)];\nargW = ' -w 0';\nargDiameter = [' --diameter ' num2str(max(g_radius)*2)];\nfracGoldFile = fullfile(tempFiberDir,'fgs.nii.gz');\nargFractionFile = [' --fraction ' fracGoldFile];\ncmd = ['trueError' argR argD_GS argVal argVec arg0 argG argM argT argGroupSize argSubSize argW argDiameter argFractionFile];\n%disp(cmd);\n[s,r] = system(cmd);\nfracG = niftiRead(fracGoldFile);\n\n% Search for the right radius to compare the selection to the gold\nargD_SS = [' -d ' fullfile(tempFiberDir,'ss_0.SBfloat')];\nfracImgs = zeros(size(repmat(b0.data,[1 1 1 length(vR)])));\nE = zeros(size(vR));\nfor rr=1:length(vR)\n strD = num2str(vR(rr)*2);\n disp(['Comparing trueError volume using test diameter ' strD ' ...']);\n argDiameter = [' --diameter ' strD];\n fracFile = fullfile(tempFiberDir,['fss' strD '.nii.gz']);\n argFractionFile = [' --fraction ' fracFile];\n cmd = ['trueError' argR argD_SS argVal argVec arg0 argG argM argT argGroupSize argSubSize argW argDiameter argFractionFile];\n %disp(cmd);\n [s,r] = system(cmd);\n ni = niftiRead(fracFile);\n fracImgs(:,:,:,rr) = ni.data;\n %E(rr) = sum(abs(ni.data(:)-fracG.data(:)))/sum(fracG.data(:)) * 100;\n E(rr) = abs((sum(ni.data(:))-sum(fracG.data(:)))/sum(fracG.data(:)) * 100);\nend\nwE = sum(fracG.data(:));\n% Cleanup the temp space\nrmdir(tempFiberDir,'s');\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/external/nfg/nfgCompareVolumeTrueError.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19953807272299748}} {"text": "function brs = ssr_brs(X,phi,x0,d,irs,conf)\n%SSR_BRS binaural room scanning (BRS) set for use with the SoundScape Renderer\n%\n% Usage: brs = ssr_brs(X,phi,x0,d,irs,conf)\n%\n% Input parameters:\n% X - listener position / m\n% phi - azimuthal head orientation / rad\n% x0 - secondary sources\n% d - corresponding driving signals\n% irs - impulse response data set for the second sources\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% brs - conf.N x 2*nangles matrix containing all impulse responses\n% (2 channels) for every angle of the BRS set\n%\n% SSR_BRS(X,phi,x0,d,irs,conf) prepares a BRS set for the given secondary\n% sources and its driving signals for the given listener position.\n% One way to use this BRS set is using the SoundScapeRenderer (SSR), see\n% http://spatialaudio.net/ssr/\n%\n% See also: ssr_brs_wfs, ssr_brs_nfchoa, ir_generic\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 6;\nnargmax = 6;\nnarginchk(nargmin,nargmax);\nisargposition(X);\nisargsecondarysource(x0);\nisargmatrix(d);\nisargscalar(phi);\nisargstruct(conf);\n\n\n%% ===== Configuration ===================================================\nN = conf.N; % Target length of BRIR impulse responses\nangles = rad(conf.ir.brsangles); % Angles for the BRIRs\nshowprogress = conf.showprogress; % Progress bar\n\n\n%% ===== Computation =====================================================\nnangles = length(angles);\n% Initial values\nbrs = zeros(N,2*nangles);\n% Generate a BRS set for all given angles\nfor ii = 1:nangles\n % Progress bar\n if showprogress, progress_bar(ii,nangles); end\n % Compute BRIR for the desired driving signals\n brs(:,(ii-1)*2+1:ii*2) = ...\n ir_generic(X,angles(ii)+phi,x0,d,irs,conf);\nend\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_ssr/ssr_brs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.19910597148859943}} {"text": "% LFCalDispEstPoses - Visualize pose estimates associated with a calibration info file\n%\n% Usage: \n% LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour )\n%\n% Draws a set of frames, one for each camera pose, in the colour defined by BaseColour. All inputs\n% except InputPath are optional. Pass an empty array \"[]\" to omit a parameter. See\n% LFUtilCalLensletCam for example usage.\n% \n% Inputs:\n% \n% InputPath : Path to folder containing CalInfo file.\n% \n% [optional] CalOptions : struct controlling calibration parameters\n% .CalInfoFname : Name of the file containing calibration estimate; note that this\n% parameter is automatically set in the CalOptions struct returned\n% by LFCalInit\n% \n% [optional] DrawFrameSizeMult : Multiplier on the displayed frame sizes\n% \n% [optional] BaseColour : RGB triplet defining a base drawing colour, RGB values are in the\n% range 0-1\n%\n% \n% User guide: LFToolbox.pdf\n% See also: LFUtilCalLensletCam\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction LFCalDispEstPoses( InputPath, CalOptions, DrawFrameSizeMult, BaseColour )\n\n%---Defaults---\nCalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );\nDrawFrameSizeMult = LFDefaultVal( 'DrawFrameSizeMult', 1 );\nBaseColour = LFDefaultVal( 'BaseColour', [1,1,0] );\n\n\n%---\nFname = fullfile(CalOptions.CalInfoFname);\nEstCamPosesV = LFStruct2Var( LFReadMetadata(fullfile(InputPath, Fname)), 'EstCamPosesV' );\n\n% Establish an appropriate scale for the drawing\nAutoDrawScale = EstCamPosesV(:,1:3);\nAutoDrawScale = AutoDrawScale(:);\nAutoDrawScale = (max(AutoDrawScale) - min(AutoDrawScale))/10;\n\n%---Draw cameras---\nBaseFrame = ([0 1 0 0 0 0; 0 0 0 1 0 0; 0 0 0 0 0 1]);\nDrawFrameMed = [AutoDrawScale * DrawFrameSizeMult * BaseFrame; ones(1,6)];\nDrawFrameLong = [AutoDrawScale*3/2 * DrawFrameSizeMult * BaseFrame; ones(1,6)];\n\nfor( PoseIdx = 1:size(EstCamPosesV, 1) )\n CurH = eye(4);\n CurH(1:3,1:3) = rodrigues( EstCamPosesV(PoseIdx,4:6) );\n CurH(1:3,4) = EstCamPosesV(PoseIdx,1:3);\n \n CurH = CurH^-1;\n \n CamFrame = CurH * DrawFrameMed(:,1:4);\n plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour.*0.5, 'LineWidth',2 );\n hold on\n \n CamFrame = CurH * DrawFrameLong(:,5:6);\n plot3( CamFrame(1,:), CamFrame(2,:), CamFrame(3,:), '-', 'color', BaseColour, 'LineWidth',2 );\nend\n\naxis equal\ngrid on\nxlabel('x [m]');\nylabel('y [m]');\nzlabel('z [m]');\ntitle('Estimated camera poses');\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/LFCalDispEstPoses.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.19908994377318534}} {"text": "function [keypointsAll,bboxAll] = backprojectKeypoints(expidx)\n\nfprintf('backprojectKeypoints()\\n');\n\n% load annolist with full size images\n[annolistOrig, imgidxs] = getAnnolist(expidx);\nfor imgidx = 1:length(annolistOrig)\n annolistOrig(imgidx).annorect = [];\nend\n\np = rcnn_exp_params(expidx);\nload(p.testGT);\nif (~exist('annolist','var'))\n annolist = single_person_annolist;\nend\nannolist_crops = annolist;\n\n[~,parts] = util_get_parts24();\n\n% load bboxes\nbboxAll = getBBoxAll(expidx,parts,length(annolist_crops));\nimgidxs_orig = zeros(length(bboxAll),1);\njidxs = [1:6 9:length(bboxAll(1).det)];\n\nfprintf('backproject bboxes()\\n');\nfor imgidx = 1:length(bboxAll)\n fprintf('.');\n [~,name] = fileparts(annolist_crops(imgidx).image.name);\n load([fileparts(p.testGT) '/T_' name(3:end)],'T');\n imgidxs_orig(imgidx) = str2double(name(3:7));\n \n det = bboxAll(imgidx).det;\n for jidx = jidxs\n detNew1 = ([det{jidx}(:,1:2) ones(size(det{jidx},1),1)]*T');\n detNew2 = ([det{jidx}(:,3:4) ones(size(det{jidx},1),1)]*T');\n det{jidx}(:,1:4) = [detNew1(:,1:2) detNew2(:,1:2)];\n % figure(101); clf; imagesc(imread(annolist(imgidx_orig).image.name)); axis equal; hold on;\n % plot(det{jidx}(:,1),det{jidx}(:,2),'ro','MarkerFaceColor','r','MarkerEdgeColor','k','MarkerSize',5);\n end\n \n bboxAll(imgidx).det = det;\n bboxAll(imgidx).imgname = annolistOrig(imgidxs_orig(imgidx)).image.name;\n if (~mod(imgidx, 100))\n fprintf(' %d/%d\\n',imgidx,length(bboxAll));\n end\nend\nfprintf(' done\\n');\n\n% merge detections\nimgidxs_merged = imgidxs_orig(1);\nimgidxs_merged_rel = 1;\nfor imgidx = 2:length(bboxAll)\n if (imgidxs_orig(imgidx) == imgidxs_merged(end))\n for jidx = jidxs\n bboxAll(imgidxs_merged_rel(end)).det{jidx} = [bboxAll(imgidxs_merged_rel(end)).det{jidx}; bboxAll(imgidx).det{jidx}];\n end\n else\n imgidxs_merged = [imgidxs_merged; imgidxs_orig(imgidx)];\n imgidxs_merged_rel = [imgidxs_merged_rel; imgidx];\n end\nend\nbboxAll = bboxAll(imgidxs_merged_rel);\n\nfprintf('nms()\\n');\nfor imgidx = 1:length(bboxAll)\n fprintf('.');\n for jidx = jidxs\n keep = nms(bboxAll(imgidx).det{jidx}, 0.5);\n bboxAll(imgidx).det{jidx} = bboxAll(imgidx).det{jidx}(keep, :);\n end\n if (~mod(imgidx, 100))\n fprintf(' %d/%d\\n',imgidx,length(bboxAll));\n end\nend\nfprintf(' done\\n');\n\nfor imgidx = 1:length(bboxAll)\n keypointsAll(imgidx).imgname = bboxAll(imgidx).imgname;\n keypointsAll(imgidx).det = cell(16,1);\nend\n\n% convert to keypoints\nfor imgidx = 1:length(bboxAll)\n points = nan(16,2);\n for jidx = jidxs\n det = bboxAll(imgidx).det{jidx};\n x = mean(det(:,[1 3]),2);\n y = mean(det(:,[2 4]),2);\n keypointsAll(imgidx).det{jidx,:} = [[x y] det(:,5)];\n [val,idx] = max(det(:,5));\n points(jidx,:) = [x(idx) y(idx)];\n end\n% figure(101); clf; imagesc(imread(keypointsAll(imgidx).imgname)); axis equal; hold on;\n% plot(points(:,1),points(:,2),'ro','MarkerFaceColor','r','MarkerEdgeColor','k','MarkerSize',5);\n% set(gca,'Ydir','reverse');\nend\n\npath = fileparts(p.evalTest);\nfnameKeypoints = [path '/keypointsAll'];\nsave(fnameKeypoints, 'keypointsAll');\n\nfnameBBox = [path '/bboxAll'];\nsave(fnameBBox, 'bboxAll');\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/utils/backprojectKeypoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.1990834422071812}} {"text": "function write_off(filename, pnt, plc)\n\n% WRITE_OFF writes a set of geometrical planar forms (called piecewise linear complex, PLC)\n% to an ascii *.off file, which is a file format created by Princeton Shape Benchmark\n%\n% Use as\n% write_stl(filename, pnt, tri)\n%\n% See also READ_OFF\n\n% Copyright (C) 2010, Cristiano Micheli\n% \n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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: write_off.m 2212 2010-11-27 11:55:07Z roboos $\n\nnedges = 0;\nfid = fopen(filename, 'wb');\nnpnt = size(pnt,1);\nnplc = size(plc,1);\n\nfprintf(fid, 'OFF\\n');\nfprintf(fid, '%d %d %d\\n',npnt,nplc,nedges);\nfor i=1:npnt\n fprintf(fid, '%f %f %f\\n', pnt(i,1), pnt(i,2), pnt(i,3)); \nend\nfor i=1:nplc\n str = '%d '; \n nvert = size(plc(i,:),2);\n str2 = 'nvert,';\n for j=1:nvert\n str = [str '%d '];\n str2 = [str2 'plc(i,' num2str(j) '),'];\n end\n str = [str '\\n''']; str2 = str2(1:end-1);\n eval(['fprintf(fid,''' str ',' str2 ');']); \nend\n\nfclose(fid);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/write_off.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754068280545827, "lm_q1q2_score": 0.1990834402913222}} {"text": "% removERP.m removes the averaged ERP from every single epoch of its corresponding epoched EEG dataset\n%\n% Input:\n%\n% EEG - epoched EEG dataset\n% ERP - averaged ERP (ERPset)\n%\n% Output:\n%\n% EEG - epoched EEG dataset\n%\n% IMPORTANT:\n% - epoched EEG dataset must have assigned bins (e.g. processed by ERPLAB).\n% - epoched EEG dataset and averaged ERP (ERPset) must have the same amount of channels, samples and sample rate.\n% - the time-locked event must be at the same sample location in both epoched EEG dataset and averaged ERP (ERPset).\n%\n%\n%\n% *** This function is part of ERPLAB Toolbox ***\n% Author: Javier Lopez-Calderon & Johanna Kreither\n% Center for Mind and Brain\n% University of California, Davis,\n% Davis, CA\n% July-August 2014\n\nfunction EEG = removERP(EEG, ERP)\n\nnepoch = EEG.trials;\nnchaneeg = EEG.nbchan;\nnpntseeg = EEG.pnts;\nsrateeeg = EEG.srate;\neegzerolatpos = find(EEG.times == 0,1,'first'); % catch zero-time locked code position,\n\nnchanerp = ERP.nchan;\nnpntserp = ERP.pnts;\nsrateerp = ERP.srate;\nerpzerolatpos = find(ERP.times == 0,1,'first'); % catch zero-time locked code position,\n\nif nchaneeg~=nchanerp\n error('ERPLAB:error', 'EEG has %g channels and ERP has %g canales!', nchaneeg, nchanerp)\nend\nif npntseeg~=npntserp\n error('ERPLAB:error', 'EEG has %g points and ERP has %g points!', npntseeg, npntserp)\nend\nif srateeeg~=srateerp\n error('ERPLAB:error', 'EEG has a srate of %g sps and ERP has a srate of %g sps!', srateeeg, srateerp)\nend\nif eegzerolatpos~=erpzerolatpos\n error('ERPLAB:error', 'The time-locked event is not located at the same sample for EEG and ERP.')\nend\nfor k=1:nepoch \n latenarray = EEG.epoch(k).eventlatency;\n biniarray = EEG.epoch(k).eventbini; \n \n if iscell(latenarray)\n latenarray = cell2mat(latenarray);\n end\n \n indxtimelock = find(latenarray == 0,1,'first'); % catch zero-time locked code position,\n bini = biniarray(indxtimelock);\n \n if isempty(bini)\n error('ERPLAB:error', 'Epoch %g does not habe a bin assigned (empty).', k)\n end \n if iscell(bini)\n bini = cell2mat(bini);\n end \n if bini<1\n error('ERPLAB:error', 'Epoch %g does not habe a bin assigned (-1).', k)\n end\n if length(bini)>1\n error('ERPLAB:error', 'Epoch %g has more than one bin assigned.', k)\n end\n \n EEG.data(:,:,k) = EEG.data(:,:,k) - ERP.bindata(:,:, bini); \nend", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/removERP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}} {"text": "function gX = whiteKernGradX(kern, X, X2)\n\n% WHITEKERNGRADX Gradient of WHITE kernel with respect to input locations.\n% FORMAT\n% DESC computes the gradident of the white noise\n% kernel with respect to the input positions where both the row\n% positions and column positions are provided separately.\n% ARG kern : kernel structure for which gradients are being\n% computed.\n% ARG x1 : row locations against which gradients are being computed.\n% ARG x2 : column locations against which gradients are being computed.\n% RETURN g : the returned gradients. The gradients are returned in\n% a matrix which is numData2 x numInputs x numData1. Where numData1 is\n% the number of data points in X1, numData2 is the number of data\n% points in X2 and numInputs is the number of input\n% dimensions in X.\n%\n% SEEALSO whiteKernParamInit, kernGradX, whiteKernDiagGradX\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006\n\n% KERN\n\nif nargin<3\n X2 = X;\nend\n\ngX = zeros(size(X2, 1), size(X2, 2), size(X, 1));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/whiteKernGradX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19908343290503466}} {"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 tests = test_spm_dcm_bmr\n% Unit Tests for test_spm_dcm_bmr\n%__________________________________________________________________________\n% Copyright (C) 2016 Wellcome Trust Centre for Neuroimaging\n\n% $Id: test_spm_dcm_bmr.m 7369 2018-07-09 09:58:03Z peter $\n\ntests = functiontests(localfunctions);\n\n% -------------------------------------------------------------------------\nfunction test_bmr(testCase)\n\ndata_path = get_data_path();\n\n% Load PEB of full DCM\nPEB = load(fullfile(data_path,'PEB_test.mat'));\nPEB = PEB.PEB;\nPEB = PEB(1);\n\n% Load DCMs\nGCM = load(fullfile(data_path,'models','GCM_simulated.mat'));\nGCM = GCM.GCM;\n\n% Limit to 3 subjects for performance\nGCM = GCM(1:3,:);\n\n% Prune connections on the B-matrix only\n[RCM,BMC,BMA] = spm_dcm_bmr(GCM,{'B'});\n\n% Check outputs have expected sizes\n[ns,nm] = size(GCM);\nassert(all(size(RCM) == size(GCM)));\nassert(all(size(BMC) == [1 ns]));\nassert(all(size(BMA) == [1 ns]));\n\n% Again with only two outputs\n[RCM,BMC] = spm_dcm_bmr(GCM,{'B'});\n\n% Check outputs have expected sizes\n[ns,nm] = size(GCM);\nassert(all(size(RCM) == size(GCM)));\nassert(all(size(BMC) == [1 ns]));\n\n% -------------------------------------------------------------------------\nfunction test_bmr_single_subject(testCase)\n\ndata_path = get_data_path();\n\n% Load PEB of full DCM\nPEB = load(fullfile(data_path,'PEB_test.mat'));\nPEB = PEB.PEB;\nPEB = PEB(1);\n\n% Load DCMs\nGCM = load(fullfile(data_path,'models','GCM_simulated.mat'));\nGCM = GCM.GCM;\n\n% Limit to 1 subject\nGCM = GCM(1,:);\n\n% Prune connections on the B-matrix only\n[RCM,BMC,BMA] = spm_dcm_bmr(GCM,{'B'});\n\n% Check outputs have expected sizes\n[ns,nm] = size(GCM);\nassert(all(size(RCM) == size(GCM)));\nassert(all(size(BMC) == [1 ns]));\nassert(all(size(BMA) == [1 ns]));\n\n% Again with only two outputs\n[RCM,BMC] = spm_dcm_bmr(GCM,{'B'});\n\n% Check outputs have expected sizes\n[ns,nm] = size(GCM);\nassert(all(size(RCM) == size(GCM)));\nassert(all(size(BMC) == [1 ns]));\n\n\n% -------------------------------------------------------------------------\nfunction data_path = get_data_path()\n\ndata_path = fullfile( spm('Dir'), 'tests', ...\n 'data', 'fMRI', 'simulated_2region');", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/tests/test_spm_dcm_bmr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}} {"text": "function [J_x0,J_xf,J_t] = sys_Dg(neq,t,x0,xf)\n\nglobal sys_params A B C D\n\n\n% J_x0 and J_xf are row vectors of length n.\n% J_t is not used.\n\nF_NUM = neq(5); \n\nJ_x0 = zeros(1, length(x0));\nJ_xf = 0*C;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22196-solution-of-fractional-optimal-control-problems/sys_dg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}} {"text": "function varargout = spwelch(s,w, varargin)\n% PWELCH (* DEPRECATED*) overloaded pwelch for spectralobjects \n% spwelch(spectralobject, waveform) - plots the spectral density\n% Pxx = pwelch(spectralobject, waveform) - returns the Power Spectral\n% Density (PSD) estimate, Pxx, of a discrete-time signal \n% vector X using Welch's averaged, modified periodogram method.\n% [Pxx, Freqs] = pwelch(spectralobject, waveform) - returns spectral\n% density and associated frequency bins.\n%\n% Options, spwelch(s,w, 'DEFAULT') - plots the spectral density using\n% pwelch's defaults (8 averaged windows, 50% overlap)\n% window is length of entire waveform..\n%\n% THIS FUNCTION HAS BEEN REPLACED WITH PWELCH, and will be removed from\n% future versions.\n\n% AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\nerror('Spectralobject:spwelch:Depricated',...\n ['spectralobject/spwelch has been deprecated. ',...\n 'Please use spectralobject/pwelch instead. the syntax is the same']);", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@spectralobject/spwelch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19886229715274964}} {"text": "function [hmm,Gamma,fehist] = hmmmar_init(data,T,options)\n%\n% Initialise the hidden Markov chain using HMM-MAR\n%\n% INPUT\n% data observations, a struct with X (time series) and C (classes, optional)\n% T length of observation sequence\n% options, structure with the training options \n% Sind\n%\n% OUTPUT\n% Gamma p(state given X)\n%\n% Author: Diego Vidaurre, University of Oxford\n% Author: Romesh Abeysuriya, University of Oxford\n\nif ~isfield(options,'maxorder')\n [~,order] = formorders(options.order,options.orderoffset,options.timelag,options.exptimelag);\n options.maxorder = order; \nend\n\n% Run two initializations for each K less than requested K, plus options.initrep K\nif options.initTestSmallerK \n init_k = [repmat(1:(options.K-1),1,2) options.K*ones(1,options.initrep)];\n init_k = init_k(end:-1:1);\nelse % Standard behaviour, test specified K options.initrep times\n init_k = options.K*ones(1,options.initrep);\nend\n\nfelast = zeros(length(init_k),1);\nmaxfo = zeros(length(init_k),1);\nfehist = cell(length(init_k),1);\nGamma = cell(length(init_k),1);\nhmm = cell(length(init_k),1);\n\nif options.useParallel && length(init_k) > 1 % not very elegant\n parfor it = 1:length(init_k)\n [hmm{it},Gamma{it},fehist{it}] = run_initialization(data,T,options,init_k(it));\n felast(it) = fehist{it}(end);\n maxfo(it) = mean(getMaxFractionalOccupancy(Gamma{it},T,options));\n if options.verbose\n if options.episodic\n fprintf('Init run %2d, Free Energy = %f \\n',it,felast(it));\n else\n fprintf('Init run %2d, %2d->%2d states, Free Energy = %f \\n',...\n it,init_k(it),size(Gamma{it},2),felast(it));\n end\n end\n end\nelse\n for it = 1:length(init_k)\n [hmm{it},Gamma{it},fehist{it}] = run_initialization(data,T,options,init_k(it));\n felast(it) = fehist{it}(end);\n maxfo(it) = mean(getMaxFractionalOccupancy(Gamma{it},T,options));\n if options.verbose\n if options.episodic\n fprintf('Init run %2d, Free Energy = %f \\n',it,felast(it));\n else\n fprintf('Init run %2d, %2d->%2d states, Free Energy = %f \\n',...\n it,init_k(it),size(Gamma{it},2),felast(it));\n end\n end\n end \nend\n\nif isfield(options,'initcriterion') && strcmpi(options.initcriterion,'FreeEnergy')\n [fe,s] = min(felast);\n if options.verbose\n fprintf('%i-th was the best iteration with FE=%f \\n',s,fe)\n end\nelse\n [fo,s] = min(maxfo);\n if options.verbose\n fprintf('%i-th was the best iteration with mean maxFO=%f \\n',s,fo)\n end \nend\n\nGamma = Gamma{s};\nhmm = hmm{s};\nfehist = fehist{s};\n\nend\n\nfunction [hmm,Gamma,fehist] = run_initialization(data,T,options,init_k)\n% INPUTS\n% - data,T,options,Sind \n% - init_k is the number of states to use for this initialization\n\n% Need to adjust the worker dirichletdiags if testing smaller K values\n%if ~options.episodic && init_k < options.K\nSind = options.Sind; \n\nif init_k < options.K\n for j = 1:length(options.DirichletDiag)\n p = options.DirichletDiag(j)/(options.DirichletDiag(j) + options.K - 1); % Probability of remaining in same state\n f_prob = dirichletdiags.mean_lifetime(); % Function that returns the lifetime in steps given the probability\n expected_lifetime = f_prob(p)/options.Fs; % Expected number of steps given the probability\n options.K = init_k;\n adjusted_DirichletDiag = dirichletdiags.get(expected_lifetime,options.Fs,options.K);\n if isfinite(adjusted_DirichletDiag) % It is NaN if there was a numerical issue\n options.DirichletDiag(j) = adjusted_DirichletDiag;\n end\n end\nend\n\ndata.C = data.C(:,1:options.K);\nif ~isfield(options,'ehmm_priorOFFvsON'), ehmm_priorOFFvsON = []; \nelse, ehmm_priorOFFvsON = options.ehmm_priorOFFvsON; \nend\n% Note - initGamma_random uses DD=1 so that there are lots of transition times, which\n% helps the inference not get stuck in a local minimum. options.DirichletDiag is\n% then used inside hmmtrain when computing the free energy\nkeep_trying = true; notries = 0; \nwhile keep_trying\n Gamma = initGamma_random(T-options.maxorder,options.K,...\n min(median(double(T))/10,500),...\n options.Pstructure,options.Pistructure,...\n options.episodic,ehmm_priorOFFvsON);\n hmm = struct('train',struct());\n hmm.K = options.K;\n hmm.train = options;\n hmm.train.Sind = Sind;\n hmm.train.cyc = max(hmm.train.initcyc,2);\n hmm.train.verbose = 0;\n hmm.train.plotGamma = 0;\n hmm = hmmhsinit(hmm);\n if isfield(hmm.train,'Gamma'), hmm.train = rmfield(hmm.train,'Gamma'); end\n [hmm,residuals] = obsinit(data,T,hmm,Gamma);\n try\n [hmm,Gamma,~,fehist] = hmmtrain(data,T,hmm,Gamma,residuals);\n fehist(end) = [];\n keep_trying = false;\n catch exception\n notries = notries + 1; \n if notries > 10\n disp('Initialisation went wrong'); \n throw(exception) \n end\n disp('Something strange happened in the initialisation - repeating')\n end\n hmm.train.verbose = options.verbose;\n hmm.train.cyc = options.cyc;\n hmm.train.plotGamma = options.plotGamma;\nend\n%fe = fehist(end);\nend\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/train/hmmmar_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}} {"text": "addpath(genpath('D:\\GitHub\\KiloSort2')) % path to kilosort folder\naddpath('D:\\GitHub\\npy-matlab')\n\nrootZ = 'H:\\DATA\\Spikes\\Benchmark2015';\n\npathToYourConfigFile = 'D:\\GitHub\\KiloSort2\\configFiles'; % take from Github folder and put it somewhere else (together with the master_file)\nrun(fullfile(pathToYourConfigFile, 'configFile384.m'))\n\nops.chanMap = 'H:\\DATA\\Spikes\\Benchmark2015\\forPRBimecToWhisper.mat';\nrootH = 'H:\\DATA\\Spikes\\temp\\';\n\nops.NchanTOT = 129;\nops.trange = [0 Inf]; % TIME RANGE IN SECONDS TO PROCESS\n\n % these settings overwrite any settings from config\nops.lam = 10^2; % weighting on the amplitude penalty (like in Kilosort1, but it has to be much larger)\n\nops.ThS = [8 8]; % lower bound on acceptable single spike quality\nops.momentum = [20 400]; % number of samples to average over\nops.minFR = 1/50; % minimum spike rate (Hz)\n\nops.sigmaMask = 30;\n\nops.Nfilt = 768; % max number of clusters\nops.nfullpasses = 1; % how many forward backward passes to do\nops.nPCs = 3; % how many PCs to project the spikes into\n\nops.useRAM = 0;\nops.nNeighPC = 3;\nops.ccsplit = .975;\n\nops.NT = 64*1024+ ops.ntbuff;\n\ndsets = {'20141202_all_es', '20150924_1_e', '20150601_all_s',...\n '20150924_1_GT', '20150601_all_GT', '20141202_all_GT'};\n\naddpath(rootZ)\n\ntic\n\nfor idk = [4 3 5] %:3 %1:length(dsets)\n fname = [dsets{idk} '.dat']; %'20141202_all_es.dat';\n \n savePath = fullfile(rootZ, dsets{idk});\n \n ops.fbinary = fullfile(savePath, fname);\n ops.fproc = fullfile(rootH, 'temp_wh2.dat'); % residual from RAM of preprocessed data\n \n % preprocess data\n rez = preprocessDataSub(ops); \n \n fname = fullfile(savePath, 'rez.mat');\n if exist(fname, 'file')\n dr = load(fname);\n rez.iorig = dr.rez.iorig;\n rez.ccb = dr.rez.ccb;\n rez.ccbsort = dr.rez.ccbsort;\n else\n rez = clusterSingleBatches(rez);\n save(fname, 'rez', '-v7.3');\n end\n \n rez = learnAndSolve8b(rez); \n \n rez = splitAllClusters(rez);\n \n fname = [dsets{idk} '.dat']; %'20141202_all_es.dat';\n [~, fn, ~] = fileparts(fname);\n \n isgood = rez.st3(:,4)\n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: July 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ncd(pathDATA)\nload('Patient51_CT'), sDataCT = sData;\nload('Patient51_PET'), sDataPET = sData;\n\n% ADJUSTING CT CONTOURS ACCORDING TO PET CONTOURS.\nsDataCT{2}.scan.contour = sDataPET{2}.scan.contour;\nnContour = length(sDataPET{2}.scan.contour);\ndownF = sDataCT{2}.scan.pixelW/sDataPET{2}.scan.pixelW;\noffsetStart = round(abs(sDataPET{3}(1).ImagePositionPatient(2)-sDataCT{3}(1).ImagePositionPatient(2))*sDataCT{2}.scan.pixelW);\noffsetEnd = round((size(sDataCT{2}.scan.volume,1)*sDataCT{2}.scan.pixelW - size(sDataPET{2}.scan.volume,1)*sDataPET{2}.scan.pixelW)/sDataCT{2}.scan.pixelW)-offsetStart;\nfor i = 1:nContour\n sDataCT{2}.scan.contour(i).boxBound(1:2,1) = round((sDataPET{2}.scan.contour(i).boxBound(1:2,1)/downF + offsetStart)); sDataCT{2}.scan.contour(i).boxBound(1:2,2) = round((sDataPET{2}.scan.contour(i).boxBound(1:2,2)/downF + offsetEnd));\n boxBound = sDataCT{2}.scan.contour(i).boxBound;\n nSlices = size(sDataCT{2}.scan.contour(i).boxMask,3);\n sDataCT{2}.scan.contour(i).boxMask = zeros(boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1,nSlices);\n for j = 1:nSlices\n sDataCT{2}.scan.contour(i).boxMask(:,:,j) = imresize(sDataPET{2}.scan.contour(i).boxMask(:,:,j),[boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1],'nearest');\n end\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/READ_DATA/Archives/correctPatient51_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1986763547726966}} {"text": "% STD_READSPECGRAM - returns the stored mean power spectrogram for an ICA component \n% or a data channel in a specified dataset. The spectrogram is \n% assumed to have been saved in a Matlab file, \n% \"[dataset_name].datspecgram\", in the same\n% directory as the dataset file. If this file doesn't exist,\n% use STD_SPECGRAM to create it.\n% Usage: \n% >> [spec, times, freqs] = std_readspecgram(ALLEEG, setindx, component, timerange, freqrange); \n%\n% Inputs:\n% ALLEEG - a vector of dataset EEG structures (may also be one dataset). \n% Must contain the dataset of interest (the 'setindx' below).\n% setindx - [integer] an index of an EEG dataset in the ALLEEG\n% structure for which to read a component spectrum.\n% component - [integer] index of the component in the selected EEG dataset \n% for which to return the spectrum\n% freqrange - [min max in Hz] frequency range to return\n%\n%\n% Outputs:\n% spec - the log-power spectrum of the requested ICA component in the\n% specified dataset (in dB)\n% freqs - vector of spectral frequencies (in Hz)\n%\n% See also STD_SPEC, POP_PRECLUST, STD_PRECLUST\n%\n% Authors: Arnaud Delorme, SCCN, INC, UCSD, February, 2008\n\n% Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, hilit@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [X, t, f] = std_readspecgram(ALLEEG, abset, comp, timerange, freqrange, rmsubjmean);\n\nif nargin < 4\n timerange = [];\nend\nif nargin < 5\n freqrange = [];\nend\n \nX = [];\n\nif iscell(comp)\n % find channel indices list\n % -------------------------\n chanind = [];\n tmpchanlocs = ALLEEG(abset).chanlocs;\n chanlabs = lower({ tmpchanlocs.labels });\n for index = 1:length(comp)\n tmp = strmatch(lower(comp{index}), chanlabs, 'exact');\n if isempty(tmp)\n error([ 'Channel ''' comp{index} ''' not found in dataset ' int2str(abset)]);\n else \n chanind = [ chanind tmp ];\n end\n end\n filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']);\n prefix = 'chan';\n inds = chanind;\nelseif comp(1) < 0\n filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']);\n prefix = 'chan';\n inds = -comp;\nelse\n filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icaspecgram']);\n prefix = 'comp';\n inds = comp;\nend\n\nfor k=1:length(inds)\n try,\n warning backtrace off;\n erpstruct = load( '-mat', filename, [ prefix int2str(inds(k)) ], 'freqs', 'times');\n warning backtrace on;\n catch\n error( [ 'Cannot read file ''' filename '''' ]);\n end\n\n tmpdat = getfield(erpstruct, [ prefix int2str(inds(k)) ]);\n if k == 1\n X = zeros([size(tmpdat) length(comp)]);\n end\n X(:,:,k) = tmpdat;\n f = getfield(erpstruct, 'freqs');\n t = getfield(erpstruct, 'times');\nend\n\n% select frequency range of interest\n% ----------------------------------\nif ~isempty(freqrange)\n maxind = max(find(f <= freqrange(end)));\n minind = min(find(f >= freqrange(1)));\nelse\n %if not, use whole spectrum\n maxind = length(f);\n minind = 1;\nend\nf = f(minind:maxind);\nX = X(minind:maxind,:,:);\n\n% select time range of interest\n% -----------------------------\nif ~isempty(timerange)\n maxind = max(find(t <= timerange(end)));\n minind = min(find(t >= timerange(1)));\nelse\n %if not, use whole spectrum\n maxind = length(t);\n minind = 1;\nend\nt = t(minind:maxind);\nX = X(:,minind:maxind,:);\n\nreturn;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_readspecgram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.19867635353556024}} {"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": "clear\n% close all\nclc;\n\naddpath(genpath('../libs'))\naddpath('./myFunc')\n% path_to_matconvnet = '../matconvnet';\npath_to_matconvnet = '../matconvnet_std';\npath_to_matconvnet = '/home/skong2/scratch/matconvnet-1.0-beta23_modifiedDagnn';\npath_to_model = '../models/';\n\nrun(fullfile(path_to_matconvnet, 'matlab', 'vl_setupnn'));\naddpath(genpath(fullfile('dependencies', 'matconvnet','examples')));\n%% read matconvnet model\nload('imdb_toydata_v3_from_mnist.mat');\n% imdb.path_to_dataset = '/run/shm/toydata';\n\n% set GPU\ngpuId = 2; %[1, 2];\ngpuDevice(gpuId);\nflagSaveFig = true; % {true false} whether to store the result\n\n\nsaveFolder = 'main007_instSeg_v1_absEucMM';\nmodelName = 'softmax_net-epoch-83.mat';\n\nsaveFolder = 'main007_instSeg_v2_absEucMM_invAlpha';\nmodelName = 'softmax_net-epoch-83.mat';\n\n%saveFolder = 'main007_instSeg_v3_absEucMM_adaptMM';\n%modelName = 'softmax_net-epoch-92.mat';\n\n%% modify network for testing\nnetMat = load( fullfile('./exp', saveFolder, modelName) );\nnetMat = netMat.net;\nnetMat = dagnn.DagNN.loadobj(netMat);\n\n% RFinfo = netMat.getVarReceptiveFields('input');\n\nrmLayerName = 'obj_instSeg_MM';\nif ~isnan(netMat.getLayerIndex(rmLayerName))\n netMat.removeLayer(rmLayerName); % remove layer\nend\nrmLayerName = 'obj_instSeg';\nif ~isnan(netMat.getLayerIndex(rmLayerName))\n netMat.removeLayer(rmLayerName); % remove layer\nend\nrmLayerName = 'obj_instSeg_reg';\nif ~isnan(netMat.getLayerIndex(rmLayerName))\n netMat.removeLayer(rmLayerName); % remove layer\nend\nnetMat.vars(netMat.layers(netMat.getLayerIndex('res7_l2norm')).outputIndexes).precious = 1;\n%% configure training environment\nsaveFolder = [strrep(saveFolder, '/', '') '_visualization'];\nif ~isdir(saveFolder) && flagSaveFig\n mkdir(saveFolder);\nend\nnetMat.move('gpu');\n% netMat.mode = 'test';\nnetMat.mode = 'normal';\ntestList = find(imdb.set==2);\nrawCountsAll = {};\n\nimgMat = [];\nsemanticMaskMat = [];\ninstanceMaskMat = [];\npredInstanceMaskMat = [];\nst = 0;\nfor i = 1:5%length(testList)\n curBatch = fullfile(imdb.path_to_dataset, imdb.imgList{testList(i)});\n datamat = load(curBatch);\n \n% datamat.imgMat = reshape(datamat.imgMat, [size(datamat.imgMat,1), size(datamat.imgMat,2), 1, size(datamat.imgMat,3)]);\n datamat.semanticMaskMat = reshape(datamat.semanticMaskMat, [size(datamat.semanticMaskMat,1), size(datamat.semanticMaskMat,2), 1, size(datamat.semanticMaskMat,3)]);\n datamat.instanceMaskMat = reshape(datamat.instanceMaskMat, [size(datamat.instanceMaskMat,1), size(datamat.instanceMaskMat,2), 1, size(datamat.instanceMaskMat,3)]);\n \n imFeed = bsxfun(@minus, datamat.imgMat, imdb.meta.meanvalue);\n inputs = {'input', gpuArray(imFeed)};\n netMat.eval(inputs) ;\n res7_l2norm = gather(netMat.vars(netMat.layers(netMat.getLayerIndex('res7_l2norm')).outputIndexes).value);\n\n imgMat(:,:,:,st+1:st+size(datamat.imgMat,4)) = datamat.imgMat;\n semanticMaskMat(:,:,:,st+1:st+size(datamat.imgMat,4)) = datamat.semanticMaskMat;\n instanceMaskMat(:,:,:,st+1:st+size(datamat.imgMat,4)) = datamat.instanceMaskMat;\n predInstanceMaskMat(:,:,:,st+1:st+size(datamat.imgMat,4)) = res7_l2norm;\n fprintf('\\t%d/%d\\n', i, length(testList));\n \n st = st + size(datamat.imgMat,4);\nend\n%% visualize\nnum = 25;\nM = 5;\nN = 5;\nh = 28;\nw = 28;\npanelSZ = round(64/2)*2;\nstepSize = (panelSZ-h)/2;\n\nshowcaseSamples_R = imgMat(:,:,1,1:num);\nshowcaseSamples_R = reshape(showcaseSamples_R, [numel(showcaseSamples_R(:,:,1,1)), num]);\nshowcaseSamples_R = showStitch(showcaseSamples_R, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\nshowcaseSamples_G = imgMat(:,:,2,1:num);\nshowcaseSamples_G = reshape(showcaseSamples_G, [numel(showcaseSamples_G(:,:,1,1)), num]);\nshowcaseSamples_G = showStitch(showcaseSamples_G, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\nshowcaseSamples_B = imgMat(:,:,3,1:num);\nshowcaseSamples_B = reshape(showcaseSamples_B, [numel(showcaseSamples_B(:,:,1,1)), num]);\nshowcaseSamples_B = showStitch(showcaseSamples_B, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\nshowcaseSamples = cat(3, showcaseSamples_R, showcaseSamples_G, showcaseSamples_B);\n\n\nshowcaseSemanticMask= semanticMaskMat(:,:,:,1:num);\nshowcaseSemanticMask = reshape(showcaseSemanticMask, [numel(showcaseSemanticMask(:,:,1,1)), num]);\nshowcaseSemanticMask = showStitch(showcaseSemanticMask, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\n\nshowcaseInstanceMask= instanceMaskMat(:,:,:,1:num);\nshowcaseInstanceMask = reshape(showcaseInstanceMask, [numel(showcaseInstanceMask(:,:,1,1)), num]);\nshowcaseInstanceMask = showStitch(showcaseInstanceMask, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\n\npredInstanceMask_R = predInstanceMaskMat(:,:,1,1:num);\npredInstanceMask_R = reshape(predInstanceMask_R, [numel(predInstanceMask_R(:,:,1,1)), num]);\npredInstanceMask_R = showStitch(predInstanceMask_R, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\npredInstanceMask_G = predInstanceMaskMat(:,:,2,1:num);\npredInstanceMask_G = reshape(predInstanceMask_G, [numel(predInstanceMask_G(:,:,1,1)), num]);\npredInstanceMask_G = showStitch(predInstanceMask_G, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\npredInstanceMask_B = predInstanceMaskMat(:,:,3,1:num);\npredInstanceMask_B = reshape(predInstanceMask_B, [numel(predInstanceMask_B(:,:,1,1)), num]);\npredInstanceMask_B = showStitch(predInstanceMask_B, [panelSZ panelSZ], M, N, 'whitelines', 'linewidth', 5);\npredInstanceMask = cat(3, predInstanceMask_R, predInstanceMask_G, predInstanceMask_B);\n\npredInstanceMask = predInstanceMask - min(predInstanceMask(:));\npredInstanceMask = predInstanceMask ./ max(predInstanceMask(:));\n\nimgFig2 = figure(2);\nsubWindowH = 2;\nsubWindowW = 2;\nset(imgFig2, 'Position', [100 100 1400 900]) % [1 1 width height]\nwindowID = 1;\nsubplot(subWindowH, subWindowW, windowID); imagesc(showcaseSamples); axis off image; title('random samples'); colorbar; windowID = windowID + 1;\nsubplot(subWindowH, subWindowW, windowID); imagesc(showcaseSemanticMask); axis off image; title('showcase SemanticMask'); caxis([0, 11]); colorbar; windowID = windowID + 1;\nsubplot(subWindowH, subWindowW, windowID); imagesc(showcaseInstanceMask); axis off image; title('showcase instanceMask'); colorbar; windowID = windowID + 1;\nsubplot(subWindowH, subWindowW, windowID); imagesc(predInstanceMask); axis off image; title('predInstanceMask'); colorbar; windowID = windowID + 1;\n\nif flagSaveFig\n showcaseSemanticMask = uint8(showcaseSemanticMask * 255/11);\n showcaseInstanceMask = showcaseInstanceMask*255/5;\n \n imwrite(showcaseSamples, fullfile(saveFolder, sprintf('%04d_showcaseSamples.bmp',i)));\n imwrite(showcaseSemanticMask, fullfile(saveFolder, sprintf('%04d_showcaseSemanticMask.bmp',i))); \n imwrite(showcaseInstanceMask, fullfile(saveFolder, sprintf('%04d_showcaseInstanceMask.bmp',i)));\n imwrite(predInstanceMask, fullfile(saveFolder, sprintf('%04d_predInstanceMask.bmp',i)));\n \n export_fig( sprintf('%s/%04d_visualization.jpg', saveFolder, i) );\n save(sprintf('%s/results.mat', saveFolder), 'imgMat', 'instanceMaskMat', 'semanticMaskMat', 'predInstanceMaskMat');\nend\n\n%% leaving blank\n\n\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/demo1_tutorial_instance_segmentation/fun4MeanShift/main001_instSeg_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19863871932796276}} {"text": "function [ Pos ] = getEEFCartesianOrientation( t )\n%% This function is used to get the endeffector cartizian orientation of the KUKA iiwa 7 R 800.\n\n%% Syntax:\n% [ Ori ] = getEEFCartisianOrientation( t )\n\n%% About:\n% This function is used to get the endeffector cartizian orientation of the KUKA iiwa 7 R 800.\n% The orientation is of the media flange of the robot relative to the base\n% frame of the robot.\n\n%% Arreguments:\n% t: is the TCP/IP connection\n% Ori: is 1x3 cell array, alpha,beta and gama angles of the endeffector,\n% the angles are measured in radians.\n\n% Copyright, Mohammad SAFEEA, 3rd of May 2017\n\ntheCommand='Eef_pos';\nfprintf(t, theCommand);\nmessage=fgets(t);\n%disp(message)\n[P1,N]=getDoubleFromString(message);\nttt=0;\nfor i=4:6\n ttt=ttt+1;\n Pos{ttt}=P1{i};\nend\n\nend\n\nfunction [jPos,j]=getDoubleFromString(message)\nn=max(max(size(message)));\nj=0;\nnumString=[];\nfor i=1:n\n if message(i)=='_'\n j=j+1;\n jPos{j}=str2num(numString);\n numString=[];\n else\n numString=[numString,message(i)];\n end\nend\nend\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/getEEFCartesianOrientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.19860634894612117}} {"text": "% eegthresh() - reject trials with out-of-bounds channel values within a\n% specified epoch time range.\n%\n% Usage:\n% >> [Iin, Iout, newsignal, elec] = eegthresh( signal, frames, ...\n% elecs, negthresh, posthresh, timerange, starttime,endtime);\n%\n% Required inputs:\n% signal - 2-D data matrix [channels, frames*sweeps], \n% or 3-D data matrix [channels, frames, sweeps]\n% frames - number of points per epoch\n% elecs - [int vector] electrode indices to reject on\n% negthresh - minimum rejection threshold(s) in uV. This can be an array \n% of values for individual electrodes. If fewer values than \n% electrodes, the last value is used for the remaining \n% electrodes.\n% posthresh - maximum rejection threshold(s) in uV (same syntax as for\n% negthresh)\n% timerange - [mintime maxtime] time range limits of the signal\n% starttime - Starting limit (in seconds or Hz) of range to perform \n% rejection (same syntax as negthresh)\n% endtime - Ending limit (in seconds or Hz) of range to perform \n% rejection (same syntax as negthresh)\n%\n% Outputs:\n% Iin - Indexes of epochs accepted\n% Iout - Indexes of epochs rejected\n% newsignal - input data after epoch rejection\n% elec - electrode that triggered the rejections (array of 0s \n% and 1s with the same number of columns as Iout\n% and number of rows = number of electrodes).\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001\n%\n% See also: pop_eegthresh(), eeglab()\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction [Iin, Iout, newsignal, elec] = eegthresh( signal, pnts, electrodes, negthresh, posthresh, timerange, starttime, endtime);\n\nif nargin < 7\n\thelp eegthresh;\n\treturn;\nend;\n\nif starttime < timerange(1)\n\tdisp('eegthresh: starting point out of range, adjusted');\n starttime = timerange(1);\nend;\t\nif endtime > timerange(2)\n\tdisp('eegthresh: ending point out of range, adjusted');\n endtime = timerange(2);\nend;\t\n\n% complete thresholds values if necessary\n%----------------------------------------\nif size(posthresh,2) < size(electrodes,2)\n\tposthresh = [ posthresh posthresh(end)*ones(1,size(electrodes,2)-size(posthresh,2))];\nend;\t\nif size(negthresh,2) < size(electrodes,2)\n\tnegthresh = [ negthresh negthresh(end)*ones(1,size(electrodes,2)-size(negthresh,2))];\nend;\n\t\n% complete timeselect values if necessary\n%----------------------------------------\nif size(starttime,2) < size(electrodes,2)\n\tstarttime = [ starttime starttime(end)*ones(1,size(electrodes,2)-size(starttime,2))];\nend;\t\nif size(endtime,2) < size(electrodes,2)\n\tendtime = [ endtime endtime(end)*ones(1,size(electrodes,2)-size(endtime,2))];\nend;\t\n\n% find the maximum for each trial\n%--------------------------------\nsweeps = size(signal(1,:),2)/pnts;\nsignal = reshape(signal(electrodes,:), size(electrodes(:),1), pnts, sweeps);\n\n% reject the selected trials\n%---------------------------\nelec = zeros(size(electrodes(:),1), sweeps);\nallelec = zeros(1, sweeps);\nfor indexe = 1:size(electrodes(:),1)\n\t% transform the time range\n\t% ------------------------\n\tframelowlimit = max(1,floor((starttime(indexe)-timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1);\t\n\tframehighlimit = floor((endtime(indexe) -timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1;\n\n\t% remove outliers\n\t% ---------------\n\tsigtmp = squeeze(signal(indexe,framelowlimit:framehighlimit,:));\n if size(signal,3) == 1, sigtmp = sigtmp'; end;\n\tsigmax = max(sigtmp, [], 1);\n\tsigmin = min(sigtmp, [], 1);\n\telec(indexe,:) = ( sigmin < negthresh(indexe) ) | ( sigmax > posthresh(indexe) );\n\tallelec = allelec | elec(indexe,:);\nend;\nIout = find( allelec == 1 );\nIin = find( allelec == 0 );\nelec = elec(:,Iout);\n\n% reject the selected trials\n%---------------------------\nnewsignal = reshape(signal, size(signal,1), pnts, sweeps);\nif ~isempty(Iin)\n\tnewsignal = newsignal(:,:,Iin);\n\tif ndims(signal) == 2\n\t\tnewsignal = newsignal(:,:);\n\tend;\nelse\n\tnewsignal = [];\nend;\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/sigprocfunc/eegthresh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}} {"text": "function ChannelMat = in_channel_cartool_els(ChannelFile)\n% IN_CHANNEL_ELS: Reads a .els file : cartesian coordinates of a set of electrodes, divided in various clusters\n% \n% USAGE: ChannelMat = in_channel_els(ChannelFile)\n%\n% INPUT: \n% - ChannelFile : name of file to open, WITH .ELS EXTENSION\n% OUTPUT:\n% - ChannelMat : Brainstorm channel structure\n%\n% FORMAT: (.ELS)\n% ASCII file :\n% Format : \"ES01\"\n% \" \"\n% \" \"\n% Repeat for each cluster :\n% \" \"\n% \" \"\n% \" \"\n% End of repeat\n% Repeat for each electrode :\n% \" ?? ??\"\n% End.\n% Notes :\n% - Cluster_type : could be seen as the dimensionality of the cluster :\n% - 0 for separated electrodes (like auxiliaries), or \"points\"\n% - 1 for a strip of electrodes, or \"line\"\n% - 2 for a grid of electrodes, or \"array\"\n% - 3 for a 3D set of electrodes, usually on the scalp\n% - optional_flag : ignored in this program\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2006-2015\n\n\n% Initialize output variable\nChannelMat = [];\n\n\n%% ===== READ ELS FILE =====\n% Open file\n[fid, message] = fopen(ChannelFile, 'r');\nif (fid == -1)\n disp(['BST> Error: Could not open file: ' message]);\n return;\nend\n% Read magic number\nreadData = fgetl(fid);\nif ~strcmp(readData, 'ES01')\n error('Invalid ELS file.');\nend\n% Read number of electrodes\nNe = str2num(fgetl(fid));\n% Read number of clusters\nNclust = str2num(fgetl(fid));\n% Read all clusters\nclusterNames = cell(1,Nclust);\nallLoc = zeros(0,3);\nallLabels = {};\nallClusters = {};\nallTypes = {};\nfor iClust = 1:Nclust\n clusterNames{iClust} = fgetl(fid);\n clusterNchan = str2num(fgetl(fid));\n clusterType = str2num(fgetl(fid));\n % Skip electrode positions and move to next cluster\n for iChan = 1:clusterNchan\n chanLine = fgetl(fid);\n readData = textscan(chanLine, '%n %n %n %s', 1);\n allLoc(end+1,:) = [readData{1:3}];\n allClusters{end+1} = clusterNames{iClust};\n if isempty(readData{4}) || isempty(readData{4}{1})\n allLabels{end+1} = sprintf('%s%02d', clusterNames{iClust}, iChan);\n else\n allLabels{end+1} = readData{4}{1};\n end\n % Channel type\n switch clusterType\n case 0, allTypes{end+1} = 'Misc';\n case 1, allTypes{end+1} = 'SEEG';\n case 2, allTypes{end+1} = 'ECOG';\n case 3, allTypes{end+1} = 'EEG';\n otherwise, allTypes{end+1} = 'EEG';\n end\n end\nend\n% Close file\nfclose(fid);\n\n% Verify the expected number of electrodes\n% If too many electrodes were read, only keep the first 'Ne' electrodes\nreadNe = size(allLoc,1);\nif (readNe < Ne)\n disp('BST> Warning: Incorrect number of electrodes in file.');\nelseif (readNe > Ne)\n allLoc(Ne+1:readNe, :) = [];\n allLabels(Ne+1:readNe, :) = [];\n allClusters(Ne+1:readNe, :) = [];\n allTypes(Ne+1:readNe, :) = [];\nend\n\n\n%% ===== SELECT CLUSTERS =====\n% If there are multiple clusters\nif (Nclust > 1)\n % Ask user to select clusters\n isSelected = java_dialog('checkbox', 'Select the clusters to import:', 'Import ELS file', [], clusterNames, ones(size(clusterNames)));\n if isempty(isSelected) || ~any(isSelected)\n return;\n end\n % Select only the required sensors\n iChannels = find(ismember(allClusters, clusterNames(isSelected==1)));\nelse\n iChannels = 1:readNe;\nend\n\n\n\n%% ===== CONVERT IN BRAINSTORM FORMAT =====\nChannelMat = db_template('channelmat');\nChannelMat.Comment = 'Cartool ELS';\nChannelMat.Channel = repmat(db_template('channeldesc'), 1, length(iChannels));\nfor i = 1:length(iChannels)\n ChannelMat.Channel(i).Name = allLabels{iChannels(i)};\n ChannelMat.Channel(i).Comment = '';\n ChannelMat.Channel(i).Type = allTypes{iChannels(i)};\n ChannelMat.Channel(i).Group = allClusters{iChannels(i)};\n ChannelMat.Channel(i).Loc = allLoc(iChannels(i),:)';\n ChannelMat.Channel(i).Orient = [];\n ChannelMat.Channel(i).Weight = 1;\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_channel_cartool_els.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}} {"text": "% Defines constants\n%\n% Author: Jonathan Karr\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 5/7/2009\nclassdef ConstantUtil\n properties (Constant=true)\n nAvogadro=6.0221417930e23;\n elements=struct(...\n 'H',1.0079,...\n 'He',4.0026,...\n 'Li',6.941,...\n 'Be',9.0122,...\n 'B',10.811,...\n 'C',12.0107,...\n 'N',14.0067,...\n 'O',15.9994,...\n 'F',18.9984,...\n 'Ne',20.1797,...\n 'Na',22.9897,...\n 'Mg',24.305,...\n 'Al',26.9815,...\n 'Si',28.0855,...\n 'P',30.9738,...\n 'S',32.065,...\n 'Cl',35.453,...\n 'Ar',39.948,...\n 'K',39.0983,...\n 'Ca',40.078,...\n 'Sc',44.9559,...\n 'Ti',47.867,...\n 'V',50.9415,...\n 'Cr',51.9961,...\n 'Mn',54.938,...\n 'Fe',55.845,...\n 'Co',58.9332,...\n 'Ni',58.6934,...\n 'Cu',63.546,...\n 'Zn',65.39,...\n 'Ga',69.723,...\n 'Ge',72.64,...\n 'As',74.9216,...\n 'Se',78.96,...\n 'Br',79.904,...\n 'Kr',83.8,...\n 'Rb',85.4678,...\n 'Sr',87.62,...\n 'Y',88.9059,...\n 'Zr',91.224,...\n 'Nb',92.9064,...\n 'Mo',95.94,...\n 'Tc',98,...\n 'Ru',101.07,...\n 'Rh',102.9055,...\n 'Pd',106.42,...\n 'Ag',107.8682,...\n 'Cd',112.411,...\n 'In',114.818,...\n 'Sn',118.71,...\n 'Sb',121.76,...\n 'Te',127.6,...\n 'I',126.9045,...\n 'Xe',131.293,...\n 'Cs',132.9055,...\n 'Ba',137.327,...\n 'La',138.9055,...\n 'Ce',140.116,...\n 'Pr',140.9077,...\n 'Nd',144.24,...\n 'Pm',145,...\n 'Sm',150.36,...\n 'Eu',151.964,...\n 'Gd',157.25,...\n 'Tb',158.9253,...\n 'Dy',162.5,...\n 'Ho',164.9303,...\n 'Er',167.259,...\n 'Tm',168.9342,...\n 'Yb',173.04,...\n 'Lu',174.967,...\n 'Hf',178.49,...\n 'Ta',180.9479,...\n 'W',183.84,...\n 'Re',186.207,...\n 'Os',190.23,...\n 'Ir',192.217,...\n 'Pt',195.078,...\n 'Au',196.9665,...\n 'Hg',200.59,...\n 'Tl',204.3833,...\n 'Pb',207.2,...\n 'Bi',208.9804,...\n 'Po',209,...\n 'At',210,...\n 'Rn',222,...\n 'Fr',223,...\n 'Ra',226,...\n 'Ac',227,...\n 'Th',232.0381,...\n 'Pa',231.0359,...\n 'U',238.0289,...\n 'Np',237,...\n 'Pu',244,...\n 'Am',243,...\n 'Cm',247,...\n 'Bk',247,...\n 'Cf',251,...\n 'Es',252,...\n 'Fm',257,...\n 'Md',258,...\n 'No',259,...\n 'Lr',262,...\n 'Rf',261,...\n 'Db',262,...\n 'Sg',266,...\n 'Bh',264,...\n 'Hs',277,...\n 'Mt',268);\n elementNumbers=struct(...\n 'H', 1,...\n 'He',4,...\n 'Li',7,...\n 'Be',9,...\n 'B', 11,...\n 'C', 12,...\n 'N', 14,...\n 'O', 16,...\n 'F', 19,...\n 'Ne',20,...\n 'Na',23,...\n 'Mg',24,...\n 'Al',27,...\n 'Si',28,...\n 'P', 31,...\n 'S', 32,...\n 'Cl',35,...\n 'Ar',40,...\n 'K', 39,...\n 'Ca',40,...\n 'Sc',45,...\n 'Ti',48,...\n 'V', 51,...\n 'Cr',52,...\n 'Mn',55,...\n 'Fe',56,...\n 'Co',59,...\n 'Ni',59,...\n 'Cu',64,...\n 'Zn',65,...\n 'Ga',70,...\n 'Ge',73,...\n 'As',75,...\n 'Se',79,...\n 'Br',80,...\n 'Kr',84,...\n 'Rb',85,...\n 'Sr',87,...\n 'Y', 89,...\n 'Zr',91,...\n 'Nb',93,...\n 'Mo',96,...\n 'Tc',98,...\n 'Ru',101,...\n 'Rh',103,...\n 'Pd',107,...\n 'Ag',108,...\n 'Cd',112,...\n 'In',115,...\n 'Sn',119,...\n 'Sb',122,...\n 'Te',128,...\n 'I', 127,...\n 'Xe',131,...\n 'Cs',133,...\n 'Ba',137,...\n 'La',139,...\n 'Ce',140,...\n 'Pr',141,...\n 'Nd',144,...\n 'Pm',145,...\n 'Sm',150,...\n 'Eu',152,...\n 'Gd',157,...\n 'Tb',159,...\n 'Dy',163,...\n 'Ho',165,...\n 'Er',167,...\n 'Tm',169,...\n 'Yb',173,...\n 'Lu',175,...\n 'Hf',178,...\n 'Ta',181,...\n 'W', 184,...\n 'Re',186,...\n 'Os',190,...\n 'Ir',192,...\n 'Pt',195,...\n 'Au',197,...\n 'Hg',201,...\n 'Tl',204,...\n 'Pb',207,...\n 'Bi',209,...\n 'Po',209,...\n 'At',210,...\n 'Rn',222,...\n 'Fr',223,...\n 'Ra',226,...\n 'Ac',227,...\n 'Th',232,...\n 'Pa',231,...\n 'U', 238,...\n 'Np',237,...\n 'Pu',244,...\n 'Am',243,...\n 'Cm',247,...\n 'Bk',247,...\n 'Cf',251,...\n 'Es',252,...\n 'Fm',257,...\n 'Md',258,...\n 'No',259,...\n 'Lr',262,...\n 'Rf',261,...\n 'Db',262,...\n 'Sg',266,...\n 'Bh',264,...\n 'Hs',277,...\n 'Mt',268);\n secondsPerMinute = 60;\n secondsPerHour=3600;\n minutesPerHour=60;\n\n realmax = 1e10;\n end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+util/ConstantUtil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19844912554963345}} {"text": "function [outColor] = nflcolor(teamName, colorType)\n%NFLCOLOR Return NFL RGB color values by team or city name\n% COLOR = NFLCOLOR(TEAMNAME,COLORTYPE) returns the 3-element RGB\n% color values of an NFL team specified using the team's city name\n% (Buffalo for example) or by the team name (Bills for example). The\n% type of color returned is determined by COLORTYPE, COLORTYPE must\n% either be 'team' for the primary team color or 'name for the color used\n% on jersy names. If COLORTYPE is omitted, the primary team color is\n% output. Inputs are not case sensitive. Partial matches are\n% supported. In cases where more than one match is found, the first\n% match is provided and a warning is generated.\n%\n% Examples:\n%\n% bengalsBlack = nflcolor('bengals', 'team');\n% bengalsOrange = nflcolor('bengals','name');\n% bengalsOrange = nflcolor('cinci','name');\n% dolphinAqua = nflcolor('miami');\n%\n% Color values are from the following web site...\n% http://en.wikipedia.org/wiki/Template:Infobox_NFL_player#Team_colors\n%\n% Note: Giants fans may wish to edit this function and claim New York for\n% themselves. As written, the fuction gives Jets colors when New York is\n% provided as the team name.\n%\n\n% Define nfl colors, column 3 is team color, column 4 is name color\nnflData = ...\n {'buffalo', 'bills', '0f4589', 'ffffff';\n 'miami', 'dolphins', '005e6a', 'ffffff';\n 'new england', 'patriots', '0d254c', 'd6d6d6';\n 'new york', 'jets', '313f36', 'ffffff';\n 'baltimore', 'ravens', '2a0365', 'd0b239';\n 'cincinnati', 'bengals', '000000', 'f03a16';\n 'cleveland', 'browns', 'de6108', '312821';\n 'pittsburgh', 'steelers', '000000', 'f1c500';\n 'houston', 'texans', '001831', 'ffffff';\n 'indianapolis', 'colts', '003b7b', 'ffffff';\n 'jacksonville', 'jaguars', '00576e', 'd0b239';\n 'tennessee', 'titans', '648fcc', '0d254c';\n 'denver', 'broncos', '10274c', 'df6109';\n 'kansas city', 'chiefs', 'b20032', 'f2c800';\n 'oakland', 'raiders', '000000', 'c4c8cb';\n 'san diego', 'chargers', '08214a', 'eec607';\n 'dallas', 'cowboys', 'c5ced6', '000080';\n 'new york', 'giants', '192f6b', 'ffffff';\n 'philadelphia', 'eagles', '003b48', 'c4c8cb';\n 'washington', 'redskins', '7d0008', 'ffbe26';\n 'chicago', 'bears', '03182f', 'df6108';\n 'detroit', 'lions', '005da6', 'c4c8cb';\n 'green bay', 'packers', '213d30', 'ffcc00';\n 'minnesota', 'vikings', '3b0160', 'f0bf00';\n 'atlanta', 'falcons', 'bd0d18', '000000';\n 'carolina', 'panthers', '000000', '0088d4';\n 'new orleans', 'saints', '000000', 'c9b074';\n 'tampa bay', 'buccaneers','b20032', 'ffffff';\n 'arizona', 'cardinals', '870619', 'ffffff';\n 'st louis', 'rams', '0d254c', 'c9b074';\n 'saint louis', 'rams', '0d254c', 'c9b074';\n 'st. louis', 'rams', '0d254c', 'c9b074';\n 'san francisco', '49ers', '840026', 'c9b074';\n 'seattle', 'seahawks', '03182f', '4eae17'};\n\nidx=strmatch(lower(teamName),nflData(:,1:2));\n\nif isempty(idx)\n error('Team name not found');\nend\n\nnEntries = size(nflData,1);\nif idx(1)>nEntries\n idx(1) = idx(1)-nEntries;\nend\n\nif length(idx)>1\n warning('nflcolor:multipleMatches',['Found multiple matches for %s, ' ...\n 'using %s'], teamName, nflData{idx(1),2});\nend\n\nif nargin<2\n colorType = 'team';\nend\n\nswitch lower(colorType)\n case 'team'\n colorHex = nflData{idx(1),3};\n case 'name'\n colorHex = nflData{idx(1),4};\n otherwise\n error('Invalid colorType specified');\nend\n\noutColor = [hex2dec(colorHex(1:2)),...\n hex2dec(colorHex(3:4)),...\n hex2dec(colorHex(5:6))]/255;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16280-nflcolor/nflcolor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.1981070332520096}} {"text": "function model=convertToCobraV2(model)\n% Generate a model structure with metabolite and reaction subfields instead of vectors.\n%\n% create a COBRA v2 model structure with model.met(m) for metabolites and\n% model.rxn(n) for reactions. This keeps all the information about a\n% metabolite or reaction in one place. The primary keys model.mets and\n% model.rxns are kept as is, and these can be used to access groups of\n% model.met or model.rxn quickly.\n%\n% Replaces (*) with [*] to denote compartment in metabolite abbreviations\n%\n%\n%INPUT\n% model.S Stoichiometric matrix \n% model.rxns Abbreviation for each reaction (primary key)\n% model.rxnNames Full name for each reaction\n% model.mets Abbreviation for each metabolite (primary key)\n% model.metNames Full name for each metabolite\n% model.biomassRxnAbbr abbreviation of biomass reaction\n%\n%OPTIONAL INPUT\n% model.metFormulas m x 1 cell array of strings with chemical \n% formula for metabolite\n% model.metCharges m x 1 numeric charge for each metabolite\n% species\n% \n%OUTPUT\n% model.S Sparse Stoichiometric matrix +/- with \n% adjustment of reactions involving C02 \n% model.SIntRxnBool Boolean of internal reactions, i.e.\n% non-mass balanced reactions\n% model.met(m).abbreviation metabolite abbreviation (primary key)\n% model.met(m).officialName metabolite name \n% model.rxn(n).abbreviation reaction abbreviation (primary key)\n% model.rxn(n).officialName reaction name\n% model.rxn(n).equation reaction equation\n% model.rxn(n).directionality qualitative directionality \n% model.rxn(n).regulationStatus {('On'),'Off'} Off if lb=ub=0 \n%\n%OPTIONAL OUTPUT\n% model.met(m).formula metabolite elemental formula\n%\n% Ronan M. T. Fleming\n\n[nMet,nRxn]=size(model.S);\n\n%make it sparse\nmodel.S=sparse(model.S);\n\nnumChar=1;\n[allMetCompartments,uniqueCompartments]=getCompartment(model.mets,numChar);\n\nif ~exist('thermoAdjustmentToS','var')\n thermoAdjustmentToS=1;\nend\n\nfor m=1:nMet\n %find the rows with columns that are all zeros\n if nnz(model.S(m,:))==0\n fprintf('%s\\n',['metabolite ' model.mets{m} ' without a reaction???']);\n% error(['metabolite ' model.mets{m} ' without a reaction.']);\n end\n \n %replace (*) with [*] to denote compartment\n model.mets{m}(end-2)='[';\n model.mets{m}(end)=']';\nend\n\n% start the conversion to a cobra v2 style model\nfprintf('%s\\n','Converting to cobra toolbox v2 style model.')\n[nMet,nRxn]=size(model.S);\n\nfor n=1:nRxn\n model.rxn(n).abbreviation=model.rxns{n};\n model.rxn(n).officialName=model.rxnNames{n};\n %equation\n equation=printRxnFormula(model,model.rxns(n),0);\n model.rxn(n).equation=equation{1};\n %directionality\n if model.lb(n)<0 && model.ub(n)>0\n model.rxn(n).directionality='reversible';\n end\n if model.lb(n)<0 && model.ub(n)<=0\n model.rxn(n).directionality='reverse';\n end\n if model.lb(n)>=0 && model.ub(n)>0\n model.rxn(n).directionality='forward';\n end\n if model.lb(n)==0 && model.ub(n)==0\n model.rxn(n).directionality='off';\n end\nend\n\n%new metabolite structure\nfor m=1:nMet\n model.met(m).abbreviation=model.mets{m};\n model.met(m).officialName=model.metNames{m};\n% model=rmfield(model,'metNames');\nend\n\nif isfield(model,'metFormulas')\n for m=1:nMet\n model.met(m).formula=model.metFormulas{m};\n end\n model=rmfield(model,'metFormulas');\nend\n\nif isfield(model,'metCharges')\n for m=1:nMet\n model.met(m).charge=model.metCharges(m);\n end\n model=rmfield(model,'metCharges');\nend\n\n% %replace any dashes in metabolite names with underscores\n% for m=1:nMet\n% x = strfind(model.met(m).abbreviation,'-');\n% if x~=0\n% %cobra v2 mets have underscores\n% model.met(m).abbreviation(x)='_';\n% %make cobra v1 mets have all underscores also\n% abbr=model.mets{m};\n% abbr(x)='_';\n% model.mets{m}=abbr;\n% end\n% end\n\n%finds the reactions in the model which export/import from the model\n%boundary i.e. mass unbalanced reactions\n%e.g. Exchange reactions\n% Demand reactions\n% Sink reactions\nmodel=findSExRxnInd(model);\n\nfprintf('%s\\n\\n','...finished converting.')", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/deprecated/_directionalityReport_old/convertToCobraV2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.1981070332520096}} {"text": "classdef CarlaEnvironment < matlab.System & matlab.system.mixin.Propagates\n % Untitled Add summary here\n %\n % This template includes the minimum set of functions required\n % to define a System object with discrete state.\n\n % Public, tunable properties\n properties\n \n end\n\n properties(DiscreteState)\n\n end\n\n % Pre-computed constants\n properties(Access = private)\n % Semantic segmentation resolution\n width = 960;\n height = 540;\n \n % RGB resolution\n rgb_width = 1920;\n rgb_height = 1080;\n \n tesla;\n last_position;\n \n ss_rgb;\n module_ss_rgb;\n \n rgb;\n module_rgb;\n \n last_update_time;\n history_array = zeros(2, 8);\n steer_spline;\n \n steer_window_avg = 0;\n push_back_time = 0;\n frames_since_last_update = 0;\n \n bias = -0.033;\n end\n\n methods(Access = protected)\n function setupImpl(obj)\n % Perform one-time calculations, such as computing constants\n port = int16(2000);\n client = py.carla.Client('localhost', port);\n client.set_timeout(10.0);\n world = client.get_world();\n \n % Spawn Vehicle\n blueprint_library = world.get_blueprint_library();\n car_list = py.list(blueprint_library.filter(\"model3\"));\n car_bp = car_list{1};\n spawn_point = py.random.choice(world.get_map().get_spawn_points());\n% spawn_point.location.x = -88.8;\n% spawn_point.location.y = 149.0;\n% spawn_point.rotation.yaw = 90;\n \n obj.tesla = world.spawn_actor(car_bp, spawn_point);\n obj.tesla.set_autopilot(false);\n \n control = obj.tesla.get_control();\n control.throttle = 0.6;\n control.steer = 0;\n obj.tesla.apply_control(control);\n \n % Semantic Segmentation\n blueprint = world.get_blueprint_library().find('sensor.camera.semantic_segmentation');\n blueprint.set_attribute('image_size_x', num2str(obj.width))\n blueprint.set_attribute('image_size_y', num2str(obj.height))\n \n transform = py.carla.Transform(py.carla.Location(pyargs('x',0.8, 'z',1.7)));\n obj.ss_rgb = world.spawn_actor(blueprint, transform, pyargs('attach_to',obj.tesla));\n\n obj.module_ss_rgb = sensorBind(obj.ss_rgb, \"ss_rgb\", \"semantic_segmentation_rgb\", \"array\");\n \n \n % RGB\n blueprint = world.get_blueprint_library().find('sensor.camera.rgb');\n blueprint.set_attribute('image_size_x', num2str(obj.rgb_width))\n blueprint.set_attribute('image_size_y', num2str(obj.rgb_height))\n \n transform = py.carla.Transform(py.carla.Location(pyargs('x',-5.0, 'z',2.5)));\n obj.rgb = world.spawn_actor(blueprint, transform, pyargs('attach_to',obj.tesla));\n\n obj.module_rgb = sensorBind(obj.rgb, \"rgb\", \"rgb\", \"array\");\n \n obj.last_position = obj.tesla.get_location();\n \n obj.last_update_time = cputime;\n end\n\n function [SEMANTIC_SEGMENTATION_RGB, RGB] = stepImpl(obj)\n \n % Semantic Segmentation \n SEMANTIC_SEGMENTATION_RGB = uint8(py.getattr(obj.module_ss_rgb, 'array'));\n \n %% Lane Detection\n control = obj.tesla.get_control();\n\n % Crop the image to region of interest\n horizontal_crop = 0.0;\n hor_start_pos = ceil(obj.width/2);\n hor_end_pos = floor(obj.width * (1 - horizontal_crop / 2));\n \n vertical_crop = .5;\n vert_start_pos = 1 + ceil(obj.height * vertical_crop);\n \n filtered_lanes = SEMANTIC_SEGMENTATION_RGB(vert_start_pos:obj.height,hor_start_pos:hor_end_pos,1) == 157;\n\n \n % Apply hough transformations to get the lines from the sensor\n % image\n BW = filtered_lanes;\n [H,T,R] = hough(BW);\n P = houghpeaks(H,5,'threshold',ceil(0.0*max(H(:))));\n lines = houghlines(BW,T,R,P,'FillGap',50,'MinLength',20);\n \n % Calculate the angles of the lines based on the x-y\n % coordinates\n angles = zeros(1, length(lines));\n for k = 1:length(lines)\n angles(k) = rad2deg(atan((lines(k).point1(2) - lines(k).point2(2))/(lines(k).point1(1) - lines(k).point2(1))));\n end\n \n % Normally from the camera position, the angle between the road\n % and the car if the car is moving straight\n ref_angle = 57;\n max_angle = max(angles);\n \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Loop to draw the nearest right lanes detected\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n imshow(filtered_lanes), hold on\n\n for k = 1:length(lines) \n angle = rad2deg(atan((lines(k).point1(2) - lines(k).point2(2))/(lines(k).point1(1) - lines(k).point2(1))));\n if ~(angle == max_angle)\n continue\n end\n\n xy = [lines(k).point1; lines(k).point2];\n plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');\n\n % Plot beginnings and ends of lines\n plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');\n plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');\n\n end\n\n set(gcf, 'Visible', 'on');\n hold off;\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n \n % If the vehicle has just spawned and not started moving, dont\n % update steer history \n started = false;\n current_location = obj.tesla.get_location();\n thres_loc = 0.001;\n \n if abs(current_location.x - obj.last_position.x) > thres_loc...\n && abs(current_location.y - obj.last_position.y) > thres_loc\n started = true;\n end\n \n % Calculate the time it took to process one frame. Really\n % necessary to make the calculations independent of the frame\n % rate. Otherwise, running simulation on a pc that can run it\n % on 20 FPS will steer 20 times vs 2 FPS steers 2 times, dt \n % scales that\n dt = cputime - obj.last_update_time;\n fac = 0.5 * tanh(0.1 * abs(ref_angle - max_angle)) * dt;\n \n obj.last_update_time = cputime;\n \n \n % How much effect the last steering has on the future steer\n mem = 0.0025;\n \n % Filter out lines that are almost horizontal\n if ~isempty(fac) && ((max_angle < 85) && (max_angle > 25)) && started\n if max_angle < ref_angle \n steer = mem * control.steer + fac;\n else\n steer = mem * control.steer - fac;\n end\n else\n steer = obj.bias;\n end\n \n % Update the spline history ~ every .2 seconds. A very high FPS\n % would polute the spline fitting\n if cputime - obj.push_back_time > .2\n \n % Delete the oldest element in the array\n obj.history_array(:,1) = [];\n \n % Most recent history weight\n weight = 1.25;\n \n % Average of the steer since the last update\n steer = (obj.steer_window_avg + steer)/(obj.frames_since_last_update + 1);\n\n % Add to the histroy\n obj.history_array = [obj.history_array, [cputime;steer]];\n\n % Pre-processing for the curve fitting\n [timeData, steerData] = prepareCurveData( obj.history_array(1,:),...\n obj.history_array(2,:));\n\n\n obj.history_array(end) = obj.history_array(end) * weight;\n\n % Fit a smoothing spline to the data\n obj.steer_spline = fit( timeData, steerData, 'smoothingspline', ...\n 'Normalize', 'on', 'SmoothingParam',0.95);\n\n obj.history_array(end) = obj.history_array(end) / weight;\n \n obj.steer_window_avg = 0;\n obj.frames_since_last_update = 0;\n \n obj.push_back_time = cputime;\n \n else\n % If not yet time to update, keep track of the steer values\n % in this time slot\n obj.steer_window_avg = obj.steer_window_avg + steer;\n obj.frames_since_last_update = obj.frames_since_last_update + 1;\n end\n \n % Predict and steer the car\n control.steer = obj.steer_spline(cputime + dt/2);\n \n obj.tesla.apply_control(control); \n obj.last_position = current_location;\n \n %% RGB sensor\n RGB = uint8(py.getattr(obj.module_rgb, 'array'));\n end\n \n function [SEMANTIC_SEGMENTATION_RGB, RGB] = isOutputComplexImpl(~)\n SEMANTIC_SEGMENTATION_RGB = false;\n RGB = false;\n end\n \n function [SEMANTIC_SEGMENTATION_RGB, RGB] = getOutputSizeImpl(obj)\n SEMANTIC_SEGMENTATION_RGB = [obj.height obj.width 3];\n RGB = [obj.rgb_height obj.rgb_width 3];\n end\n \n function [SEMANTIC_SEGMENTATION_RGB, RGB] = getOutputDataTypeImpl(~)\n SEMANTIC_SEGMENTATION_RGB = 'uint8';\n RGB = 'uint8';\n end\n\n function [SEMANTIC_SEGMENTATION_RGB, RGB] = isOutputFixedSizeImpl(~)\n SEMANTIC_SEGMENTATION_RGB = true;\n RGB = true;\n end\n \n function resetImpl(~)\n % Initialize / reset discrete-state properties\n end\n end\n \n methods(Access= public)\n function delete(obj)\n % Delete the car from the Carla world\n if ~isempty(obj.tesla)\n obj.tesla.destroy();\n end\n \n % Semantic segmentation sensor\n if ~isempty(obj.ss_rgb)\n obj.ss_rgb.destroy();\n end\n\n % RGB camera\n if ~isempty(obj.rgb)\n obj.rgb.destroy();\n end\n end\n end\nend\n ", "meta": {"author": "darkscyla", "repo": "MATLAB-Carla-Interface", "sha": "a089f34784b75c66490ce6055dfefaded6117409", "save_path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface", "path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface/MATLAB-Carla-Interface-a089f34784b75c66490ce6055dfefaded6117409/Proof Of Concept/Python API/Examples/5_LaneFollowing/CarlaEnvironment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}} {"text": "% GET THE GLOBAL TRAJECTORY DATA FOR AN INDIVIDUAL OBJECT\nfunction [currentFigure,figureSet] = GetFigure_objectTrajectory(SIM,DATA,currentFigure)\n\nfigureSet = [];\nfor n = 1:DATA.totalObjects\n [currentFigure,figureSet(n)] = BuildObjectTrajectoryFigure(SIM,DATA,currentFigure,n);\nend\n% ASSEMBLE TABBED FIGURE\nwindowHandle = GetTabbedFigure(figureSet,'OpenMAS Trajectory Overview');\nset(windowHandle,'Position',DATA.figureProperties.windowSettings); % Maximise the figure in the tab\nsavefig(windowHandle,[SIM.outputPath,'global-trajectory-overview']); % Save the output figure\nend\n\n% Generate the trajectory figure for the object\nfunction [currentFigure,figureHandle] = BuildObjectTrajectoryFigure(SIM,DATA,currentFigure,objectNum)\n\n% Declare title string for figure \ntitlestr = sprintf('Global trajectory data for %s over a period of %ss',SIM.OBJECTS(objectNum).name,num2str(SIM.TIME.endTime));\n\nobjectLabel = sprintf('[ID-%s] %s',num2str(SIM.OBJECTS(objectNum).objectID),SIM.OBJECTS(objectNum).name);\n\n% CONFIGURE THE PLOT ATTRIBUTES\nfigurePath = strcat(SIM.outputPath,sprintf('global-trajectories-%s',sprintf('id-%s-%s',num2str(SIM.OBJECTS(objectNum).objectID),SIM.OBJECTS(objectNum).name)));\nfigureHandle = figure('Name',objectLabel);\nset(figureHandle,'Position', DATA.figureProperties.windowSettings); % [x y width height]\nset(figureHandle,'Color',DATA.figureProperties.figureColor); % Background colour \nset(figureHandle,'Visible','off');\nplotCellWidth = 4; plotCellA = 1; % The width of each figure, the start of the plot\nsetappdata(figureHandle, 'SubplotDefaultAxesLocation', [0.1, 0.1, 0.85, 0.80]); \n\n% EXTRACT TIME-STATE DATA FROM THE TRAJECTORY MATRIX\n%[objectStates] = OMAS_getTrajectoryData_mex(DATA.globalTrajectories,SIM.globalIDvector,SIM.OBJECTS(objectNum).objectID,inf);\n[objectStates] = OMAS_getTrajectoryData(DATA.globalTrajectories,SIM.globalIDvector,SIM.OBJECTS(objectNum).objectID,inf);\n\n% STATE NAME VECTOR\nstateTags = {{'$x$','$(m)$'},{'$y$','$(m)$'},{'$z$','$(m)$'},...\n {'$u$','$(m/s)$'},{'$v$','$(m/s)$'},{'$w$','$(m/s)$'},...\n {'$\\phi$','$(rad)$'},{'$\\theta$','$(rad)$'},{'$\\psi$','$(rad)$'}};\n% CONVERT QUATERNION STATE TO EULER ANGLE STATES \neulerStates = zeros(9,size(objectStates,2)); \nfor i = 1:size(objectStates,2) \n eulerStates(1:6,i) = objectStates(1:6,i);\n eulerStates(7:9,i) = OMAS_geometry.quaternionToEulers(objectStates(7:10,i)); \nend \n\nclear objectStates;\n\n% FOR EACH OBJECTS PERSPECTIVE\nstateVectorLength = size(eulerStates,1);\nfor n = 1:stateVectorLength \n % CALCULATE THE ABSOLUTE SEPERATION FROM ALL OTHER OBJECTS OVER TIME\n plotCellB = n*plotCellWidth; % The end of the plot\n plotLocation = subplot(stateVectorLength,plotCellWidth,[plotCellA plotCellB]);\n \n % PLOT THE SEPERATION DATA ON CURRENT FIGURE\n plot(plotLocation,DATA.timeVector(1:SIM.TIME.endStep),...\n eulerStates(n,1:SIM.TIME.endStep),...\n 'LineStyle','-',...\n 'LineWidth',DATA.figureProperties.lineWidth,...\n 'Color','b');\n % Y-axes\n ylabel(plotLocation,stateTags{n},...\n 'Interpreter',DATA.figureProperties.interpreter,...\n 'fontname',DATA.figureProperties.fontName,...\n 'Fontweight',DATA.figureProperties.fontWeight,...\n 'FontSize',DATA.figureProperties.axisFontSize,...\n 'FontSmoothing','on');\n % Axes\n set(plotLocation,...\n 'TickLabelInterpreter',DATA.figureProperties.interpreter,...\n 'fontname',DATA.figureProperties.fontName,...\n 'Fontweight',DATA.figureProperties.fontWeight,...\n 'FontSize',DATA.figureProperties.axisFontSize,...\n 'FontSmoothing','on',...\n 'Color',DATA.figureProperties.axesColor);\n grid on; box on; grid minor;\n plotLocation.XAxis.MinorTickValues = plotLocation.XAxis.Limits(1):SIM.TIME.dt:plotLocation.XAxis.Limits(2);\n % ADD FIGURE TITLE TO FIRST PLOT HEADER\n if n == 1\n % Append title to first subplot\n title(plotLocation,titlestr,...\n 'Interpreter',DATA.figureProperties.interpreter,...\n 'fontname',DATA.figureProperties.fontName,...\n 'Fontweight',DATA.figureProperties.fontWeight,...\n 'Fontsize',DATA.figureProperties.titleFontSize,...\n 'FontSmoothing','on'); \n \n end\n % Prevent overlap of x-label\n if n == stateVectorLength\n % X-axis\n xlabel(plotLocation,'t (s)',...\n 'Interpreter',DATA.figureProperties.interpreter,...\n 'fontname',DATA.figureProperties.fontName,...\n 'Fontweight',DATA.figureProperties.fontWeight,...\n 'FontSize',DATA.figureProperties.axisFontSize,...\n 'FontSmoothing','on');\n else\n set(plotLocation,'XTickLabel',[]); \n end\n % Define the x-limits\n xlim([SIM.TIME.startTime,SIM.TIME.endTime]); % Ensures plot alignment/sizing\n % Move to next subplot location \n plotCellA = plotCellA + plotCellWidth;\nend\nhold off; \n\n% SAVE THE OUTPUT FIGURE\nset(figureHandle,'Visible','on'); % Make it visable for saving\nsavefig(figureHandle,figurePath); % As matlab figure \n% Publish as .pdf if requested\nif DATA.figureProperties.publish\n\tGetFigurePDF(figureHandle,figurePath); \nend\nset(figureHandle,'Visible','off');\ncurrentFigure = currentFigure + 1; % Iterate the plot count\nend\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/figures/GetFigure_objectTrajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1980516930153985}} {"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 plot_path(paths, mapClass, SFCs)\n% PLOT_PATH Visualize a path and sfc's ellipses\n% PLOT_PATH(path mapClass, SFCs) creates a figure showing a path through\n% the environment. \n% SFCs provide functions for drawing ellipses: drawEllipsoids();\n\npersistent map decomps init;\nif isempty(init)\n map = mapClass;\n decomps = SFCs;\n init = 1;\nend\n\nfigure('Name','Animation');\n\nhold on;\nfor i = 1:size(map.blocks,1)\n block = map.blocks(i, :);\n drawBlock(block);\nend\n\npath = paths{1};\n\n% draw Inflated obstacle\nfor i = 1:size(map.blocks,1)\n margin = map.margin;\n block = map.blocks(i, :);\n block(1,1:3) = block(1,1:3) - margin;\n block(1,4:6) = block(1,4:6) + margin;\n block(7) = max(150, block(7)); block(8) = max(150, block(8)); block(9) = max(150, block(9)); %% set color\n drawBlock(block);\nend\n\nif size(path,1) > 0\n % pcshow(path, [0,1,0],'MarkerSize', 0.1);\n % The lower left corner position, width and height. 260 here is exactly 7cm\n% set(gcf,'position', [500 500 260 220]);\n% set(gcf,'position', [500 500 400 400]); % big pic\n% set(gcf,'position', [500 500 300 300]); % small pic\n set(gcf,'color','w');\n set(gca,'color','w');\n \n %% Display the unit of x y z\n% xlabel('x length(m)');\n% ylabel('y length(m)');\n% zlabel('z length(m)');\n \nend\n\n% Set the axis range\naxis_add = 2*map.res(1);\naxis([map.boundary.ld(1)-axis_add, map.boundary.ru(1)+axis_add, ... \n map.boundary.ld(2)-axis_add, map.boundary.ru(2)+axis_add, ...\n map.boundary.ld(3)-axis_add, map.boundary.ru(3)+axis_add])\n\nhold on\nfor j = 1 : size(paths, 2)\n if j == 1\n % JPS's result\n% plot3(paths{j}(:,1), paths{j}(:,2), paths{j}(:,3),'-*','color','k','LineWidth',3);\n elseif j == 2\n % JPS() + simple path() result: \n% plot3(paths{j}(:,1), paths{j}(:,2), paths{j}(:,3),'-*','color','#A2142F','LineWidth',3);\n plot3(paths{j}(:,1), paths{j}(:,2), paths{j}(:,3),'-*','color','k','LineWidth',3);\n end\nend\nhold off\n\nset(gca,'DataAspectRatio',[0.1 0.1 0.1]);\n\n% drawEllipsoid = true;\nif (exist('drawEllipsoid') && (drawEllipsoid == true))\n decomps{1}.drawEllipsoids();\n% decomps{2}.drawEllipsoids();\nend\n\ngrid on\n\nview(30, 10);\nhold off;\n\nend\n\nfunction drawBlock(block)\n \n x = [ones(4,1) * block(1); ones(4,1) * block(4)];\n y = [ones(2,1) * block(5); ones(2,1) * block(2); ones(2,1) * block(5); ones(2,1) * block(2)];\n z = [block(3);block(6);block(3);block(6);block(3);block(6);block(3);block(6)];\n\n\n vert = [x, y, z];\n fac = [1 2 6 5;2 3 7 6;3 4 8 7;4 1 5 8;1 2 3 4;5 6 7 8];\n c = block(7:9)/255;\n patch('Vertices',vert,'Faces',fac,...\n 'FaceVertexCData',hsv(6),'FaceColor',c,'FaceAlpha',.2);\n\n \n x = [ones(4,1) * block(1); ones(4,1) * block(4)];\n y = [block(2);block(5);block(2);block(5);block(2);block(5);block(2);block(5)];\n z = [ones(2,1) * block(3); ones(2,1) * block(6); ones(2,1) * block(3); ones(2,1) * block(6)];\n\n vert = [x, y, z];\n fac = [1 2 6 5;2 3 7 6;3 4 8 7;4 1 5 8;1 2 3 4;5 6 7 8];\n c = block(7:9)/255;\n patch('Vertices',vert,'Faces',fac,...\n 'FaceVertexCData',hsv(6),'FaceColor',c,'FaceAlpha',.2);\nend", "meta": {"author": "LenaShengzhen", "repo": "AerialRobotics", "sha": "b3fe62f2df62cb91e8b5a53791868f9848c74005", "save_path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics", "path": "github-repos/MATLAB/LenaShengzhen-AerialRobotics/AerialRobotics-b3fe62f2df62cb91e8b5a53791868f9848c74005/Motion_Planning/draw/plot_path.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19786854523442743}} {"text": "%Simulation test case\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Author: Jared Jacobs, jmjacobs@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 7/13/2010\nclassdef Simulation_KnowledgeBase_Test < TestCase\n methods\n function this = Simulation_KnowledgeBase_Test(name)\n this = this@TestCase(name);\n end\n \n function testInitializationFromKnowledgeBase(~)\n dbConnectionParameters = getConfig();\n database = edu.stanford.covert.db.MySQLDatabase(dbConnectionParameters);\n kbWID = edu.stanford.covert.cell.kb.KnowledgeBaseUtil.selectLatestKnowledgeBase(database);\n kb = edu.stanford.covert.cell.kb.KnowledgeBase(database, kbWID);\n\n sim = edu.stanford.covert.cell.sim.Simulation(kb.states, kb.processes);\n sim.initializeConstants(kb);\n sim.applyOptions('lengthSec', 10, 'verbosity', 0, 'seed', 1);\n fitter = edu.stanford.covert.cell.sim.util.FitConstants(sim, struct('method', 'heuristic', 'verbosity', 0));\n fitter.run();\n sim.run();\n\n assertElementsAlmostEqual(...\n 1 / (9.0 * 3600) * log(2), sim.state('MetabolicReaction').growth(:,:,1),...\n 'relative', 35e-2);\n \n database.close();\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src_test/+edu/+stanford/+covert/+cell/+sim/Simulation_KnowledgeBase_Test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.1977009496470258}} {"text": "function [a, b] = isintent(this,intent)\n% Correspondance between fieldnames and NIfTI intent codes\n% FORMAT ind = isintent(this,intent)\n% this - GIfTI object\n% intent - fieldnames\n% a - indices of found intent(s)\n% b - indices of dataarrays of found intent(s)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: isintent.m 6345 2015-02-20 12:25:50Z guillaume $\n\na = [];\nb = [];\nif ischar(intent), intent = cellstr(intent); end\nfor i=1:length(this(1).data)\n switch this(1).data{i}.attributes.Intent(14:end)\n case 'POINTSET'\n [tf, loc] = ismember('vertices',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n [tf, loc] = ismember('mat',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n case 'TRIANGLE'\n [tf, loc] = ismember('faces',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n case 'VECTOR'\n [tf, loc] = ismember('normals',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n case 'NODE_INDEX'\n [tf, loc] = ismember('indices',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n case cdata\n [tf, loc] = ismember('cdata',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n if strcmp(this(1).data{i}.attributes.Intent(14:end),'LABEL')\n [tf, loc] = ismember('labels',intent);\n if tf\n a(end+1) = loc;\n b(end+1) = i;\n end\n end\n otherwise\n fprintf('Intent %s is ignored.\\n',this.data{i}.attributes.Intent);\n end\nend\n%[d,i] = unique(a);\n%if length(d) < length(a)\n% warning('Several fields match intent type. Using first.');\n% a = a(i);\n% b = b(i);\n%end\n\nfunction c = cdata\n\nc = {\n'NONE'\n'CORREL'\n'TTEST'\n'FTEST'\n'ZSCORE'\n'CHISQ'\n'BETA'\n'BINOM'\n'GAMMA'\n'POISSON'\n'NORMAL'\n'FTEST_NONC'\n'CHISQ_NONC'\n'LOGISTIC'\n'LAPLACE'\n'UNIFORM'\n'TTEST_NONC'\n'WEIBULL'\n'CHI'\n'INVGAUSS'\n'EXTVAL'\n'PVAL'\n'LOGPVAL'\n'LOG10PVAL'\n'ESTIMATE'\n'LABEL'\n'NEURONAMES'\n'GENMATRIX'\n'SYMMATRIX'\n'DISPVECT'\n'QUATERNION'\n'DIMLESS'\n'TIME_SERIES'\n'RGB_VECTOR'\n'RGBA_VECTOR'\n'SHAPE'\n'CONNECTIVITY_DENSE'\n'CONNECTIVITY_DENSE_TIME'\n'CONNECTIVITY_PARCELLATED'\n'CONNECTIVITY_PARCELLATED_TIME'\n'CONNECTIVITY_CONNECTIVITY_TRAJECTORY'\n};\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/gifti/@gifti/private/isintent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}} {"text": "function scalar = array2scalar(F_array, grid, ge, ft, axis, osc, physQ, intercept)\n\nchkarg(istypesizeof(grid, 'Grid2d') || istypesizeof(grid, 'Grid3d'), ...\n\t'\"grid\" should be instance of Grid2d or Grid3d.');\nchkarg(istypesizeof(ge, 'GT'), '\"ge\" should be instance of GT.');\nchkarg(istypesizeof(ft, 'FT'), '\"ft\" should be instance of FT.');\nchkarg(istypesizeof(axis, 'Axis'), '\"axis\" should be instance of Axis.');\nchkarg(istypesizeof(osc, 'Oscillation'), '\"osc\" should be instance of Oscillation.');\nchkarg(istypesizeof(physQ, 'PhysQ'), '\"physQ\" should be instance of PhysQ.');\n\nis3D = true;\nif istypesizeof(grid, 'Grid2d')\n\tis3D = false;\nend\n\nif ft == FT.e\n gt = ge; % grid type for E-field\nelse % ft == FT.h\n gt = alter(ge); % grid type for H-field\nend\n\ngt_array = gt(ones(1, Axis.count));\ngt_array(axis) = alter(gt);\n\nif is3D\n\tgrid3d = grid;\n\tchkarg(istypesizeof(F_array, 'arbitrary', grid3d.N), '\"F_array\" should be %d-by-%d-by-%d array.', grid3d.Ncell{:});\n\n\tV = F_array;\n\tfor w = Axis.elems\n\t\tV = attach_extra_F(V, ft, gt_array(w), axis, grid3d.bc(w), w, grid3d.kBloch(w)*grid3d.L(w));\n\tend\n\t\n\tscalar = Scalar3d(V, grid3d, gt_array, osc, physQ, [physQ.symbol, '_', char(axis)]);\nelse % grid is Grid2d\n\tif nargin < 7 % no intercept\n\t\tintercept = NaN;\n\tend\n\tchkarg(istypesizeof(intercept, 'real'), '\"intercept\" should be real.'); % NaN is real\n\t\n\tgrid2d = grid;\n\tchkarg(istypesizeof(F_array, 'arbitrary', grid2d.N), '\"F_array\" should be %d-by-%d array.', grid2d.Ncell{:});\n\n\tgt_array = gt_array(grid2d.axis);\n\n\tif axis == grid2d.axis(Dir.h)\n\t\taxis_temp = Axis.x;\n\telseif axis == grid2d.axis(Dir.v)\n\t\taxis_temp = Axis.y;\n\telse % axis == grid2d.normal_axis\n\t\taxis_temp = Axis.z;\t\n\tend\n\t\n\tC = F_array;\n\tC = attach_extra_F(C, ft, gt_array(Dir.h), axis_temp, grid2d.bc(Dir.h), Axis.x, grid2d.kBloch(Dir.h)*grid2d.L(Dir.h)); % treat C as 3D array with one element in 3rd dimension\n\tC = attach_extra_F(C, ft, gt_array(Dir.v), axis_temp, grid2d.bc(Dir.v), Axis.y, grid2d.kBloch(Dir.v)*grid2d.L(Dir.v)); % treat C as 3D array with one element in 3rd dimension\n\n\tscalar = Scalar2d(C, grid2d, gt_array, osc, physQ, [physQ.symbol, '_', char(axis)], intercept);\nend\n\nfunction Fw_array = attach_extra_F(Fw_array, ft, gt, w, bc_v, v, kvLv)\n% Augment the Fw array with ghost boundary elements in the v-axis.\n% Surprisingly, this function combines attach_extra_E() and attach_extra_H().\n\n% chkarg(istypesizeof(Fw_array, 'complex', [0 0 0]), '\"Fw_array\" should be 3D array with complex elements.');\nchkarg(istypesizeof(ft, 'FT'), '\"ft\" should be instance of FT.');\nchkarg(istypesizeof(gt, 'GT'), '\"gt\" should be instance of GT.');\nchkarg(istypesizeof(w, 'Axis'), '\"w\" should be instance of Axis.');\nchkarg(istypesizeof(bc_v, 'BC'), '\"bc_v\" should be instance of BC.');\nchkarg(istypesizeof(v, 'Axis'), '\"v\" should be instance of Axis.');\nchkarg(istypesizeof(kvLv, 'real'), '\"kvLv\" should be real.');\n\nind_n = {':',':',':'};\nind_p = {':',':',':'};\nNv = size(Fw_array, int(v));\nif gt == GT.prim\n\tif bc_v == BC.p\n\t\tind_p{v} = 1;\n\t\tFw_array = cat(int(v), Fw_array, Fw_array(ind_p{:})*exp(-1i*kvLv));\n\telse % bc_v == BC.e or BC.m\n\t\t% At the ghost point tangential primary fields are always zero, so\n\t\t% normal dual fields are also zero.\n\t\tsize_extra = size(Fw_array);\n\t\tsize_extra(v) = 1;\n\t\tFw_array = cat(int(v), Fw_array, zeros(size_extra));\n\tend\nelse % gt == GT.dual\n\tif bc_v == BC.p\n\t\tind_n{v} = Nv;\n\t\tind_p{v} = 1;\n\t\tFw_array = cat(int(v), Fw_array(ind_n{:})*exp(1i*kvLv), Fw_array, Fw_array(ind_p{:})*exp(-1i*kvLv));\n\telse % bc_v == BC.e or BC.m\n\t\tind_n{v} = 1;\n\t\tind_p{v} = Nv;\n\t\tft_match_bc = (ft == FT.e && bc_v == BC.e) || (ft == FT.h && bc_v == BC.m);\n\t\tif (v ~= w && ft_match_bc) || (v == w && ~ft_match_bc)\n\t\t\tFw_array = cat(int(v), -Fw_array(ind_n{:}), Fw_array, Fw_array(ind_p{:}));\n\t\telse % (v == w && ft_match_bc) || (v ~= w && ~ft_match_bc)\n\t\t\tFw_array = cat(int(v), Fw_array(ind_n{:}), Fw_array, Fw_array(ind_p{:}));\n\t\tend\n\tend\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/array2scalar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19761246859997844}} {"text": "function [header,tracks] = trk_read(filePath)\n%TRK_READ - Load TrackVis .trk files\n%TrackVis displays and saves .trk files in LPS orientation. After import, this\n%function attempts to reorient the fibers to match the orientation of the\n%original volume data.\n%\n% Syntax: [header,tracks] = trk_read(filePath)\n%\n% Inputs:\n% filePath - Full path to .trk file [char]\n%\n% Outputs:\n% header - Header information from .trk file [struc]\n% tracks - Track data structure array [1 x nTracks]\n% nPoints - # of points in each streamline\n% matrix - XYZ coordinates (in mm) and associated scalars [nPoints x 3+nScalars]\n% props - Properties of the whole tract (ex: length)\n%\n% Example:\n% exDir = '/path/to/along-tract-stats/example';\n% subDir = fullfile(exDir, 'subject1');\n% trkPath = fullfile(subDir, 'CST_L.trk');\n% [header tracks] = trk_read(trkPath);\n%\n% Other m-files required: none\n% Subfunctions: get_header\n% MAT-files required: none\n%\n% See also: http://www.trackvis.org/docs/?subsect=fileformat\n% http://github.com/johncolby/along-tract-stats/wiki/orientation\n\n% Author: John Colby (johncolby@ucla.edu)\n% UCLA Developmental Cognitive Neuroimaging Group (Sowell Lab)\n% Mar 2010\n\n% Parse in header\nfid = fopen(filePath, 'r');\nheader = get_header(fid);\n\n% Check for byte order\nif header.hdr_size~=1000\n fclose(fid);\n fid = fopen(filePath, 'r', 'b'); % Big endian for old PPCs\n header = get_header(fid);\nend\n\nif header.hdr_size~=1000, error('Header length is wrong'), end\n\n% Check orientation\n[maxX, ix] = max(abs(header.image_orientation_patient(1:3)));\n[maxY, iy] = max(abs(header.image_orientation_patient(4:6)));\n% Martin: Bugfix here when image_orientation_patient is empty...\nif maxX == 0 && maxY == 0\n ix = 1;\n iy = 2;\n iz = 3;\nelse\n iz = 1:3;\n iz([ix iy]) = [];\nend\n\n% Fix volume dimensions to match the reported orientation.\nheader.dim = header.dim([ix iy iz]);\nheader.voxel_size = header.voxel_size([ix iy iz]);\n\n% Parse in body\nif header.n_count > 0\n\tmax_n_trks = header.n_count;\nelse\n\t% Unknown number of tracks; we'll just have to read until we run out.\n\tmax_n_trks = inf;\nend\n\n% It's impossible to preallocate the \"tracks\" variable because we don't\n% know the number of points on each curve ahead of time; we find out by\n% reading the file. The line below suppresses preallocation warnings.\n%#ok<*AGROW>\n\niTrk = 1;\nwhile iTrk <= max_n_trks\n\tpts = fread(fid, 1, 'int');\n\tif feof(fid)\n\t\tbreak;\n\tend\n tracks(iTrk).nPoints = pts;\n tracks(iTrk).matrix = fread(fid, [3+header.n_scalars, tracks(iTrk).nPoints], '*float')';\n if header.n_properties\n tracks(iTrk).props = fread(fid, header.n_properties, '*float');\n end\n \n % Modify orientation of tracks (always LPS) to match orientation of volume\n coords = tracks(iTrk).matrix(:,1:3);\n coords = coords(:,[ix iy iz]);\n if header.image_orientation_patient(ix) < 0\n coords(:,ix) = header.dim(ix)*header.voxel_size(ix) - coords(:,ix);\n end\n if header.image_orientation_patient(3+iy) < 0\n coords(:,iy) = header.dim(iy)*header.voxel_size(iy) - coords(:,iy);\n end\n tracks(iTrk).matrix(:,1:3) = coords;\n\tiTrk = iTrk + 1;\nend\n\nif header.n_count == 0\n\theader.n_count = length(tracks);\nend\n\nfclose(fid);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction header = get_header(fid)\n\nheader.id_string = fread(fid, 6, '*char')';\nheader.dim = fread(fid, 3, 'short')';\nheader.voxel_size = fread(fid, 3, 'float')';\nheader.origin = fread(fid, 3, 'float')';\nheader.n_scalars = fread(fid, 1, 'short')';\nheader.scalar_name = fread(fid, [20,10], '*char')';\nheader.n_properties = fread(fid, 1, 'short')';\nheader.property_name = fread(fid, [20,10], '*char')';\nheader.vox_to_ras = fread(fid, [4,4], 'float')';\nheader.reserved = fread(fid, 444, '*char');\nheader.voxel_order = fread(fid, 4, '*char')';\nheader.pad2 = fread(fid, 4, '*char')';\nheader.image_orientation_patient = fread(fid, 6, 'float')';\nheader.pad1 = fread(fid, 2, '*char')';\nheader.invert_x = fread(fid, 1, 'uchar');\nheader.invert_y = fread(fid, 1, 'uchar');\nheader.invert_z = fread(fid, 1, 'uchar');\nheader.swap_xy = fread(fid, 1, 'uchar');\nheader.swap_yz = fread(fid, 1, 'uchar');\nheader.swap_zx = fread(fid, 1, 'uchar');\nheader.n_count = fread(fid, 1, 'int')';\nheader.version = fread(fid, 1, 'int')';\nheader.hdr_size = fread(fid, 1, 'int')';\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/external/trk/trk_read.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19761246859997844}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Released under the MIT License.\n% If you use this code, please cite the following paper:\n% Mahmoud Afifi, Abdelrahman Abdelhamed, Abdullah Abuolaim, Abhijith \n% Punnappurath, and Michael S Brown. CIE XYZ Net: Unprocessing Images for \n% Low-Level Computer Vision Tasks. arXiv preprint, 2020.\n%\n% Author: Mahmoud Afifi | Email: mafifi@eecs.yorku.ca, m.3afifi@gmail.com\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% demo with operators\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Please adjust pp_code/postprocessing.m with your custom functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nclc\nclear\nclose all\n\nfilename = fullfile('..','images','a0280-IMG_0854.JPG');\n\ndevice = 'gpu';\n\nload(fullfile('models','model_sRGB-XYZ-sRGB.mat'));\n %|res1|I-res1|XYZ|RGB|res2|RGB+res2\npp_method = 'none|none|denoise+deblur|none|none'; \n%post-processing methods: denoise, deblur, dehaze, editdetails, \n% exposure-fusion, transfer-colors, chrom-adapt, super-res\n%The order is: localLayer|sRGB-localLayer|CIE XYZ|sRGB|localLayer\n\nshow = 1;\n\nsave_output = 1;\n\nopt = []; %extra options, if needed\n\nif save_output == 1\n out_dir = fullfile('..','results');\n if exist(out_dir, 'dir') == 0\n mkdir(out_dir);\n end\nend\n\nimage = im2double(imread(filename));\n\nif length(size(image)) ~= 3\n error('cannot deal with grayscale images');\nend\n\n\nfprintf('processing image %s...\\n', filename);\n\n[~,name,~] = fileparts(filename);\n\ntasks = strsplit(pp_method,'|');\n\noutput_XYZ = applyLocalMapping(nets.local_sRGB, image, ...\n 'to-xyz', device, tasks{1}, opt);\n\noutput_XYZ = applyGlobalMapping(nets.global_sRGB, output_XYZ,device, ...\n tasks{2}, opt);\n\nif strcmpi(tasks{3},'none') == 0\n output_XYZ = postprocessing(output_XYZ,tasks{3},opt);\nend\n\noutput_sRGB = applyGlobalMapping(nets.global_XYZ, output_XYZ,device, ...\n tasks{4}, opt);\n\noutput_sRGB = applyLocalMapping(nets.local_XYZ, output_sRGB, ...\n 'to-srgb', device, tasks{5}, opt);\n\n\noutput_sRGB(output_sRGB>1) = 1;\noutput_sRGB(output_sRGB<0) = 0;\n\nif save_output == 1\n imwrite(output_sRGB,fullfile(out_dir, [name '_result.png']));\nend\n\nif show == 1\n subplot(1,2,1);imshow(image); title('input');\n subplot(1,2,2);imshow(output_sRGB); title('result');\n linkaxes\nend\n\n\n", "meta": {"author": "mahmoudnafifi", "repo": "CIE_XYZ_NET", "sha": "44398b114cf2c04bc1543303af661100e2240bc1", "save_path": "github-repos/MATLAB/mahmoudnafifi-CIE_XYZ_NET", "path": "github-repos/MATLAB/mahmoudnafifi-CIE_XYZ_NET/CIE_XYZ_NET-44398b114cf2c04bc1543303af661100e2240bc1/Matlab/demo_single_image_with_operators.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.19749078334670886}} {"text": "function g = modelLogLikeGradients(model)\n\n% MODELLOGLIKEGRADIENTS Compute a model's gradients wrt log likelihood.\n% FORMAT\n% DESC is a wrapper function to compute the gradients of the log\n% likelihood of a given model.\n% ARG model : the model for which likelihoods are computed.\n% RETURN g : teh gradients of the likelihood with respect to the\n% parameters.\n%\n% SEEALSO : modelCreate\n%\n% COPYRIGHT : Neil D. Lawrence, 2006, 2005\n\n% MLTOOLS\n\nfhandle = str2func([model.type 'LogLikeGradients']);\ng = fhandle(model);\n\nif isfield(model, 'paramGroups')\n g = g*model.paramGroups;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/modelLogLikeGradients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}} {"text": "function [rf, info] = readrfvnmr(filename,verbosity)\n\n% RF = READRFVNMR(FILENAME) reads a Varian VNMR format RF pulse\n% description in FILENAME and generates an RF matrix with 3 columns\n% specifying angle, magnitude, and duration.\n%\n% FILENAME can be in working directory, ~/vnmrsys/shapelib, or \n% $vnmrsystem/shapelib and can be specified with or with trailing .RF\n\n% Author: L. Martyn Klassen\n% Copyright 2003 Robarts Research Institute\n% This program is copyrighted worldwide by the Robarts Research\n% Institute. Any distribution, copying or redistribution is expressly\n% forbidden.\n% Created: April 17, 2003 14:22\n% Modified: N/A\n\nif nargin < 2\n verbosity = 0;\n if nargin < 1\n error('READRFVNMR requires RF file name.');\n end\nend\n\n% info defaults to an empty structure\ninfo = struct;\n\n% Get the vnmrsystem path\n[status, vnmrpath] = unix('echo $vnmrsystem');\nif status == 0\n % Strip end-of-line character\n vnmrpath = vnmrpath(1:end-1);\nelse\n % Make a guess - good for RRI\n vnmrpath = '/vnmr';\nend\n\nfid = findfile(filename, vnmrpath);\nif fid < 0\n % Check if user forgot .RF or .rf ending\n orgfilename = filename;\n filename = [orgfilename '.RF'];\n fid = findfile(filename, vnmrpath);\n if fid < 0\n filename = [orgfilename '.rf'];\n fid = findfile(filename, vnmrpath);\n if fid < 0\n error('READRFVNMR unable to find %s', orgfilename);\n end\n end\nend\n\nif verbosity > 0\n % Report what file was actually opened for reading\n disp(sprintf('READRFVNMR reading file %s', fopen(fid)));\nend\n\n% Get the first line of the file\nfileline = fgets(fid);\nlinenumber = 1;\nrf = zeros(3,0);\nwhile ischar(fileline)\n % Strip out any comment indicated by #\n idxcomment = strfind(fileline,'#');\n if ~isempty(idxcomment)\n % Look for information normally stored in header\n % It must be commented so we don't need to do this every line\n idx = strfind(fileline, 'VERSION');\n if ~isempty(idx)\n info.version = sscanf(fileline(idx+7:end), '%s', 1);\n end\n idx = strfind(fileline, 'TYPE');\n if ~isempty(idx)\n info.type = sscanf(fileline(idx+4:end), '%s', 1);\n end\n idx = strfind(fileline, 'MODULATION');\n if ~isempty(idx)\n info.modulation = sscanf(fileline(idx+10:end), '%s', 1);\n end\n idx = strfind(fileline, 'EXCITEWIDTH');\n if ~isempty(idx)\n info.excitewidth = sscanf(fileline(idx+11:end), '%f', 1);\n end\n idx = strfind(fileline, 'INVERTWIDTH');\n if ~isempty(idx)\n info.invertwidth = sscanf(fileline(idx+11:end), '%f', 1);\n end\n idx = strfind(fileline, 'INTEGRAL');\n if ~isempty(idx)\n info.integral = sscanf(fileline(idx+8:end), '%f', 1);\n end\n idx = strfind(fileline, 'RF_FRACTION');\n if ~isempty(idx)\n info.aref = sscanf(fileline(idx+11:end), '%f', 1);\n end\n idx = strfind(fileline, 'AREF');\n if ~isempty(idx)\n info.aref = sscanf(fileline(idx+4:end), '%f', 1);\n end\n idx = strfind(fileline, 'b1excite');\n if ~isempty(idx)\n info.b1excite = sscanf(fileline(idx+8:end), '%f', 1);\n end\n idx = strfind(fileline, 'b1invert');\n if ~isempty(idx)\n info.b1invert = sscanf(fileline(idx+8:end), '%f', 1);\n end\n \n % Strip out everything after the comment indicator\n fileline = fileline(1:idxcomment(1));\n end\n \n % Kill the last character: end-of-line or #\n fileline(end) = [];\n \n % If the line is empty skip it\n if ~isempty(fileline)\n % if it blank then skip\n if any(fileline ~= ' ')\n [A,count, errmsg, nextindex] = sscanf(fileline, '%f', inf);\n \n % If read failed, output the error\n if ~isempty(errmsg)\n fclose(fid)\n error('READRFVNMR failed with read error: %s', errmsg);\n end\n \n % Each line is to contain 3 and only 3 numbers\n if (count > 0) & (count ~= 3)\n fclose(fid);\n error('READRFVNMR malformed line number %d', linenumber);\n end\n \n % Store the read values into rf array\n rf(:,linenumber) = A;\n linenumber = linenumber + 1;\n end\n end\n % Get the next line\n fileline = fgets(fid);\nend\nfclose(fid);\n\n% Add a default aref value if not found\nif ~isfield(info, 'aref')\n info.aref = 0.5;\nend\n\n% Switch from row to column orientation\nrf = rf';\nreturn\n\n\nfunction fid = findfile(filename, vnmrpath)\n% Search local, user vnmrsys, and global vnmrsys for RF file\nfid = fopen(filename, 'r');\nif fid < 0\n orgfilename = filename;\n filename = ['~/vnmrsys/shapelib/' orgfilename];\n fid = fopen(filename, 'r');\n if fid < 0\n filename = [vnmrpath '/shapelib/' orgfilename];\n fid = fopen(filename, 'r');\n end\nend\nreturn\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/inputOutput/mklassenTools/readrfvnmr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}} {"text": "% pop_rejcont() - reject continuous portions of data based on spectrum\n% thresholding. First, contiguous data epochs are extracted\n% and a standard spectrum thresholding algorithm is\n% applied. Regions of contiguous epochs larger than a\n% specified size are then labeled as artifactual.\n%\n% Usage:\n% >> pop_rejcont( INEEG ) % pop-up interative window mode\n% >> [OUTEEG, selectedregions] = pop_rejcont( INEEG, 'key', 'val');\n%\n% Inputs:\n% INEEG - input dataset\n%\n% Optional inputs:\n% 'elecrange' - [integer array] electrode indices {Default: all electrodes} \n% 'epochlength' - [float] epoch length in seconds {Default: 0.5 s}\n% 'overlap' - [float] epoch overlap in seconds {Default: 0.25 s}\n% 'freqlimit' - [min max] frequency range too consider for thresholding\n% Default is [35 128] Hz.\n% 'threshold' - [float] frequency upper threshold in dB {Default: 10}\n% 'contiguous' - [integer] number of contiguous epochs necessary to \n% label a region as artifactual {Default: 4 }\n% 'addlength' - [float] once a region of contiguous epochs has been labeled\n% as artifact, additional trailing neighboring regions on\n% each side may also be added {Default: 0.25 s}\n% 'eegplot' - ['on'|'off'] plot rejected portions of data in a eegplot\n% window. Default is 'off'.\n% 'onlyreturnselection' - ['on'|'off'] this option when set to 'on' only\n% return the selected regions and does not remove them \n% from the datasets. This allow to perform quick\n% optimization of the rejected portions of data.\n% 'precompstruct' - [struct] structure containing precomputed spectrum (see\n% Outputs) to be used instead of computing the spectrum.\n% 'verbose' - ['on'|'off'] display information. Default is 'off'.\n% 'taper' - ['none'|'hamming'] taper to use before FFT. Default is\n% 'none' for backward compatibility but 'hamming' is\n% recommended.\n%\n% Outputs:\n% OUTEEG - output dataset with updated joint probability array\n% selectedregions - frames indices of rejected electrodes. Array of n x 2\n% n being the number of regions and 2 for the beginning\n% and end of each region.\n% precompstruct - structure containing precomputed data. This structure\n% contains the spectrum, the frequencies and the EEGLAB\n% dataset used as input with epochs extracted.\n%\n% Author: Arnaud Delorme, CERCO, UPS/CNRS, 2009-\n%\n% Example:\n% EEG = pop_rejcont(EEG, 'elecrange',[1:32] ,'freqlimit',[20 40] ,'threshold',...\n% 10,'epochlength',0.5,'contiguous',4,'addlength',0.25, 'taper', 'hamming');\n% \n% See also: eegthresh()\n\n% Copyright (C) 2009 Arnaud Delorme, CERCO, UPS/CNRS\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction [EEG selectedregions precompstruct com ] = pop_rejcont(EEG, varargin);\n\ncom = '';\nif nargin < 1\n help pop_rejcont;\n return;\nend;\n\nif nargin < 2\n firstelec = 'EXG1'; % first non EEG channel\n % take all scalp electrodes\n % -------------------------\n if ~isempty(EEG.chanlocs)\n tmpchanlocs = EEG.chanlocs;\n indelec = strmatch( firstelec, { tmpchanlocs.labels });\n \n if isempty(indelec), elecrange = 1:EEG.nbchan;\n else elecrange = 1:(indelec-1);\n end;\n else\n elecrange = 1:EEG.nbchan;\n end;\n elecrange = deblank(vararg2str(elecrange));\n %elecrange = elecrange(2:end-1);\n \n% promptstr = { 'Channel range' ...\n% 'Frequency range (Hz)' ...\n% 'Frequency threshold in dB' ...\n% 'Epoch segment length (s)' ...\n% 'Minimum number of contiguous epochs' ...\n% 'Add trails before and after regions (s)' ...\n% };\n% initstr = { elecrange '20 40' '10' '0.5' '4' '0.25' };\n% result = inputdlg2(promptstr, 'Reject portions of continuous data - pop_rejcont', 1, initstr);\n uilist = { { 'style' 'text' 'string' 'Channel range' } ...\n { 'style' 'edit' 'string' elecrange } ...\n { 'style' 'text' 'string' 'Frequency range (Hz)' } ...\n { 'style' 'edit' 'string' '20 40' } ...\n { 'style' 'text' 'string' 'Frequency threshold in dB' } ...\n { 'style' 'edit' 'string' '10' } ...\n { 'style' 'text' 'string' 'Epoch segment length (s)' } ...\n { 'style' 'edit' 'string' '0.5' } ...\n { 'style' 'text' 'string' 'Minimum number of contiguous epochs' } ...\n { 'style' 'edit' 'string' '4' } ...\n { 'style' 'text' 'string' 'Add trails before and after regions (s)' } ...\n { 'style' 'edit' 'string' '0.25' } ...\n { 'style' 'text' 'string' 'Use hanning window before computing FFT' } ...\n { 'style' 'checkbox' 'string' '' 'value' 1 } ...\n };\n geom = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] };\n result = inputgui('uilist', uilist, 'geometry', geom);\n if length( result ) == 0 return; end;\n \n options = { 'elecrange' str2num(result{1}) ...\n 'freqlimit' str2num(result{2}) ...\n 'threshold' str2double(result{3}) ...\n 'epochlength' str2double(result{4}) ...\n 'contiguous' str2double(result{5}) ...\n 'addlength' str2double(result{6}) ...\n 'taper' fastif(result{7}, 'hamming', 'none') };\nelse\n options = varargin;\nend;\n\nopt = finputcheck(options, { 'threshold' { 'real';'cell' } [] 10;\n 'freqlimit' { 'real';'cell' } [] [35 128];\n 'elecrange' 'real' [] [1:EEG.nbchan];\n 'rejectori' 'real' [] [];\n 'contiguous' 'real' [] 4;\n 'addlength' 'real' [] 0.25;\n 'precompstruct' 'struct' [] struct([]);\n 'eegplot' 'string' { 'on';'off' } 'off';\n 'onlyreturnselection' 'string' { 'on';'off' } 'off';\n 'verbose' 'string' { 'on';'off' } 'on';\n 'taper' 'string' { 'none' 'hamming' } 'none';\n 'overlap' 'real' [] 0.25;\n 'epochlength' 'real' [] 0.5 }, 'pop_rejcont');\nif isstr(opt), error(opt); end;\nif ~iscell(opt.threshold) && length(opt.threshold) == 2 && ...\n iscell(opt.freqlimit) && length(opt.freqlimit) == 2\n opt.threshold = { opt.threshold(1) opt.threshold(2) };\nend;\nif ~iscell(opt.threshold), opt.threshold = { opt.threshold }; end;\nif ~iscell(opt.freqlimit), opt.freqlimit = { opt.freqlimit }; end;\n\n%EEG.event = [];\ngrouplen = opt.contiguous/2*opt.epochlength*EEG.srate+1; % maximum number of points for grouping regions\ncolor = [ 0 0.9 0]; % color of rejection window\n\nNEWEEG = EEG;\nif isempty(opt.precompstruct)\n % compute power spectrum\n % ----------------------\n % average reference \n % NEWEEG.data(opt.elecrange,:) = NEWEEG.data(opt.elecrange,:)-repmat(mean(NEWEEG.data(opt.elecrange,:),1), [length(opt.elecrange) 1]);\n\n % only keep boundary events\n % -------------------------\n tmpevent = NEWEEG.event;\n if ~isempty(tmpevent)\n if isnumeric( tmpevent(1).type )\n NEWEEG.event = [];\n else\n boundEvent = strmatch('boundary', { tmpevent.type }, 'exact');\n NEWEEG.event = NEWEEG.event(boundEvent);\n end;\n end;\n\n [TMPNEWEEG] = eeg_regepochs(NEWEEG, opt.overlap, [0 opt.epochlength], NaN);\n %[TMPNEWEEG indices] = pop_rejspec(TMPNEWEEG, 1, [1:64], -100, 15, 30, 45, 0, 0);\n %rejepoch = find(indices);\n \n tmpdata = TMPNEWEEG.data;\n if strcmpi(opt.taper, 'hamming'), \n tmpdata = bsxfun(@times, tmpdata, hamming(size(TMPNEWEEG.data,2))');\n end;\n tmp = fft(tmpdata, [], 2);\n freqs = linspace(0, TMPNEWEEG.srate/2, size(tmp,2)/2);\n freqspectrum = freqs(2:end); % remove DC (match the output of PSD)\n tmp = tmp(:,2:size(tmp,2)/2,:);\n warning('off', 'MATLAB:log:logOfZero');\n tmpspec = 10*log10(abs(tmp).^2); \n warning('on', 'MATLAB:log:logOfZero');\n tmpspec = tmpspec - repmat( mean(tmpspec,3), [1 1 TMPNEWEEG.trials]);\n specdata = tmpspec;\n\n % compute mean spectrum\n % ---------------------\n meanspectrum = nan_mean(specdata(opt.elecrange, :, :), 1);\n precompstruct.spec = meanspectrum;\n precompstruct.freqs = freqspectrum;\n precompstruct.EEG = TMPNEWEEG;\nelse\n meanspectrum = opt.precompstruct.spec;\n freqspectrum = opt.precompstruct.freqs;\n TMPNEWEEG = opt.precompstruct.EEG;\n precompstruct = opt.precompstruct;\nend;\n\n% apply threshold to average of all electrodes\n% --------------------------------------------\nrejepoch = [];\nfor iReject = 1:length(opt.threshold)\n threshold = opt.threshold{iReject};\n freqLim = opt.freqlimit{iReject};\n if length(threshold) == 1, threshold = [ -100 threshold ]; end;\n [I1 tmpRejEpoch NS Erej] = eegthresh( meanspectrum, size(meanspectrum,2), 1, threshold(1), threshold(2), [freqspectrum(1) freqspectrum(end)], freqLim(1), freqLim(2));\n rejepoch = union_bc(rejepoch, tmpRejEpoch);\n if strcmpi(opt.verbose, 'on')\n fprintf('%d regions selected for rejection, threshold %3.2f-%3.2f dB, frequency limits %3.1f-%3.1f\\n', length(tmpRejEpoch), threshold(1), threshold(2), freqLim(1), freqLim(2));\n end;\nend;\n\n% build the winrej array for eegplot\n% ----------------------------------\nwinrej = [];\nif ~isempty(find(cellfun(@isempty, { TMPNEWEEG.event.epoch }) == 1))\n error('Some events are not associated with any epoch');\nend;\ntmpevent = TMPNEWEEG.event;\nallepoch = [ tmpevent.epoch ];\nif ~isempty(rejepoch)\n for index = 1:length(rejepoch)\n eventepoch = find( rejepoch(index) == allepoch );\n if strcmpi(TMPNEWEEG.event(eventepoch(1)).type, 'X')\n urevent = TMPNEWEEG.event(eventepoch(1)).urevent;\n lat = TMPNEWEEG.urevent(urevent).latency;\n winrej = [ winrej; lat lat+opt.epochlength*TMPNEWEEG.srate-1 color ]; %Erej(:,index)'];\n else\n error('Wrong type for epoch');\n end;\n end;\n winrej(:,6:6+length(opt.elecrange)-1) = 0;\nend;\n\n% remove isolated regions and merge others\n% ----------------------------------------\nmerged = 0;\nisolated = 0;\nfor index = size(winrej,1):-1:1\n if size(winrej,1) >= index && winrej(index,2) - winrej(index,1) > grouplen, winrej(index,:) = []; isolated = isolated + 1;\n elseif index == 1 && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1;\n elseif index == size(winrej,1) && size(winrej,1) > 1 && winrej(index,1) - winrej(index-1,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1;\n elseif index > 1 && size(winrej,1) > 1 && index < size(winrej,1) && winrej(index+1,1) - winrej(index,2) > grouplen && ...\n winrej(index,1) - winrej(index-1,2) > grouplen\n winrej(index,:) = [];\n isolated = isolated + 1;\n elseif index < size(winrej,1) && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) <= grouplen\n winrej(index,2) = winrej(index+1,2);\n winrej(index+1,:) = [];\n merged = merged + 1;\n end;\nend;\nif strcmpi(opt.verbose, 'on')\n fprintf('%d regions merged\\n', merged);\n fprintf('%d regions removed\\n', isolated);\nend;\n\n% add time before and after each region\n% -------------------------------------\nfor index = 1:size(winrej,1)\n winrej(index,1) = max(1, winrej(index,1)-opt.addlength*EEG.srate);\n winrej(index,2) = min(EEG.pnts, winrej(index,2)+opt.addlength*EEG.srate);\nend;\n\n% plot result\n% -----------\nif ~isempty(winrej) \n selectedregions = winrej(:,1:2);\n if strcmpi(opt.onlyreturnselection, 'off')\n % merge with initial regions\n if ~isempty(opt.rejectori)\n winrej(:,3) = 1; % color\n for iRow = 1:size(opt.rejectori,1)\n winrej(end+1,1:2) = opt.rejectori(iRow,:);\n winrej(end ,4) = 1; % color\n winrej(end ,5) = 1; % color\n end;\n end;\n \n command = '[EEG LASTCOM] = pop_select(EEG, ''nopoint'', TMPREJ(:,1:2)); eegh(LASTCOM); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM); eeglab redraw';\n if nargin < 2 || strcmpi(opt.eegplot, 'on')\n eegplot(NEWEEG.data(opt.elecrange,:), 'srate', NEWEEG.srate, 'winrej', winrej, 'command', command, 'events', EEG.event, 'winlength', 50);\n disp('Green is overlap');\n disp('Light blue is ORIGINAL rejection');\n disp('Yellow is AUTOMATIC rejection');\n else\n NEWEEG = pop_select(EEG, 'nopoint', round(selectedregions));\n end;\n EEG = NEWEEG;\n else\n EEG = [];\n end;\nelse\n selectedregions = [];\n if strcmpi(opt.verbose, 'on')\n disp('No region removed');\n end;\nend;\nif nargout > 3\n com = sprintf('EEG = pop_rejcont(EEG, %s);', vararg2str(options));\nend;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/eeglab14_0_0b/functions/popfunc/pop_rejcont.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}} {"text": "% std_interp() - interpolate, if needed, a list of named data channels \n% for all datasets included in a STUDY. Currently assumes\n% that all channels have uniform locations across datasets.\n%\n% Usage: >> [STUDY ALLEEG] = std_interp(STUDY, ALLEEG, chans, method);\n%\n% Inputs: \n% STUDY - EEGLAB STUDY structure\n% ALLEEG - EEGLAB vector containing all EEG dataset structures in the STUDY.\n% chans - [Cell array] cell array of channel names (labels) to interpolate \n% into the data if they are missing from one of the datasets.\n% method - [string] griddata() method to use for interpolation.\n% See >> help eeg_interp() {default:'spherical'}\n%\n% Important limitation:\n% This function currently presuposes that all datasets have the same channel \n% locations (with various channels from a standard set possibly missing). \n% If this is not the case, the interpolation will not be performed.\n%\n% Output: \n% STUDY - study structure.\n% ALLEEG - updated datasets.\n%\n% Author: Arnaud Delorme, CERCO, CNRS, August 2006-\n%\n% See also: eeg_interp()\n\n% Copyright (C) Arnaud Delorme, CERCO, 2006, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% Deprecated:\n% - [chanlocs structure] channel location structure containing\n% a full channel structure (missing channels in the current \n% dataset are interpolated).\n\nfunction [STUDY, ALLEEG] = std_interp(STUDY, ALLEEG, chans, method);\n\nif nargin < 2\n help std_interp;\n return;\nend;\nif nargin < 3\n chans = [];\nend;\nif nargin < 4\n method = 'spherical';\nend;\n\n% union of all channel structures\n% -------------------------------\nalllocs = eeg_mergelocs(ALLEEG.chanlocs);\n\n% check electrode names to interpolate\n% ------------------------------------\nif iscell(chans)\n alllabs = lower({ alllocs.labels });\n for index = 1:length(chans)\n tmpind = strmatch(lower(chans{index}), alllabs, 'exact');\n if isempty(tmpind)\n error( sprintf('Channel named ''%s'' not found in any dataset', chans{index}));\n end;\n end;\nend;\n\n% read all STUDY datasets and interpolate electrodes\n% ---------------------------------------------------\nfor index = 1:length(STUDY.datasetinfo)\n tmpind = STUDY.datasetinfo(index).index;\n tmplocs = ALLEEG(tmpind).chanlocs;\n\n % build electrode location structure for interpolation\n % ----------------------------------------------------\n [tmp tmp2 id1] = intersect({tmplocs.labels}, {alllocs.labels});\n if isempty(chans)\n interplocs = alllocs;\n elseif iscell(chans)\n [tmp tmp2 id2] = intersect( chans, {alllocs.labels});\n interplocs = alllocs(union(id1, id2));\n else\n interplocs = chans;\n end;\n \n if length(interplocs) ~= length(tmplocs)\n \n % search for position of electrode in backup structure\n % ----------------------------------------------\n extrachans = [];\n if isfield(ALLEEG(tmpind).chaninfo, 'nodatchans')\n if isfield(ALLEEG(tmpind).chaninfo.nodatchans, 'labels')\n extrachans = ALLEEG(tmpind).chaninfo.nodatchans;\n end;\n end;\n tmplabels = { tmplocs.labels };\n for i=1:length(interplocs)\n ind = strmatch( interplocs(i).labels, tmplabels, 'exact');\n if ~isempty(ind)\n interplocs(i) = tmplocs(ind); % this is necessary for polhemus\n elseif ~isempty(extrachans)\n ind = strmatch( interplocs(i).labels, { extrachans.labels }, 'exact');\n if ~isempty(ind)\n fprintf('Found position of %s in chaninfo structure\\n', interplocs(i).labels);\n interplocs(i) = extrachans(ind);\n end;\n end;\n end;\n \n % perform interpolation\n % ---------------------\n EEG = eeg_retrieve(ALLEEG, index);\n EEG = eeg_checkset(EEG);\n EEG = eeg_interp(EEG, interplocs, method);\n EEG.saved = 'no';\n EEG = pop_saveset(EEG, 'savemode', 'resave');\n \n % update dataset in EEGLAB\n % ------------------------\n if isstr(ALLEEG(tmpind).data)\n tmpdata = ALLEEG(tmpind).data;\n [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind);\n ALLEEG(tmpind).data = tmpdata;\n ALLEEG(tmpind).saved = 'yes';\n clear EEG;\n else\n [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind);\n ALLEEG(tmpind).saved = 'yes';\n end;\n else\n fprintf('No need for interpolation for dataset %d\\n', tmpind);\n end;\nend;\n \n \nfunction checkchans(STUDY, ALLEEG)\n\n % Check to see if all the channels have the same coordinates\n % (check only the theta field)\n % ----------------------------------------------------------\n for index = 1:length(STUDY.datasetinfo)\n tmpind = STUDY.datasetinfo(index).index;\n tmplocs = ALLEEG(tmpind).chanlocs;\n [tmp id1 id2] = intersect({tmplocs.labels}, {alllocs.labels});\n for ind = 1:length(id1)\n if tmplocs(id1(ind)).theta ~= alllocs(id2(ind)).theta\n\n % find datasets with different coordinates\n % ----------------------------------------\n for ind2 = 1:length(STUDY.datasetinfo)\n tmplocs2 = ALLEEG(ind2).chanlocs;\n tmpmatch = strmatch(alllocs(id2(ind)).labels, { tmplocs2.labels }, 'exact');\n if ~isempty(tmpmatch) \n if alllocs(id2(ind)).theta == tmplocs2(tmpmatch).theta\n datind = ind2;\n break;\n end;\n end;\n end;\n\n error(sprintf( [ 'Dataset %d and %d do not have the same channel location\\n' ...\n 'for electrode ''%s''' ], datind, tmpind, tmplocs(id1(ind)).labels));\n end;\n end;\n end;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/studyfunc/std_interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19726667062774916}} {"text": "clear;\nnetStruct = load('../data/vgg16_cuhk_batch32_Rankloss_2:1:0.5_margin1_re/net-epoch-60.mat');\nnet = dagnn.DagNN.loadobj(netStruct.net);\nclear netStruct;\nnet.mode = 'test' ;\nnet.move('gpu') ;\nnet.removeLayer('RankLoss');\nnet.conserveMemory = true;\nim_mean = reshape(net.meta.normalization.averageImage,1,1,3);\n\nload('../dataset/CUHK-PEDES-prepare/url_data.mat');\np = imdb.images.data(imdb.images.set==3);\nff = [];\n%%------------------------------\n\nfor i = 1:numel(p)\n disp(i);\n str = p{i};\n im = imread(str);\n oim = im;\n f = getFeature2(net,oim,im_mean,'x0','fc1_1bn');\n f = sum(sum(f,1),2);\n f2 = getFeature2(net,fliplr(oim),im_mean,'x0','fc1_1bn');\n f2 = sum(sum(f2,1),2);\n f = f+f2;\n size4 = size(f,4);\n f = reshape(f,[],size4)';\n f = norm_zzd(f);\n ff = cat(1,ff,f);\nend\nsave('./resnet_cuhk_img.mat','ff','-v7.3');\n%}\n\nff = [];\nload('../dataset/CUHK-PEDES-prepare/cuhk_word2.mat');\ntest_word = wordcnn(:,end-6155:end);\n\nfor i = 1:6156\n disp(i);\n content = test_word(:,i);\n len = numel(find(content>0));\n txtinput = zeros(len,7263,'single');\n for k=1:len \n txtinput(k,content(k))=1;\n end\n %transfer it to different location\n win = 57-len;\n input = zeros(56,7263,win,'single');\n for kk = 1:win\n input(kk:kk+len-1,:,kk) = txtinput;\n end\n input = reshape(input,1,56,7263,[]);\n f = getFeature2(net,input,[],'data2','fc5_2bn');\n f = sum(f,4);\n size4 = size(f,4);\n f = reshape(f,[],size4)';\n f = norm_zzd(f);\n ff = cat(1,ff,f);\nend\nsave('./resnet_cuhk_txt.mat','ff','-v7.3');\n\nevaluate;\n", "meta": {"author": "layumi", "repo": "Image-Text-Embedding", "sha": "58f858da887f12ca94301c4f44113e2464d414ee", "save_path": "github-repos/MATLAB/layumi-Image-Text-Embedding", "path": "github-repos/MATLAB/layumi-Image-Text-Embedding/Image-Text-Embedding-58f858da887f12ca94301c4f44113e2464d414ee/test_cuhk/extract_pic_feature_word2_plus_vgg16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37387582974820255, "lm_q1q2_score": 0.1971509027184731}} {"text": "% MAKE_TIMEWARP - Select a subset of epochs containing a given event sequence, and return \n% a matrix of latencies for time warping the selected epochs to a common \n% timebase in NEWTIMEF. Events in the given sequence may be further \n% restricted to those with specified event field values.\n% Usage:\n% >> timeWarp = make_timewarp(EEG, eventSequence, 'key1',value1,\n% 'key2',value2,...);\n%\n% Inputs:\n% EEG - dataset structure\n% eventSequence - cell array containing a sequence of event type strings. \n% For example, to select epochs containing a 'movement Onset' \n% event followed by a 'movement peak', use\n% {'movement Onset' 'movement peak'} \n% The output timeWarp matrix will contain the epoch latencies\n% of the two events for each selected epoch. \n%\n% Optional inputs (in 'key', value format):\n% 'baselineLatency' - (ms) the minimum acceptable epoch latency for the first\n% event in the sequence {default: 0}\n% 'eventConditions' - cell array specifying conditions on event fields.\n% For example, for a sequence consisting of two\n% events with (velocity) fields vx and vy, use\n% {vx>0' 'vx>0 && vy<1'} \n% To accept events unconditionally, use empty strings,\n% for example {'vx>0','',''} {default: no conditions}\n% 'maxSTDForAbsolute' - (positive number of std. devs.) Remove epochs containing events \n% whose latencies are more than this number of standard deviations\n% from the mean in the selected epochs. {default: Inf -> no removal}\n% 'maxSTDForRelative' - (positive number of std. devs.) Remove epochs containing inter-event\n% latency differences larger or smaller than this number of standard deviations\n% from the mean in the selected epochs. {default: Inf -> no removal}\n% Outputs:\n% timeWarp - a structure with latencies (time-warp matrix with fields\n% timeWarp.latencies - an (N, M) timewarp matrix for use in NEWTIMEF \n% where N = number of selected epochs containing the specified sequence,\n% M = number of events in specified event sequence.\n% timeWarp.epochs - a (1, M) vector giving the index of epochs with the \n% specified sequence. Only these epochs should be passed to NEWTIMEF.\n% timeWarp.eventSequence - same as the 'eventSequence' input variable.\n% Example:\n% % Create a timewarp matrix for a sequence of events, first an event of type 'movement Onset' followed by \n% % a 'movement peak' event, with event fields vx and vy:\n%\n% >> timeWarp = make_timewarp(EEG, {'movement Onset' 'movement% peak'},'baselineLatency', 0 ...\n% ,'eventConditions', {'vx>0' 'vx>0 && vy<1'});\n%\n% % To remove events with latencies more than 3 standard deviations from the mean OR 2 std. devs. \n% % from the mean inter-event difference:\n%\n% >> timeWarp = make_timewarp(EEG, {'movement Onset' 'movement peak'},'baselineLatency', 0, ... \n% 'eventConditions', {'vx>0' 'vx>0 && vy<1'},'maxSTDForAbsolute', 3,'maxSTDForRelative', 2);\n%\n% Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008\n% See also: SHOW_EVENTS, NEWTIMEF\n\n% Copyright (C) Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction timeWarpStructure = make_timewarp(EEG, eventSequence, varargin)\n\ninputKeyValues = finputcheck(varargin, ...\n {'baselineLatency' 'real' [] 0; ...\n 'eventConditions' 'cell' {} {} ; ...\n 'maxSTDForAbsolute' 'real' [0 Inf] Inf; ...\n 'maxSTDForRelative' 'real' [0 Inf] Inf...\n });\n\nbaselineLatency = [];\nmaxSTDForAbsolute = 0;\nmaxSTDForRelative = 0;\neventConditions = [];\n\n% place key values into function workspace variables\ninputKeyValuesFields = fieldnames(inputKeyValues);\nfor i=1:length(inputKeyValuesFields)\n eval([inputKeyValuesFields{i} '= inputKeyValues.' inputKeyValuesFields{i} ';']);\nend\n\n\nif length(eventConditions) < length(eventSequence)\n for i = (length(eventConditions)+1):length(eventSequence)\n eventConditions{i} = '';\n end\nend\n\nepochsIsAcceptable = ones(1, length(EEG.epoch));\nfor epochNumber = 1:length(EEG.epoch)\n eventNameID = 1;\n minimumLatency = baselineLatency;\n timeWarp{epochNumber} = [];\n while eventNameID <= length(eventSequence) % go tthrought event names and find the event that comes after a certain event with correct type and higher latency\n\n firstLatency = eventsOfCertainTypeAfterCertainLatencyInEpoch(EEG.epoch(epochNumber), eventSequence{eventNameID}, minimumLatency, eventConditions{eventNameID});\n if isempty(firstLatency) % means there were no events, so the epoch is not acceptable\n break;\n else\n timeWarp{epochNumber} = [timeWarp{epochNumber}; firstLatency];\n minimumLatency = firstLatency;\n eventNameID = eventNameID + 1;\n end\n end\n\n if length(timeWarp{epochNumber}) < length(eventSequence)\n epochsIsAcceptable(epochNumber) = false;\n end\nend\n\n\nacceptableEpochs = find(epochsIsAcceptable);\n\nif isempty(acceptableEpochs)\n timeWarp = {}; % no epoch meet the criteria\nelse\n timeWarp = cell2mat(timeWarp(acceptableEpochs));\n \n rejectedEpochesBasedOnLateny = union_bc(rejectEventsBasedOnAbsoluteLatency(timeWarp), rejectEventsBasedOnRelativeLatency(timeWarp));\n timeWarp(:,rejectedEpochesBasedOnLateny) = [];\n acceptableEpochs(rejectedEpochesBasedOnLateny) = [];\n \nend\n\n% since latencies and accepted epochs always have to be together, we put them in one structure\ntimeWarpStructure.latencies = timeWarp'; % make it suitable for newtimef()\n\nif isempty(timeWarpStructure.latencies) % when empty, it becomes a {} instead of [], so we change it to []\n timeWarpStructure.latencies = [];\nend\n\ntimeWarpStructure.epochs = acceptableEpochs;\ntimeWarpStructure.eventSequence = eventSequence;\n\n function rejectedBasedOnLateny = rejectEventsBasedOnRelativeLatency(timeWarp)\n % remeve epochs in which the time warped event is further than n\n % standard deviations to mean of latency distance between events\n timeWarpDiff = diff(timeWarp);\n rejectedBasedOnLateny = [];\n for eventNumber = 1:size(timeWarpDiff, 1)\n rejectedBasedOnLateny = [rejectedBasedOnLateny find(abs(timeWarpDiff(eventNumber, :)- mean(timeWarpDiff(eventNumber, :))) > maxSTDForRelative * std(timeWarpDiff(eventNumber, :)))];\n end\n rejectedEpochesBasedOnLateny = unique_bc(rejectedBasedOnLateny);\n end\n\n function rejectedBasedOnLateny = rejectEventsBasedOnAbsoluteLatency(timeWarp)\n % remeve instances in which the time warped event is further than n\n % standard deviations to mean\n rejectedBasedOnLateny = [];\n for eventNumber = 1:size(timeWarp, 1)\n rejectedBasedOnLateny = [rejectedBasedOnLateny find(abs(timeWarp(eventNumber, :)- mean(timeWarp(eventNumber, :))) > maxSTDForAbsolute* std(timeWarp(eventNumber, :)))];\n end\n rejectedEpochesBasedOnLateny = unique_bc(rejectedBasedOnLateny);\n end\n\n function [firstLatency resultEventNumbers] = eventsOfCertainTypeAfterCertainLatencyInEpoch(epoch, certainEventType, certainLatency, certainCondition)\n resultEventNumbers = [];\n firstLatency = []; % first event latency that meets the critria\n for eventNumber = 1:length(epoch.eventtype)\n% if strcmp(certainEventType, epoch.eventtype(eventNumber)) && epoch.eventlatency{eventNumber} >= certainLatency && eventMeetsCondition(epoch, eventNumber, certainCondition)\n if eventIsOfType(epoch.eventtype(eventNumber), certainEventType) && epoch.eventlatency{eventNumber} >= certainLatency && eventMeetsCondition(epoch, eventNumber, certainCondition)\n resultEventNumbers = [resultEventNumbers eventNumber];\n\n if isempty(firstLatency)\n firstLatency = epoch.eventlatency{eventNumber};\n end\n end\n end\n end\n\n function result = eventMeetsCondition(epoch, eventNumber, condition)\n if strcmp(condition,'') || strcmp(condition,'true')\n result = true;\n else\n\n % get the name thatis before themfor field in the epoch, then remove 'event' name\n epochField = fieldnames(epoch);\n for i=1:length(epochField)\n epochField{i} = strrep(epochField{i},'event',''); % remove event from the beginning of field names\n condition = strrep(condition, epochField{i}, ['cell2mat(epoch.event' epochField{i} '(' num2str(eventNumber) '))' ]);\n end\n\n result = eval(condition);\n end\n\n end\n\n function result = eventIsOfType(eventStr, types)\n % if events are numbers, turn them into strings before comparison\n if ischar(types)\n if iscell(eventStr) && isnumeric(cell2mat(eventStr))\n eventStr = num2str(cell2mat(eventStr));\n end\n \n result = strcmp(eventStr, types);\n else % it must be a cell of strs\n result = false;\n for i=1:length(types)\n result = result || strcmp(eventStr, types{i}); \n end\n end\n end\n \nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/make_timewarp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.19715090271847308}} {"text": "function [TruePositives, FalseNegatives] = testDrugMetabolism(model, microbeID, biomassReaction, database)\n% Performs an FVA and reports those drug metabolites (exchange reactions)\n% that can be taken up and/or secreted by the model and should be secreted according to\n% data (true positives) and those bile acid metabolites that cannot be secreted by\n% the model but should be secreted according to in vitro data (false\n% negatives).\n%\n% INPUT\n% model COBRA model structure\n% microbeID Microbe ID in carbon source data file\n% biomassReaction Biomass objective functions (low flux through BOF\n% required in analysis)\n% database Structure containing rBioNet reaction and metabolite\n% database\n%\n% OUTPUT\n% TruePositives Cell array of strings listing all drug metabolites\n% (exchange reactions) that can be taken up and/or secreted by the model\n% and in in vitro data.\n% FalseNegatives Cell array of strings listing all drug metabolites\n% (exchange reactions) that cannot be taken up and/or secreted by the model\n% but should be secreted according to in vitro data.\n%\n% .. Author:\n% Almut Heinken, April 2020\n% March 2022 - changed code to string-matching to make\n% it more robust\n\nglobal CBT_LP_SOLVER\nif isempty(CBT_LP_SOLVER)\n initCobraToolbox\nend\n\n% read drug metabolism table\ndataTable = readInputTableForPipeline('drugTable.txt');\n\ncorrRxns = {'eALP','EX_r788(e)','EX_r406(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cALP','EX_r788(e)','EX_r406(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cAzNAD','EX_bzd(e)','EX_abz_ala_b(e)','EX_5asa(e)','EX_olsa(e)','EX_neopront(e)','EX_sanilamide(e)','EX_ssz(e)','EX_sulfp(e)','EX_tab(e)','EX_pront(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cAzNADP','EX_bzd(e)','EX_abz_ala_b(e)','EX_5asa(e)','EX_olsa(e)','EX_neopront(e)','EX_sanilamide(e)','EX_ssz(e)','EX_sulfp(e)','EX_tab(e)','EX_pront(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eBGal','EX_gal(e)','EX_fru(e)','EX_lactl(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cBGal','EX_lactl(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cBRV','EX_brv(e)','EX_srv(e)','EX_bvu(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cCda','EX_dfduri(e)','EX_dfdcytd(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eCda','EX_dfduri(e)','EX_dfdcytd(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cCgr','EX_digoxin(e)','EX_digitoxin(e)','EX_dihydro_digitoxin(e)','EX_dihydro_digoxin(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cCodA','EX_5fura(e)','EX_fcsn(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eCodA','EX_5fura(e)','EX_fcsn(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cDpdNAD','EX_dh5fura(e)','EX_5fura(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cDpdNADP','EX_dh5fura(e)','EX_5fura(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eDpdNADP','EX_dh5fura(e)','EX_5fura(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cHpd','EX_4hphac(e)','EX_pcresol(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'TdcA','EX_34dhphe(e)','EX_dopa(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'Dadh','EX_mtym(e)','EX_dopa(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cNAT','EX_5asa(e)','EX_isnzd(e)','EX_acisnzd(e)','EX_ac5asa(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eNAT','EX_5asa(e)','EX_isnzd(e)','EX_acisnzd(e)','EX_ac5asa(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eNit','EX_nzp(e)','EX_chlphncl(e)','EX_nchlphncl(e)','EX_7a_czp(e)','EX_anzp(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'cNit','EX_nzp(e)','EX_chlphncl(e)','EX_nchlphncl(e)','EX_7a_czp(e)','EX_anzp(e)','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','';'eUidA','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(e)','EX_2oh_cbz_glc(e)','EX_2oh_mtz(e)','EX_2oh_mtz_glc(e)','EX_3meacmp(e)','EX_3hibup_S(e)','EX_3hibupglu_S(e)','EX_3oh_cbz(e)','EX_3oh_cbz_glc(e)','EX_3oh_dlor(e)','EX_3oh_dlor_glc(e)','EX_3oh_mdea(e)','EX_3oh_mdea_glc(e)','EX_3oh_mxn(e)','EX_3oh_mxn_glc(e)','EX_4dh_tpno(e)','EX_4dh_tpno_1glc(e)','EX_4hmdgluc(e)','EX_4oh_dcf(e)','EX_4oh_dcf_glc(e)','EX_4oh_kp(e)','EX_4oh_kp_glc(e)','EX_4oh_levole(e)','EX_4oh_levole_glc(e)','EX_4oh_meth(e)','EX_4oh_meth_glc(e)','EX_4oh_propl(e)','EX_4oh_propl_glc(e)','EX_4oh_trz(e)','EX_4oh_trz_glc(e)','EX_4oh_vcz(e)','EX_4oh_vcz_glc(e)','EX_4ohmdz(e)','EX_5oh_sulfp(e)','EX_5oh_sulfp_glc(e)','EX_5ohfvs(e)','EX_5ohfvsglu(e)','EX_6bhglz(e)','EX_6bhglzglc(e)','EX_6ohfvs(e)','EX_6ohfvsglu(e)','EX_7bhglz(e)','EX_7bhglzglc(e)','EX_7oh_efv(e)','EX_7oh_efv_glc(e)','EX_814dioh_efv(e)','EX_814dioh_efv_glc(e)','EX_8oh_efv(e)','EX_8oh_efv_glc(e)','EX_ac_amn_b_gly(e)','EX_ac_amn_b_gly_glc(e)','EX_acmp(e)','EX_acmp_glc(e)','EX_acmpglu(e)','EX_alpz_4oh(e)','EX_alpz_4oh_glc(e)','EX_alpz_aoh(e)','EX_alpz_aoh_glc(e)','EX_am14(e)','EX_am14_glc(e)','EX_am1ccs(e)','EX_am1cglc(e)','EX_am5(e)','EX_am5_glc(e)','EX_am6(e)','EX_am6_glc(e)','EX_amio(e)','EX_amio_c(e)','EX_amio_c_glc(e)','EX_amio_glc(e)','EX_amn_b_gly(e)','EX_amn_b_gly_glc(e)','EX_amntd_m6(e)','EX_amntd_m6_glc(e)','EX_atvacid(e)','EX_atvacylgluc(e)','EX_atvethgluc(e)','EX_atvlac(e)','EX_atvlacgluc(e)','EX_bhpm(e)','EX_bhpm_glc(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_bsn(e)','EX_bsn_glc(e)','EX_bz(e)','EX_bz_glc(e)','EX_caribup_s(e)','EX_caribupglu_S(e)','EX_cbz(e)','EX_cbz_glc(e)','EX_cd6168(e)','EX_cd6168_glc(e)','EX_chlphncl(e)','EX_chlphncl_glc(e)','EX_clcxb(e)','EX_clcxb_c(e)','EX_clcxb_c_glc(e)','EX_clcxb_glc(e)','EX_clobi_c(e)','EX_clobi_glc(e)','EX_crvsm1(e)','EX_crvsm23(e)','EX_cvm1gluc(e)','EX_cvm23gluc(e)','EX_daa(e)','EX_daa_glc(e)','EX_dcf(e)','EX_dcf_glc(e)','EX_ddea(e)','EX_ddea_glc(e)','EX_des_astzl(e)','EX_des_astzl_glc(e)','EX_digoxin(e)','EX_digoxin_glc(e)','EX_dlb(e)','EX_dlb_glc(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(e)','EX_doh_etr_glc(e)','EX_doh_vcz(e)','EX_doh_vcz_glc(e)','EX_dxo(e)','EX_dxo_glc(e)','EX_efv(e)','EX_efv_glc(e)','EX_eltr(e)','EX_eltr_glc(e)','EX_eltr_m3(e)','EX_eltr_m4(e)','EX_eztmb(e)','EX_eztmb_glc(e)','EX_fvs(e)','EX_fvsgluc(e)','EX_fvstet(e)','EX_fvstetglu(e)','EX_glc3meacp(e)','EX_gltmn(e)','EX_gltmn_glc(e)','EX_gmfl(e)','EX_gmfl_glc(e)','EX_gmfl_mI(e)','EX_gmfl_mI_glc(e)','EX_gmfl_mII(e)','EX_gmfl_mII_glc(e)','EX_gmfl_mIII(e)','EX_gmfl_mIII_glc(e)','EX_gtacmp(e)','EX_hst(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_ibup_S(e)','EX_ibupgluc(e)','EX_imn(e)','EX_imn_glc(e)','EX_inv(e)','EX_inv_m1(e)','EX_isosorbide_5mn(e)','EX_isosorbide_5mn_glc(e)','EX_kprofen(e)','EX_kprofen_glc(e)','EX_lst4exp(e)','EX_lstn(e)','EX_lstn1gluc(e)','EX_lstnm4(e)','EX_lstnm7(e)','EX_mdz(e)','EX_mdz_glc(e)','EX_mdzglc(e)','EX_miso(e)','EX_miso_glc(e)','EX_mrphn(e)','EX_mrphn_3glc(e)','EX_mrphn_6glc(e)','EX_mtz(e)','EX_mtz_glc(e)','EX_N_oh_phtn(e)','EX_N_oh_phtn_glc(e)','EX_nsldp_m5(e)','EX_nsldp_m5_glc(e)','EX_nverp(e)','EX_nverp_glc(e)','EX_odsm_egltmn(e)','EX_odsm_egltmn_glc(e)','EX_odsm_gltmn(e)','EX_odsm_gltmn_glc(e)','EX_oh_etr(e)','EX_oh_etr_glc(e)','EX_oh_pbl(e)','EX_oh_pbl_glc(e)','EX_phppa(e)','EX_phppa_glc(e)','EX_phtn_glc(e)','EX_prob(e)','EX_prob_glc(e)','EX_pront(e)','EX_pront_glc(e)','EX_propl(e)','EX_propl_glc(e)','EX_prx_mI(e)','EX_prx_mI_glc(e)','EX_prx_mII(e)','EX_prx_mII_glc(e)','EX_ptvst(e)','EX_ptvstgluc(e)','EX_pvs(e)','EX_pvsgluc(e)','EX_R_6oh_warf(e)','EX_R_6oh_warf_glc(e)','EX_R_7oh_warf(e)','EX_R_7oh_warf_glc(e)','EX_R_8oh_warf(e)','EX_R_8oh_warf_glc(e)','EX_r406(e)','EX_r406_glc(e)','EX_r529(e)','EX_r529_glc(e)','EX_rep(e)','EX_rep_glc(e)','EX_rpn_104557(e)','EX_rpn_104557_cb_glc(e)','EX_rpn_96990(e)','EX_rpn_96990_glc(e)','EX_rpn_oh(e)','EX_rpn_oh_glc(e)','EX_rsv(e)','EX_rsvgluc(e)','EX_S_4oh_warf(e)','EX_S_4oh_warf_glc(e)','EX_S_6oh_warf(e)','EX_S_6oh_warf_glc(e)','EX_sb_611855(e)','EX_sb_y(e)','EX_sch_488128(e)','EX_sch_57871(e)','EX_sch_57871_glc(e)','EX_sfnd_1689(e)','EX_sfnd_1689_glc(e)','EX_sftz(e)','EX_sftz_glc(e)','EX_simvgluc(e)','EX_smap(e)','EX_smap_glc(e)','EX_smvacid(e)','EX_sn38(e)','EX_sn38g(e)','EX_spz(e)','EX_spz_glc(e)','EX_spz_sfn(e)','EX_spz_sfn_glc(e)','EX_stg(e)','EX_stg_m3(e)','EX_stg_m4(e)','EX_tat(e)','EX_tgz(e)','EX_tgz_glc(e)','EX_thsacmp(e)','EX_tlf_a(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_tlms(e)','EX_tlms_glc(e)','EX_tmacmp(e)','EX_tolcp(e)','EX_tolcp_ac(e)','EX_tolcp_ac_glc(e)','EX_tolcp_am(e)','EX_tolcp_am_glc(e)','EX_tolcp_glc(e)','EX_tpno_1glc_4g(e)','EX_tpno_4g(e)','EX_tpno_4glc(e)','EX_tpnoh(e)','EX_tsacmgluc(e)';'cUidA','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(e)','EX_2oh_cbz_glc(e)','EX_2oh_mtz(e)','EX_2oh_mtz_glc(e)','EX_3meacmp(e)','EX_3hibup_S(e)','EX_3hibupglu_S(e)','EX_3oh_cbz(e)','EX_3oh_cbz_glc(e)','EX_3oh_dlor(e)','EX_3oh_dlor_glc(e)','EX_3oh_mdea(e)','EX_3oh_mdea_glc(e)','EX_3oh_mxn(e)','EX_3oh_mxn_glc(e)','EX_4dh_tpno(e)','EX_4dh_tpno_1glc(e)','EX_4hmdgluc(e)','EX_4oh_dcf(e)','EX_4oh_dcf_glc(e)','EX_4oh_kp(e)','EX_4oh_kp_glc(e)','EX_4oh_levole(e)','EX_4oh_levole_glc(e)','EX_4oh_meth(e)','EX_4oh_meth_glc(e)','EX_4oh_propl(e)','EX_4oh_propl_glc(e)','EX_4oh_trz(e)','EX_4oh_trz_glc(e)','EX_4oh_vcz(e)','EX_4oh_vcz_glc(e)','EX_4ohmdz(e)','EX_5oh_sulfp(e)','EX_5oh_sulfp_glc(e)','EX_5ohfvs(e)','EX_5ohfvsglu(e)','EX_6bhglz(e)','EX_6bhglzglc(e)','EX_6ohfvs(e)','EX_6ohfvsglu(e)','EX_7bhglz(e)','EX_7bhglzglc(e)','EX_7oh_efv(e)','EX_7oh_efv_glc(e)','EX_814dioh_efv(e)','EX_814dioh_efv_glc(e)','EX_8oh_efv(e)','EX_8oh_efv_glc(e)','EX_ac_amn_b_gly(e)','EX_ac_amn_b_gly_glc(e)','EX_acmp(e)','EX_acmp_glc(e)','EX_acmpglu(e)','EX_alpz_4oh(e)','EX_alpz_4oh_glc(e)','EX_alpz_aoh(e)','EX_alpz_aoh_glc(e)','EX_am14(e)','EX_am14_glc(e)','EX_am1ccs(e)','EX_am1cglc(e)','EX_am5(e)','EX_am5_glc(e)','EX_am6(e)','EX_am6_glc(e)','EX_amio(e)','EX_amio_c(e)','EX_amio_c_glc(e)','EX_amio_glc(e)','EX_amn_b_gly(e)','EX_amn_b_gly_glc(e)','EX_amntd_m6(e)','EX_amntd_m6_glc(e)','EX_atvacid(e)','EX_atvacylgluc(e)','EX_atvethgluc(e)','EX_atvlac(e)','EX_atvlacgluc(e)','EX_bhpm(e)','EX_bhpm_glc(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_bsn(e)','EX_bsn_glc(e)','EX_bz(e)','EX_bz_glc(e)','EX_caribup_s(e)','EX_caribupglu_S(e)','EX_cbz(e)','EX_cbz_glc(e)','EX_cd6168(e)','EX_cd6168_glc(e)','EX_chlphncl(e)','EX_chlphncl_glc(e)','EX_clcxb(e)','EX_clcxb_c(e)','EX_clcxb_c_glc(e)','EX_clcxb_glc(e)','EX_clobi_c(e)','EX_clobi_glc(e)','EX_crvsm1(e)','EX_crvsm23(e)','EX_cvm1gluc(e)','EX_cvm23gluc(e)','EX_daa(e)','EX_daa_glc(e)','EX_dcf(e)','EX_dcf_glc(e)','EX_ddea(e)','EX_ddea_glc(e)','EX_des_astzl(e)','EX_des_astzl_glc(e)','EX_digoxin(e)','EX_digoxin_glc(e)','EX_dlb(e)','EX_dlb_glc(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(e)','EX_doh_etr_glc(e)','EX_doh_vcz(e)','EX_doh_vcz_glc(e)','EX_dxo(e)','EX_dxo_glc(e)','EX_efv(e)','EX_efv_glc(e)','EX_eltr(e)','EX_eltr_glc(e)','EX_eltr_m3(e)','EX_eltr_m4(e)','EX_eztmb(e)','EX_eztmb_glc(e)','EX_fvs(e)','EX_fvsgluc(e)','EX_fvstet(e)','EX_fvstetglu(e)','EX_glc3meacp(e)','EX_gltmn(e)','EX_gltmn_glc(e)','EX_gmfl(e)','EX_gmfl_glc(e)','EX_gmfl_mI(e)','EX_gmfl_mI_glc(e)','EX_gmfl_mII(e)','EX_gmfl_mII_glc(e)','EX_gmfl_mIII(e)','EX_gmfl_mIII_glc(e)','EX_gtacmp(e)','EX_hst(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_ibup_S(e)','EX_ibupgluc(e)','EX_imn(e)','EX_imn_glc(e)','EX_inv(e)','EX_inv_m1(e)','EX_isosorbide_5mn(e)','EX_isosorbide_5mn_glc(e)','EX_kprofen(e)','EX_kprofen_glc(e)','EX_lst4exp(e)','EX_lstn(e)','EX_lstn1gluc(e)','EX_lstnm4(e)','EX_lstnm7(e)','EX_mdz(e)','EX_mdz_glc(e)','EX_mdzglc(e)','EX_miso(e)','EX_miso_glc(e)','EX_mrphn(e)','EX_mrphn_3glc(e)','EX_mrphn_6glc(e)','EX_mtz(e)','EX_mtz_glc(e)','EX_N_oh_phtn(e)','EX_N_oh_phtn_glc(e)','EX_nsldp_m5(e)','EX_nsldp_m5_glc(e)','EX_nverp(e)','EX_nverp_glc(e)','EX_odsm_egltmn(e)','EX_odsm_egltmn_glc(e)','EX_odsm_gltmn(e)','EX_odsm_gltmn_glc(e)','EX_oh_etr(e)','EX_oh_etr_glc(e)','EX_oh_pbl(e)','EX_oh_pbl_glc(e)','EX_phppa(e)','EX_phppa_glc(e)','EX_phtn_glc(e)','EX_prob(e)','EX_prob_glc(e)','EX_pront(e)','EX_pront_glc(e)','EX_propl(e)','EX_propl_glc(e)','EX_prx_mI(e)','EX_prx_mI_glc(e)','EX_prx_mII(e)','EX_prx_mII_glc(e)','EX_ptvst(e)','EX_ptvstgluc(e)','EX_pvs(e)','EX_pvsgluc(e)','EX_R_6oh_warf(e)','EX_R_6oh_warf_glc(e)','EX_R_7oh_warf(e)','EX_R_7oh_warf_glc(e)','EX_R_8oh_warf(e)','EX_R_8oh_warf_glc(e)','EX_r406(e)','EX_r406_glc(e)','EX_r529(e)','EX_r529_glc(e)','EX_rep(e)','EX_rep_glc(e)','EX_rpn_104557(e)','EX_rpn_104557_cb_glc(e)','EX_rpn_96990(e)','EX_rpn_96990_glc(e)','EX_rpn_oh(e)','EX_rpn_oh_glc(e)','EX_rsv(e)','EX_rsvgluc(e)','EX_S_4oh_warf(e)','EX_S_4oh_warf_glc(e)','EX_S_6oh_warf(e)','EX_S_6oh_warf_glc(e)','EX_sb_611855(e)','EX_sb_y(e)','EX_sch_488128(e)','EX_sch_57871(e)','EX_sch_57871_glc(e)','EX_sfnd_1689(e)','EX_sfnd_1689_glc(e)','EX_sftz(e)','EX_sftz_glc(e)','EX_simvgluc(e)','EX_smap(e)','EX_smap_glc(e)','EX_smvacid(e)','EX_sn38(e)','EX_sn38g(e)','EX_spz(e)','EX_spz_glc(e)','EX_spz_sfn(e)','EX_spz_sfn_glc(e)','EX_stg(e)','EX_stg_m3(e)','EX_stg_m4(e)','EX_tat(e)','EX_tgz(e)','EX_tgz_glc(e)','EX_thsacmp(e)','EX_tlf_a(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_tlms(e)','EX_tlms_glc(e)','EX_tmacmp(e)','EX_tolcp(e)','EX_tolcp_ac(e)','EX_tolcp_ac_glc(e)','EX_tolcp_am(e)','EX_tolcp_am_glc(e)','EX_tolcp_glc(e)','EX_tpno_1glc_4g(e)','EX_tpno_4g(e)','EX_tpno_4glc(e)','EX_tpnoh(e)','EX_tsacmgluc(e)'};\n\nTruePositives = {};\nFalseNegatives = {};\n% find microbe index in drug metabolism table\nmInd = find(strcmp(dataTable(:,1), microbeID));\nif isempty(mInd)\n warning(['Microbe \"', microbeID, '\" not found in drug data file.'])\nelse\n % perform FVA\n % set BOF\n if ~any(ismember(model.rxns, biomassReaction)) || nargin < 3\n error(['Biomass reaction \"', biomassReaction, '\" not found in model.'])\n end\n model = changeObjective(model, biomassReaction);\n % set a low lower bound for biomass\n % model = changeRxnBounds(model, biomassReaction, 1e-3, 'l');\n % list exchange reactions\n exchanges = model.rxns(strncmp('EX_', model.rxns, 3));\n % open all exchanges\n model = changeRxnBounds(model, exchanges, -1000, 'l');\n model = changeRxnBounds(model, exchanges, 1000, 'u');\n\n % get the reactions to test\n rxns = {};\n for i=2:size(dataTable,2)\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n end\n end\n\n % flux variability analysis on reactions of interest\n rxns = unique(rxns);\n rxns = rxns(~cellfun('isempty', rxns));\n rxnsInModel=intersect(rxns,model.rxns);\n if ~isempty(rxnsInModel)\n currentDir=pwd;\n try\n [minFlux, maxFlux, ~, ~] = fastFVA(model, 0, 'max', 'ibm_cplex', ...\n rxnsInModel, 'S');\n catch\n warning('fastFVA could not run, so fluxVariability is instead used. Consider installing fastFVA for shorter computation times.');\n cd(currentDir)\n [minFlux, maxFlux] = fluxVariability(model, 0, 'max', rxnsInModel);\n end\n\n % active flux\n flux = rxnsInModel(minFlux < -1e-6);\n flux = union(flux,rxnsInModel(maxFlux > 1e-6));\n else\n flux = {};\n end\n % check all exchanges corresponding to drug uptake/secretion\n % in this case, all of them should be carrying flux\n for i=2:size(dataTable,2)\n findCorrRxns = [];\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n end\n end\n if ~isempty(findCorrRxns)\n allEx = corrRxns(findCorrRxns,2:end);\n allEx = allEx(~cellfun(@isempty, allEx));\n\n TruePositives = union(TruePositives, intersect(allEx, flux));\n FalseNegatives = union(FalseNegatives, setdiff(allEx, flux));\n end\n end\nend\n\n% replace reaction IDs with metabolite names\nif ~isempty(TruePositives)\n TruePositives = TruePositives(~cellfun(@isempty, TruePositives));\n TruePositives=strrep(TruePositives,'EX_','');\n TruePositives=strrep(TruePositives,'(e)','');\n \n for i=1:length(TruePositives)\n TruePositives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),TruePositives{i})),2};\n end\nend\n\n% warn about false negatives\nif ~isempty(FalseNegatives)\n FalseNegatives = FalseNegatives(~cellfun(@isempty, FalseNegatives));\n FalseNegatives=strrep(FalseNegatives,'EX_','');\n FalseNegatives=strrep(FalseNegatives,'(e)','');\n for i = 1:length(FalseNegatives)\n FalseNegatives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),FalseNegatives{i})),2};\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/reconstruction/demeter/suite/tests/testDrugMetabolism.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.19710928009943324}} {"text": "function script_extract_vgg16_conv_features(image_set, voc_year, varargin)\n% image_set: string with the PASCAL VOC imaget set name, e.g. 'test','trainval',...\n% voc_year: string with the PASCAL VOC challenge year of the imaget set, e.g. '2007','2012',...\n% \n% This file is part of the code that implements the following ICCV2015 accepted paper:\n% title: \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% authors: Spyros Gidaris, Nikos Komodakis\n% institutation: Universite Paris Est, Ecole des Ponts ParisTech\n% Technical report: http://arxiv.org/abs/1505.01749\n% code: https://github.com/gidariss/mrcnn-object-detection\n% \n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2015 Spyros Gidaris\n% \n% \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% Technical report: http://arxiv.org/abs/1505.01749\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n\nip = inputParser;\nip.addOptional('start', 1, @isscalar); % index of the first image in the set from which it will start extracting the feature maps.\nip.addOptional('end', 0, @isscalar); % index of the last image in the set till which it will extract the feature maps. \nip.addOptional('scales', [480 576 688 874 1200], @ismatrix);\nip.addOptional('gpu_id', 0, @isnumeric); \nip.addOptional('use_flips', false, @islogical);\n\nip.parse(varargin{:});\nopts = ip.Results;\n\nmean_pix = [103.939, 116.779, 123.68];\nnet_files_dir = fullfile(pwd,'data','vgg_pretrained_models');\nnet_def_file = fullfile(net_files_dir,'vgg16_conv5_deploy.prototxt');\nnet_weights_file = fullfile(net_files_dir,'VGG_ILSVRC_16_Convolutional_Layers.caffemodel');\nassert(exist(net_files_dir,'dir')>0);\nassert(exist(net_def_file,'file')>0);\nassert(exist(net_weights_file,'file')>0);\n\nimage_db = load_image_dataset('image_set',image_set,...\n 'voc_year',voc_year,'use_flips',opts.use_flips);\n\nfeat_cache_name = 'VGG_ILSVRC_16_layers';\nfeat_cache_dir_parent = fullfile(pwd, 'feat_cache');\nfeat_cache_dir_child = fullfile(feat_cache_dir_parent, feat_cache_name);\nfeat_cache_dir_image_set = fullfile(feat_cache_dir_child, image_db.image_set_name);\n\nmkdir_if_missing(feat_cache_dir_parent);\nmkdir_if_missing(feat_cache_dir_child);\nmkdir_if_missing(feat_cache_dir_image_set);\n\ncaffe_set_device( opts.gpu_id );\ncaffe.reset_all();\nnet = caffe_load_model( net_def_file, {net_weights_file});\n\nextract_conv_features_all_images(net, image_db.image_paths, feat_cache_dir_image_set, ...\n 'start',opts.start,'end',opts.end,'scales',opts.scales,'mean_pix',mean_pix);\n\ncaffe.reset_all();\n\nend\n\n", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/script_extract_vgg16_conv_features.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19704265085804076}} {"text": "function [img, fileinfo] = read_hdr(filename)\n\n% load_hdr - loading a radiance RBGE file.\n%\n% [img, fileinfo] = read_rle_rgbe(filename);\n%\n% Written by Lawrence A. Taplin (taplin@cis.rit.edu)\n%\n% Based loosely on the c-code RGBE implementation written by Bruce Walters\n% http://www.graphics.cornell.edu/~bjw/rgbe.html\n%\n% function to read a run length encoded RGBE picture file and header. This does\n% not work if the image is not RLE!!!\n\ndo_rescale = 0;\n\n% check if the image is in classical image (eg. TIFF) format\nif ~strcmp(filename(end-2:end), 'hdr')\n img = double(imread(filename));\n if do_rescale\n img = rescale(img);\n end\n fileinfo = [];\n return;\nend\n\ntic\n\n%open the file\nfid = fopen(filename,'r');\n\nif fid<0\n error(['File not found:' filename '.']);\nend\n\n%read the magic number\ntline = fgetl(fid);\nif length(tline)<3 | tline(1:2) ~= '#?'\n error('invalid header');\nend\nfileinfo.identifier = tline(3:end);\n\n%read the header variables into a structure\ntline = fgetl(fid);\nwhile ~isempty(tline)\n %find and set the variable name\n n = strfind(tline,'=');\n if ~isempty(n) % skip stuff I don't understand\n vname = lower(tline(1:n(1)-1));\n vval = tline(n+1:end);\n fileinfo = setfield(fileinfo,vname,tline(n+1:end));\n fprintf('Variable = %s, Value = %s\\n',vname, vval);\n end\n %read the next line\n tline = fgetl(fid);\nend\n\n%set the resolution variables\ntline = fgetl(fid);\nfileinfo.Ysign = tline(1);\n[fileinfo.height,count,errmsg,nextindex] = sscanf(tline(4:end),'%d',1);\nfileinfo.Xsign = tline(nextindex+4);\n[fileinfo.width,count,errmsg,nextindex] = sscanf(tline(nextindex+7:end),'%d',1);\nfprintf('resolution: %s\\n',tline);\n\n%allocate space for the scan line data\nimg = zeros(fileinfo.height, fileinfo.width, 3);\n\n%read the scanline data\nif fileinfo.format == '32-bit_rle_rgbe';\n fprintf('Decoding RLE Data stream\\n');\nend\n\n%read the remaining data\n[data, count] = fread(fid,inf,'uint8');\nfclose(fid);\n\nscanline_width = fileinfo.width;\nnum_scanlines = fileinfo.height;\n\nif ((scanline_width < 8)|(scanline_width > 32767))\n % run length encoding is not allowed so read flat\n img = rgbe2float(reshape(data,fileinfo.width,fileinfo.height,4));\n return;\nend\n\nscanline_buffer = repmat(uint8(0),scanline_width,4);\ndp = 1; %set the data pointer to the begining of the read data\n\n% read in each successive scanline */\nfor scanline=1:num_scanlines\n % if mod(scanline,fix(num_scanlines/100))==0\n % fprintf('scanline = %d\\n',scanline);\n % end\n %\n if (data(dp) ~= 2) | (data(dp+1) ~= 2)% | (bitget(data(dp+2),8)~=1)\n error('this file is not run length encoded');\n end\n\n if (bitshift(data(dp+2),8)+data(dp+3))~=scanline_width % -128\n error('wrong scanline width');\n end\n\n dp = dp+4;\n\n % read each of the four channels read the scanline into the buffer\n for i=1:4\n ptr = 1;\n while(ptr <= scanline_width)\n if (data(dp) > 128) % a run of the same value\n count = data(dp)-128;\n if ((count == 0)|(count-1 > scanline_width - ptr))\n warning('bad scanline data');\n end\n scanline_buffer(ptr:ptr+count-1,i) = data(dp+1);\n dp = dp+2;\n ptr = ptr+count;\n else % a non-run\n count = data(dp);\n dp = dp+1;\n if ((count == 0)|(count-1 > scanline_width - ptr))\n warning('bad scanline data');\n end\n scanline_buffer(ptr:ptr+count-1,i) = data(dp:dp+count-1);\n ptr = ptr+count;\n dp = dp+count;\n end\n end\n end\n\n % now convert data from buffer into floats\n img(scanline,:,:) = rgbe2float(scanline_buffer);\nend\n\ntoc\n\n\n% rescale to 0-1\nif do_rescale\n a = min(img(:));\n b = max(img(:));\n img = (img-a)/(b-a);\nend\n\n\n% standard conversion from float pixels to rgbe pixels\n% the last dimension is assumed to be color\nfunction [rgbe] = float2rgbe(rgb)\ns = size(rgb);\nrgb = reshape(rgb,prod(s)/3,3);\nrgbe = reshape(repmat(uint8(0),[s(1:end-1),4]),prod(s)/3,4);\nv = max(rgb,[],2); %find max rgb\nl = find(v>1e-32); %find non zero pixel list\nrgbe(l,4) = uint8(round(128.5+log(v)/log(2))); %find E\nrgbe(l,1:3) = uint8(rgb(l,1:3)./repmat(2.^(double(rgbe(l,4))-128-8),1,3)); %find rgb multiplier\nreshape(rgbe,[s(1:end-1),4]); %reshape back to original dimensions\n\n% standard conversion from rgbe to float pixels */\n% note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels */\n% in the range [0,1] to map back into the range [0,1]. */\nfunction [rgb] = rgbe2float(rgbe)\ns = size(rgbe);\nrgbe = reshape(rgbe,prod(s)/4,4);\nrgb = zeros(prod(s)/4,3);\nl = find(rgbe(:,4)>0); %nonzero pixel list\nrgb(l,:) = double(rgbe(l,1:3)).*repmat(2.^(double(rgbe(l,4))-128-8),1,3);\nrgb = reshape(rgb,[s(1:end-1),3]);\n", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_image/load_hdr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}} {"text": "function aboxes_out = post_process_candidate_detections_all_imgs(...\n aboxes_in, nms_iou_thrs, thresh_val, varargin)\n% post_process_candidate_detections_all_imgs performs the post-processing \n% step of non-maximum-suppression and optionally of box voting on the\n% candidate bounding box detections of a set of images. \n% \n% INPUTS:\n% 1) aboxes_in: contains the candidate bounding box detections of each image. \n% It can be of two forms:\n% a) (the flag is_per_class must being set to false) a NI x 1 cell array \n% where NI is the number of images. The aboxes_in{i} element contains \n% the candidate bounding box detection of the i-th image in the form of a \n% NB_i x (4 + C) array where C is the number of categories and NB_i\n% is the number of candidate detection boxes of the i-th image. The first \n% 4 columns of this array contain the bounding box coordinates in the \n% form of [x0,y0,x1,y1] (where the (x0,y0) and (x1,y1) are the top-left \n% and bottom-right corners) and the rest C columns contain the confidence \n% score of the bounding boxes for each of the C categories.\n% b) (the flag is_per_class must being set to true) a C x 1 cell array \n% where C is the number of categories. The aboxes_in{j} element in this case \n% is NI x 1 cell array, where NI is the number of images, with the candidate \n% bounding box detections of the j-th category for each image. The\n% element aboxes_in{j}{i} is a NB_{i,j} x 5 array, where NB_{i,j} is the\n% number candidate bounding box detections of the i-th image for the j-th\n% category. The first 4 columns of this array are the bounding box \n% coordinates in the form of [x0,y0,x1,y1] (where the (x0,y0) and (x1,y1) \n% are the top-left and bottom-right corners) and the 5-th column contains\n% the confidence score of each bounding box with respect to the j-th category. \n% 2) nms_iou_thrs: scalar value with the IoU threshold that will be used \n% during the non-max-suppression step.\n% 3) thresh_val: is a C x 1 array, where C is the number of categories.\n% It must contains the threshold per category that will be used for \n% removing candidate boxes with low confidence prior to applying the \n% non-max-suppression step.\n% OPTIONAL INPUT:\n% 4) is_per_class: boolean value that if set to false, then the 1.a) form\n% of the aboxes_in input parameter will be expected; otherwise, if set to \n% true then the 1.b) form of the aboxes_in input parameter will be expected\n% 5) max_per_image: scalar value with the maximum number of detection per\n% image and per category. Default value: 200.\n% 6) do_bbox_voting: boolean value that if is set to True then the box voting\n% step is applied. Default value: false\n% 7) box_ave_iou_thresh: scalar value with the minimum IoU threshold that \n% is used in order to define the neighbors of bounding box during the box\n% voting step. Default value: 0.5\n% 8) add_val: scalar value that is added to the confidence score of bounding\n% boxes in order to compute the box weight during the box voting step. \n% Default value: 1.5\n% 9) use_not_static_thr: boolean value that if set to true, then the threshold\n% (param thresh_val) that is applied on the candidate bounding box\n% detections will be modified (decreased from its input value) such that \n% the average number of detections per image and per category to be \n% ave_per_image. Default value: true\n% 10) ave_per_image: scalar value with the desired average number of\n% detections per image and per category. Used only when the use_not_static_thr\n% input parameter is set to true. default value: 5\n% \n% \n% OUTPUT:\n% 1) aboxes_out: is a C x 1 array where C is the number of \n% categories. The aboxes_out{j} element is a NI x 1 cell array, where NI is\n% the number of images, with the bounding box detections of the j-th \n% category for each image. The element aboxes_out{j}{i} is a ND_{i,j} x 5 array, \n% where ND_{i,j} is the number bounding box detections for the i-th image \n% and the j-th category. The first 4 columns of this array contain the \n% bounding box coordinates in the form of [x0,y0,x1,y1] (where the (x0,y0) \n% and (x1,y1) are the top-left and bottom-right corners) and the 5-th \n% column contains the confidence score of each bounding box with respect to\n% the j-th category. \n% \n% This file is part of the code that implements the following ICCV2015 accepted paper:\n% title: \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% authors: Spyros Gidaris, Nikos Komodakis\n% institution: Universite Paris Est, Ecole des Ponts ParisTech\n% Technical report: http://arxiv.org/abs/1505.01749\n% code: https://github.com/gidariss/mrcnn-object-detection\n% \n% Part of the code in this file comes from the R-CNN code: \n% https://github.com/rbgirshick/rcnn\n% \n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2015 Spyros Gidaris\n% \n% \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% Technical report: http://arxiv.org/abs/1505.01749\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n% Copyright (c) 2014, Ross Girshick\n% \n% This file is part of the R-CNN code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% ---------------------------------------------------------\n\nip = inputParser;\nip.addParamValue('is_per_class', false, @islogical);\nip.addParamValue('do_bbox_voting', false, @islogical);\nip.addParamValue('box_ave_thresh', 0.5, @isnumeric);\nip.addParamValue('use_not_static_thr', true, @islogical);\nip.addParamValue('ave_per_image', 5, @isnumeric);\nip.addParamValue('max_per_image', 200, @isnumeric);\nip.addParamValue('add_val', 1.5, @isnumeric);\n\nip.parse(varargin{:});\nopts = ip.Results;\n\nis_per_class = opts.is_per_class;\ndo_bbox_voting = opts.do_bbox_voting;\nbox_ave_thresh = opts.box_ave_thresh;\nuse_not_static_thr = opts.use_not_static_thr;\nmax_per_image = opts.max_per_image;\nave_per_image = opts.ave_per_image;\nadd_val = opts.add_val;\n\nif ~is_per_class\n num_imgs = length(aboxes_in);\n num_classes = size(aboxes_in{1},2) - 4;\nelse\n num_classes = length(aboxes_in);\n num_imgs = length(aboxes_in{1});\nend\n\nmax_per_set = ceil(ave_per_image * num_imgs);\naboxes_out = cell(num_classes, 1);\nfor i = 1:num_classes, aboxes_out{i} = cell(num_imgs, 1); end\n\nthresh_val_all = ones(num_classes,1,'single') * thresh_val;\n\nfor i = 1:num_imgs \n % get the candidate bounding box detection of one image \n if ~is_per_class\n assert(size(aboxes_in{i},2) == (4 + num_classes));\n bbox_cand_dets = aboxes_in{i}; \n else\n bbox_cand_dets = cell(num_classes,1);\n for j = 1:num_classes\n assert(size(aboxes_in{j}{i},2) == 5);\n bbox_cand_dets{j} = aboxes_in{j}{i};\n end\n end\n \n % post-process the candidate bounding box detection of one image\n bbox_detections_per_class = post_process_candidate_detections( ...\n bbox_cand_dets, thresh_val_all, nms_iou_thrs, max_per_image, ...\n do_bbox_voting, box_ave_thresh, add_val );\n \n for j = 1:num_classes\n aboxes_out{j}{i} = bbox_detections_per_class{j};\n end\n\n if (mod(i, 1000) == 0) && use_not_static_thr\n for j = 1:num_classes\n [aboxes_out{j}, thresh_val_all(j)] = keep_top_k(aboxes_out{j}, i, max_per_set, thresh_val_all(j));\n end\n end\nend\n\nif use_not_static_thr\n disp(thresh_val_all(:)');\n for i = 1:num_classes\n % go back through and prune out detections below the found threshold\n aboxes_out{i} = prune_detections(aboxes_out{i}, thresh_val_all(i));\n end\nend\n\ntotal_num_bboxes = zeros(num_classes, 1);\nfor j = 1:num_classes\n total_num_bboxes(j) = sum(cellfun(@(x) size(x,1), aboxes_out{j}, 'UniformOutput', true));\nend\n\nfprintf('Average number of bounding boxes per class\\n');\ndisp(total_num_bboxes(:)' / num_imgs);\nfprintf('Average number of bounding boxes in total\\n');\ndisp(sum(total_num_bboxes) / num_imgs);\nend\n\nfunction [boxes, thresh] = keep_top_k(boxes, end_at, top_k, thresh)\n% keep top K detections\nX = cat(1, boxes{1:end_at});\nif isempty(X), return; end\n\nscores = sort(X(:,end), 'descend');\nthresh = scores(min(length(scores), top_k));\nfor image_index = 1:end_at\n bbox = boxes{image_index};\n keep = find(bbox(:,end) >= thresh);\n boxes{image_index} = bbox(keep,:);\nend\n\nend\n\nfunction bbox_dets = prune_detections(bbox_dets, thresh)\nfor j = 1:length(bbox_dets)\n if ~isempty(bbox_dets{j})\n bbox_dets{j}(bbox_dets{j}(:,end) < thresh ,:) = [];\n end\nend\nend", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/postprocessing/post_process_candidate_detections_all_imgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.19666720799424553}} {"text": "function [o, others] = slover(params, others, varargin)\n% class constructor for slice overlay (slover) object\n% FORMAT [o, others] = slover(params, others, varargin)\n%\n% Inputs\n% params - either:\n% - action string implementing class methods (see below)\n% - array of image names / vol structs to display\n% - structure with some fields for object (see below)\n% others - structure, containing extra fields for object (or children)\n% varargin - maybe some other parameters for action calls (see below)\n%\n% Outputs\n% o - slover object\n% others - any unrecognized fields from params, others\n%\n% Object fields are:\n% - img - array of structs with information for images to display\n% - img structs contain fields\n% type - one of {'truecolour' 'split', 'contour'};\n% truecolour - displays transparent (see prop) image\n% overlaid with any previous\n% split - in defined area, replaces image present (SPM\n% type activation display)\n% contour - contour map of image overlaid. See help\n% for contours function in matlab\n% vol - vol struct info (see spm_vol)\n% can also be vol containing image as 3d matrix\n% set with add_blobs method\n% cmap - colormap for this image\n% nancol - color for NaN. If scalar, this is an index into\n% the image cmap. If 1x3 vector, it's a colour\n% prop - proportion of intensity for this cmap/img\n% func - function to apply to image before scaling to cmap\n% (and therefore before min/max thresholding. E.g. a func of\n% 'i1(i1==0)=NaN' would convert zeros to NaNs\n% range - 2x1 vector of values for image to distribute colormap across\n% the first row of the colormap applies to the first\n% value in 'range', and the last value to the second\n% value in 'range'\n% outofrange - behavior for image values to the left and\n% right of image limits in 'range'. Left means\n% colormap values < 1, i.e for image values <\n% range(1), if (range(1)\n% range(1) where (range(1)>range(2)). If missing,\n% display min (for Left) and max (for Right) value from colormap.\n% Otherwise should be a 2 element cell array, where\n% the first element is the colour value for image values\n% left of 'range', and the second is for image values\n% right of 'range'. Scalar values for\n% colour index the colormap, 3x1 vectors are colour\n% values. An empty array attracts default settings\n% appropriate to the mode - i.e. transparent colour (where\n% img(n).type is truecolour), or split colour. Empty cells\n% default to 0. 0 specifies that voxels with this\n% colour do not influence the image (split =\n% background, true = black)\n% hold - resampling order for image (see spm_sample_vol) -\n% default 1\n% background - value when resampling outside image - default\n% NaN\n% linespec - string, applies only to contour map,\n% e.g. 'w-' for white continuous lines\n% contours - vector, applies to contour map only, defines\n% values in image for which to show contours\n% (see help contours)\n% linewidth - scalar, width in points of contour lines\n%\n% - transform - either - 4x4 transformation to apply to image slice position,\n% relative to mm given by slicedef, before display\n% or - text string, one of axial, coronal, sagittal\n% These orientations assume the image is currently\n% (after its mat file has been applied) axially\n% oriented\n% - slicedef - 2x3 array specifying dimensions for slice images in mm\n% where rows are x,and y of slice image, and cols are neg max dim,\n% slice separation and pos max dim\n% - slices - vector of slice positions in mm in z (of transformed image)\n% - figure - figure handle for slice display figure\n% The object used for the display is attached as 'UserData'\n% to this figure\n% - figure_struct - stored figure parameters (in case figure dies and\n% needs to be recreated)\n% - refreshf - flag - if set or empty, refresh axis info for figure\n% else assume this is OK\n% - clf - flag, non zero -> clear figure before display. Redundant\n% if refreshf == 0\n% - resurrectf - if not zero, and figure (above) does not exist, will\n% attempt to recreate figure with same area properties.\n% Otherwise painting will give an error.\n% - userdata - flag, non zero -> attaches object to figure when ploting,\n% for use by callbacks (default is 1)\n% - area - struct with fields\n% position - bottom left, x size y size 1x4 vector of\n% area in which to display slices\n% units - one of\n% inches,centimeters,normalized,points,{pixels}\n% halign - one of left,{center},right\n% valign - one of top,{middle},bottom\n% - xslices - no of slices to display across figure (defaults to an optimum)\n% - cbar - if empty, missing, no colourbar. If an array of integers, then\n% indexes img array, and makes colourbar for each cmap for\n% that img. Cbars specified in order of appearance L->R\n% - labels - struct can be:\n% - empty (-> default numerical labels)\n% - 'none' (string) (no labels)\n% - or contain fields:\n% colour - colour for label text\n% size - font size in units normalized to slice axes\n% format - if = cell array of strings =\n% labels for each slice in Z. If is string, specifies\n% sprintf format string for labelling in distance of the\n% origin (Xmm=0, Ymm=0) of each slice from plane containing\n% the AC, in mm, in the space of the transformed image\n% - callback - callback string for button down on image panels. THe\n% following examples assume that you have the 'userdata'\n% field set to 1, giving you access to underlying object\n% To print to the matlab window the equivalent position in\n% mm of the position of a mouse click on one of the image\n% slices, set callback to:\n% 'get_pos(get(gcf, ''UserData''))'\n% To print the intensity values of the images at the clicked point:\n% ['so_obj = get(gcf, ''UserData''); ' ...\n% 'point_vals(so_obj, get_pos(so_obj))']\n% - printstr - string for printing slice overlay figure window, e.g.\n% 'print -dpsc -painters -noui' (the default)\n% - printfile - name of file to print output to; default 'slices.ps'\n%\n% Action string formats:\n% FORMAT [cmap warnstr] = slover('getcmap', cmapname)\n% Gets colormap named in cmapname string\n%\n% FORMAT [mx mn] = slover('volmaxmin', vol)\n% Returns maximum and minimum finite values from vol struct 'vol'\n%\n% FORMAT vol = slover('blobs2vol', XYZ, vals, mat)\n% returns (pseudo) vol struct for 3d blob volume specified\n% in matrices as above\n%\n% FORMAT vol = slover('matrix2vol', mat3d, mat)\n% returns (pseudo) vol struct for 3d matrix\n% input matrices as above\n%\n% FORMAT obj = slover('basic_ui' [,dispf])\n% Runs basic UI to fetch some parameters, does display, returns object\n% If optional dispf parameter = 0, supresses display\n%__________________________________________________________________________\n\n% Matthew Brett\n% $Id: slover.m 6623 2015-12-03 18:38:08Z guillaume $\n\nmyclass = 'slover';\n\n% Default object structure\ndefstruct = struct('img', [], ...\n 'transform', 'axial', ...\n 'slicedef', [], ...\n 'slices', [], ...\n 'figure', [], ...\n 'figure_struct', [], ...\n 'refreshf', 1, ...\n 'clf', 1, ...\n 'resurrectf', 1, ...\n 'userdata', 1, ...\n 'area', [], ...\n 'xslices', [], ...\n 'cbar', [], ...\n 'labels', [], ...\n 'callback', ';', ...\n 'printstr', 'print -dpsc -painters -noui', ...\n 'printfile', 'slices.ps');\n\nif nargin < 1\n o = class(defstruct, myclass);\n others = [];\n return\nend\nif nargin < 2\n others = [];\nend\n\n% parse out string action calls (class functions)\nif ischar(params)\n switch params\n case 'getcmap'\n if nargin < 2\n error('Need colormap name');\n end\n o = pr_getcmap(others);\n return\n case 'volmaxmin'\n if nargin < 2\n error('Need volume to calculate max/min');\n end\n [o,others] = pr_volmaxmin(others);\n return\n case 'blobs2vol'\n if nargin < 4\n error('Need XYZ, vals, mat');\n end\n o = pr_blobs2vol(others, varargin{:});\n return\n case 'matrix2vol'\n if nargin < 3\n error('Need matrix and mat');\n end\n o = pr_matrix2vol(others, varargin{:});\n return\n case 'basic_ui'\n o = pr_basic_ui(others, varargin{:});\n if ~isempty(o), o = paint(o); end\n return\n end\n \n % if not action string, must be filename(s)\n params = spm_vol(params);\nend\n\n% Could these just be image vol structs?\nif isfield(params, 'fname')\n for i = 1:numel(params)\n obj.img(i).vol = params(i);\n end\n params = obj;\nend\n\n% Deal with passed objects of this (or child) class\nif isa(params, myclass)\n o = params;\n % Check for simple form of call\n if isempty(others), return, end\n \n % Otherwise, we are being asked to set fields of object\n [p,others] = mars_struct('split', others, defstruct);\n o = mars_struct('ffillmerge', o, p);\n return\nend\n\n% fill params with defaults, parse into fields for this object, children\nparams = mars_struct('fillafromb', params, others);\n[params, others] = mars_struct('ffillsplit', defstruct, params);\n\n% set the slover object\no = class(params, myclass);\n\n% refill with defaults\no = fill_defaults(o);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/@slover/slover.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.37022538564692037, "lm_q1q2_score": 0.196667200611852}} {"text": "%Transcription\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 8/6/2011\nclassdef Transcription\n %plotting\n methods (Static = true)\n function plotRNA_Polymerase_States(sim, axesHandle, time, ~)\n import edu.stanford.covert.util.ConstantUtil;\n \n rnaPol = sim.state('RNAPolymerase');\n \n maxState = max(rnaPol.transcripts.transcriptionUnitLengths);\n if ndims(rnaPol.states) == 3\n colors = zeros([size(rnaPol.states) 3]);\n else\n colors = zeros([size(rnaPol.states) 1 3]);\n end\n for i = 1:size(rnaPol.states, 1)\n for k = 1:size(rnaPol.states, 3)\n switch rnaPol.states(i, 1, k)\n case rnaPol.notExistValue\n colors(i,1,k,:) = [1 0 0];\n case rnaPol.freeValue\n colors(i,1,k,:) = [0 1 0];\n case rnaPol.nonSpecificallyBoundValue\n colors(i,1,k,:) = [0 0 1];\n otherwise\n colors(i,1,k,:) = repmat(max(0, rnaPol.states(i,1,k)) / maxState, 1, 3);\n end\n end\n end\n \n colors = reshape(colors, [], size(rnaPol.states, 3), 3);\n image(colors, 'Parent', axesHandle);\n \n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'RNA Polymerase', 'fontSize', 8);\n \n xTick = get(axesHandle, 'XTick');\n xTickLabel = round((xTick - 0.5) * max(time) / ConstantUtil.secondsPerHour / max(xTick));\n set(axesHandle, 'XTickLabel', xTickLabel);\n end\n \n function plotRNA_Polymerase_State_Occupancies(sim, axesHandle, time, ~)\n rnaPol = sim.state('RNAPolymerase');\n \n labels = cell(4,1);\n labels{rnaPol.activelyTranscribingIndex} = 'Actively Transcribing';\n labels{rnaPol.specificallyBoundIndex} = 'Specifically Bound';\n labels{rnaPol.nonSpecificallyBoundIndex} = 'Non-specifically Bound';\n labels{rnaPol.freeIndex} = 'Free';\n \n plotHandles = plot(axesHandle, time / 3600, permute(rnaPol.stateOccupancies, [3 1 2]));\n legend(plotHandles, labels);\n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'Occupancy', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n end\n \n function plotRNA_Polymerases(sim, axesHandle, time, ~)\n rnaPol = sim.state('RNAPolymerase');\n \n rnaPolymeraseGeneStates = rnaPol.states;\n rnaPolymeraseGenomeStates = zeros(size(rnaPolymeraseGeneStates));\n for i = 1:size(rnaPolymeraseGeneStates,1)\n for k = 1:size(rnaPolymeraseGeneStates,3)\n switch rnaPolymeraseGeneStates(i, 1, k)\n case rnaPol.specificallyBoundValue\n rnaPolymeraseGenomeStates(i, 1, k) = rnaPol.transcripts.transcriptionUnitFivePrimeCoordinates(rnaPol.transcripts.boundTranscriptionUnits(i,1,k));\n case rnaPol.activelyTranscribingValue\n rnaPolymeraseGenomeStates(i, 1, k) = rnaPol.transcripts.transcriptionUnitFivePrimeCoordinates(rnaPol.transcripts.boundTranscriptionUnits(i,1,k))+...\n (2*rnaPol.transcripts.transcriptionUnitDirections(rnaPol.transcripts.boundTranscriptionUnits(i,1,k))-1)*(rnaPolymeraseGeneStates(i,1,k)-1);\n end\n end\n end\n \n plot(axesHandle, time/3600, permute(rnaPolymeraseGenomeStates, [3 1 2]), '.');\n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'Genome Coordinate', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n ylim(axesHandle, [rnaPol.freeValue-1 rnaPol.transcripts.genomeLength+1]);\n end\n \n function plotRNA_Polymerase_Bound_Transcription_Units(sim, axesHandle, time, ~)\n rnaPol = sim.state('RNAPolymerase');\n \n numTimePoints = size(rnaPol.states,3);\n \n polymeraseTUs = rnaPol.transcripts.boundTranscriptionUnits;\n boundTUs = zeros(length(rnaPol.transcripts.transcriptionUnitLengths), 1, numTimePoints);\n for i = 1:size(polymeraseTUs,1)\n for k = 1:size(polymeraseTUs,3)\n if polymeraseTUs(i,1,k) > 0\n boundTUs(polymeraseTUs(i,1,k),1,k) = ...\n boundTUs(polymeraseTUs(i,1,k),1,k) + 1;\n end\n end\n end\n \n boundTUs = permute(boundTUs, [1 3 2]);\n colors = repmat(boundTUs/(max(max(boundTUs))),[1 1 3]);\n \n image(colors,'Parent',axesHandle);\n xlabel(axesHandle,'Time (h)','fontSize',8);\n ylabel(axesHandle,'Transcription Unit','fontSize',8);\n \n xTick = get(axesHandle,'XTick');\n xTickLabel = round((xTick-0.5)*max(time)/3600/max(xTick));\n set(axesHandle,'XTickLabel',xTickLabel);\n end\n \n function plotNTPs(sim, axesHandle, time, ~)\n p = sim.process('Transcription');\n \n plotHandles = plot(axesHandle, time / 3600, permute(p.substrates(p.substrateIndexs_ntp, :, :), [3 1 2]));\n legend(plotHandles, p.substrateWholeCellModelIDs(p.substrateIndexs_ntp));\n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'NTPs', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n end\n \n function plotNMPs(sim, axesHandle, time, ~)\n p = sim.process('Transcription');\n \n plotHandles = plot(axesHandle, time / 3600, permute(p.substrates(p.substrateIndexs_nmp, :, :), [3 1 2]));\n legend(plotHandles, p.substrateWholeCellModelIDs(p.substrateIndexs_nmp));\n xlabel(axesHandle,'Time (h)', 'fontSize', 8);\n ylabel(axesHandle,'NMPs', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n end\n \n %plot translation limits\n function plotTranscription_Limits(sim, axesHandle, time, ~)\n p = sim.process('Transcription');\n \n plotHandles = plot(axesHandle, time / 3600, permute(p.substrates(p.substrateIndexs_ntp), [3 1 2]));\n legend(plotHandles, p.substrateWholeCellModelIDs(p.substrateIndexs_ntp));\n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'NTP', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n end\n \n function plotBound_Transcription_Factors(sim, axesHandle, time, ~)\n p = sim.process('Transcription');\n \n transcriptionFactors = p.enzymes(p.enzymeIndexs_transcriptionFactors, :, :);\n boundTranscriptionFactors = p.boundEnzymes(p.enzymeIndexs_transcriptionFactors, :, :);\n \n plotHandles = plot(axesHandle, time / 3600, permute(boundTranscriptionFactors./(transcriptionFactors+boundTranscriptionFactors), [3 1 2]));\n legend(plotHandles, p.enzymeNames(p.enzymeIndexs_transcriptionFactors));\n xlabel(axesHandle, 'Time (h)', 'fontSize', 8);\n ylabel(axesHandle, 'Fraction Bound', 'fontSize', 8);\n xlim(axesHandle, [0 max(1, time(end))] / 3600);\n ylim(axesHandle, [0 1]);\n end\n end\nend", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+analysis/Transcription.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1966591613488892}} {"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": "\nfunction d2img = draw_2Dskeleton_MSRA(tline,frameId,folderId,modelId,coord_pixel)\n \n db_path = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/MSRA/cvpr15_MSRAHandGestureDB/';\n jointNum = 21;\n cubicSz = 200;\n imgWidth = 320;\n imgHeight = 240;\n folder_list = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"I\",\"IP\",\"L\",\"MP\",\"RP\",\"T\",\"TIP\",\"Y\"];\n \n coord_pixel = squeeze(coord_pixel);\n rgb_img = ones(imgHeight,imgWidth,3);\n refDepths = zeros(1,jointNum);\n line_width = 4;\n\n bin_name = strcat(db_path,'P',num2str(modelId),'/',folder_list(folderId),'/',sprintf('%06d',frameId-1),'_depth.bin');\n splitted = strsplit(tline);\n\n for jid = 1:jointNum\n refDepths(1,jid) = -str2num(splitted{(jid-1)*3+3});\n end\n refDepth = (min(refDepths(:)) + max(refDepths(:)))/2;\n\n fp_bin = fopen(bin_name,'r');\n img_info = fread(fp_bin,6,'int');\n left = img_info(3);\n top = img_info(4);\n right = img_info(5)-1;\n bottom = img_info(6)-1;\n\n img = fread(fp_bin,[right-left+1 bottom-top+1],'float');\n img = permute(img,[2,1]);\n img(img==0) = refDepth+cubicSz/2;\n fclose(fp_bin);\n \n img = img - refDepth;\n img = img/(cubicSz/2);\n img(img>1) = 1;\n img(img<-1) = -1;\n \n img = img + 1;\n img = img/2;\n \n rgb_img(:,:,1) = 255/255;\n rgb_img(:,:,2) = 240/255;\n rgb_img(:,:,3) = 204/255;\n \n rgb_img(top:bottom,left:right,1) = img*255/255;\n rgb_img(top:bottom,left:right,2) = img*240/255;\n rgb_img(top:bottom,left:right,3) = img*204/255;\n \n \n f = figure;\n set(f, 'visible', 'off');\n imshow(rgb_img);\n hold on;\n\n plot([coord_pixel(1,1),coord_pixel(1,18)],[coord_pixel(2,1),coord_pixel(2,18)],'Color',[255/255,153/255,153/255],'LineWidth',line_width) %wrist to thumb mcp\n plot([coord_pixel(1,18),coord_pixel(1,19)],[coord_pixel(2,18),coord_pixel(2,19)],'Color',[255/255,102/255,102/255],'LineWidth',line_width) %thumb mcp to thumb pip\n plot([coord_pixel(1,19),coord_pixel(1,20)],[coord_pixel(2,19),coord_pixel(2,20)],'Color',[255/255,51/255,51/255],'LineWidth',line_width) %thumb pip to thumb dip\n plot([coord_pixel(1,20),coord_pixel(1,21)],[coord_pixel(2,20),coord_pixel(2,21)],'Color',[255/255,0/255,0/255],'LineWidth',line_width) %thumb dip to thumb tip\n\n plot([coord_pixel(1,1),coord_pixel(1,2)],[coord_pixel(2,1),coord_pixel(2,2)],'Color',[153/255,255/255,153/255],'LineWidth',line_width) %wrist to index mcp\n plot([coord_pixel(1,2),coord_pixel(1,3)],[coord_pixel(2,2),coord_pixel(2,3)],'Color',[102/255,255/255,102/255],'LineWidth',line_width) %index mcp to index pip\n plot([coord_pixel(1,3),coord_pixel(1,4)],[coord_pixel(2,3),coord_pixel(2,4)],'Color',[51/255,255/255,51/255],'LineWidth',line_width) %index pip to index dip\n plot([coord_pixel(1,4),coord_pixel(1,5)],[coord_pixel(2,4),coord_pixel(2,5)],'Color',[0/255,255/255,0/255],'LineWidth',line_width) %index dip to index tip\n\n plot([coord_pixel(1,1),coord_pixel(1,6)],[coord_pixel(2,1),coord_pixel(2,6)],'Color',[255/255,204/255,153/255],'LineWidth',line_width) %wrist to middle mcp\n plot([coord_pixel(1,6),coord_pixel(1,7)],[coord_pixel(2,6),coord_pixel(2,7)],'Color',[255/255,178/255,102/255],'LineWidth',line_width) %middle mcp to middle pip\n plot([coord_pixel(1,7),coord_pixel(1,8)],[coord_pixel(2,7),coord_pixel(2,8)],'Color',[255/255,153/255,51/255],'LineWidth',line_width) %middle pip to middle dip\n plot([coord_pixel(1,8),coord_pixel(1,9)],[coord_pixel(2,8),coord_pixel(2,9)],'Color',[255/255,128/255,0/255],'LineWidth',line_width) %middle dip to middle tip\n\n plot([coord_pixel(1,1),coord_pixel(1,10)],[coord_pixel(2,1),coord_pixel(2,10)],'Color',[153/255,204/255,255/255],'LineWidth',line_width) %wrist to ring mcp\n plot([coord_pixel(1,10),coord_pixel(1,11)],[coord_pixel(2,10),coord_pixel(2,11)],'Color',[102/255,178/255,255/255],'LineWidth',line_width) %ring mcp to ring pip\n plot([coord_pixel(1,11),coord_pixel(1,12)],[coord_pixel(2,11),coord_pixel(2,12)],'Color',[51/255,153/255,255/255],'LineWidth',line_width) %ring pip to ring dip\n plot([coord_pixel(1,12),coord_pixel(1,13)],[coord_pixel(2,12),coord_pixel(2,13)],'Color',[0/255,128/255,255/255],'LineWidth',line_width) %ring dip to ring tip\n\n plot([coord_pixel(1,1),coord_pixel(1,14)],[coord_pixel(2,1),coord_pixel(2,14)],'Color',[255/255,153/255,255/255],'LineWidth',line_width) %wrist to little mcp\n plot([coord_pixel(1,14),coord_pixel(1,15)],[coord_pixel(2,14),coord_pixel(2,15)],'Color',[255/255,102/255,255/255],'LineWidth',line_width) %little mcp to little pip\n plot([coord_pixel(1,15),coord_pixel(1,16)],[coord_pixel(2,15),coord_pixel(2,16)],'Color',[255/255,51/255,255/255],'LineWidth',line_width) %little pip to little dip\n plot([coord_pixel(1,16),coord_pixel(1,17)],[coord_pixel(2,16),coord_pixel(2,17)],'Color',[255/255,0/255,255/255],'LineWidth',line_width) %little dip to little tip\n \n\n colorList = [\n 230/255 230/255 0/255;\n \n 153/255 255/255 153/255;\n 102/255 255/255 102/255;\n 51/255 255/255 51/255;\n 0/255 255/255 0/255;\n\n 255/255 204/255 153/255;\n 255/255 178/255 102/255;\n 255/255 153/255 51/255;\n 255/255 128/255 0/255;\n \n 153/255 204/255 255/255;\n 102/255 178/255 255/255;\n 51/255 153/255 255/255;\n 0/255 128/255 255/255;\n \n 255/255 153/255 255/255;\n 255/255 102/255 255/255;\n 255/255 51/255 255/255;\n 255/255 0/255 255/255;\n \n 255/255 153/255 153/255;\n 255/255 102/255 102/255;\n 255/255 51/255 51/255;\n 255/255 0/255 0/255;\n ];\n\n scatter(coord_pixel(1,:),coord_pixel(2,:),100,colorList,'filled');\n\n set(gca,'Units','normalized','Position',[0 0 1 1]); %# Modify axes size\n set(gcf,'Units','pixels','Position',[200 200 2*imgWidth 2*imgHeight]); %# Modify figure size\n\n frame = getframe(gcf);\n framedata = frame.cdata;\n \n xmin = min(coord_pixel(1,:));\n xmax = max(coord_pixel(1,:));\n ymin = min(coord_pixel(2,:));\n ymax = max(coord_pixel(2,:));\n\n len = max(xmax-xmin+1,ymax-ymin+1) + 70;\n xcenter = (xmin + xmax)/2;\n ycenter = (ymin + ymax)/2;\n \n xmin = max(round(xcenter - len/2),1);\n xmax = min(round(xmin + len),imgWidth);\n ymin = max(round(ycenter - len/2),1);\n ymax = min(round(ymin + len),imgHeight);\n \n framedata = framedata(2*ymin:2*ymax,2*xmin:2*xmax,:);\n\n hold off;\n close(f); \n\n d2img = framedata;\n \nend\n", "meta": {"author": "mks0601", "repo": "V2V-PoseNet_RELEASE", "sha": "8b436182161337bba3adb1690e0bc834ef72e9f2", "save_path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE", "path": "github-repos/MATLAB/mks0601-V2V-PoseNet_RELEASE/V2V-PoseNet_RELEASE-8b436182161337bba3adb1690e0bc834ef72e9f2/vis/msra/draw_2Dskeleton_MSRA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664376237036088}} {"text": "function plot_overlap_recall_curve(iou_files, methods, num_candidates, fh, ...\n names_in_plot, legend_location, use_long_labels, custom_legend)\n \n if nargin < 7\n use_long_labels = false;\n end\n if nargin < 8\n custom_legend = [];\n end\n \n [~,method_order] = sort([methods.sort_key]);\n methods = methods(method_order);\n iou_files = iou_files(method_order);\n if ~isempty(custom_legend)\n custom_legend = custom_legend(method_order);\n end\n \n labels = {methods.short_name};\n long_labels = {methods.name};\n assert(numel(iou_files) == numel(labels));\n n = numel(iou_files);\n\n num_pos = zeros(n, 1);\n \n figure(fh);\n for i = 1:n\n data = load(iou_files{i});\n thresh_idx = find( ...\n [data.best_candidates.candidates_threshold] <= num_candidates, 1, 'last');\n experiment = data.best_candidates(thresh_idx);\n [overlaps, recall, auc] = compute_average_recall(experiment.best_candidates.iou);\n \n display_auc = auc * 100;\n % round to first decimal\n display_auc = round(display_auc * 10) / 10;\n display_num_candidates = mean([experiment.image_statistics.num_candidates]);\n display_num_candidates = round(display_num_candidates * 10) / 10;\n number_str = sprintf('%g (%g)', display_auc, display_num_candidates);\n if names_in_plot\n labels{i} = sprintf('%s %s', labels{i}, number_str);\n long_labels{i} = sprintf('%s %s', long_labels{i}, number_str);\n else\n labels{i} = number_str;\n long_labels{i} = number_str;\n end\n num_pos(i) = numel(overlaps);\n line_style = '-';\n if methods(i).is_baseline\n line_style = '--';\n end\n if ~isempty(methods(i).line_style)\n line_style = methods(i).line_style;\n end\n plot(overlaps, recall, 'Color', methods(i).color, 'LineWidth', 1.5, 'LineStyle', line_style);\n hold on;\n end\n grid on;\n xlabel('IoU overlap threshold');\n ylabel('recall');\n xlim([0.5, 1]);\n ylim([0, 1]);\n if ~strcmp(legend_location, 'none')\n if ~isempty(custom_legend)\n lgnd = legend(custom_legend, 'Location', legend_location);\n elseif use_long_labels\n lgnd = legend(long_labels, 'Location', legend_location);\n else\n lgnd = legend(labels, 'Location', legend_location);\n end\n % set(lgnd, 'color','none');\n % legendshrink(0.5);\n legend boxoff;\n end\nend\n", "meta": {"author": "hosang", "repo": "detection-proposals", "sha": "858368afffde5ff4028020fcb1dd4381705ccbfb", "save_path": "github-repos/MATLAB/hosang-detection-proposals", "path": "github-repos/MATLAB/hosang-detection-proposals/detection-proposals-858368afffde5ff4028020fcb1dd4381705ccbfb/recall/plot_overlap_recall_curve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496064}} {"text": "function imStack=analyze2mrLoadRet3TSeries(inFileRoot,outFileRoot,nVols,firstVolIndex,doRotate,scaleFact,flipFlag)\n% function imStack=analyze2mrLoadRet3TSeries(inFileRoot,outFileRoot,nVols,firstVolIndex,doRotate,scaleFact,flipFlag)\n% Converts from analyze functional image data to mrLoadRet TSeries format\n% Analyze functional data are stored as N individual volumes, each with S slices\n% mrLoadRet has S individual files with N acquisitions in each.\n% the doRotate param allows to you roate the functional data by doRotate*90 degrees\n% Try to read the the first volume to see if it's there and get the dimensions of all the rest\n\n\n% TODO: 1: Rotate these so that they are in the same orientation as the anatomicals\n% (Maybe make this a flag)\n% 2: Why can't we see the anatomicals? Claims not to be able to read from /Raw/Anatomy/Inplane\n% 3: Why can't we load in the corAnal? We do this by hand perfectly well but it won't do it from mrLoadRet\n% 4: Do we want to resample the functional data? Or is this the moment to go to mrLoadRet3?\n% \n%\n% ARW 032703 : Now saves out data in mrLoadRet3.0 format (.mat as opposed to .dat files)\n\n\nif (~exist('firstVolIndex','var'))\n firstVolIndex=1;\nend\n\nif (~exist('scaleFact','var'))\n scaleFact=[1 1]; % No interpolation. (Scaling=1)\nend\n\nif (length(scaleFact)~=2) % If we just get a scalar for the scale factor, assume that it applies in both dimensions\n scaleFact=repmat(scaleFact(1),2);\nend\n\nif (~exist('doRotate','var'))\n doRotate=1; % This is on by default. Rotates 1*90 degrees\nend\n\nif (~exist('flipFlag','var'))\n flipFlag=1; % This is on by default. Flips up/down after rotation\nend\nsuffix=sprintf('%04d',firstVolIndex);\n\nfileName=[inFileRoot,suffix,'.hdr'];\n\nV=spm_vol(fileName);\nim=spm_read_vols(V);\n\n[y,x,nSlices]=size(im);\nfprintf('Read in a volume of size %d, %d, %d',y,x,nSlices);\n\n\n% Pre-allocate memory: This is a monster and will fail on many machines. \nfprintf('\\nTrying to allocate an array with %d elements...\\n',y*x*nSlices*nVols);\n\nif (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged\n funcVol=zeros(y,x,nSlices,nVols);\nelse\n funcVol=zeros(x,y,nSlices,nVols);\nend\n fprintf('Rotating by %d x 90, flipFlag=%d',doRotate,flipFlag);\n \nfor t=0:(nVols-1)\n thisImIndex=t+firstVolIndex;\n suffix=sprintf('%04d',thisImIndex);\n fileName=[inFileRoot,suffix];\n V=spm_vol(fileName);\n im=spm_read_vols(V);\n \n % Do the rotation and scaling\n \n if (mod(doRotate,2)) % When we rotate by 180 degrees the x and y dimensions remain unchanged\n im2=zeros(y,x,nSlices);\n else\n im2=zeros(x,y,nSlices);\n end\n fprintf('\\nVol=%d',thisImIndex);\n \n for thisSlice=1:nSlices\n imSlice=squeeze(im(:,:,thisSlice));\n %s imSlice=imresize(imSlice,[scaleFact(1)*y,scaleFact(2)*x],'nearest');\n \n im2(:,:,thisSlice)=rot90(imSlice,doRotate);\n if (flipFlag)\n \n im2(:,:,thisSlice)=flipud(im2(:,:,thisSlice));\n end\n \n end % next imSlice\n \n funcVol(:,:,:,t+1)=im2;\n %fprintf('.');\n \nend\nsize(funcVol);\n[y x nSlices nVols]=size(funcVol);\n\n% Now write them out in a different format\nfprintf('\\nDone reading data: Writing now...\\n');\nfor t=1:nSlices\n suffix=int2str(t);\n tSeries=squeeze(funcVol(:,:,t,:));\n [a,b,c]=size(tSeries);\n fprintf('\\nSize before: %d by %d by %d vols ',a,b,c);\n \n tSeries=squeeze(shiftdim(tSeries,2));\n \n \n \n [a,b,c]=size(tSeries);\n fprintf('\\nSize after:%d samples by %d by %d',a,b*scaleFact(1),c*scaleFact(2));\n \n % Reshape tSeries here\n tSeries=reshape(tSeries,a,(b*c));\n \n \n if ~exist(outFileRoot,'dir')\n mkdir(outFileRoot);\n end\n\n pathStr = fullfile(outFileRoot,['tSeries',num2str(t)]);\n%disp(['Saving: ',pathStr]);\n save(pathStr,'tSeries');\n\n fprintf('_');\nend\nfprintf('\\nDone\\n');\nimStack='pathStr';\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/analyze/analyze2mrLoadRet3TSeriesOriginal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19647810142500816}} {"text": "function out = spm_run_reorient(varargin)\n% SPM job execution function\n% takes a harvested job data structure and call SPM functions to perform\n% computations on the data.\n% Input:\n% job - harvested job data structure (see matlabbatch help)\n% Output:\n% out - computation results, usually a struct variable.\n%__________________________________________________________________________\n% Copyright (C) 2006-2014 Wellcome Trust Centre for Neuroimaging\n\n% Volkmar Glauche\n% $Id: spm_run_reorient.m 6078 2014-06-30 18:10:33Z guillaume $\n\njob = varargin{1};\nif isfield(job.transform,'transprm')\n job.transform.transM = spm_matrix(job.transform.transprm);\nelseif isfield(job.transform,'transF')\n load(char(job.transform.transF), 'M');\n job.transform.transM = M;\nend\n\nK = numel(job.srcfiles);\nspm_progress_bar('Init', K, 'Reorient', 'Images completed');\nif isempty(job.prefix)\n \n % read and write separately, so duplicates get harmlessly overwritten\n MM = zeros(4, 4, K);\n for k = 1:K\n MM(:, :, k) = spm_get_space(job.srcfiles{k});\n end\n for k = 1:K\n spm_get_space(job.srcfiles{k}, job.transform.transM * MM(:, :, k));\n spm_progress_bar('Set',k);\n end\n out.files = job.srcfiles;\n \nelse\n \n out.files = cell(size(job.srcfiles));\n for k = 1:K\n V = spm_vol(job.srcfiles{k});\n X = spm_read_vols(V);\n V.mat = job.transform.transM * V.mat;\n V.fname = spm_file(V.fname, 'prefix',job.prefix);\n spm_write_vol(V,X);\n out.files{k} = [V.fname ',' num2str(V.n(1))];\n spm_progress_bar('Set',k);\n end\n \nend\nspm_progress_bar('Clear');\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_reorient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.1961615844507089}} {"text": "% Formatting_step1_cleanup\n\nclear all;close all;clc\n\ncode_dir = 'C:\\Users\\Xiu\\Dropbox\\Github\\FishExplorer';\naddpath(genpath(code_dir));\n\n%% Set Manaully!\n% file directories\nM_dir = GetFishDirectories();\nM_tcutoff = {3500,[],[],3500,3600,4000,1800,[],... % Fish 1-8\n [],5000,[] }; % FIsh 9-11\n\nfpsec = 1.97; % Hz\n\n% also check manual frame-correction section below\n\n%%\npoolobj=parpool(8);\n%%\nrange_fish = 15;\n\nfor i_fish = range_fish,\n tic\n disp(['i_fish = ', num2str(i_fish)]); \n\n %% load data\n disp(['load data: fish ' num2str(i_fish)]);\n data_dir = M_dir{i_fish};\n if exist(fullfile(data_dir,'cell_resp_dim_lowcut.mat'), 'file'),\n load(fullfile(data_dir,'cell_resp_dim_lowcut.mat'));\n elseif exist(fullfile(data_dir,'cell_resp_dim.mat'), 'file'),\n load(fullfile(data_dir,'cell_resp_dim.mat'));\n else\n errordlg('find data to load!');\n end\n \n load(fullfile(data_dir,'cell_info.mat'));\n if exist(fullfile(data_dir,'cell_resp_lowcut.stackf'), 'file'),\n cell_resp_full = read_LSstack_fast_float(fullfile(data_dir,'cell_resp_lowcut.stackf'),cell_resp_dim);\n elseif exist(fullfile(data_dir,'cell_resp.stackf'), 'file'),\n cell_resp_full = read_LSstack_fast_float(fullfile(data_dir,'cell_resp.stackf'),cell_resp_dim);\n else\n errordlg('find data to load!');\n end\n \n load(fullfile(data_dir,'frame_turn.mat'));\n frame_keys = frame_turn;\n \n %% load anatomy\n tiffname = fullfile(data_dir,'ave.tif');\n info = imfinfo(tiffname,'tiff');\n nPlanes = length(info);\n s1 = info(1).Height;\n s2 = info(1).Width;\n ave_stack = zeros(s1,s2,nPlanes);\n for i=1:nPlanes,\n ave_stack(:,:,i) = imread(tiffname,i);\n end\n\n %% fix the left-right flip in the anatomy stack and subsequent cell_info\n anat_stack = fliplr(ave_stack);\n \n [s1,s2,~] = size(ave_stack);\n for i_cell = 1:length(cell_info),\n % fix '.center'\n cell_info(i_cell).center(2) = s2-cell_info(i_cell).center(2)+1; %#ok<*SAGROW>\n end\n \n %% reformat coordinates\n numcell_full = cell_resp_dim(1);\n temp = [cell_info(:).center];\n XY = reshape(temp',[],numcell_full)';\n Z = [cell_info.slice]';\n CellXYZ = horzcat(XY,Z);\n \n \n %% Manual occasional frame corrections: ONLY RUN ONCE!!!!!!!!!\n \n if true,\n % add 1 frame at start: ------------- for which fish again? all till F11?\n cell_resp_full = horzcat(cell_resp_full(:,1),cell_resp_full);\n frame_keys = vertcat(frame_keys(1,:),frame_keys);\n end\n\n % correction of an error in Fish #1\n if i_fish == 1,\n cell_resp_full = horzcat(cell_resp_full(:,1:20),cell_resp_full);\n end\n \n %% Crop end of experiment (when cell-segmentation drift > ~1um, manually determined)\n if ~isempty(M_tcutoff{i_fish}),\n cell_resp_full = cell_resp_full(:,1:M_tcutoff{i_fish});\n frame_keys = frame_keys(1:M_tcutoff{i_fish},:);\n end\n\n %% detrend \n CR_dtr = zeros(size(cell_resp_full));\n tmax=size(cell_resp_full,2);\n numcell_full=size(cell_resp_full,1);\n\n parfor i=1:numcell_full,\n cr = cell_resp_full(i,:);\n crd = 0*cr;\n for j=1:100:tmax,\n if j<=150,\n tlim1 = 1;\n tlim2 = 300;\n elseif j>tmax-150,\n tlim1 = tmax-300;\n tlim2 = tmax;\n else\n tlim1 = j-150;\n tlim2 = j+150;\n end\n crr = cr(tlim1:tlim2);\n crd(max(1,j-50):min(tmax,j+50)) = prctile(crr,15);\n end\n% if mod(i,100)==0,\n% disp(num2str(i));\n% end\n CR_dtr(i,:) = cr-crd;\n end\n \n TimeSeries = single(CR_dtr);\n\n \n %% Place holder for registered coordinates from morphing to ZBrain\n CellXYZ_norm = CellXYZ;\n \n \n \n %% Save files\n\n % directory to save data formatted for distribution:\n save_masterdir = GetNestedDataDir();\n save_dir = fullfile(save_masterdir,['subject_' num2str(i_fish)]);\n if ~exist(save_dir, 'dir')\n mkdir(save_dir);\n end\n \n % save time-series\n h5create(fullfile(save_dir,'TimeSeries.h5'),'/TimeSeries',size(TimeSeries),'Datatype','single','ChunkSize',[1000 100]);\n h5write(fullfile(save_dir,'TimeSeries.h5'),'/TimeSeries',TimeSeries);\n\n % save .mat files\n filename = fullfile(save_dir,'CoreInfo.mat');\n varList = {'CellXYZ','anat_stack','fpsec'};\n save(filename,varList{:});\n \n filename = fullfile(save_dir,'OptionalInfo.mat');\n varList = {'numcell_full','CellXYZ_norm'};\n save(filename,varList{:}); \n \n filename = fullfile(save_dir,'AdditionalInfo.mat');\n save(filename,'frame_keys');\n\n %%\n toc\nend\n\n%%\n% delete(poolobj);\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/GUI preload processing/old/Formatting_step1_cleanup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.19614436791330103}} {"text": "function [varargout]= fileutil_concatBV(file_list, varargin)\n% FILEUTIL_CONCATBV - concatenate files which are stored in BrainVision format\n%\n% Synopsis:\n% [DAT, MRK, MNT]= fileutil_concatBV(FILE_LIST, 'Property, 'Value', ...)\n%\n% Arguments:\n% FILE_LIST: list of file names (no extension)\n%\n% Returns:\n% DAT: structure of continuous or epoched signals\n% MRK: marker structure\n% MNT: electrode montage structure\n%\n% Properties:\n% are passed to file_loadBV\n%\n% Description:\n% This function is called by file_loadBV in case the file name argument\n% is a cell array of file names. Typically there is no need to call this \n% function directly.\n%\n%\n\nif ~iscell(file_list),\n file_list= {file_list};\nend\n\nT= zeros(1, length(file_list));\ndataOffset = 0;\nfor ii= 1:length(file_list),\n [cnt, mrk, hdr]= file_loadBV(file_list{ii}, varargin{:});\n T(ii)= size(cnt.x,1);\n if ii==1,\n ccnt= cnt;\n curmrk= mrk;\n else\n if ~isequal(cnt.clab, ccnt.clab),\n warning(['inconsistent clab structure will be repaired ' ...\n 'by using the intersection']); \n commonclab= intersect(cnt.clab, ccnt.clab);\n cnt= proc_selectChannels(cnt, commonclab{:});\n ccnt= proc_selectChannels(ccnt, commonclab{:});\n end\n if ~isequal(cnt.fs, ccnt.fs)\n error('inconsistent sampling rate'); \n end\n ccnt.x= cat(1, ccnt.x, cnt.x);\n \n mrk.time= mrk.time + dataOffset*1000/cnt.fs;\n \n% % find markers in the loaded interval\n% inival= find(curmrk.time > skip*1000/cnt.fs & ...\n% curmrk.time <= (skip+maxlen)*1000/cnt.fs);\n% curmrk= mrk_selectEvents(curmrk, inival);\n% %let the markers start at zero\n% curmrk.time= curmrk.time - skip*1000/cnt.fs;\n \n curmrk = mrk_mergeMarkers(curmrk, mrk);\n \n end\n dataOffset = dataOffset + T(ii);\n\nend\n\nccnt.T= T;\nif length(file_list)>1,\n ccnt.title= [ccnt.title ' et al.'];\n ccnt.file= strcat(fileparts(ccnt.file), file_list);\nend\n\nvarargout= cell(1, nargout);\nvarargout{1}= ccnt;\nif nargout>1,\n varargout{2}= curmrk;\n if nargout>2,\n varargout{3}= hdr;\n end\nend\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/fileio/private/fileutil_concatBV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.19614043462178754}} {"text": "function calcFeatureImportanceRF_Aerts(pathRF,nPerms,seed)\n\nstartpath = pwd;\ncd(pathRF), load('testingVariableImportance') % 'variableImportance' gets out of there\n\n[percentAUCdecrease,varNames] = calcFeatureImportanceRF_HN(pathRF,nPerms,'DeathSign','CT',seed);\nvariableImportance.DeathSign.CT.percentAUCdecrease = percentAUCdecrease;\nvariableImportance.DeathSign.CT.varNames = varNames;\ncd(pathRF), save('testingVariableImportance','variableImportance')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/calcFeatureImportanceRF_Aerts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}} {"text": "function calcAllAertsFeatures_batchHN_temp(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% function calcAllSeparateTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,scale_mat,Ng_mat,nBatch,matlabPATH)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes SEPARATE texture features for all patients, for\n% all different combinations of the following texture extraction parameters:\n% - Scale: Resolution at which the ROI is isotropically resampled.\n% - Ng: Number of gray-levels in the quantization process. \n%\n% Different extraction parameters are passed as arrays or cells in the\n% function in order to test all possible combinations. This function is \n% used for SEPARATE scans specifically. See Ref. [1,2] and 'prepareVolume.m' \n% for more details.\n%\n% Texture features are computed for all head and neck (HN) DICOM imaging \n% data downloaded from The Cancer Imaging Archive (TCIA) website at: \n% , and first organized \n% in a 'DATA' directory using the function readAllDICOM_HN.m. Results are \n% then saved in a folder 'TEXTURES' in the HN WORKSPACE.\n% -------------------------------------------------------------------------\n% REFERENCES:\n% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the \n% early prediction of different tumour outcomes in head and neck cancer.\n% The Journal of Nuclear Medicine, aa(bb), xxx-yyy. \n% doi:\n% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and \n% MRI texture features for the prediction of lung metastases in soft-tissue \n% sarcomas of the extremities. Physics in Medicine and Biology, 60(14), \n% 5471-5496. doi:10.1088/0031-9155/60/14/5471\n% -------------------------------------------------------------------------\n% INPUTS:\n% 1. pathData: Full path to the HN sData files directory.\n% --> Ex: '/myProject/WORKSPACE/DATA'\n% 2. pathText: Full path to the HN non texture features directory.\n% --> Ex: '/myProject/WORKSPACE/FEATURES/TEXTURES'\n% 3. namePT: Cell of strings of all PET sData files to read\n% --> Ex: {'HGJ_001_PT.PTscan.mat';'HGJ_022_PT.PTscan.mat'}\n% 4. namePT: Cell of strings of all CT sData files to read\n% --> Ex: {'HGJ_001_CT.CTscan.mat';'HGJ_022_CT.CTscan.mat'}\n% 5. nameROI: Cell of strings specifying the ROI names to analyze for the\n% patients defined by \"namePT\" and \"nameCT\"\n% --> Ex: {'GTV';'GTV-P'}\n% 6. outcomes: Structure specifying the status (1 or 0) for different\n% outcomes in HN cancer. Contains: outcomes.Failure, \n% outcomes.Locoregional, outcomes.Distant. See ref.[1] for \n% more details.\n% 7. featType: Either 'GTVp' for primary GTV, or 'GTVtot' for primaty GTV +\n% nodal GTVs\n% --> Ex: 'GTVp'\n% 8. scale_mat: Array vector specifying the different 'Scale' values to test.\n% --> Ex: [1,2,3,4,5]\n% 9. Ng_mat: Array vector specifying the different 'Ng' values to test.\n% --> Ex: [8,16,32,64]\n% 10. nBatch: Number of parallel batch.\n% --> Ex: 8\n% 11. matlabPATH: Full path to the MATLAB excutable on the system.\n% --> Ex: 'matlab' (symbolic link)\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\nind = strfind(namePT{1},'_'); cohortID = namePT{1}(1:ind-1);\ncd(pathText), mkdir(['batchLog_',cohortID,'_',featType,'_AertsFeatures']), cd(['batchLog_',cohortID,'_',featType,'_AertsFeatures']), pathBatch = pwd;\ntime = 60; % Number of seconds to wait before checking if parallel computations are done\nnameOutcomes = fieldnames(outcomes); nOutcomes = numel(nameOutcomes);\nscans = {'PT','CT'}; nScans = numel(scans);\n\n% PRODUCE BATCH COMPUTATIONS\nnPatient = numel(namePT); valid = ones(nPatient,1);\nfor i = 1:nPatient\n if isempty(nameROI{i})\n valid(i) = 0;\n end\nend\nindValid = find(valid); nPatient = numel(indValid);\nif nPatient < nBatch\n nBatch = nPatient;\nend\n[patients] = batchPatients(nPatient,nBatch);\nsave('workspace','pathData','pathText','namePT','nameCT','nameROI','patients','indValid','featType'), pause(5);\nfor i = 1:nBatch\n nameScript = ['batch',num2str(i),'_script.m'];\n fid = fopen(nameScript,'w');\n fprintf(fid,'load(''workspace'')\\n');\n fprintf(fid,['calcAllAertsFeatures_HN(pathData,pathText,namePT(indValid(patients{',num2str(i),'})),nameCT(indValid(patients{',num2str(i),'})),nameROI(indValid(patients{',num2str(i),'})),featType)\\n']);\n fprintf(fid,['system(''touch batch',num2str(i),'_end'');\\n']);\n fprintf(fid,'clear all');\n fclose(fid);\n system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nBatch)\ndelete('workspace.mat')\n\n% % GROUPING RESULTS FROM ALL BATCH\n% nPatient = numel(namePT);\n% names = {namePT,nameCT};\n% for scan = 1:nScans\n% cd(pathText)\n% sign = struct;\n% signTemp = zeros(nPatient,4); % 4-feature signature\n% tempText = cell(1,nPatient); % Cell used to load patient textures only once\n% for p = 1:nPatient\n% ind = strfind(names{scan}{p},'.'); namePatientScan = names{scan}{p}(1:ind(1)-1);\n% if exist([namePatientScan,'_',featType,'_sign.mat'],'file')\n% load([namePatientScan,'_',featType,'_sign']) % Variable 'signature' is now in MATLAB workspace\n% else\n% load([namePatientScan,'_','GTVp','_sign']) % Variable 'signature' is now in MATLAB workspace\n% end\n% tempText{p} = signature;\n% end\n% for p = 1:nPatient\n% signTemp(p,:) = tempText{p};\n% end\n% sign.Data = signTemp;\n% for o = 1:nOutcomes\n% [sign.Spearman.(nameOutcomes{o}).rs,sign.Spearman.(nameOutcomes{o}).p] = corr(sign.Data,outcomes.(nameOutcomes{o}),'type','Spearman','rows','pairwise');\n% end\n% cd .., save(['AertsSign_',cohortID,'_',scans{scan},'_',featType],'sign')\n% end\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/calcAllAertsFeatures_batchHN_temp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.1957686760259442}} {"text": "function [f0,irms,df,amp]=f0track5(f0v,vrv,dfv,pwt,pwh,aav,shiftm,imgi)\n\n%\tF0 trajectory tracker\n%\t[f0,irms,df,amp]=f0track2(f0v,vrv,dfv,shiftm,imgi)\n%\t\tf0\t: extracted F0 (Hz)\n%\t\tirms\t: relative interfering energy in rms\n%\n%\tf0v\t: fixed point frequency vector\n%\tvrv\t: relative interfering energy vector\n%\tdfv\t: fixed point slope vector\n%\tpwt\t: total power\n%\tpwh\t: power in higher frequency range\n%\taav\t: amplitude list for fixed points\n%\tshiftm\t: frame update period (ms)\n%\timgi\t: display indicator, 1: display on (default), 0: off\n%\t\n%\tThis is a very primitive and conventional algorithm.\n\n%\tcoded by Hideki Kawahara\n%\tcopyright(c) Wakayama University/CREST/ATR\n%\t10/April/1999 first version\n%\t17/May/1999 relative fq jump thresholding\n%\t01/August/1999 parameter tweeking\n% 07/Dec./2002 waitbar was added\n% 13/Jan./2005 bug fix on lines 58, 97 (Thanx Ishikasa-san)\n%\t30/April/2005 modification for Matlab v7.0 compatibility\n%\t10/Aug./2005 modified by Takahashi on waitbar\n%\t10/Sept./2005 modified by Kawahara on waitbar\n\nif nargin==7; imgi=1; end; %10/Sept./2005\nvrv=sqrt(vrv);\n[~,mm]=size(vrv);\nmm=min(mm,length(pwt));\n\nf0=zeros(1,mm);\nirms=ones(1,mm);\ndf=ones(1,mm);\namp=zeros(1,mm);\nvon=0;\n[mxvr,ixx]=min(vrv);\nhth=0.12;\t% highly confident voiced threshould (updated on 01/August/1999)\nlth=0.9;\t% threshold to loose confidence\nbklm=100;\t% back track length for voicing decision\nlalm=10;\t% look ahead length for silence decision\nbkls=bklm/shiftm;\nlals=lalm/shiftm;\nhtr=10*log10(pwh./pwt);\n\nthf0j=0.04*sqrt(shiftm); % 4 % of F0 is the limit of jump\nii=1;\nf0ref=0;\nhtrth=-2.0; % was -3 mod 2002.6.3\nif imgi==1; hpg=waitbar(0,'F0 tracking'); end; % 07/Dec./2002 by H.K.%10/Aug./2005\nwhile ii < mm+1\n\tif (von == 0) && (mxvr(ii)10000)+(f0v(jxx,jj)>10000);\n\t\t\tif (((gomi>thf0j) || (vrv(jxx,jj)>lth) || (htr(jj)>htrth))&&(f0v(jxx,jj)<1000)) && htr(jj)>-18\n%\t\t\t\tdisp(['break pt1 at ' num2str(jj)])\n\t\t\t\tbreak\n\t\t\tend;\n\t\t\tif (gomi>thf0j)\n%\t\t\t\tdisp(['break pt2 at ' num2str(jj)])\n\t\t\t\tbreak\n\t\t\tend;\n\t\t\t\n\t\t\tf0(jj)=f0v(jxx,jj);\n\t\t\tirms(jj)=vrv(jxx,jj);\n\t\t\tdf(jj)=dfv(jxx,jj);\n\t\t\tamp(jj)=aav(jxx,jj);\n\t\t\tf0ref=f0(jj);\n\t\tend;\n\t\tf0ref=f0v(ixx(ii),ii);\n\tend;\n\tif (f0ref>0) && (f0ref<10000)\n\t\t[gomi,jxx]=min(abs((f0v(:,ii)-f0ref)/f0ref));\n\telse\n\t\tgomi=10;\n\tend;\n\tif (von ==1) && (mxvr(ii)>hth)\n\t\tfor jj=ii:min(mm,ii+lals)\n\t\t\tii=jj;\n\t\t\t[gomi,jxx]=min(abs((f0v(:,ii)-f0ref)/f0ref));\n\t\t\tgomi=gomi+(f0ref>10000)+(f0v(jxx,ii)>10000);\n\t\t\tif (gomi< thf0j) && ((htr(ii)=1000))\n\t\t\t\tf0(ii)=f0v(jxx,ii);\n\t\t\t\tirms(ii)=vrv(jxx,ii);\n\t\t\t\tdf(ii)=dfv(jxx,ii);\n\t\t\t\tamp(ii)=aav(jxx,ii);\n\t\t\t\tf0ref=f0(ii);\n\t\t\tend;\n\t\t\tif (gomi>thf0j) || (vrv(jxx,ii)>lth) || ((htr(ii)>htrth)&&(f0v(jxx,ii)<1000))\n\t\t\t\tvon = 0;f0ref=0;\n\t\t\t\tbreak\n\t\t\tend;\n\t\tend;\n\telseif (von==1) && (gomi < thf0j) && ((htr(ii)=1000))\n\t\tf0(ii)=f0v(jxx,ii);\n\t\tirms(ii)=vrv(jxx,ii);\n\t\tdf(ii)=dfv(jxx,ii);\n\t\tamp(ii)=aav(jxx,ii);\n\t\tf0ref=f0(ii);\n\telse\n\t\tvon=0;\n\tend;\n if imgi==1; waitbar(ii/mm); end; %,hpg); % 07/Dec./2002 by H.K.%10/Aug./2005\n\tii=ii+1;\nend;\nif imgi==1; close(hpg); end;%10/Aug./2005\n", "meta": {"author": "HidekiKawahara", "repo": "legacy_STRAIGHT", "sha": "964684981fe12cd232c5e882259dff126b3af0f2", "save_path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT", "path": "github-repos/MATLAB/HidekiKawahara-legacy_STRAIGHT/legacy_STRAIGHT-964684981fe12cd232c5e882259dff126b3af0f2/src/f0track5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.19576867214369875}} {"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": "classdef prtRv < prtAction\n % prtRv Base class for all prt random variables\n %\n % This is an abstract class from which all prt random variables\n % inherit. It can not be instantiated. prtRv contains the following \n % properties:\n %\n % name - Name of the random variable.\n % userData - Structure for holding additional related to the\n % random variable.\n % nDimensions - Number of dimensions of the vector space\n % represented by the random variable.\n %\n % The prtRv class has the following methods\n %\n % plotPdf - Plot the pdf of the random variable\n % plotCdf - Plot the cdf of the random variable\n %\n % The prtRv class has the following methods, most of which are\n % overloaded. If a method is not overloaded, it is because it is not\n % possible to implement the functionality.\n %\n % pdf - Output the pdf of the random variable evaluated at the points\n % specified\n %\n % logPdf - Output the log-pdf of the random variable evaluated at the\n % points specified (for many distributions, this can be\n % calculated more easily than simply log(pdf(R,X))\n %\n % cdf - Output the cdf of the random variable evaluated at the\n % points specified\n %\n % draw - Draw samples from the random variable\n %\n % mle - Perform maximum likelihood estimation of the objects parameters \n % using the specified data\n %\n % See also: prtRvMvn, prtRvGmm, prtRvMultinomial, prtRvUniform,\n % prtRvUniformImproper, prtRvVq\n\n\n\n\n\n\n\n properties\n plotOptions = prtRv.initializePlotOptions()\n end\n properties (Abstract = true, Hidden = true, Dependent = true)\n nDimensions % The number of dimensions\n end\n methods (Abstract, Hidden=true)\n [bool, reasonStr] = isValid(R)\n end\n methods\n % These functions are default \"error\" functions incase a\n % subclass has not specified these standard methods.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function vals = pdf(R,X) %#ok\n % PDF Output the pdf of the random variable evaluated at the points specified\n %\n % pdf = RV.pdf(X) returns the value of the pdf of the prtRv\n % object evaluated at X. X must be an N x nDims matrix, where N\n % is the number of locations to evaluate the pdf, and nDims is\n % the same as the number of dimensions, nDimensions, of the\n % prtRv object RV.\n missingMethodError(R,'pdf');\n end\n\n function vals = logPdf(R,X)\n % LOGPDF Output the log pdf of the random variable evaluated at the points specified\n %\n % logpdf = RV.logpdf(X) returns the logarithm of value of the\n % pdf of the prtRv object evaluated at X. X must be an N x\n % nDims matrix, where N is the number of locations to evaluate\n % the pdf, and nDims is the same as the number of dimensions,\n % nDimensions, of the prtRv object RV.\n vals = log(R.pdf(X));\n end\n \n function vals = cdf(R,X) %#ok\n % CDF Output the cdf of the random variable evaluated at the points specified\n %\n % cdf = RV.cdf(X) returns the value of the cdf of the prtRv\n % object evaluated at X. X must be an N x nDims matrix, where\n % N is the number of locations to evaluate the pdf, and nDims\n % is the same as the number of dimensions, nDimensions, of the\n % prtRv object RV.\n\n missingMethodError(R,'cdf');\n end\n \n function vals = draw(R,N) %#ok\n % DRAW Draw random samples from the distribution described by the prtRv object\n %\n % VAL = RV.draw(N) generates N random samples drawn from the\n % distribution described by the prtRv object RV. VAL will be a\n % N x nDimensions vector, where nDimensions is the number of\n % dimensions of RV.\n\n missingMethodError(R,'draw');\n end\n\n function vals = mle(R,X) %#ok\n % MLE Compute the maximum likelihood estimate \n %\n % RV = RV.mle(X) computes the maximum likelihood estimate based\n % the data X. X should be nObservations x nDimensions. \n missingMethodError(R,'mle');\n end\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % These functions are default plotting functions\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function varargout = plotPdf(R,varargin)\n % PLOTPDF Plot the pdf of the prtRv\n %\n % R.plotPdf()\n % R.plotPdf([xMin yMin (zMin) xMax yMax (zMax)]); \n \n varargout = {};\n [isValid, reasonStr] = R.isValid;\n if R.isPlottable\n \n if nargin > 1 % Calculate appropriate limits from covariance\n plotLims = varargin{1};\n else\n plotLims = plotLimits(R);\n end\n [linGrid, gridSize] = prtPlotUtilGenerateGrid(plotLims(1:2:end), plotLims(2:2:end), R.plotOptions.nSamplesPerDim);\n \n imageHandle = prtPlotUtilPlotGriddedEvaledFunction(R.pdf(linGrid), linGrid, gridSize, R.plotOptions.colorMapFunction(R.plotOptions.nColorMapSamples),varargin{2:end});\n \n if nargout\n varargout = {imageHandle};\n end\n else\n if isValid\n error('prt:prtRv:plot','This RV object cannont be plotted because it has too many dimensions.')\n else\n error('prt:prtRv:plot','This RV object cannot be plotted. This RV is not yet valid %s.',reasonStr);\n end\n end\n end\n function varargout = plotLogPdf(R,varargin)\n % plotLogPdf Plot the pdf of the prtRv\n %\n % R.plotLogPdf()\n % R.plotLogPdf([xMin yMin (zMin) xMax yMax (zMax)]); \n \n varargout = {};\n [isValid, reasonStr] = R.isValid;\n if R.isPlottable\n \n if nargin > 1 % Calculate appropriate limits from covariance\n plotLims = varargin{1};\n else\n plotLims = plotLimits(R);\n end\n \n [linGrid, gridSize] = prtPlotUtilGenerateGrid(plotLims(1:2:end), plotLims(2:2:end), R.plotOptions.nSamplesPerDim);\n \n imageHandle = prtPlotUtilPlotGriddedEvaledFunction(R.logPdf(linGrid), linGrid, gridSize, R.plotOptions.colorMapFunction(R.plotOptions.nColorMapSamples),varargin{2:end});\n \n if nargout\n varargout = {imageHandle};\n end\n else\n if isValid\n error('prt:prtRv:plot','This RV object cannont be plotted because it has too many dimensions.')\n else\n error('prt:prtRv:plot','This RV object cannot be plotted. This RV is not yet valid %s.',reasonStr);\n end\n end\n end\n \n function varargout = plotCdf(R,varargin)\n %PLOTCDF Plot the cdf of the prtRv\n % R.plotCdf()\n % R.plotCdf([xMin yMin (zMin) xMax yMax (zMax)]); \n \n varargout = {};\n [isValid, reasonStr] = R.isValid;\n if R.isPlottable\n \n if nargin > 1 % Calculate appropriate limits from covariance\n plotLims = varargin{1};\n else\n plotLims = plotLimits(R);\n end\n \n [linGrid,gridSize] = prtPlotUtilGenerateGrid(plotLims(1:2:end), plotLims(2:2:end), R.plotOptions.nSamplesPerDim);\n \n imageHandle = prtPlotUtilPlotGriddedEvaledFunction(R.cdf(linGrid), linGrid, gridSize, R.plotOptions.colorMapFunction(R.plotOptions.nColorMapSamples));\n \n if nargout\n varargout = {imageHandle};\n end\n else\n if isValid\n error('prt:prtRv:plot','This RV object cannont be plotted because it has too many dimensions for plotting.')\n else\n error('prt:prtRv:plot','This RV object cannot be plotted. This RV is not yet valid %s.',reasonStr);\n end\n end\n end\n end\n \n methods (Hidden = true)\n % As a default we just use the monte carlo limits.\n % If a sub-class implements plotLimits ezPdfPlot or ezCdfPlot\n % should use that.\n function limits = plotLimits(R)\n limits = monteCarloPlotLimits(R);\n end\n \n function val = isPlottable(R)\n val = ~isempty(R.nDimensions) && R.nDimensions < 4 && R.isValid;\n end\n end\n \n methods (Access = protected, Hidden = true)\n function Obj = trainAction(Obj, DataSet)\n Obj = Obj.mle(DataSet);\n end\n \n function DataSet = runAction(Obj, DataSet)\n DataSet = DataSet.setObservations(Obj.logPdf(DataSet));\n end\n \n function xOut = runActionFast(Obj, xIn, ds) %#ok\n xOut = Obj.logPdf(xIn);\n end\n end\n \n \n methods (Access = 'private', Hidden = true)\n function missingMethodError(R,methodName) %#ok\n error('The method %s is not defined for this prtRv object',methodName);\n end\n end\n methods (Access = 'private',Hidden = true,Static = true)\n function plotOptions = initializePlotOptions()\n if ~isdeployed\n plotOptions = prtOptionsGet('prtOptionsRvPlot');\n else\n plotOptions = prtOptions.prtOptionsRvPlot;\n end\n end\n end\n \n methods (Access = 'protected', Hidden = true)\n function X = dataInputParse(R,X) %#ok\n % dataInputParse - Parse inputs for RVs that only require the\n % data. Since most RVs need only the observations (X). This\n % function allows RVs to operate on prtDataSetStandard()s and \n % a data matrix.\n \n if isnumeric(X) || islogical(X)\n % Quick exit from this ifelse so we don't call isa\n % which can be slow\n elseif isa(X,'prtDataSetStandard')\n X = X.getObservations();\n else\n error('prt:prtRv','Input to mle() must be a matrix of data or a prtDataSet.');\n end\n \n end\n \n function R = constructorInputParse(R,varargin)\n \n nIn = length(varargin);\n\n % Quick Exit for the zero input constructor\n if nIn == 0\n return\n elseif mod(nIn,2)\n error('prt:prtRv:constructorInputParse','Inputs must be supplied by as string/value pairs');\n end\n \n R = prtUtilAssignStringValuePairs(R,varargin{:});\n\n end\n \n \n function val = monteCarloCovariance(R,nSamples)\n % Calculates the sample covariance of drawn data\n if nargin < 2 || isempty(nSamples)\n nSamples = 1e3;\n end\n val = cov(draw(R,nSamples));\n end\n\n function val = monteCarloMean(R,nSamples)\n % Calculates the sample mean of drawn data\n if nargin < 2 || isempty(nSamples)\n nSamples = 1e3;\n end\n val = mean(draw(R,nSamples));\n end\n \n function limits = monteCarloPlotLimits(R,nStds,nSamples)\n % Calculate plotting limits\n if nargin < 2 || isempty(nStds)\n nStds = 2;\n end\n if nargin < 3 || isempty(nSamples)\n nSamples = []; % Let the defaults from monteCarloMean and \n % monteCarloCovariance decide.\n end\n \n mu = monteCarloMean(R,nSamples);\n C = monteCarloCovariance(R,nSamples);\n \n minX = min(mu, [], 1)' - nStds*sqrt(diag(C));\n maxX = max(mu, [], 1)' + nStds*sqrt(diag(C));\n \n limits = zeros(1,2*length(minX));\n limits(1:2:end) = minX;\n limits(2:2:end) = maxX;\n end\n end\n methods (Hidden = true)\n function S = toStructure(obj)\n % toStructure(obj)\n % This default prtRv method adds all properties defined in\n % the class of obj into the structure, that are:\n % GetAccess: public\n % Hidden: false\n % other prtRvs (that are properties, contained in cells,\n % or fields of structures) are also converted to structures.\n \n MetaInfo = meta.class.fromName(class(obj));\n \n propNames = {};\n for iProperty = 1:length(MetaInfo.Properties)\n if isequal(MetaInfo.Properties{iProperty}.DefiningClass,MetaInfo) && strcmpi(MetaInfo.Properties{iProperty}.GetAccess,'public') && ~MetaInfo.Properties{iProperty}.Hidden\n propNames{end+1} = MetaInfo.Properties{iProperty}.Name; %#ok\n end\n end\n \n S.class = 'prtRv';\n S.prtRvType = class(obj);\n for iProp = 1:length(propNames)\n cProp = obj.(propNames{iProp});\n for icProp = 1:length(cProp) % Allow for arrays of objects\n cOut = prtUtilFindPrtActionsAndConvertToStructures(cProp(icProp));\n if icProp == 1\n cVal = repmat(cOut,size(cProp));\n else\n cVal(icProp) = cOut;\n end\n end\n S.(propNames{iProp}) = cVal;\n end\n S.userData = obj.userData;\n end\n end\nend\n\n\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/rv/prtRv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.195694220917307}} {"text": "function [grid, cfg] = ft_prepare_sourcemodel(cfg, vol, sens)\n\n% FT_PREPARE_SOURCEMODEL helps to make a source model that can be\n% used for source reconstruction, beamformer scanning, linear\n% estimation and MEG interpolation.\n%\n% Use as\n% [grid, cfg] = prepare_dipole_grid(cfg)\n% where the configuration structure contains the details on how the source\n% model should be constructed.\n%\n% A source model can be constructed based on\n% - regular 3D grid with explicit specification\n% - regular 3D grid with specification of the resolution\n% - regular 3D grid, based on segmented MRI, restricted to gray matter\n% - surface grid based on brain surface from volume conductor\n% - surface grid based on head surface from external file\n% - using user-supplied grid positions, which can be regular or irregular\n% - cortical sheet that was created in MNE or Freesurfer\n% The approach that will be used depends on the configuration options that\n% you specify.\n%\n% Configuration options for generating a regular 3-D grid\n% cfg.grid.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n% cfg.grid.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n% cfg.grid.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto')\n% cfg.grid.resolution = number (e.g. 1 cm) for automatic grid generation\n%\n% Configuration options for a predefined grid\n% cfg.grid.pos = N*3 matrix with position of each source\n% cfg.grid.dim = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional)\n% cfg.grid.inside = vector with indices of the sources inside the brain (optional)\n% cfg.grid.outside = vector with indices of the sources outside the brain (optional)\n% The following fields are not used in this function, but will be copied along to the output\n% cfg.grid.leadfield\n% cfg.grid.filter or alternatively cfg.grid.avg.filter\n% cfg.grid.subspace\n% cfg.grid.lbex\n%\n% Configuration options for cortex segmentation, i.e. for placing dipoles in grey matter\n% cfg.mri = can be filename, MRI structure or segmented MRI structure\n% cfg.sourceunits = 'mm' or 'cm' (default is 'cm')\n% cfg.mriunits = 'mm' or 'cm' (default is 'mm')\n% cfg.threshold = 0.1, relative to the maximum value in the segmentation\n% cfg.smooth = 5, smoothing in voxels\n%\n% Configuration options for reading a cortical sheet from file\n% cfg.headshape = string, should be a *.fif file\n%\n% Other configuration options\n% cfg.vol = volume conduction model\n% cfg.grad = gradiometer definition\n% cfg.elec = electrode definition\n% cfg.grid.tight = 'yes' or 'no' (default is automatic)\n% cfg.inwardshift = depth of the bounding layer for the source space, relative to the head model surface (default = 0)\n% cfg.symmetry = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = [])\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% See also FT_SOURCEANALYSIS, FT_MEGREALIGN, FT_DIPOLEFITTING, FT_PREPARE_LEADFIELD\n\n% Searching through the code, it seems that the following cfg fields are being used\n% cfg.grid\n% cfg.mri\n% cfg.headshape\n% cfg.tightgrid\n% cfg.symmetry\n% cfg.smooth\n% cfg.threshold\n% cfg.spheremesh\n% cfg.inwardshift\n% cfg.mriunits\n% cfg.sourceunits\n\n% Copyright (C) 2004-2011, Robert Oostenveld\n%\n% %Log$\n\n% set the defaults\nif ~isfield(cfg, 'symmetry'), cfg.symmetry = []; end\nif ~isfield(cfg, 'grid'), cfg.grid = []; end\n\nif ~isfield(cfg, 'vol') && nargin>1\n % put it in the configuration structure\n % this is for backward compatibility, 13 Januari 2011\n cfg.vol = vol;\nend\n\nif ~isfield(cfg, 'sens') && nargin>2\n % put it in the configuration structure\n % this is for backward compatibility, 13 Januari 2011\n cfg.grad = sens;\nend\n\n% for backward compatibility\nif isfield(cfg, 'tightgrid')\n cfg.grid.tight = cfg.tightgrid;\n cfg = rmfield(cfg, 'tightgrid');\nend\n\nif isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'xgrid') && ~ischar(cfg.grid.xgrid)\n error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.xgrid simultaneously');\nend\nif isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'ygrid') && ~ischar(cfg.grid.ygrid)\n error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.ygrid simultaneously');\nend\nif isfield(cfg.grid, 'resolution') && isfield(cfg.grid, 'zgrid') && ~ischar(cfg.grid.zgrid)\n error('You cannot specify cfg.grid.resolution and an explicit cfg.grid.zgrid simultaneously');\nend\n\n% a grid can be constructed based on a number of ways\nbasedonauto = isfield(cfg.grid, 'resolution'); % regular 3D grid with specification of the resolution\nbasedongrid = isfield(cfg.grid, 'xgrid') && ~ischar(cfg.grid.xgrid); % regular 3D grid with explicit specification\nbasedonpos = isfield(cfg.grid, 'pos'); % using user-supplied grid positions, which can be regular or irregular\nbasedonshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape); % surface grid based on inward shifted head surface from external file\nbasedonmri = isfield(cfg, 'mri'); % regular 3D grid, based on segmented MRI, restricted to gray matter\nbasedonvol = false; % surface grid based on inward shifted brain surface from volume conductor\nbasedoncortex = isfield(cfg, 'headshape') && (iscell(cfg.headshape) || ft_filetype(cfg.headshape, 'neuromag_fif') || ft_filetype(cfg.headshape, 'freesurfer_triangle_binary')); % cortical sheet from MNE or Freesurfer, also in case of multiple files/hemispheres\n\nif basedonshape && basedoncortex\n % treating it as cortical sheet has preference\n basedonshape = false;\nend\n\nif basedongrid && basedonpos\n % fall back to default behaviour, in which the pos overrides the grid\n basedongrid = false;\nend\n\nif ~any([basedonauto basedongrid basedonpos basedonshape basedonmri basedoncortex]) && nargin>1 && ~isempty(cfg.vol)\n % fall back to default behaviour, which is to create a surface grid (e.g. used in MEGRELIGN)\n basedonvol = 1;\nend\n\n% these are mutually exclusive, but printing all requested methods here\n% facilitates debugging of weird configs. Also specify the defaults here to\n% keep the overview\nif basedonauto\n fprintf('creating dipole grid based on automatic 3D grid with specified resolution\\n');\n if ~isfield(cfg.grid, 'xgrid'), cfg.grid.xgrid = 'auto'; end\n if ~isfield(cfg.grid, 'ygrid'), cfg.grid.ygrid = 'auto'; end\n if ~isfield(cfg.grid, 'zgrid'), cfg.grid.zgrid = 'auto'; end\n if ~isfield(cfg, 'inwardshift'), cfg.inwardshift = 0; end % in this case for inside detection, % FIXME move to cfg.grid\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'yes'; end\nend\n\nif basedongrid\n fprintf('creating dipole grid based on user specified 3D grid\\n');\n if ~isfield(cfg, 'inwardshift'), cfg.inwardshift = 0; end % in this case for inside detection, % FIXME move to cfg.grid\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'no'; end\nend\n\nif basedonpos\n fprintf('creating dipole grid based on user specified dipole positions\\n');\n if ~isfield(cfg, 'inwardshift'), cfg.inwardshift = 0; end % in this case for inside detection, % FIXME move to cfg.grid\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'no'; end\nend\n\nif basedonshape\n fprintf('creating dipole grid based on inward-shifted head shape\\n');\n if ~isfield(cfg, 'spheremesh'), cfg.spheremesh = 642; end % FIXME move spheremesh to cfg.grid\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'no'; end\nend\n\nif basedoncortex\n if ~isfield(cfg, 'sourceunits'); cfg.sourceunits = 'cm'; end\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'no'; end\nend\n\nif basedonmri\n fprintf('creating dipole grid based on grey matter from segmented MRI\\n');\n if ~isfield(cfg, 'threshold'), cfg.threshold = 0.1; end % relative\n if ~isfield(cfg, 'smooth'); cfg.smooth = 5; end % in voxels\n if ~isfield(cfg, 'sourceunits'); cfg.sourceunits = 'cm'; end\n if ~isfield(cfg, 'mriunits'); cfg.mriunits = 'mm'; end\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'yes'; end\nend\n\nif basedonvol\n fprintf('creating dipole grid based on inward-shifted brain surface from volume conductor model\\n');\n if ~isfield(cfg, 'spheremesh'), cfg.spheremesh = 642; end % FIXME move to cfg.grid\n if ~isfield(cfg.grid, 'tight'), cfg.grid.tight = 'no'; end\nend\n\n% these are mutually exclusive\nif sum([basedonauto basedongrid basedonpos basedonshape basedonmri basedonvol basedoncortex])~=1\n error('incorrect cfg specification for constructing a dipole grid');\nend\n\nneedspm = isfield(cfg, 'smooth') && ~strcmp(cfg.smooth, 'no');\nif needspm\n % check if SPM is in path, do not add any of them to the path yet\n hasspm2 = ft_hastoolbox('SPM2');\n hasspm8 = ft_hastoolbox('SPM8');\n \n if ~hasspm2 && ~hasspm8\n % is neither is on the path, try adding SPM8\n try, hasspm8 = ft_hastoolbox('SPM8', 1); end\n end\n \n if ~hasspm8\n % if SPM8 could not be added, try adding SPM2\n try, ft_hastoolbox('SPM2', 1); end\n end\nend\n\n% start with an empty grid\ngrid = [];\n\n% copy the volume conductor and sensor array out of the cfg\nif isfield(cfg, 'vol')\n vol = cfg.vol;\nelse\n vol = [];\nend\n\n% these are mutually exclusive\nif isfield(cfg, 'grad')\n sens = cfg.grad;\nelseif isfield(cfg, 'elec')\n sens = cfg.elec;\nelse\n sens = [];\nend\n\nif basedonauto\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % construct a regular 3D grid that spans a box encompassing all electrode\n % or gradiometer coils, this will typically also cover the complete brain\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if ischar(cfg.grid.xgrid) && strcmp(cfg.grid.xgrid, 'auto')\n grid.xgrid = floor(min(sens.pnt(:,1))):cfg.grid.resolution:ceil(max(sens.pnt(:,1)));\n end\n if ischar(cfg.grid.ygrid) && strcmp(cfg.grid.ygrid, 'auto')\n grid.ygrid = floor(min(sens.pnt(:,2))):cfg.grid.resolution:ceil(max(sens.pnt(:,2)));\n end\n if ischar(cfg.grid.zgrid) && strcmp(cfg.grid.zgrid, 'auto')\n grid.zgrid = floor(min(sens.pnt(:,3))):cfg.grid.resolution:ceil(max(sens.pnt(:,3)));\n end\n grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\n [X, Y, Z] = ndgrid(grid.xgrid, grid.ygrid, grid.zgrid);\n grid.pos = [X(:) Y(:) Z(:)];\nend\n\nif basedongrid\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % a detailled xgrid/ygrid/zgrid has been specified, the other details\n % still need to be determined\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n grid.xgrid = cfg.grid.xgrid;\n grid.ygrid = cfg.grid.ygrid;\n grid.zgrid = cfg.grid.zgrid;\n grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\n [X, Y, Z] = ndgrid(grid.xgrid, grid.ygrid, grid.zgrid);\n grid.pos = [X(:) Y(:) Z(:)];\nend\n\nif basedonpos\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % a grid is already specified in the configuration, reuse as much of the\n % prespecified grid as possible (but only known objects)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if isfield(cfg.grid, 'pos')\n grid.pos = cfg.grid.pos;\n end\n if isfield(cfg.grid, 'mom')\n grid.mom = cfg.grid.mom;\n end\n if isfield(cfg.grid, 'dim')\n grid.dim = cfg.grid.dim;\n end\n if isfield(cfg.grid, 'xgrid')\n % FIXME is it desirable to have this in the grid?\n grid.xgrid = cfg.grid.xgrid;\n end\n if isfield(cfg.grid, 'ygrid')\n % FIXME is it desirable to have this in the grid?\n grid.ygrid = cfg.grid.ygrid;\n end\n if isfield(cfg.grid, 'zgrid')\n % FIXME is it desirable to have this in the grid?\n grid.zgrid = cfg.grid.zgrid;\n end\n if isfield(cfg.grid, 'dim')\n grid.dim = cfg.grid.dim;\n elseif isfield(grid, 'xgrid') && isfield(grid, 'ygrid') && isfield(grid, 'zgrid')\n grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\n end\n if isfield(cfg.grid, 'inside')\n grid.inside = cfg.grid.inside;\n end\n if isfield(cfg.grid, 'outside')\n grid.outside = cfg.grid.outside;\n end\n if isfield(cfg.grid, 'lbex')\n grid.lbex = cfg.grid.lbex;\n end\n if isfield(cfg.grid, 'subspace')\n grid.subspace = cfg.grid.subspace;\n end\n if isfield(cfg.grid, 'leadfield')\n grid.leadfield = cfg.grid.leadfield;\n end\n if isfield(cfg.grid, 'filter')\n grid.filter = cfg.grid.filter;\n end\n if isfield(cfg.grid, 'tight')\n grid.tight = cfg.grid.tight;\n end\n % this is not supported any more\n if isfield(cfg.grid, 'avg') && isfield(cfg.grid.avg, 'filter')\n error('please put your filters in cfg.grid instead of cfg.grid.avg');\n end\nend\n\nif basedonmri\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % construct a grid based on the segmented MRI that is provided in the\n % configuration, only voxels in gray matter will be used\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % convert the source/functional data into the same units as the anatomical MRI\n scale = 1;\n switch cfg.sourceunits\n case 'mm'\n scale = scale / 1000;\n case 'cm'\n scale = scale / 100;\n case 'dm'\n scale = scale / 10;\n case 'm'\n scale = scale / 1;\n otherwise\n error('unknown physical dimension in cfg.sourceunits');\n end\n switch cfg.mriunits\n case 'mm'\n scale = scale * 1000;\n case 'cm'\n scale = scale * 100;\n case 'dm'\n scale = scale * 10;\n case 'm'\n scale = scale * 1;\n otherwise\n error('unknown physical dimension in cfg.mriunits');\n end\n \n if ~isfield(cfg.grid, 'resolution')\n switch cfg.sourceunits\n case 'mm'\n cfg.grid.resolution = 10;\n case 'cm'\n cfg.grid.resolution = 1;\n case 'dm'\n cfg.grid.resolution = 0.1;\n case 'm'\n cfg.grid.resolution = 0.01;\n end\n end\n \n if ischar(cfg.mri)\n % read the segmentation from file\n mri = ft_read_mri(cfg.mri);\n mri.gray = double(mri.anatomy);\n elseif isstruct(cfg.mri) && ~isfield(cfg.mri, 'gray')\n % looks like a segmentation that has already been loaded in memory\n mri = cfg.mri;\n mri.gray = double(mri.anatomy);\n elseif isstruct(cfg.mri) && isfield(cfg.mri, 'gray')\n % looks like a complete segmentation from VOLUMESEGMENT\n mri = cfg.mri;\n mri.gray = double(mri.gray);\n else\n error('cannot determine the format of the segmentation in cfg.mri');\n end\n \n % apply a smoothing of a certain amount of voxels\n if ~strcmp(cfg.smooth, 'no');\n fprintf('smoothing gray matter segmentation with %d voxels\\n', cfg.smooth);\n spm_smooth(mri.gray, mri.gray, cfg.smooth);\n end\n \n % determine for each voxel whether it belongs to the cortex\n if isfield(cfg, 'threshold')\n fprintf('thresholding gray matter segmentation at a relative value of %f\\n', cfg.threshold);\n head = mri.gray./max(mri.gray(:)) > cfg.threshold;\n else\n error('you must specify cfg.threshold for cortex segmentation');\n end\n \n ind = find(head(:));\n fprintf('%d from %d voxels in the segmentation are marked as cortex (%.0f%%)\\n', length(ind), prod(size(head)), 100*length(ind)/prod(size(head)));\n [X,Y,Z] = ndgrid(1:mri.dim(1), 1:mri.dim(2), 1:mri.dim(3)); % create the grid in MRI-coordinates\n posmri = [X(ind) Y(ind) Z(ind) ones(length(ind),1)]; % take only the inside voxels\n poshead = mri.transform * posmri'; % transform to head coordinates\n poshead = poshead(1:3,:)';\n posmri = posmri(:,1:3);\n resolution = cfg.grid.resolution*scale; % source and mri can be expressed in different units (e.g. cm and mm)\n xgrid = floor(min(poshead(:,1))):resolution:ceil(max(poshead(:,1))); % create the grid in head-coordinates\n ygrid = floor(min(poshead(:,2))):resolution:ceil(max(poshead(:,2))); % with 'consistent' x,y,z definitions\n zgrid = floor(min(poshead(:,3))):resolution:ceil(max(poshead(:,3)));\n [X,Y,Z] = ndgrid(xgrid,ygrid,zgrid);\n pos2head = [X(:) Y(:) Z(:) ones(length(X(:)),1)]';\n pos2mri = mri.transform \\ pos2head; % transform to MRI-coordinates\n pos2mri = round(pos2mri(1:3,:))';\n pos2head = pos2head(1:3,:)';\n pos2mri = pos2mri(:,1:3);\n % it might be that the box with the points does not completely fit into the MRI\n sel = find(pos2mri(:,1)<1 | pos2mri(:,1)>size(head,1) | ...\n pos2mri(:,2)<1 | pos2mri(:,2)>size(head,2) | ...\n pos2mri(:,3)<1 | pos2mri(:,3)>size(head,3));\n if isempty(sel)\n % use the efficient implementation\n inside = head(sub2ind(mri.dim, pos2mri(:,1), pos2mri(:,2), pos2mri(:,3)));\n else\n % only loop over the points that can be dealt with\n inside = zeros(length(xgrid)*length(ygrid)*length(zgrid), 1);\n for i=setdiff(1:size(pos2mri,1), sel(:)')\n inside(i) = head(pos2mri(i,1), pos2mri(i,2), pos2mri(i,3));\n end\n end\n inside = find(inside);\n \n grid.pos = pos2head/scale; % convert to source units\n grid.xgrid = xgrid/scale; % convert to source units\n grid.ygrid = ygrid/scale; % convert to source units\n grid.zgrid = zgrid/scale; % convert to source units\n grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\n grid.inside = inside(:);\n grid.outside = setdiff(1:size(grid.pos,1),grid.inside)';\n \n fprintf('the regular 3D grid encompassing the cortex contains %d grid points\\n', size(grid.pos,1));\n fprintf('%d grid points inside gray matter\\n', length(grid.inside));\n fprintf('%d grid points outside gray matter\\n', length(grid.outside));\nend\n\nif basedoncortex\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % read it from a *.fif file that was created using Freesurfer and MNE\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if iscell(cfg.headshape)\n % FIXME loop over all files, this should be two hemispheres\n keyboard\n end\n switch ft_filetype(cfg.headshape)\n case 'freesurfer_triangle_binary'\n % it contains a cortical sheet which was created by the Freesurfer software\n shape = ft_read_headshape(cfg.headshape, 'format', 'freesurfer_triangle_binary');\n case 'neuromag_fif'\n % fif files can contain a variety of objects\n % here we assume that it contains a cortical sheet which was created by the MNE software\n shape = ft_read_headshape(cfg.headshape, 'format', 'mne_source');\n otherwise\n % use autodetection\n shape = ft_read_headshape(cfg.headshape);\n end\n grid.pos = shape.pnt;\n grid.tri = shape.tri;\n grid = ft_convert_units(grid, cfg.sourceunits);\nend\n\nif basedonshape\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % use the headshape to make a superficial dipole layer (e.g.\n % for megrealign). Assume that all points are inside the volume.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % get the surface describing the head shape\n if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')\n % use the headshape surface specified in the configuration\n headshape = cfg.headshape;\n elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3\n % use the headshape points specified in the configuration\n headshape.pnt = cfg.headshape;\n elseif ischar(cfg.headshape)\n % read the headshape from file\n headshape = ft_read_headshape(cfg.headshape);\n else\n error('cfg.headshape is not specified correctly')\n end\n if ~isfield(headshape, 'tri')\n % generate a closed triangulation from the surface points\n headshape.pnt = unique(headshape.pnt, 'rows');\n headshape.tri = projecttri(headshape.pnt);\n end\n grid.pos = headsurface([], [], 'headshape', headshape, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);\n grid.inside = 1:size(grid.pos,1);\n grid.outside = [];\nend\n\nif basedonvol\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % use the volume conduction model to make a superficial dipole layer (e.g.\n % for megrealign). Assume that all points are inside the volume.\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n grid.pos = headsurface(vol, sens, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);\n grid.inside = 1:size(grid.pos,1);\n grid.outside = [];\nend\n\n% FIXME use inside_vol instead of this replication of code\n% determine the dipole locations inside the brain volume\nif ~isfield(grid, 'inside') && ~isfield(grid, 'outside')\n if ft_voltype(vol, 'infinite') || ft_voltype(vol, 'halfspace')\n % an empty vol in combination with gradiometers indicates a magnetic dipole\n % in an infinite vacuum, i.e. all dipoles can be considered to be inside\n grid.inside = 1:size(grid.pos,1);\n grid.outside = [];\n outside = zeros(1,size(grid.pos,1));\n for i =1:size(grid.pos,1);\n invacuum = false;\n dip1 = grid.pos(i,:);\n % condition of dipoles falling in the non conductive halfspace\n invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2;\n if invacuum\n outside(i) = 1;\n end\n end\n grid.outside = find(outside);\n grid.inside = find(~outside);\n else\n if isfield(sens, 'ori') && isfield(sens, 'pnt') && isfield(sens, 'tra')\n % in case of MEG, make a triangulation of the outermost surface\n if isfield(cfg, 'headshape')\n % use the specified headshape to construct the bounding triangulation\n [pnt, tri] = headsurface(vol, sens, 'headshape', cfg.headshape, 'inwardshift', cfg.inwardshift, 'surface', 'skin');\n else\n % use the volume conductor model to construct the bounding triangulation\n [pnt, tri] = headsurface(vol, sens, 'inwardshift', cfg.inwardshift, 'surface', 'skin');\n end\n else\n % in case of EEG, make a triangulation of the innermost surface\n [pnt, tri] = headsurface(vol, sens, 'inwardshift', cfg.inwardshift, 'surface', 'brain');\n end\n % determine the dipole positions that are inside the triangulated surface\n tmp = bounding_mesh(grid.pos, pnt, tri);\n grid.inside = find(tmp==1);\n grid.outside = find(tmp==0);\n end\nelseif ~isfield(grid, 'inside')\n grid.inside = setdiff(1:size(grid.pos,1), grid.outside);\nelseif ~isfield(grid, 'outside')\n grid.outside = setdiff(1:size(grid.pos,1), grid.inside);\nend\n\nif strcmp(cfg.grid.tight, 'yes')\n fprintf('%d dipoles inside, %d dipoles outside brain\\n', length(grid.inside), length(grid.outside));\n fprintf('making tight grid\\n');\n xmin = min(grid.pos(grid.inside,1));\n ymin = min(grid.pos(grid.inside,2));\n zmin = min(grid.pos(grid.inside,3));\n xmax = max(grid.pos(grid.inside,1));\n ymax = max(grid.pos(grid.inside,2));\n zmax = max(grid.pos(grid.inside,3));\n xmin_indx = find(grid.xgrid==xmin);\n ymin_indx = find(grid.ygrid==ymin);\n zmin_indx = find(grid.zgrid==zmin);\n xmax_indx = find(grid.xgrid==xmax);\n ymax_indx = find(grid.ygrid==ymax);\n zmax_indx = find(grid.zgrid==zmax);\n sel = (grid.pos(:,1)>=xmin & grid.pos(:,1)<=xmax); % select all grid positions inside the tight box\n sel = sel & (grid.pos(:,2)>=ymin & grid.pos(:,2)<=ymax); % select all grid positions inside the tight box\n sel = sel & (grid.pos(:,3)>=zmin & grid.pos(:,3)<=zmax); % select all grid positions inside the tight box\n grid.pos = grid.pos(sel,:);\n % update the inside and outside vector\n tmp = zeros(1,prod(grid.dim));\n tmp(grid.inside) = 1; % these are originally inside the brain\n tmp(grid.outside) = 0; % these are originally outside the brain\n tmp = tmp(sel); % within the tight box, these are inside the brain\n grid.inside = find(tmp);\n grid.outside = find(~tmp);\n grid.xgrid = grid.xgrid(xmin_indx:xmax_indx);\n grid.ygrid = grid.ygrid(ymin_indx:ymax_indx);\n grid.zgrid = grid.zgrid(zmin_indx:zmax_indx);\n grid.dim = [length(grid.xgrid) length(grid.ygrid) length(grid.zgrid)];\nend\nfprintf('%d dipoles inside, %d dipoles outside brain\\n', length(grid.inside), length(grid.outside));\n\n% apply the symmetry constraint, i.e. add a symmetric dipole for each location defined sofar\n% set up the symmetry constraints\nif ~isempty(cfg.symmetry)\n if strcmp(cfg.symmetry, 'x')\n reduce = [1 2 3]; % select the parameters [x1 y1 z1]\n expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1]\n mirror = [1 1 1 -1 1 1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 -x1 y\n elseif strcmp(cfg.symmetry, 'y')\n reduce = [1 2 3]; % select the parameters [x1 y1 z1]\n expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1]\n mirror = [1 1 1 1 -1 1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 -y\n elseif strcmp(cfg.symmetry, 'z')\n reduce = [1 2 3]; % select the parameters [x1 y1 z1]\n expand = [1 2 3 1 2 3]; % repeat them as [x1 y1 z1 x1 y1 z1]\n mirror = [1 1 1 1 1 -1]; % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 y1\n else\n error('unrecognized symmetry constraint');\n end\n fprintf('each source describes two dipoles with symmetry along %s axis\\n', cfg.symmetry);\n % expand the number of parameters from one (3) to two dipoles (6)\n grid.pos = grid.pos(:,expand) .* repmat(mirror, size(grid.pos,1), 1);\nend\n\n% FIXME should the cfg be added to the output grid?\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fieldtrip_partial/ft_prepare_sourcemodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.195667429192124}} {"text": "function [sDataPET] = correctPatient24_HN(pathDATA)\n% -------------------------------------------------------------------------\n% function [sDataPET] = correctPatient24_HN(pathDATA)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% Reason of existence of the function: the RTstruct of the PET scan of\n% patient 24 is incomplete (most probably it was previously incorrectly \n% processed by MIM). The problem is solved by copying and processing the \n% 'contour' structure of the CT scan.\n% -------------------------------------------------------------------------\n% INPUTS:\n% - pathDATA: Full path to the 'DATA' folder of the HN workspace.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - sData: Corrected sData.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: July 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ncd(pathDATA)\nload('Patient24_CT'), sDataCT = sData;\nload('Patient24_PET'), sDataPET = sData;\n\n% ADJUSTING PET CONTOURS ACCORDING TO CT CONTOURS.\nsDataPET{2}.scan.contour = sDataCT{2}.scan.contour;\nnContour = length(sDataPET{2}.scan.contour);\ndownF = sDataPET{2}.scan.pixelW/sDataCT{2}.scan.pixelW;\noffsetStart = round(abs(sDataPET{3}(1).ImagePositionPatient(2)-sDataCT{3}(1).ImagePositionPatient(2))*sDataCT{2}.scan.pixelW);\noffsetEnd = round((size(sDataCT{2}.scan.volume,1)*sDataCT{2}.scan.pixelW - size(sDataPET{2}.scan.volume,1)*sDataPET{2}.scan.pixelW)/sDataCT{2}.scan.pixelW)-offsetStart;\nfor i = 1:nContour\n sDataPET{2}.scan.contour(i).boxBound(1:2,1) = round((sDataCT{2}.scan.contour(i).boxBound(1:2,1) - offsetStart)/downF); sDataPET{2}.scan.contour(i).boxBound(1:2,2) = round((sDataCT{2}.scan.contour(i).boxBound(1:2,2) - offsetEnd)/downF);\n boxBound = sDataPET{2}.scan.contour(i).boxBound;\n nSlices = size(sDataPET{2}.scan.contour(i).boxMask,3);\n sDataPET{2}.scan.contour(i).boxMask = zeros(boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1,nSlices);\n for j = 1:nSlices\n sDataPET{2}.scan.contour(i).boxMask(:,:,j) = imresize(sDataCT{2}.scan.contour(i).boxMask(:,:,j),[boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1],'nearest');\n end\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/READ_DATA/Archives/correctPatient24_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.195634311401413}} {"text": "%GUI script for reading ctf data into eeglab.\n%to run type ctf2eeglab on the command line.\n\nclear all;\nfolder = uigetdir('*.ds','Data Set Finder');\n[ctf2] = ctf_read_res4(folder,1);\nsensors = {'meg','eeg','ref','vc'};\nsensloc = 'ctf2.sensor.index';\nsensorlen = '1:';\nnum2str(length(ctf2.sensor.index.meg_sens));\n\nk = menu('Choose the channels you would like to use:','MEG','EEG','Reference','Virtual');\nsensloc = strcat(sensloc,sensors(k));\nsensorlen = strcat(sensorlen, num2str(length(eval(sensloc{1})))); \nprompt = {'Enter Sensor Numbers to Read (ie 2:7 or 1 3 7 23 65)'};\ntitle = 'Input for Sensor Range (Default is all sensors)';\nlines = 1;\ndef = {sensorlen};\nsensnum = inputdlg(prompt,title,lines,def);\nfor i = str2num(sensnum{1});\n if ~ismember(str2num(def{1}),i)\n errordlg('There is no such sensor','Sensor Range Error')\n exit(1);\n end\nend\n\ntrialnums = '1:';\ntrialnums = strcat(trialnums, num2str(ctf2.setup.number_trials));\nprompt2 = {'Enter the trials you would like to use(ie 1:3 or 2 4 5):'};\ndef2 = {trialnums};\ntrials = inputdlg(prompt2, 'Input for trial range', 1,def2);\nfor i = str2num(trials{1})\n if ~ismember(str2num(def2{1}),i)\n errordlg('Trial not in dataset','Trial Error')\n exit(1);\n end\nend\nbutton = questdlg('Would you like to use markers?','Use Markers?','Yes','No','Yes');\nif strcmp(button,'Yes')\n [marker_info] = readmarkerfile(folder);\n markers = marker_info.marker_names;\n m = menu('Please choose which marker you would like to use', markers);\nend\nprompt = {'Enter the start time (sec):', 'Enter the end time:'};\ntitle = 'Time Window';\nlines = 1;\ndef = {'0', '.15'};\ndef(1) = {num2str(ctf2.setup.start_sec)};\ndef(2) = {num2str(ctf2.setup.end_sec)};\nmarkeranswer = inputdlg(prompt,title,lines,def);\nwind = [0 0];\nwind(1) = str2num(markeranswer{1});\nwind(2) = str2num(markeranswer{2});\n\nif strcmp(button,'Yes')\n [data]=readepochs(folder,'marker_info',marker_info,'ctf',ctf2,sensors{k}, str2num(sensnum{1}),'trials',str2num(trials{1}), 'markers',markers(m),'window', wind);\nelse\n [data]=readepochs(folder,'ctf',ctf2,sensors{k}, str2num(sensnum{1}),'trials',str2num(trials{1}), 'window', wind);\nend\n\n\n%wind = [-.1 .15];\n%[data]=readepochs(folder,'markers',{'click'},'window',wind);\n%[data]=readepochs(folder,'window',wind,'trials',[1:10],'megsens',[2:7]);\n\ndat=permute(data.epochs{1},[2,1,3]);\nsize(dat)\n[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;\n\nEEG = pop_importdata( 'nbchan', size(dat,1), 'dataformat', 'array', 'data', 'dat', 'pnts', size(dat,2), 'srate', data.setup.sample_rate, 'xmin', wind(1));\n[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, CURRENTSET, 'setname',data.setup.subject);\neeglab redraw;\n\nfor i=1:size(dat,1)\n if ~isempty(data.sensor.location)\n EEG.chanlocs(i).labels=char(data.sensor.label(i));\n EEG.chanlocs(i).X=data.sensor.location(1,i);\n EEG.chanlocs(i).Y=data.sensor.location(2,i);\n EEG.chanlocs(i).Z=data.sensor.location(3,i);\n end\nend\nEEG.chanlocs=pop_chanedit(EEG.chanlocs, 'convert', 'cart2topo', 'convert', 'cart2sph');\n[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);\neeglab redraw;\nclear dat data ctf2 marker_info markers sensors;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ctfimport1.03/ctf2eeglab_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.1956343097397451}} {"text": "function val = viewGetVolume(vw,param,varargin)\n% Get data from various view structures\n%\n% This function is wrapped by viewGet. It should not be called by anything\n% else other than viewGet.\n%\n% This function retrieves information from the view that relates to a\n% specific component of the application.\n%\n% We assume that input comes to us already fixed and does not need to be\n% formatted again.\n\nif notDefined('vw'), vw = getCurView; end\nif notDefined('param'), error('No parameter defined'); end\n\nmrGlobals;\nval = [];\n\n\nswitch param\n \n case 'nodes'\n % Return the array of nodes. Only gray views have nodes. See help\n % for mrManDist.m for a description of the node structure. In\n % brief, nodes are 8 x nvoxels. The first 3 rows correspond to the\n % voxel location and the next 5 correspond to gray graph-related\n % data.\n % nodes = viewGet(vw, 'nodes');\n if isfield(vw, 'nodes'), val = vw.nodes;\n else\n val = [];\n warning('vista:viewError', 'Nodes not found.');\n end\n case 'xyznodes'\n % Return the xyz coordinates of the gray voxels as found in nodes\n % array. Assumes a Gray view. See case 'nodes' and help for\n % mrManDist for more information.\n %\n % Must call this sagittal, axial coronal or whatever the mapping is\n % ras, 06/07 -- I believe it's [cor axi sag]. coords is [axi cor sag].\n %\n % xyzNodes = viewGet(vw, 'xyz nodes');\n nodes = viewGet(vw,'nodes');\n val = nodes(1:3,:);\n case 'nodegraylevel'\n % Return the gray level of each voxel as determined by the nodes\n % array. Assumes a Gray view. See case 'nodes' and help for\n % mrManDist for more information.\n % nodeGrayLevel = viewGet(vw, 'gray level');\n nodes = viewGet(vw,'nodes');\n val = nodes(6,:);\n case 'nnodes'\n % Return the number of nodes. Assumes a Gray view. See case 'nodes'\n % and help for mrManDist for more information.\n % nNodes = viewGet(vw, 'number of nodes');\n val = size( viewGet(vw, 'nodes'), 2 );\n case 'edges'\n % Return the edge structure of the gray graph. Assumes a Gray view.\n % See help for mrManDist for more information.\n % edges = viewGet(vw, 'edges');\n if isfield(vw, 'edges'), val = vw.edges;\n else val = []; warning('vista:viewError', 'Edges not found.'); end\n case 'nedges'\n % Return the number of edges in the gray graph. Assumes a Gray\n % view. See case 'edges' and help for mrManDist for more\n % information.\n % nEdges = viewGet(vw, 'number of edges');\n val = length( viewGet(vw, 'edges') );\n case 'allleftnodes'\n % Return the subset of nodes in the Gray graph that are in the left\n % hemisphere. See mrgGrowGray and mrManDist.\n % allLeftNodes = viewGet(vw, 'all left nodes');\n val = vw.allLeftNodes;\n case 'allleftedges'\n % Return the subset of edges in the Gray graph that are in the left\n % hemisphere. See mrgGrowGray and mrManDist.\n % allLeftEdges = viewGet(vw, 'all left edges');\n val = vw.allLeftEdges;\n if isempty(val) && Check4File('Gray/coords')\n % Try laoding from the Gray/coords file\n load('Gray/coords', 'allLeftEdges')\n val = allLeftEdges;\n end\n case 'allrightnodes'\n % Return the subset of nodes in the Gray graph that are in the\n % right hemisphere. See mrgGrowGray and mrManDist.\n % allRightNodes = viewGet(vw, 'all right nodes');\n val = vw.allRightNodes;\n if isempty(val) && Check4File('Gray/coords')\n % Try laoding from the Gray/coords file\n load('Gray/coords', 'allRightNodes')\n val = allRightNodes;\n end\n \n case 'allrightedges'\n % Return the subset of edges in the Gray graph that are in the\n % right hemisphere. See mrgGrowGray and mrManDist.\n % allRightEdges = viewGet(vw, 'all right edges');\n val = vw.allRightEdges;\n \n case 'allnodes'\n % Return all nodes from Gray graph by taking union of allLeftNodes\n % and allRightNodes.\n %\n % This is NOT necessarily the same as simply returning 'vw.nodes'.\n % When we install a segmentation, we can either keep all the nodes\n % in the gray graph, or only those that fall within the functional\n % field of view (to save space). When we do the latter, the fields\n % vw.coords, vw.nodes, and vw.edges contain only the coords, nodes,\n % and eges within the functional field of view. However the fields\n % vw.allLeftNodes, vw.allLeftEdges, vw.allRightNodes, and\n % vw.allRightEdges contain the edges and nodes for the entire\n % hemisphere\n %\n % Example: nodes = viewGet(vw, 'all nodes');\n val = [vw.allLeftNodes'; vw.allRightNodes']';\n \n \n case 'alledges'\n % Return all edges from Gray graph by taking union of allLeftEdges\n % and allRightEdges. See 'allnodes' for explanation.\n %\n % Example: edges = viewGet(vw, 'all edges');\n val = [vw.allLeftEdges vw.allRightEdges];\n \n case 'coords'\n % Return all the coordinates in the current view. If in Flat view,\n % return the coordinates for a particular slice (slice specified in\n % varargin{1}). If in Inplane view, slice specification is\n % optional. If in Gray or Volume view, slice specification is\n % ignored.\n % \n % coords = viewGet(vw, 'coords');\n % \n % slice = viewGet(vw, 'current slice');\n % coords = viewGet(vw,'coords', slice);\n try\n switch lower(viewGet(vw, 'viewType'))\n case 'flat'\n %% separate coords for each flat hemisphere\n if length(varargin) ~= 1\n error('You must specify which hemisphere.');\n end\n hname = varargin{1};\n switch hname\n case 'left'\n val = vw.coords{1};\n case 'right'\n val = vw.coords{2};\n otherwise\n error('Bad hemisphere name');\n end\n case {'gray', 'volume', 'hiddengray'}\n val = vw.coords;\n case 'inplane'\n % These coords are for inplane anat. Functional coords\n % may have different values (if\n % upSampleFactor(vw,scan) ~= 1)\n dims = viewGet(vw, 'anatomysize');\n if length(varargin) >= 1 % then we want coords for just one slice\n slice = varargin{1};\n indices = 1+prod([dims(1:2) slice-1]):prod([dims(1:2) slice]);\n val=indices2Coords(indices,dims);\n else\n indices = 1:prod(dims);\n val=indices2Coords(indices,dims);\n end\n end\n catch ME\n val=[];\n warning(ME.identifier, ME.message);\n fprintf('[%s]: Coords not found.', mfilename);\n end\n \n case 'allcoords'\n % Return all coords from Gray graph, including those that are not\n % included in the functional field of view. See 'allnodes' for\n % explanation. If session was initialized with the option\n % 'keepAllNodes' == true, then this call will be identical to\n % viewGet(vw.coords). \n %\n % Optional input: hemi ('right' 'left' 'both') for right, left or both\n %\n % Example: coords = viewGet(vw, 'allcoords', 'right');\n nodes = viewGet(vw, 'nodes');\n \n if length(varargin) ~= 1\n hname = 'both';\n else\n hname = varargin{1};\n end\n \n switch hname\n case 'left'\n subnodes = viewGet(vw, 'all left nodes');\n [~, ia] = intersectCols(nodes(1:3,:), subnodes(1:3,:));\n case 'right'\n subnodes = viewGet(vw, 'all right nodes');\n [~, ia] = intersectCols(nodes(1:3,:), subnodes(1:3,:));\n otherwise\n ia = 1:size(nodes,2);\n end\n \n val = nodes([2 1 3], ia);\n \n case 'coordsfilename'\n % Return the path to the file in which coordinates are stored.\n % Assumes that a gray view has been created (though current view\n % can be any type).\n % coordsFileName = viewGet(vw, 'coords file name');\n homeDir = viewGet(vw, 'homedir');\n if isempty(homeDir), val = ['Gray' filesep 'coords.mat'];\n else val = [homeDir filesep 'Gray' filesep 'coords.mat'];\n end\n case 'ncoords'\n % Return the number of coordinates in the current view. See case\n % 'coords'.\n % nCoords = viewGet(vw, 'number of coords');\n val = size( viewGet(vw, 'Coords'), 2 );\n \n case 'classfilename'\n % Return the path to either the left or the right gray/white\n % classification file.\n % fname = viewGet(vw, 'class file name', 'left');\n % fname = viewGet(vw, 'class file name', 'right');\n if (length(varargin) == 1), hemisphere = varargin{1};\n else hemisphere = 'left';\n end\n switch lower(hemisphere)\n case {'left' 'l'}\n if ~checkfields(vw,'leftClassFile') || isempty(vw.leftClassFile);\n [~,val] = GetClassFile(vw, 0, 1);\n else\n val = vw.leftClassFile;\n end\n case {'right' 'r'}\n if ~checkfields(vw,'rightClassFile') || isempty(vw.rightClassFile)\n [~,val] = GetClassFile(vw, 1, 1);\n else\n val = vw.rightClassFile;\n end\n otherwise\n error('Unknown hemisphere');\n end\n \n case {'classdata','class','classification','whitematter'}\n % classFileRight = viewGet(vw,'class data','right');\n if length(varargin) == 1, hemisphere = varargin{1};\n else error('You must specify right/left hemisphere.');\n end\n switch lower(hemisphere)\n case 'left'\n val = GetClassFile(vw, 0);\n case 'right'\n val = GetClassFile(vw, 1);\n otherwise\n error('Unknown hemisphere');\n end\n \n case {'graymatterfilename','graypath','grayfilename','grayfile'}\n % grayFile = viewGet(vw,'Gray matter filename','right');\n if length(varargin) == 1, hemisphere = varargin{1};\n else error('You must specify right/left hemisphere.');\n end\n switch lower(hemisphere)\n case 'left'\n if checkfields(vw,'leftPath')\n val = vw.leftPath;\n end\n case 'right'\n if checkfields(vw,'rightPath')\n val = vw.rightPath;\n end\n otherwise\n error('Unknown hemisphere');\n end\n \n otherwise\n error('Unknown viewGet parameter');\n \nend\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/GetSet/View/viewGetVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}} {"text": "function hFit = dfaddparamfit(hFit, fitname, distname, dsname, fitframe, exclname, useestimated, fixedvals)\n%DFADDPARAMFIT Add parametric fit in dfittool\n\n% $Revision: 1.1.6.10 $ $Date: 2004/01/24 09:35:10 $\n% Copyright 2003-2004 The MathWorks, Inc.\n\nbadfit = false; % badfit=true means fit failed or not attempted\ncovok = true; % covariance calculation can be done\nif isempty(hFit)\n newfit = true;\n hFit = stats.dffit(fitname, fitframe);\nelse\n newfit = false;\nend\nlisteners = hFit.listeners;\nset(listeners, 'Enabled', 'off');\n\nframeContents = fitframe.getContentPane;\ncomponentsVector = get(frameContents,'Components');\nfittingPanel = componentsVector(1);\n\n% Get data set to fit\nds=find(getdsdb,'name',dsname);\nhFit.distname = distname;\nhFit.dataset = dsname;\nhFit.fittype = 'param'; \nhFit.dshandle = ds;\n\n% Store some GUI values in fit\nhFit.pfixedtext = fixedvals;\nhFit.pestimated = useestimated;\n\n% Extract data from this data set\nalpha = 0.05;\nhExcl = dfgetexclusionrule(exclname);\n[x, cens, freq] = getincludeddata(ds,hExcl);\n\n% Get information about the requested distribution\ndist = dfgetdistributions(distname);\nif length(dist)~=1 || isempty(x)\n if length(dist)~=1\n emsg = 'Bad distribution name.';\n else\n emsg = 'No data remaining after exclusion rule applied.';\n end\n wmsg = '';\n badfit = true;\nend\nif length(dist)==1\n hFit.enablebounds = dist.hasconfbounds;\nend\n\n% Perform the fit\nlasterr('');\nlastwarn('');\nws = warning('off');\nif badfit\n p = [];\nelse\n try\n nparams = length(dist.pnames);\n if dist.censoring\n censargs = {cens freq};\n else\n if ~isempty(cens) && any(cens)\n error('stats:dfaddparamfit:NoCensoring',...\n 'Censoring not allowed with the %s distribution', distname);\n elseif ~isempty(freq) && any(freq~=1)\n x = expandInput(x,freq);\n freq = [];\n end\n censargs = {};\n end\n \n % How many output variables will this return?\n if dist.paramvec\n nparamvars = 1;\n else\n nparamvars = nparams;\n end\n \n fixedparams = cell(0,1);\n if any(~useestimated)\n for j=1:nparams\n if ~useestimated(j)\n txt = deblank(fixedvals{j});\n if isempty(txt)\n error('stats:dfaddparamfit:BadParam',...\n 'Invalid value for parameter %s', dist.pnames{j});\n end\n num = str2double(txt);\n if ~isfinite(num)\n error('stats:dfaddparamfit:BadParam',...\n 'Invalid value for parameter %s', dist.pnames{j});\n end\n fixedparams{length(fixedparams)+1} = num;\n end\n end\n end\n \n % Set up a cell array to receive outputs, then do the fit\n pcell = cell(nparamvars,1);\n [pcell{:}] = feval(dist.fitfunc, x, fixedparams{:}, alpha, censargs{:});\n\n % Extract results into a single vector\n if dist.paramvec\n p = pcell{1};\n else\n p = [pcell{:}];\n end\n catch\n p = [];\n end\nend\nwarning(ws);\n\nif ~badfit\n if ~isempty(lastwarn)\n wmsg = sprintf('Warning: %s',lastwarn);\n else\n wmsg = '';\n end\n emsg = lasterr;\n newmsg = '';\n if any(~isfinite(p))\n newmsg = 'Fit produced infinite parameter estimates.';\n elseif numel(p)~=numel(dist.pnames) || ~isnumeric(p)\n newmsg = 'Fit function returned bad parameter values';\n end\n if ~isempty(newmsg)\n badfit = true;\n emsg = combinemsg(emsg,newmsg);\n end\n\n % Any type of failure so far makes the covariance calculation questionable\n if ~isempty(wmsg) || ~isempty(emsg)\n covok = false;\n end\nend\n\n% Try to get a likelihood value\nif isempty(p)\n pcov = [];\n nlogl = NaN;\nelse\n try\n if ~isempty(dist.likefunc)\n if covok\n [nlogl,pcov] = feval(dist.likefunc, p, x, censargs{:});\n else\n nlogl = feval(dist.likefunc, p, x, censargs{:});\n pcov = [];\n end\n else\n pcov = [];\n nlogl = localnlogl(num2cell(p),dist.pdffunc,dist.cdffunc,x,cens,freq);\n end\n newmsg = '';\n catch\n newmsg = lasterr;\n end\n if isempty(newmsg) && (~isnumeric(nlogl) || ~isscalar(nlogl))\n newmsg = 'Result must be a numeric scalar';\n end\n if isnan(nlogl)\n nlogl = NaN; % explicitly set to real nan to remove imaginary part\n end\n if ~isempty(newmsg);\n pcov = [];\n nlogl = NaN;\n wmsg = combinemsg(wmsg,...\n sprintf('Error while evaluating likelihood:\\n%s',...\n newmsg));\n end\n \nend\n\n% Get the range over which to show the fit\ndffig = dfgetset('dffig');\nax = findall(dffig,'Type','axes','Tag','main');\nxlim = get(ax,'XLim');\n\n% Create a fit object using the information we calculated\nif badfit\n resultsText = emsg;\nelse\n try\n hFit = storefitresults(hFit, dist, p, pcov, nlogl, xlim, hExcl, exclname);\n resultsText = getresults(hFit);\n catch\n resultsText = lasterr;\n badfit = true;\n end\nend\n\nresultsText = combinemsg(wmsg,resultsText);\n\n% Show results\nhFit.resultstext = resultsText;\nfittingPanel.setResults(resultsText)\n\nif ~isempty(hFit)\n if ~newfit && ~(hFit.isgood == ~badfit)\n \t\tcom.mathworks.toolbox.stats.FitsManager.getFitsManager.fitIsGoodChanged(java(hFit), ~badfit);\n end\n hFit.isgood = ~badfit;\n if newfit\n\t hFit.plot = 1;\n % Add to fit array\n connect(hFit,getfitdb,'up');\n end\nend\n\nif hFit.plot\n % Determine if bounds can be shown\n if ~dist.hasconfbounds\n hFit.showbounds = false;\n end\n \n % Update plotted curve\n updateplot(hFit);\n\n % Update plot limits\n dfswitchyard('dfupdatexlim');\n dfswitchyard('dfupdateylim');\nend\n\nset(listeners, 'Enabled', 'on');\n\nif ~newfit\n com.mathworks.toolbox.stats.FitsManager.getFitsManager.fitChanged(...\n java(hFit),fitname,fitname);\nend\n\n% Display a more prominent warning outside the results text\nif ~badfit && ~isempty(wmsg)\n warndlg(wmsg,'Distribution Fitting Warning','modal');\nend\n\n% ----------------------------------------------\nfunction hFit = storefitresults(hFit, dist, p, pcov, nlogl, xlim, hExcl, exclname)\n% Update its properties\nhFit.distspec = dist;\nhFit.params = p;\nhFit.pcov = pcov;\nhFit.pfixed = false(size(p));\nhFit.loglik = -nlogl;\nhFit.support = dist.support;\nhFit.exclusionrule = hExcl;\nhFit.exclusionrulename = exclname;\n\nhFit.xlim = xlim;\nsetftype(hFit,dfgetset('ftype'));\n\n\n% ---------------------------------------------\nfunction nlogl = localnlogl(p, pdf, cdf, x, cens, freq)\n% Calculate negative log likelihood\n\n% Handle defaults for option inputs\nif isempty(cens)\n cens = false(size(x));\nelse\n cens = (cens == 1);\nend\nif isempty(freq)\n freq = ones(size(x));\nend\n\n% Compute for uncensored observations\nnlogl = - sum(freq(~cens) .* log(feval(pdf, x(~cens), p{:})));\n\n% Add component for censored observations\nif any(cens)\n nlogl = nlogl - sum(freq(cens) .* log(1-feval(cdf, x(cens), p{:})));\nend\n\n% -----------------------------------\nfunction msg = combinemsg(msg,newmsg)\n%COMBINEMSG Combine multiple messages into a single message\nif isempty(msg)\n msg = newmsg;\nelseif ~isempty(newmsg)\n msg = sprintf('%s\\n\\n%s',msg,newmsg);\nend\n\n% -----------------------------------------\nfunction expanded = expandInput(input,freq)\n%EXPANDDATA Expand out an input vector using element frequencies.\nif ~isequal(size(input),size(freq))\n error('stats:dfaddparamfit:InputSizeMismatch',...\n 'Input argument sizes must match.');\nend\n\n% Remove points that have zero frequency\nt = (freq == 0);\nif any(t)\n input(t) = [];\n freq(t) = [];\nend\n\n% Expand the remainder\ni = cumsum(freq);\nj = zeros(1, i(end));\nj(i(1:end-1)+1) = 1;\nj(1) = 1;\nexpanded = input(cumsum(j));\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/weightedstats/private/dfaddparamfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}} {"text": "%Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.\n%Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.\n%\n%THE BSD LICENSE\n%\n%Redistribution and use in source and binary forms, with or without\n%modification, are permitted provided that the following conditions\n%are met:\n%\n%1. Redistributions of source code must retain the above copyright\n% notice, this list of conditions and the following disclaimer.\n%2. Redistributions in binary form must reproduce the above copyright\n% notice, this list of conditions and the following disclaimer in the\n% documentation and/or other materials provided with the distribution.\n%\n%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction flann_set_distance_type(type, order)\n%FLANN_LOAD_INDEX Loads an index from disk\n%\n% Marius Muja, March 2009\n\n distances = struct('euclidean', 1, 'manhattan', 2, 'minkowski', 3, 'max_dist', 4, 'hik', 5, 'hellinger', 6, 'chi_square', 7, 'cs', 7, 'kullback_leibler', 8, 'kl', 8);\n function id = value2id(map,value)\n id = map.(value);\n end\n\n\n if ~isnumeric(type),\n type = value2id(distances,type);\n end\n if type~=3\n order = 0;\n end\n nearest_neighbors('set_distance_type', type, order);\nend\n", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/3rdparty/flann/flann_set_distance_type.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19546295367409275}} {"text": "function write_neuralynx_ncs(filename, ncs);\n\n% WRITE_NEURALYNX_NCS writes continuous data to a NCS file\n% The input data should be scaled in uV.\n%\n% Use as\n% write_neuralynx_ncs(filename, ncs)\n%\n% See also READ_NEURALYNX_NCS\n\n% Copyright (C) 2005-2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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: write_neuralynx_ncs.m 2885 2011-02-16 09:41:58Z roboos $\n\nif ~isa(ncs.TimeStamp, 'uint64')\n error('timestamps should be uint64');\nend\n\n% convert the data from uV into V\nncs.dat = ncs.dat * 1e-6;\n% scale the data and convert to 16 bits,\n% this has to be done prior to writing the header\nADMaxValue = double(intmax('int16'));\nADMaxVolts = max(abs(ncs.dat(:)));\nif ADMaxVolts>0\n ADBitVolts = ADMaxVolts / ADMaxValue;\nelse\n ADBitVolts = 1;\nend\nncs.dat = int16(ncs.dat / ADBitVolts);\n% update the header with the calibration values\nncs.hdr.ADBitVolts = ADBitVolts;\nncs.hdr.ADMaxValue = ADMaxValue;\n\n% construct the header\nbuf = [];\nbuf = [buf sprintf('######## Neuralynx Data File Header\\r\\n')];\nbuf = [buf sprintf('## File Name: %s\\r\\n', filename)];\nbuf = [buf sprintf('## Time Opened: (m/d/y): %s At Time: %s\\r\\n', datestr(clock, 'mm/dd/yy'), datestr(clock, 'HH:MM:SS'))];\nf = fieldnames(ncs.hdr);\nfor i=1:length(f)\n v = getfield(ncs.hdr, f{i});\n switch class(v)\n case 'char'\n buf = [buf sprintf('-%s\\t%s\\r\\n', f{i}, v)];\n case 'double'\n buf = [buf sprintf('-%s\\t%s\\r\\n', f{i}, num2str(v))];\n otherwise\n error('unknown class in writing header');\n end\nend\n\n% pad the rest of the header with zeros\nbuf((end+1):16384) = 0;\n\n% open the file and write the header\nfid = fopen(filename, 'wb', 'ieee-le');\nfwrite(fid, buf);\n\n% The format of a continuous sampled record is\n% int64 TimeStamp\n% int32 ChanNumber\n% int32 SampFreq\n% int32 NumValidSamp\n% int16 Samp[0] ... int16 Samp[511]\n% Note that if NumValidSamp < 512, Samp[n], where n >= NumValidSamp, will\n% contain random data.\n\nfor i=1:size(ncs.dat,2)\n % write a single continuous data record\n fwrite(fid, ncs.TimeStamp(i) , 'uint64');\n fwrite(fid, ncs.ChanNumber(i) , 'int32');\n fwrite(fid, ncs.SampFreq(i) , 'int32');\n fwrite(fid, ncs.NumValidSamp(i), 'int32');\n fwrite(fid, ncs.dat(:,i) , 'int16');\nend\n\n% close the file\nfclose(fid);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/write_neuralynx_ncs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.19533598376847597}} {"text": "classdef tblock < matlab.unittest.TestCase\n % tblock Unit tests for transformer.layer.block\n \n % Copyright 2020 The MathWorks, Inc.\n \n properties(Constant, Access=private)\n block = @gpt2.layer.block\n end\n \n properties(TestParameter)\n Input = struct(...\n 'Scalar', 1,...\n 'Vector', 1:5,...\n 'Matrix', reshape(1:6,[3,2]))\n end\n \n methods(Test)\n function outputHasInputSize(test,Input)\n % The block is simply a composition of other layers. Simply\n % verify the output of a block is the same size as the input,\n % and as such the blocks can be stacked.\n x = dlarray(Input);\n C = size(Input,1);\n weights = test.randomWeights(C);\n hyperParameters.NumHeads = 1;\n y = test.block(x,[],weights,hyperParameters);\n test.verifySize(y,size(x));\n end\n \n function outputHasInputSizeWithPasts(test,Input)\n % As above but using \"pasts\" - a concatenation of key and value\n % matrices.\n x = dlarray(Input);\n C = size(Input,1);\n weights = test.randomWeights(C);\n hyperParameters.NumHeads = 1;\n % Provide a fake past of sequence length 1\n K_fake = dlarray(rand(C,1));\n V_fake = dlarray(rand(C,1));\n past = cat(5,K_fake,V_fake);\n [y,present] = test.block(x,past,weights,hyperParameters);\n test.verifySize(y,size(x));\n % The size of presents is the size of past except the sequence\n % dimension gets extended by the sequence length of y\n exp_present_size = size(past);\n exp_present_size(2) = exp_present_size(2)+size(y,2);\n test.verifySize(present,exp_present_size);\n end\n end\n \n methods(Access=private)\n function weights = randomWeights(test,C)\n % C is num features, or latent dimension of the block\n g1 = dlarray(rand(C,1));\n b1 = dlarray(rand(C,1));\n g2 = dlarray(rand(C,1));\n b2 = dlarray(rand(C,1));\n W_A1 = dlarray(rand(3*C,C));\n W_A2 = dlarray(rand(C));\n b_A1 = dlarray(rand(3*C,1));\n b_A2 = dlarray(rand(C,1));\n W_P1 = dlarray(rand(C));\n b_P1 = dlarray(rand(C,1));\n W_P2 = dlarray(rand(C));\n b_P2 = dlarray(rand(C,1));\n weights = test.prepareBlockWeightsStruct(g1,b1,W_A1,b_A1,W_A2,b_A2,g2,b2,W_P1,b_P1,W_P2,b_P2);\n end\n \n function s = prepareBlockWeightsStruct(test,g1,b1,W_A1,b_A1,W_A2,b_A2,g2,b2,W_P1,b_P1,W_P2,b_P2)\n % Merge various structs that have the appropriate weight naming\n % syntax.\n s_ln = test.prepareLayerNormWeightsStruct(g1,b1,g2,b2);\n s_attn = test.prepareAttentionWeightsStruct(W_A1,b_A1,W_A2,b_A2);\n s_mlp = test.prepareMLPWeightsStruct(W_P1,b_P1,W_P2,b_P2);\n c = {s_ln,s_attn,s_mlp};\n fn = cellfun(@fieldnames,c,'UniformOutput',false);\n fn = cat(1,fn{:});\n fv = cellfun(@struct2cell,c,'UniformOutput',false);\n fv = cat(1,fv{:});\n s = struct();\n for i = 1:numel(fn)\n s.(fn{i}) = fv{i};\n end\n end\n \n function s = prepareAttentionWeightsStruct(~,W1,b1,W2,b2)\n % Prepare a struct compatible with the weights input of\n % attention. These are for the fully connected layers.\n s = struct(...\n 'attn_c_attn_w_0',W1,...\n 'attn_c_attn_b_0',b1,...\n 'attn_c_proj_w_0',W2,...\n 'attn_c_proj_b_0',b2);\n end\n \n function s = prepareLayerNormWeightsStruct(~,g1,b1,g2,b2)\n % Prepare a struct of weights compatible with the two layer\n % norm calls in block\n s = struct(...\n 'ln_1_g_0',g1,...\n 'ln_1_b_0',b1,...\n 'ln_2_g_0',g2,...\n 'ln_2_b_0',b2);\n end\n \n function s = prepareMLPWeightsStruct(~,W1,b1,W2,b2)\n % Create a struct of weights to be consumed by\n % transformer.layer.multiLayerPerceptron\n s = struct(...\n 'mlp_c_fc_w_0',W1,...\n 'mlp_c_fc_b_0',b1,...\n 'mlp_c_proj_w_0',W2,...\n 'mlp_c_proj_b_0',b2);\n end\n end\nend", "meta": {"author": "matlab-deep-learning", "repo": "transformer-models", "sha": "87f02af6b91c5bd7ac8479ea433f20435644d165", "save_path": "github-repos/MATLAB/matlab-deep-learning-transformer-models", "path": "github-repos/MATLAB/matlab-deep-learning-transformer-models/transformer-models-87f02af6b91c5bd7ac8479ea433f20435644d165/test/gpt2/layer/tblock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35220179564702836, "lm_q1q2_score": 0.19528549339230522}} {"text": "function val = fgGet(fg,param,varargin)\n%Get values from a fiber group structure\n%\n% val = fgGet(fg,param,varargin)\n%\n% Parameters\n% General\n% 'name'\n% 'type'\n% 'colorrgb'\n% 'thickness'\n% 'visible'\n%\n% Fiber related\n% 'nfibers'- Number of fibers in this group\n% 'nodes per fiber' - Number of nodes per fiber.\n% 'fibers' - Fiber coordinates\n% 'fibernames'\n% 'fiberindex'\n%\n% ROI and image coord related\n% 'unique image coords'\n% 'nodes to imagecoords' -\n% 'voxel2fiber node pairs' - For each roi coord, an Nx2 matrix of\n% (fiber number,node number)\n% 'nodes in voxels' - Nodes inside the voxels of roi coords\n% 'voxels in fg' - Cell array of the roiCoords touched by each fiber\n% 'voxels2fibermatrix' - Binary matrix (voxels by fibers). 1s when a\n% fiber is in a voxel of the roiCoords (which are, sadly, implicit).\n%\n% Tensor and tractography related\n% 'tensors' - Tensors for each node\n%\n%\n% See also: dwiGet/Set, fgCreate; fgSet\n%\n% (c) Stanford VISTA Team\n\n% NOTES: \n% Programming TODO:\n% We should store the transforms needed to shift the fg coordinates\n% between acpc and image space.\n\n% I eliminated these checks because this function is now called many many\n% times and this slows the computations (Franco).\n%\n%if notDefined('fg'),error('fiber group required.'); end\n% if notDefined('param'), error('param required.'); end\n\nval = [];\n\nswitch mrvParamFormat(param)\n \n % Basic fiber parameters\n case 'name'\n val = fg.name;\n case 'type' % Should always be fibergroup\n val = fg.type;\n \n % Fiber visualization settings.\n case 'colorrgb'\n val = fg.colorRgb;\n case 'thickness'\n val = fg.thickness;\n case 'visible'\n val = fg.visible;\n \n % Simple fiber properties --\n case {'fibers'}\n % val = fgGet(fg,'fibers',fList);\n %\n % Returns a 3xN matrix of fiber coordinates corresponding to the\n % fibers specified in the integer vector, fList. This differs from\n % the dtiH (mrDiffusion) representation, where fiber coordinates\n % are stored as a set of cell arrays for each fiber.\n if ~isempty(varargin)\n list = varargin{1};\n val = cell(length(list),1);\n for ii=1:length(list)\n val{ii} = fg.fibers{ii};\n end\n else\n val = fg.fibers;\n end\n case 'fibernames'\n val = fg.fiberNames;\n case 'fiberindex'\n val = fg.fiberIndex;\n case 'nfibers'\n val = length(fg.fibers);\n case {'nodesperfiber','nsamplesperfiber','nfibersamples'}\n % fgGet(fg,'n samples per fiber ')\n % How many samples per fiber. This is about equal to\n % their length in mm, though we need to write the fiber lengths\n % routine to actually calculate this.\n nFibers = fgGet(fg,'n fibers');\n val = zeros(1,nFibers);\n for ii=1:nFibers\n val(ii) = length(fg.fibers{ii});\n end\n \n % Fiber group (subgroup) properties.\n % These are used when we classify fibers into subgroups. We should\n % probably clean up this organization which is currently\n %\n % subgroup - length of fibers, an index of group identity\n % subgroupNames()\n % .subgroupIndex - Probably should go away and the index should\n % just be\n % .subgroupName - Probably should be moved up.\n %\n case {'ngroups','nsubgroups'}\n val = length(fg.subgroupNames);\n case {'groupnames'}\n val = cell(1,fgGet(fg,'n groups'));\n for ii=1:nGroups\n val{ii} = fg.subgroupNames(ii).subgroupName;\n end\n \n % DTI properties\n case 'tensors'\n val = fg.tensors;\n \n % Fiber to coord calculations\n case {'imagecoords'}\n % c = fgGet(fgAcpc,'image coords',fgList,xForm);\n % c = fgGet(fgAcpc,'image coords',fgList,xForm);\n %\n % Return the image coordinates of a specified list of fibers\n % Returns a matrix that is fgList by 3 of the image coordinates for\n % each node of each fiber.\n %\n % Fiber coords are represented at fine resolution in ACPC space.\n % These coordinates are rounded and in image space\n if ~isempty(varargin)\n fList = varargin{1};\n if length(varargin) > 1\n xForm = varargin{2};\n % Put the fiber coordinates into image space\n fg = dtiXformFiberCoords(fg,xForm);\n end\n else\n % In this case, the fiber coords should already be in image\n % space.\n nFibers = fgGet(fg,'n fibers');\n fList = 1:nFibers;\n end\n \n % Pull out the coordinates and floor them. These are in image\n % space.\n nFibers = length(fList);\n val = cell(1,nFibers);\n if nFibers == 1\n %val = round(fg.fibers{fList(1)}'); \n val = floor(fg.fibers{fList(1)}');\n\n else\n for ii=1:nFibers\n %val{ii} = round(fg.fibers{fList(ii)}'); \n val{ii} = floor(fg.fibers{fList(ii)}');\n\n end\n end\n \n case {'uniqueimagecoords'}\n % coords = fgGet(fgIMG,'unique image coords');\n %\n % The fg input must be in IMG space.\n %\n % Returns the unique image coordinates of all the fibers as an Nx3\n % matrix of integers.\n % val = round(horzcat(fg.fibers{:})'); \n val = floor(horzcat(fg.fibers{:})');\n val = unique(val,'rows');\n \n case {'nodes2voxels'}\n % nodes2voxels = fgGet(fgImg,'nodes2voxels',roiCoords)\n %\n % The roiCoords are a matrix of Nx3 coordinates. They describe a\n % region of interest, typically in image space or possibly in acpc\n % space.\n %\n % We return a cell array that is a mapping of fiber nodes to voxels in\n % the roi. The roi is specified as an Nx3 matrix of coordinates.\n % The returned cell array, nodes2voxels, has the same number of\n % cells as there are fibers.\n %\n % Unlike the fiber group cells, which have a 3D coordinate of each\n % node, this cell array has an integer that indexes the row of\n % roiCoords that contains the node. If a node is not in any of the\n % roiCoords, the entry in node2voxels{ii} for that node is zero.\n % This means that node is outside the 'roiCoords'.\n %\n % Once again: The cell nodes2voxels{ii} specifies whether each\n % node in the iith fiber is inside a voxel in the roiCoords. The\n % value specifies the row in roiCoords that contains the node.\n %\n if isempty(varargin), error('roiCoords required');\n else\n roiCoords = varargin{1};\n end\n \n % Find the roiCoord for each node in each fiber.\n nFiber = fgGet(fg,'n fibers');\n val = cell(nFiber,1);\n for ii=1:nFiber\n % if ~mod(ii,200), fprintf('%d ',ii); end\n % Node coordinates in image space\n nodeCoords = fgGet(fg,'image coords',ii);\n \n % The values in loc are the row of the coords matrix that contains\n % that sample point in a fiber. For example, if the number 100 is\n % in the 10th position of loc, then the 10th sample point in the\n % fiber passes through the voxel in row 100 of coords.\n [~, val{ii}] = ismember(nodeCoords, roiCoords, 'rows');\n end\n \n case {'voxel2fibernodepairs','v2fn'}\n % voxel2FNpairs = fgGet(fgImg,'voxel 2 fibernode pairs',roiCoords);\n % voxel2FNpairs = fgGet(fgImg,'voxel 2 fibernode pairs',roiCoords,nodes2voxels);\n %\n % The return is a cell array whose size is the number of voxels.\n % The cell is a Nx2 matrix of the (fiber, node) pairs that pass\n % through it.\n %\n % The value N is the number of nodes in the voxel. The first\n % column is the fiber number. The second column reports the indexes\n % of the nodes for each fiber in each voxel.\n tic\n fprintf('\\n[fgGet] Computing fibers/nodes pairing in each voxel...')\n if length(varargin) < 1, error('Requires the roiCoords.');\n else\n roiCoords = varargin{1};\n nCoords = size(roiCoords,1);\n end\n if length(varargin) < 2\n % We assume the fg and the ROI coordinates are in the same\n % coordinate frame.\n nodes2voxels = fgGet(fg,'nodes 2 voxels',roiCoords);\n else nodes2voxels = varargin{2};\n end\n \n nFibers = fgGet(fg,'nFibers');\n voxelsInFG = fgGet(fg,'voxels in fg',nodes2voxels);\n roiNodesInFG = fgGet(fg,'nodes in voxels',nodes2voxels);\n val = cell(1,nCoords);\n for thisFiber=1:nFibers\n voxelsInFiber = voxelsInFG{thisFiber}; % A few voxels, in a list\n nodesInFiber = roiNodesInFG{thisFiber}; % The corresponding nodes\n \n % Then add a row for each (fiber,node) pairs that pass through\n % the voxels for this fiber.\n for jj=1:length(voxelsInFiber)\n thisVoxel = voxelsInFiber(jj);\n % Print out roi coord and fiber coord to verify match\n % roiCoords(thisVoxel,:)\n % fg.fibers{thisFiber}(:,nodesInFiber(jj))\n % Would horzcat be faster?\n val{thisVoxel} = cat(1,val{thisVoxel},[thisFiber,nodesInFiber(jj)]);\n end\n end\n fprintf('process completed in: %2.3fs.\\n',toc)\n\n case {'nodesinvoxels'}\n % nodesInVoxels = fgGet(fg,'nodes in voxels',nodes2voxels);\n %\n % This cell array is a modified form of nodes2voxels (see above).\n % In that cell array every node in every fiber has a number\n % referring to its row in roiCoords, or a 0 when the node is not in\n % any roiCoord voxel.\n %\n % This cell array differs only in that the 0s removed. This\n % is used to simplify certain calculations.\n %\n if length(varargin) <1\n error('Requires nodes2voxels cell array.');\n end\n \n nodes2voxels = varargin{1};\n nFibers = fgGet(fg,'nFibers');\n val = cell(1,nFibers);\n \n % For each fiber, this is a list of the nodes that pass through\n % a voxel in the roiCoords\n for ii = 1:nFibers\n % For each fiber, this is a list of the nodes that pass through\n % a voxel in the roiCoords\n lst = (nodes2voxels{ii} ~= 0);\n val{ii} = find(lst);\n end\n \n case 'voxelsinfg'\n % voxelsInFG = fgGet(fgImg,'voxels in fg',nodes2voxels);\n %\n % A cell array length n-fibers. Each cell has a list of the voxels\n % (rows of roiCoords) for a fiber.\n %\n % This routine eliminates the 0's in the nodes2voxels lists.\n %\n if length(varargin) < 1, error('Requires nodes2voxels cell array.'); end\n \n nodes2voxels = varargin{1};\n nFibers = fgGet(fg,'nFibers');\n val = cell(1,nFibers);\n for ii = 1:nFibers\n % These are the nodes that pass through a voxel in the\n % roiCoords\n lst = (nodes2voxels{ii} ~= 0);\n val{ii} = nodes2voxels{ii}(lst);\n end\n \n case {'voxels2fibermatrix','v2fm'}\n % v2fm = fgGet(fgImg,'voxels 2 fiber matrix',roiCoords);\n % Or,\n % v2fnPairs = fgGet(fgImg,'v2fn',roiCoords);\n % v2fm = fgGet(fgImg,'voxels 2 fiber matrix',roiCoords, v2fnPairs);\n %\n % mrvNewGraphWin; imagesc(v2fm)\n %\n % Returns a binary matrix of size Voxels by Fibers.\n % When voxel ii has at least one node from fiber jj, there is a one\n % in v2fm(ii,jj). Otherwise, the entry is zero.\n %\n \n % Check that the fg is in the image coordspace:\n if isfield(fg, 'coordspace') && ~strcmp(fg.coordspace, 'img')\n error('Fiber group is not in the image coordspace, please xform');\n end\n \n if isempty(varargin), error('roiCoords required');\n else\n roiCoords = varargin{1};\n nCoords = size(roiCoords,1);\n if length(varargin) < 2\n v2fnPairs = fgGet(fg,'v2fn',roiCoords);\n else\n v2fnPairs = varargin{2};\n end\n end\n \n % Allocate matrix of voxels by fibers\n val = zeros(nCoords,fgGet(fg,'n fibers'));\n \n % For each coordinate, find the fibers. Set those entries to 1.\n for ii=1:nCoords\n if ~isempty(v2fnPairs{ii})\n f = unique(v2fnPairs{ii}(:,1));\n end\n val(ii,f) = 1;\n end\n \n case {'fibersinroi','fginvoxels','fibersinvoxels'}\n % fList = fgGet(fgImg,'fibersinroi',roiCoords);\n %\n % v2fn = fgGet(fgImg,'v2fn',roiCoords);\n % fList = fgGet(fgImg,'fibersinroi',roiCoords,v2fn);\n %\n % Returns an integer vector of the fibers with at least\n % one node in a region of interest.\n %\n % The fg and roiCoords should be in the same coordinate frame.\n %\n if isempty(varargin), error('roiCoords required');\n elseif length(varargin) == 1\n roiCoords = varargin{1};\n v2fnPairs = fgGet(fg,'v2fn',roiCoords);\n elseif length(varargin) > 1\n roiCoords = varargin{1};\n v2fnPairs = varargin{2};\n end\n \n val = []; nCoords = size(roiCoords,1);\n for ii=1:nCoords\n if ~isempty(v2fnPairs{ii})\n val = cat(1,val,v2fnPairs{ii}(:,1));\n end\n end\n val = sort(unique(val),'ascend');\n \n case {'coordspace','fibercoordinatespace','fcspace'}\n % In some cases, the fg might contain information telling us in which\n % coordinate space its coordinates are set. This information is set\n % as a struct. Each entry in the struct can be either a 4x4 xform\n % matrix from the fiber coordinates to that space (with eye(4) for\n % the space in which the coordinates are defined), or (if the xform\n % is not know) an empty matrix.\n \n cspace_fields = fields(fg.coordspace);\n val = [];\n for f=1:length(cspace_fields)\n this_field = cspace_fields{f};\n if isequal(getfield(fg.coordspace, this_field), eye(4))\n val = this_field;\n end\n end\n \n otherwise\n error('Unknown fg parameter: \"%s\"\\n',param);\nend\n\nreturn\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/fg/fgGet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.19523797718870103}} {"text": "% ------------------------------------------------------------------------ \n% Copyright (C)\n% Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n% University of California Berkeley (UCB) - USA\n% \n% Jordi Pont-Tuset \n% Pablo Arbelaez \n% June 2014\n% ------------------------------------------------------------------------ \n% This file is part of the MCG package presented in:\n% Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,\n% \"Multiscale Combinatorial Grouping,\"\n% Computer Vision and Pattern Recognition (CVPR) 2014.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------\nfunction stats = eval_labels(labels_folder,database,gt_set,n_cands)\n\nif nargin<2\n database = 'pascal2012';\nend\nif nargin<3\n gt_set = 'val2012';\nend\nif nargin<4\n % Number of sampled candidates\n n_cands = [10:5:100,125:25:1000,1500:500:6000,10000];\nend\n\n% Get the name of the folder to refer to the method\nif strcmp(labels_folder(end),filesep)\n labels_folder(end) = [];\nend\ntmp = strfind(labels_folder,filesep);\nif isempty(tmp)\n method_name = labels_folder;\nelse\n method_name = labels_folder(tmp(end)+1:end);\nend\n\nres_dir = fullfile(root_dir,'results',database, method_name);\nstats_file = fullfile(root_dir,'results',database, [method_name '_' gt_set '.mat']);\n\n% Is the result already gathered?\nif exist(stats_file, 'file')\n load(stats_file) \n recompute = 0;\n disp(['Loaded: ' stats_file '.'])\nelse\n disp(['RECOMPUTING: ' stats_file '.'])\n recompute = 1;\nend\n\nif recompute\n %% Evaluate and save each image independently to be able to parallelize\n % You can adapt the matlabpool to your system\n eval_and_save_labels(labels_folder,database,gt_set);\n \n %% Gather and save results\n % Load which images to consider\n im_ids = database_ids(database,gt_set);\n \n % Store and initialize\n stats.n_cands = n_cands;\n stats.gt_set = gt_set;\n stats.obj_classes = [];\n \n % Compute statistics\n stats.num_objects = 0;\n for ii=1:numel(im_ids)\n res_file = fullfile(res_dir, [im_ids{ii} '.mat']);\n if exist(res_file,'file')\n load(res_file)\n for jj=1:length(stats.n_cands)\n curr_n_cands = min(stats.n_cands(jj), size(jaccards,2));\n to_consider = 1:curr_n_cands;\n stats.all_n_masks(ii,jj) = length(to_consider);\n if (stats.all_n_masks(ii,jj)>0) \n for kk=1:size(jaccards,1)\n [stats.max_J(stats.num_objects+kk,jj), which_one] = max(jaccards(kk,to_consider));\n stats.max_indicator(stats.num_objects+kk,jj) = to_consider(which_one);\n stats.max_fp(stats.num_objects+kk,jj) = false_pos(kk,to_consider(which_one));\n stats.max_fn(stats.num_objects+kk,jj) = false_neg(kk,to_consider(which_one));\n stats.max_inters(stats.num_objects+kk,jj) = inters(kk,to_consider(which_one));\n end\n end\n end\n stats.obj_classes = [stats.obj_classes; obj_classes(1:size(inters,1))]; \n stats.num_objects = stats.num_objects + size(jaccards,1);\n else\n error([res_file ' not found']); \n end\n end\n \n % Check\n if size(stats.obj_classes,1)~=stats.num_objects \n error('Something went wrong')\n end\n \n stats.mean_n_masks = mean(stats.all_n_masks);\n \n % ----- Jaccard at instance level (J_i) ----\n % It is the mean best jaccard for all objects\n stats.jaccard_object = mean(stats.max_J);\n \n \n % ----- Compute jaccard at class level (J_c) ----\n class_ids = unique(stats.obj_classes);\n for ii=1:length(class_ids)\n curr_class = class_ids(ii);\n stats.per_class_results{ii}.num_objects = sum(stats.obj_classes==curr_class);\n \n stats.per_class_results{ii}.max_fp = stats.max_fp(logical(stats.obj_classes==curr_class),:);\n stats.per_class_results{ii}.max_fn = stats.max_fn(logical(stats.obj_classes==curr_class),:);\n stats.per_class_results{ii}.max_inters = stats.max_inters(logical(stats.obj_classes==curr_class),:);\n stats.per_class_results{ii}.max_J = stats.max_J(logical(stats.obj_classes==curr_class),:);\n stats.per_class_results{ii}.meanmax = mean(stats.per_class_results{ii}.max_J);\n\n stats.per_class_results{ii}.global_fp = sum(stats.per_class_results{ii}.max_fp,1);\n stats.per_class_results{ii}.global_fn = sum(stats.per_class_results{ii}.max_fn,1);\n stats.per_class_results{ii}.global_inters = sum(stats.per_class_results{ii}.max_inters,1);\n \n % Compute per-class total inters, fp, fn\n stats.per_class_results{ii}.global_J = ...\n stats.per_class_results{ii}.global_inters ./...\n (stats.per_class_results{ii}.global_inters+...\n stats.per_class_results{ii}.global_fp +...\n stats.per_class_results{ii}.global_fn);\n end\n \n % Compute global mean on all classes\n tmp = [];\n for ii=1:length(class_ids)\n tmp = [tmp; stats.per_class_results{ii}.global_J]; %#ok\n end\n stats.jaccard_class = mean(tmp,1);\n\n save(stats_file,'stats');\n \n % Remove temporal results folder\n rmdir(res_dir,'s');\nend\nend\n", "meta": {"author": "s-gupta", "repo": "rcnn-depth", "sha": "7a7baf7dcccc6fdf6be7c13d16828064d89dff4e", "save_path": "github-repos/MATLAB/s-gupta-rcnn-depth", "path": "github-repos/MATLAB/s-gupta-rcnn-depth/rcnn-depth-7a7baf7dcccc6fdf6be7c13d16828064d89dff4e/mcg/src/benchmark/eval_labels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.19523797227197662}} {"text": "function [sicd_meta] = rgazcomp_file(input_filename_cphd, output_filename_sicd, varargin)\n%RGAZCOMP_FILE Applies the most simple of IFPs (range-azimuth compression)\n%on a file of motion-compensated phase history data in CPHD file format and\n%writes to a SICD file with appropriate metadata\n%\n% RGAZCOMP_FILE(INPUT_FILENAME_CPHD, OUTPUT_FILENAME_SICD, 'PropertyName', PropertyValue, ...)\n%\n% Property name Description\n% resolution Desired resolution 3dB IPR width\n% ([range_resolution azimuth_resolution]) in\n% meters. The necessary pulses and samples for\n% image formation at this resolution will be\n% calculated (taken from middle of data.) If\n% pulse_range and/or sample_range properties are\n% defined, then this parameter is ignored. Default\n% is the full resolution that the collect supports.\n% pulse_range Set of pulses to use for image formation. (For\n% example, 1:1000.) Default is to calculate this\n% from resolution property.\n% sample_range Set of samples to use for image formation. (For\n% example, 1:1000.) Default is to calculate this\n% from resolution property.\n% channel Channel to use from CPHD file. Default is 1.\n% sample_rate Image domain oversample ratios. Default is 1.\n% max_block_size When data can't be processed within memory, this\n% is the size of the blocks (in bytes) to use\n% process the data.\n% quiet If false, this reports stats on collection and\n% IFP parameters. Default is true.\n%\n% Note for larger datasets, this routine executes \"out of core\" storing of\n% intermediate results in temporary files, which should be automatically\n% cleaned up upon completion of this function. However, if function is\n% stopped in the middle, either through an error or user intervention, some\n% of the files may remain in MATLAB's temporary directory (tempdir).\n% \n% Authors: Wade Schwartzkopf, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n%% Parse input parameters and read metadata\nph_reader = open_ph_reader(input_filename_cphd);\nifp_params = select_pulses_samples_cphd(ph_reader, varargin{:}); % Parse generic IFP parameters\np1 = inputParser;\np1.KeepUnmatched=true;\np1.addParamValue('max_block_size',[], @isscalar);\np1.addParamValue('sample_rate',1, @isscalar);\np1.FunctionName = mfilename;\np1.parse(varargin{:});\nifp_params.sample_rate = p1.Results.sample_rate;\nmax_block_size = p1.Results.max_block_size;\nif isempty(max_block_size)\n if ispc\n [uv, sv] = memory;\n % max_block_size is just the size of the largest single array we\n % will handle at once. We will need significantly more memory than\n % this. A factor of 16 seems to be reasonable. Its a nice round\n % power of two that seems to avoid swapping in limited testing.\n max_block_size = min(sv.PhysicalMemory.Available/16, ...\n uv.MaxPossibleArrayBytes);\n else % Can't gauge memory in UNIX, so just put arbitrary value\n max_block_size = 2^27; % About 100Meg\n end\nend\ncphd_meta = ph_reader.get_meta();\n[ignore, nbdata] = ph_reader.read_cphd(ifp_params.pulse_range, [], 1);\nif ~strcmpi(cphd_meta.CollectionID.RadarMode.ModeType,'SPOTLIGHT') || ...\n any(any(diff(nbdata.SRPPos))) % Assure spotlight data\n error('RGAZCOMP_FILE:UNSUPPORTED_COLLECT_TYPE','Unsupported collection mode. Only spotlight data is supported.');\nend\nif any(diff(nbdata.SC0)) || any(diff(nbdata.SCSS))\n error('RGAZCOMP_FILE:UNSUPPORTED_COLLECT_TYPE','Unsupported data type. Must have constant Fx0/Fx_SS.');\nend\nif any(diff(diff(ifp_params.sample_range)))\n error('RGAZCOMP_FILE:UNSUPPORTED_COLLECT_TYPE','Selected samples must be regularly spaced.');\nend\nif ~strcmp(cphd_meta.Global.DomainType, 'FX')\n error('RGAZCOMP_FILE:UNSUPPORTED_FILE_TYPE','Unsupported CPHD type. Currently only FX domain is supported.');\nend\n\n%% Compute some values we will need\n% Number of pulses and samples that we will be processing in this function.\n% Defined here purely for conciseness of notation.\nnum_pulses = length(ifp_params.pulse_range);\nnum_samples = length(ifp_params.sample_range);\n\n% Decide whether we can process in memory, or whether we need to use\n% intermediate files. We hope to avoid using intermediate files since file\n% reads and writes take the great majority of the processing time here. In\n% one profiling test, file reads and writes took 98% of the time of this\n% funcion. For this reason, we have attempted to minimize the number of\n% reads and writes, and we try to comment in the code sections that affect\n% these file I/O delays. Unfortunately virtual memory and swapping (which\n% is non-optimal file I/O out of our control) is much worse than the file\n% I/O explicitly handled in this function, so try to set max_block_size to\n% something as large as possible without the operating system resorting to\n% virtual memory.\ndata_element_size = 8; % In bytes. Assumes single precision data\nprocess_in_blocks = max_block_size<(num_pulses*num_samples*prod(ifp_params.sample_rate)*data_element_size);\nif process_in_blocks\n warning('RGAZCOMP_FILE:FILE_PROCESSING','This data must be processed through intermediate files, rather than all in memory. This could take a while...');\nend\n\nifp_params.image_size_pixels = floor(ifp_params.sample_rate .* [num_samples num_pulses]);\nsicd_meta = rgazcomp_sicd_meta(cphd_meta,nbdata,ifp_params);\n\n%% Range FFT across samples\n% The FFT will be done in separably in two steps, first in range and then\n% in azimuth.\n\n% Setup temporary file\n% The range FFT stage includes an in-order read (CPHD is written in\n% \"pulse-major\" order) and an in-order write (data interpolated in range).\n% We have to \"corner-turn\" (or transpose) after the range FFT (as we do on\n% all 4 steps), but it is typically faster to read from a file out-of-order\n% than write out-of-order, so we will do the corner-turn in the read of the\n% azimuth FFT, rather than the write of this range FFT stage.\nif process_in_blocks\n filename_range_fft = tempname;\n tempsicdmeta.ImageData.NumRows = num_pulses;\n tempsicdmeta.ImageData.NumCols = ifp_params.image_size_pixels(1);\n writer_range_interp = SIOWriter(filename_range_fft, tempsicdmeta, 'include_sicd_metadata', false);\nend\n\n% Iterate through sets of pulses for range FFT\nfirst_pulse_in_set=1; % Out of all pulses selected for processing\nmax_num_lines = floor(max_block_size/(num_samples*data_element_size));\nwb_hand=waitbar(0,'Range FFT...');\nwhile(first_pulse_in_set.\n%\n% RTB LIBRARY:\n%\n% Copyright (C) 1993-2014, by Peter I. Corke\n% http://www.petercorke.com\n% Released under the GNU Lesser General Public license\n\nfunction c = collisions(robot, q, cmdl, dyn_cmdl, dyn_T)\n\n% VERSION WITH BASE CHECKING\n% pts = robot.points;\npts = robot.points(end-robot.n+1:end);\nfor i = length(pts): -1: 1\n numPts(i) = size(pts{i},1);\n pts{i}(:,4) = 1;\n pts{i} = pts{i}';\nend\n\nif isempty(cmdl), checkfuns = []; else checkfuns = cmdl.checkFuns; end\nif nargin > 3\n dyn_checkfuns = dyn_cmdl.checkFuns;\n if nargin == 4 || isempty(dyn_T)\n tool = robot.tool;\n dyn_T = [];\n end\nelse\n dyn_checkfuns = [];\nend\n\n% VERSION WITH BASE CHECKING\n% base = length(pts) - robot.n;\n% switch base\n% case 0\n% % No base\n% case 1\n% T = robot.base;\n% trPts = T * pts{1};\n% points = trPts (1:3,:)';\n% if any(checkfuns{1}(points(:,1),points(:,2),points(:,3)))\n% C(:) = 1;\n% display('Base is colliding');\n% return;\n% end\n% otherwise\n% error('robot has missing or extra points');\n% end\n\nposes = size(q,1);\nc = false(poses, 1);\n\nnan = any(isnan(q),2);\nc(nan) = true;\nnotnan = find(~nan)';\n\nT0 = robot.base;\n\nfor p = notnan\n T = T0;\n prevPts = 0;\n for i = 1: robot.n;\n T = T * robot.links(i).A(q(p,i));\n if numPts(i) % Allows some links to be STLless\n % VERSION WITH BASE CHECKING\n % nextPts = prevPts+numPts(i+base);\n % trPts(:,prevPts+1:nextPts) = T * pts{i+base};\n nextPts = prevPts+numPts(i);\n trPts(:,prevPts+1:nextPts) = T * pts{i};\n prevPts = nextPts;\n end\n end\n \n % Does same thing as cmdl.collision(trPoints(1:3,:)'), but\n % Does not have to access object every time - quicker\n for i = 1: length(checkfuns)\n if any(checkfuns{i}(trPts(1,:), trPts(2,:), trPts(3,:)))\n c(p) = true;\n break;\n end\n end\n \n % Then check the dynamic collision models, if any\n for i = 1: length(dyn_checkfuns)\n if isempty(dyn_T)\n dyn_trPts = T*tool \\ trPts;\n else\n dyn_trPts = dyn_T(:,:,p,i) \\ trPts;\n end\n if any(dyn_checkfuns{i}(dyn_trPts(1,:), dyn_trPts(2,:), ...\n dyn_trPts(3,:)))\n c(p) = true;\n break;\n end\n end\n \nend\nend", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/contrib/pHRIWARE/@SerialLinked/collisions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1950763820913916}} {"text": "function [M, movie] = tSeriesMovie(vw, scans, anatFlag, varargin)\n% [M movie] = tSeriesMovie(vw, scans, anatFlag, [options]):\n%\n% Make a movie of the selected tSeries, using the current view's\n% settings, and play using mplay viewer. Intended as a replacement\n% for makeTSeriesMovie.\n%\n% NOTE: The code auto-resizes the movie to fit the screen nicely. Although\n% this is a benefit, it usually causes the lower line of the mplay tool to\n% turn black; this line contains some useful information like the current\n% frame and image size. To get this info back, press the second button \n% from the left (\"truesize\") in the movie window's toolbar. \n%\n% vw: the view struct. Currently supports inplane and flat level views.\n%\n% scans: set of scans to view from current data type.\n%\n% anatFlag: if 1, will threshold the tSeries and superimpose\n% the parts above threshold on top of the view's anat image.\n% Defaults to 0.\n%\n% Returns M, a matrix of the tSeries, and movie, an object-\n% oriented struct generated by mplay used for programmatic\n% control of the movie. If anatFlag is 0, M is size\n% x by y by nFrames, where x and y are the view's slice dims.\n% If anatFlag is 1, M is a 4-D array of size x by y by 3 by nFrames,\n% where each 3-D subvolume is a truecolor image.\n%\n% Options: [case-insensitive]\n% slices, [val]: set slice numbers (defaults to current slice).\n% WARNING: >1 slice can be very memory-hungry\n% zoom, [val]: set zoom area (as with axis command)\n% detrend, [val]: set detrend flag (see detrendTSeries for vals)\n% convertToPct,[flag]: if 1, will convert to % signal change.\n% applyHisto,[flag]: flag to apply standard histogram criterion (on\n% by default) in which the tails of the intensity\n% histogram are clipped.\n% compareFrames,[frame]: if nonzero, will make a truecolor move in which \n% the red channel is the tSeries, and the \n% blue-green channel is a reference frame --\n% e.g., if 1, the first frame of the tSeries\n% meanThresh,[val]: set threshold for raw functionals -- any parts\n% of the tSeries below this value (normalized \n% from 0 to 1 --> min to max of tSeries) will \n% be zeroed.\n% funcClip,[val]: set clip values for functionals, if\n% superimposing tSeries on anatomicals \n% (i.e., anatFlag = 1). Values outside\n% this range won't be overlaid. Default [0.2 1]\n% fps,[val]: Set default frames per second of playback\n% in the movie player.\n% saveAvi,[path]: export the tSeries movie to an .AVI file\n% in the specified path. If path is set to\n% 'dialog', will pop up a dialog to interactively\n% set the target file. Note that because of\n% codecs, exporting on Windows produces smaller\n% files than on linux (at least in my\n% experience). Uses movie2avi.\n%\n%\n% More info on the mplay movie player for matlab:\n%\n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3250&objectType=file\n%\n% Thanks Don Orofino!\n%\n% ras 12/04: wrote it.\n% ras 03/05: added avi export.\n% ras 11/06: added multiple slices option.\nif notDefined('scans'), scans = viewGet(vw, 'curScan'); end\nif notDefined('anatFlag'), anatFlag = 0; end\n\n%%%%% default params\nslices = viewGet(vw, 'curSlice');\nsDims = viewGet(vw, 'sliceDims',scans(1));\nif checkfields(vw,'ui','zoom')\n zoom = vw.ui.zoom;\n rsFactor = upSampleFactor(vw,scans(1));\n zoom(3:4) = zoom(3:4) ./ rsFactor(1);\n zoom(1:2) = zoom(1:2) ./ rsFactor(2);\n zoom = round(zoom);\n zoom(zoom==0) = 1;\nelse\n zoom = [1 sDims(2) 1 sDims(1)];\nend\ndetrend = 0;\nconvertToPct = 0;\napplyHisto = 0; % use histogram-based thresholding like makeTSeriesMovie\ncompareFrame = 0; % compare to a reference frame (if 0, don't compare)\nmeanThresh = 0; % normalized raw intensity threshold\nfuncClip = [0.2 1]; % clipping values for overlaying functionals, if anatFlag==1\nautoCmap = 1; % flag to use the full cmap range (if anatFlag==1)\nmovieFlag = 1; % call the mplay GUI\nfps = 15;\nsaveAvi = '';\nviewType = viewGet(vw,'viewType');\nframes = true; % true = use all frames from each scan; false = use 1st / last frame only\n\n%%%%% parse the option flags\nopts = unNestCell(varargin); % to enable recursive passing of options\nfor i = 1:length(opts)\n if ischar(opts{i})\n switch lower(opts{i})\n case 'slices', slices = opts{i+1};\n case 'zoom', zoom = opts{i+1};\n case 'detrend', detrend = opts{i+1};\n case 'converttopct', convertToPct= opts{i+1};\n case 'applyhisto', applyHisto = opts{i+1};\n case 'compareframes', compareFrame= opts{i+1};\n case 'meanthresh', meanThresh = opts{i+1};\n case 'funcclip', funcClip = opts{i+1};\n case 'fps', fps = opts{i+1};\n case 'saveavi', saveAvi = opts{i+1};\n case 'frames', frames = opts{i+1};\n case 'autocmap', autoCmap = opts{i+1};\n case 'nomovie', movieFlag = 0;\n end\n end\nend\n\n%%%%% check view type\nif isequal(viewType,'Flat')\n [M, movie] = flatLevelMovie(vw,scans,saveAvi);\n return\nelseif isequal(viewType,'Volume') || isequal(viewType,'Gray')\n error('Volume/Gray support not provided yet.')\nend\n\n%%%%% init M intensity array\nM = [];\n\n%%%%% if >1 slices, run recursively\nif length(slices) > 1\n [M, movie] = tSeriesMovieSlices(vw, scans, slices, anatFlag, opts);\n return\nend\n\n%%%%% get tSeries from selected scans\nnFrames = 0;\nhwait = mrvWaitbar(0,'Loading tSeries for movie...');\nfor scan = scans\n tSeries = loadtSeries(vw,scan,slices(1));\n if frames, % get just the requested frames, throw out the rest\n % make sure we don't try to get more frames than exist (could\n % happen if the number of frames differs across scans)\n validframes = frames <= viewGet(vw, 'nframes', scan);\n % now restrict the tseries\n tSeries = tSeries(frames(validframes), :); \n end\n \n % update frame count\n nFrames = nFrames + size(tSeries,1); \n \n % detrend if selected\n if detrend ~= 0\n tSeries = detrendTSeries(tSeries, detrend, 20);\n end\n\t \n % append to M\n M = [M; tSeries];\n \n mrvWaitbar(find(scans==scan)/length(scans),hwait);\nend\nclose(hwait);\n\n%%%%% apply histogram criterion\nif applyHisto==1\n M = histoThresh(M);\nend\n\n\n% if a mean intensity threshold is set, mask out stuff \n% that doesn't have strong mean signal\nif meanThresh > 0\n meanImg = mean(M,1);\n meanImg = rescale2(meanImg,[],[0 1000]);\n mask = (meanImg > 1000*meanThresh);\nend\n\n% convert to pct if selected\nif convertToPct==1\n M = M ./ repmat(mean(M,1),[nFrames 1]);\nend\n\n% now apply mask if selected\nif meanThresh > 0\n mask = repmat(mask,[nFrames 1]);\n M(mask==0) = min(M(:))-1;\nend\n\n%%%%% reshape and apply zoom\nM = reshape(M', [sDims(1) sDims(2) nFrames]);\nM = M(zoom(3):zoom(4),zoom(1):zoom(2),:); \n\n%%%%% if anat flag set, convert M to 4D truecolor x time array\nif anatFlag==1 \n\thwait = mrvWaitbar(0,'Superimposing over anat image...');\n \n % get cmap from map mode\n modeInfo = viewGet(vw,'mapMode');\n numColors = modeInfo.numColors;\n numGrays = modeInfo.numGrays;\n cmap = 255 .* modeInfo.cmap(numGrays+1:end,:);\n \n % make an overlay, indexing into the rows of cmap\n clipVals = min(M(:)) + funcClip .* (max(M(:))-min(M(:)));\n overlay = uint8(rescale2(M, clipVals, [0 numColors]));\n if ~isequal(dataSize(vw,1),viewGet(vw,'Size'))\n \n % adjust zoom to be of view size again, not data size\n rsFactor = upSampleFactor(vw,scans(1));\n zoom(3:4) = zoom(3:4) .* rsFactor(1);\n zoom(1:2) = zoom(1:2) .* rsFactor(2);\n \n % now up-sample the overlay to match the view resolution\n newSize = [zoom(4)-zoom(3) zoom(2)-zoom(1) nFrames];\n overlay = upSampleRep(overlay,newSize);\n \n end\n mrvWaitbar(1/4,hwait);\n \n % re-initialize M as a 4D array w/ the anat background\n anatImg = recomputeAnatImage(vw);\n anatImg = anatImg(zoom(3):zoom(4),zoom(1):zoom(2));\n anatImg = normalize(anatImg,0,255);\n M = uint8(repmat(anatImg,[1 1 nFrames 3]));\n \n mrvWaitbar(1/2,hwait);\n \n % get the values for which the overlay > 0\n locs3D = find(overlay>0);\n [yy, xx, zz] = ind2sub(size(overlay),locs3D);\n \n % auto-scale the colormap\n if autoCmap==1\n overlay(locs3D) = rescale2(overlay(locs3D),[],[1 numColors]);\n end\n \n % for each color channel, plug in the appropriate\n % values from the cmap into the overlay locations\n for col = 1:3\n locs4D = sub2ind(size(M),yy,xx,zz,repmat(col,size(yy)));\n M(locs4D) = cmap(overlay(locs3D),col); \n mrvWaitbar(1/2+col/6,hwait);\n end\n close(hwait);\n \n % mplay likes the 4D truecolor array rows x cols x 3 x frames,\n % so permute to this order:\n M = permute(M,[1 2 4 3]);\nelseif compareFrame > 0\n % make an R G B movie in which the red channel is the tSeries,\n % and the G,B channels are the reference frame\n ref = repmat(M(:,:,compareFrame), [1 1 nFrames 2]);\n M = cat(4, M, ref);\n M = permute(M, [1 2 4 3]);\n M = uint8(rescale2(M,[],[0 2^8-1])); \nelse\n % just reduce it to a uint8, for the purpose of rendering\n % (seems tricky to find a way around this bottleneck):\n M = uint8(rescale2(M,[],[0 2^8-1]));\nend\n\n%%%%% plug into mplayer\nif movieFlag==1\n global mrSESSION dataTYPES;\n movie = implay(M,fps);\n \n ttltxt = sprintf('Movie: %s %s %s, Slice %i', ...\n mrSESSION.sessionCode, ...\n dataTYPES(vw.curDataType).name, ...\n num2str(scans), slices(1));\n %set(get(movie,'hfig'),'Name',ttltxt);\n \n % play the movie\n %movie.play\nend\n\n%%%%% export to AVI if selected\nif ~isempty(saveAvi)\n if isequal(saveAvi,'dialog')\n % put up a dialog to get path\n [f p] = uiputfile('*.avi','Save .avi movie as...');\n saveAvi = fullfile(p,f);\n end\n \n % check for .avi extension\n [~, p, ext] = fileparts(saveAvi);\n if ~isequal(lower(ext),'.avi')\n saveAvi = [saveAvi '.avi'];\n end\n \n % construct a matlab movie struct for the export\n mov = repmat(struct('cdata',[],'colormap',[]),1,nFrames);\n for frame = 1:nFrames\n if ndims(M)==4\n mov(frame).cdata = M(:,:,:,frame);\n else\n mov(frame).cdata = repmat(M(:,:,frame),[1 1 3]);\n end\n end\n \n % now export the movie\n if ispc\n codec = 'Indeo3';\n else\n codec = 'None';\n end\n movie2avi(mov,saveAvi,'Compression',codec,'Quality',100,'FPS',fps);\n fprintf('Exported movie to %s.\\n',saveAvi);\nend\n\n\nreturn\n% /-------------------------------------------------------------------/ %\n\n\n\n\n% /-------------------------------------------------------------------/ %\nfunction [M, movie] = tSeriesMovieSlices(vw, scans, slices, anatFlag, varargin)\n% code to recursively call the main function (tSeriesMovie)\n% for each slice, and assemble a montage across slices.\n% Can be very memory-intensive.\nM = []; movie = [];\n\n%%%%% params\nmovieFlag = 1; % call the mplay GUI\nfps = 15;\nsaveAvi = '';\n\n% remove the 'slices' specification for recursion\nopts = unNestCell(varargin);\n% for i=1:length(opts), opts{i} = lower(opts{i}); end\nii = cellfind(opts, 'slices'); \nok = setdiff(1:length(opts), [ii ii+1]);\nopts = opts(ok); \n\n% parse movie options\nfor i = 1:length(opts)\n if ischar(opts{i})\n switch lower(opts{i})\n case 'fps', fps = opts{i+1};\n case 'saveavi',\n\t\t\t\t% if there's a flag to save an .AVI file, we only want to\n\t\t\t\t% do that saving here, not in the recursive call to\n\t\t\t\t% tSeriesMovie below. So, mark it here, but removeit from\n\t\t\t\t% the options list\n\t\t\t\tsaveAvi = opts{i+1};\n\t\t\t\topts{i} = []; opts{i+1} = [];\n case 'nomovie', movieFlag = 0;\n end\n end\nend\n\n% get movie data for each slice\nhwait = mrvWaitbar(0, 'Creating Montage Across Slices...');\nset(hwait, 'Position', get(hwait, 'Position')+[0 100 0 0]);\n\nnSlices = length(slices);\nfor i = 1:nSlices\n slice{i} = tSeriesMovie(vw, scans, anatFlag, 'slices', slices(i), ...\n 'nomovie', opts);\n mrvWaitbar(.8 * (i/nSlices), hwait);\nend\n\n\n%%%%%% make montage\nnRows = ceil(sqrt(nSlices));\nnCols = ceil(nSlices/nRows);\nif nSlices < nRows*nCols % pad out extra images\n for i = nSlices+1:nRows*nCols\n slice{i} = zeros(size(slice{1}));\n end\nend\nslice = reshape(slice, [nCols nRows])';\n\nmrvWaitbar(.95, hwait);\n\nfor r = 1:nRows\n row = [];\n for c = 1:nCols\n row = cat(2, row, slice{1,c});\n end\n\n % be memory-efficient: clear the row we just grabbed\n slice = slice(2:end,:);\n \n M = cat(1, M, row);\nend\n\nclose(hwait);\n\n\n%%%%% show movie if selected\nif movieFlag==1\n global mrSESSION dataTYPES;\n movie = mplay(M,fps);\n ttltxt = sprintf( 'Movie: %s %s %s, Slices %s', ...\n mrSESSION.sessionCode, ...\n dataTYPES(vw.curDataType).name, ...\n num2str(scans), num2str(slices) );\n set(get(movie,'hfig'), 'Name', ttltxt);\nend\n\n%%%%% export to AVI if selected\nif ~isempty(saveAvi)\n if isequal(saveAvi,'dialog')\n % put up a dialog to get path\n [f p] = uiputfile('*.avi','Save .avi movie as...');\n saveAvi = fullfile(p,f);\n end\n \n % check for .avi extension\n [f p ext] = fileparts(saveAvi);\n if ~isequal(lower(ext),'.avi')\n saveAvi = [saveAvi '.avi'];\n end\n \n % construct a matlab movie struct for the export\n nFrames = size(M, ndims(M));\n mov = repmat( struct('cdata',[], 'colormap',[]), 1, nFrames );\n for frame = 1:nFrames\n if ndims(M)==4\n mov(frame).cdata = M(:,:,:,frame);\n else\n mov(frame).cdata = repmat(M(:,:,frame),[1 1 3]);\n end\n\tend\n \n\t% allow the movie path to refer to directories that have not yet been\n\t% created (like 'Movies/')\n\tensureDirExists( fileparts(fullpath(saveAvi)) );\n\t\n % now export the movie\n if ispc\n codec = 'Indeo5';\n else\n codec = 'None';\n end\n movie2avi(mov, saveAvi, 'Compression', codec, 'Quality', 100, 'FPS', fps);\n fprintf('Exported movie to %s.\\n', saveAvi);\nend\n\n%% lastly, play the movie if it exists\nif movieFlag==1\n movie.play\nend\n\nreturn\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/View/tSeriesMovie.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.19473590779299357}} {"text": "function a = shake();\nglobal layout;\nrand('twister',sum(100*clock));\n\na=1;\nfigure(1);\nplot([0 1],[.25 .25],'k',[0 1],[.5 .5],'k',[0 1],[.75 .75],'k',[0 1],[1 1],'k'); hold on;\nplot([.25 .25],[0 1],'k',[.5 .5],[0 1],'k',[.75 .75],[0 1],'k',[1 1],[0 1],'k');\naxis([0 1 0 1],'equal','square');\n\n\nCube(1).letter = {'L','R','Y','T','T','E'};\nCube(2).letter = {'V','T','H','R','W','E'};\nCube(3).letter = {'E','G','H','W','N','E'};\nCube(4).letter = {'S','E','O','T','I','S'};\nCube(5).letter = {'A','N','A','E','E','G'};\nCube(6).letter = {'I','D','S','Y','T','T'};\nCube(7).letter = {'O','A','T','T','O','W'};\nCube(8).letter = {'M','T','O','I','C','U'};\nCube(9).letter = {'A','F','P','K','F','S'};\nCube(10).letter = {'X','L','D','E','R','I'};\nCube(11).letter = {'H','C','P','O','A','S'};\nCube(12).letter = {'E','N','S','I','E','U'};\nCube(13).letter = {'Y','L','D','E','V','R'};\nCube(14).letter = {'Z','N','R','N','H','L'};\nCube(15).letter = {'N','M','I','Qu','H','U'};\nCube(16).letter = {'O','B','B','A','O','J'};\n\nrand(1,16);\n[temp,order]=sort(rand(1,16));\nCube=Cube(order);\n\nfor i=1:4,\n\tfor j=1:4,\n\t\tlayout{i,j} = Cube(i+(j-1)*4).letter(ceil(rand*6));\n\t\ttext(i/4-.15,j/4-.13,layout{i,j},'FontSize',20);\n\tend;\nend;\nset(gca,'XTick',[],'YTick',[]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25562-boggle/boggle/shake.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.19473590411694508}} {"text": "function [nodes,edges,classData] = mrgGrowGray(classData,numLayers,layer0,hemisphere)\n%\n% [nodes,edges,classData] = mrgGrowGray(classInfo,[numLayers],[layer0],[hemisphere='left'])\n%\n% This routine calls the mex function grow_gray with the parameters\n% specified by the user and loads the class file if necessary\n%\n% INPUTS :\n% - classInfo : a variable loaded from a class file or \n% a path string pointing to the class file\n% - numLayers : number of layers to grow the gray matter\n% - layer0 : optional input argument. (Default 0)\n% - 0 : no white matter included in the gray graph\n% - 1 : the white boundary included in the gray graph. \n% In this case, the layer number of the boundary will be 0. \n% - 2 : All the white matter fully connected is included\n% in the gray graph\n%\n% OUTPUTS :\n% - nodes : structure containing nodes of the gray matter\n% - edges : structure containing edges of the gray matter\n% - classData : matlab class file structure containing the output\n%\n% Example:\n% To visualize a mesh with, say, two layers of gray superimposed do this.\n% fName=fullfile(mrvDataRootPath,'anatomy','anatomyV','left','left.Class');\n% [nodes,edges,classData] = mrgGrowGray(fName,2);\n% wm = uint8( (classData.data == classData.type.white) | (classData.data == classData.type.gray));\n% msh = meshColor(meshSmooth(meshBuildFromClass(wm,[1 1 1])));\n% meshVisualize(msh,2);\n%\n% To see the gray matter and white matter in a slice, along with their\n% connectivity, use this. Change the third argument of mrGrowGray to\n% change the type of connectivity you visualize.\n%\n% fName ='X:\\anatomy\\nakadomari\\left\\20050901_fixV1\\left.Class';\n% [nodes,edges,classData] = mrgGrowGray(fName,2,2);\n% mrgDisplayGrayMatter(nodes,edges,80,[120 140 120 140]);\n%\n% NOTE: M. Schira says that the gray nodes should be more densely\n% connected to reduce the error in the distance measurements. We should\n% look into completing the connections in mrGrowGray.\n%\n% HISTORY:\n% GB 01/11/06 wrote it.\n% 2008.07.07 RFD: fixed bug in VOI clipping.\n% 2008.12.19 DY: fixed hemisphere variable setting bug\n%\n% (c) Stanford VISTA Team, 2006\n\nif notDefined('numLayers'), numLayers = 3; end\nif notDefined('layer0'), layer0 = 0; end\nif notDefined('hemisphere'), hemisphere = 'left'; end\nif ischar(classData), classData = readClassFile(classData,0,0,hemisphere); end\n\nvoi = classData.header.voi;\ndata = classData.data;\n% RFD: added the \"| ... 160\". I think this is the type code for 'selected\n% gray matter', but it's not listed in \ndata(data(:) == classData.type.gray) = classData.type.unknown;\n\nfprintf('Growing %i gray layers...\\n',numLayers);\nif layer0, \n fprintf('White matter included in the gray graph...\\n'); \nelse\n fprintf('White matter excluded in the gray graph...\\n');\nend\n\n% Growgray should ignore extra labels, but doesn't-= so we 'clean' it's\n% class data.\ncleanData = data;\ncleanData(cleanData>=classData.type.other) = classData.type.unknown;\n[nodes,edges] = grow_gray(cleanData,numLayers,voi,layer0);\n\ngrayMatter = nodes(1:3,nodes(6,:) ~= 0)+1;\noutOfVoi = grayMatter(1,:)<=voi(1) | grayMatter(1,:)>voi(2) ...\n | grayMatter(2,:)<=voi(3) | grayMatter(2,:)>voi(4) ...\n | grayMatter(3,:)<=voi(5) | grayMatter(3,:)>voi(6);\ngrayMatter(:,outOfVoi) = [];\ndata(sub2ind(size(data),...\n grayMatter(1,:) - voi(1),...\n grayMatter(2,:) - voi(3),...\n grayMatter(3,:) - voi(5))) = classData.type.gray;\n\nclassData.data = data;\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/MrGray/GrowGrayMatter/mrgGrowGray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.19465798159745276}} {"text": "function [EEG, choppedFront, choppedBack] = chop(EEG, frontChop, backChop)\n% Deletes all but specified seconds from outside first and last event\n%\n% This removes bad segments from the beginning and end of the data\n% set, which often correspond to bad times for continuous EEG\n%\n% Parameters:\n% EEG = EEGLAB structure\n% frontChop = \nchoppedFront = 0;\nchoppedBack = 0;\nif size(EEG.data, 3) > 1\n warning('chop:DataNotContinuous', 'Only works on continuous data');\n return;\nelseif nargin < 3\n error('chop:NotEnoughArguments', 'Requires 3 arguments');\nelseif isempty(EEG.event)\n warning('chop:NoEvents', 'EEG has no events, so no chop is done');\n return;\nend\nsrate = EEG.srate;\nfirstEventTime = double(EEG.event(1).latency - 1)/srate;\nlastEventTime = double(EEG.event(end).latency - 1)/srate;\nlastDataTime = double(EEG.pnts-1)/srate;\nchoppedFront = max(0, firstEventTime - frontChop);\nendTime = min(lastDataTime, lastEventTime + backChop);\nchoppedBack = lastDataTime - endTime;\nEEG = pop_select(EEG, 'time', [choppedFront, endTime]);\nboundaryEvents = strcmpi({EEG.event.type}, 'boundary');\nif sum(strcmpi(EEG.event(1).type, 'boundary')) > 0\n fprintf('Removing %g boundary events\\n', sum(boundaryEvents));\n EEG.event(boundaryEvents) = [];\nend", "meta": {"author": "VisLab", "repo": "EEG-Clean-Tools", "sha": "9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e", "save_path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools", "path": "github-repos/MATLAB/VisLab-EEG-Clean-Tools/EEG-Clean-Tools-9ac9ea0c21d44b57f9e9f93b62ca727c7b75c73e/PrepPipeline/utilities/chop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460230820929084}} {"text": "function calcAllFusedTextures_HN(pathData,pathText,namePT,nameCT,nameROI,featType,CTweight_mat,scale_mat,algo_cell,Ng_mat)\n% -------------------------------------------------------------------------\n% function calcAllFusedTextures_HN(pathData,pathText,namePT,nameCT,nameROI,featType,CTweight_mat,scale_mat,Ng_mat)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% This function computes FUSED texture features for all patients, for all \n% different combinations of the following texture extraction parameters:\n% - CT weight: Weight given to MRI wavelet low-pass sub-bands in the \n% PET/CT fusion process. \n% - Scale: Resolution at which the ROI is isotropically resampled.\n% - Ng: Number of gray-levels in the quantization process. \n%\n% Different extraction parameters are passed as arrays or cells in the\n% function in order to test all possible combinations. This function is \n% used for FUSED scans specifically. See Ref. [1,2] and 'prepareVolume.m' \n% for more details.\n%\n% Texture features are computed for all head and neck (HN) DICOM imaging \n% data downloaded from The Cancer Imaging Archive (TCIA) website at: \n% Ex: '/myProject/WORKSPACE/DATA'\n% 2. pathNonText: Full path to the HN non texture features directory.\n% --> Ex: '/myProject/WORKSPACE/FEATURES/NON_TEXTURES'\n% 3. namePT: Cell of strings of all PET sData files to read\n% --> Ex: {'HGJ_001_PT.PTscan.mat';'HGJ_022_PT.PTscan.mat'}\n% 4. namePT: Cell of strings of all CT sData files to read\n% --> Ex: {'HGJ_001_CT.CTscan.mat';'HGJ_022_CT.CTscan.mat'}\n% 5. nameROI: Cell of strings specifying the ROI names to analyze for the\n% patients defined by \"namePT\" and \"nameCT\"\n% --> Ex: {'GTV';'GTV-P'}\n% 6. featType: Either 'GTVp' for primary GTV, or 'GTVtot' for primaty GTV +\n% nodal GTVs\n% 7. CTweight_mat: Array vector specifying the different CT weights to test\n% --> Ex: [1/4,1/3,1/2,2/3,3/4]\n% 8. scale_mat: Array vector specifying the different 'Scale' values to test.\n% --> Ex: [1,2,3,4,5]\n% 9. Ng_mat: Array vector specifying the different 'Ng' values to test.\n% --> Ex: [8,16,32,64]\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: March 2016\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath=pwd;\n\n% INITIALIZATION\nnPatient = numel(namePT);\n\n% COMPUTATION\nfprintf('\\n')\nfor i = 1:nPatient\n cd(pathData)\n sDataPT = load(namePT{i}); sDataPT = struct2cell(sDataPT); sDataPT = sDataPT{1};\n sDataCT = load(nameCT{i}); sDataCT = struct2cell(sDataCT); sDataCT = sDataCT{1};\n tStart = tic;\n fprintf(['\\n*********************** COMPUTING TEXTURES: FUSED %s and %s ***********************'],namePT{i},nameCT{i})\n [textures] = calcPatientFusText_HN(sDataPT,sDataCT,nameROI{i},CTweight_mat,scale_mat,algo_cell,Ng_mat);\n ind = strfind(namePT{i},'_'); namePatient = namePT{i}(1:ind(2)-1);\n cd(pathText), save([namePatient,'_PTCT_',featType,'_text'],'textures')\n time = toc(tStart);\n fprintf('TOTAL TIME: %.2f seconds\\n',time)\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/FEATURES_COMPUTATIONS/calcAllFusedTextures_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19460230820929084}} {"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 [header,tracks] = trk_read(filePath)\n%TRK_READ - Load TrackVis .trk files\n%TrackVis displays and saves .trk files in LPS orientation. After import, this\n%function attempts to reorient the fibers to match the orientation of the\n%original volume data.\n%\n% Syntax: [header,tracks] = trk_read(filePath)\n%\n% Inputs:\n% filePath - Full path to .trk file [char]\n%\n% Outputs:\n% header - Header information from .trk file [struc]\n% tracks - Track data structure array [1 x nTracks]\n% nPoints - # of points in each streamline\n% matrix - XYZ coordinates (in mm) and associated scalars [nPoints x 3+nScalars]\n% props - Properties of the whole tract (ex: length)\n%\n% Example:\n% exDir = '/path/to/along-tract-stats/example';\n% subDir = fullfile(exDir, 'subject1');\n% trkPath = fullfile(subDir, 'CST_L.trk');\n% [header tracks] = trk_read(trkPath);\n%\n% Other m-files required: none\n% Subfunctions: get_header\n% MAT-files required: none\n%\n% See also: http://www.trackvis.org/docs/?subsect=fileformat\n% http://github.com/johncolby/along-tract-stats/wiki/orientation\n\n% Author: John Colby (johncolby@ucla.edu)\n% UCLA Developmental Cognitive Neuroimaging Group (Sowell Lab)\n% Mar 2010\n\n% Parse in header\nfid = fopen(filePath, 'r');\nheader = get_header(fid);\n\n% Check for byte order\nif header.hdr_size~=1000\n fclose(fid);\n fid = fopen(filePath, 'r', 'b'); % Big endian for old PPCs\n header = get_header(fid);\nend\n\nif header.hdr_size~=1000, error('Header length is wrong'), end\n\n% Check orientation\n[tmp ix] = max(abs(header.image_orientation_patient(1:3)));\n[tmp iy] = max(abs(header.image_orientation_patient(4:6)));\niz = 1:3;\niz([ix iy]) = [];\n\n% Fix volume dimensions to match the reported orientation.\nheader.dim = header.dim([ix iy iz]);\nheader.voxel_size = header.voxel_size([ix iy iz]);\n\n% Parse in body\nif header.n_count > 0\n\tmax_n_trks = header.n_count;\nelse\n\t% Unknown number of tracks; we'll just have to read until we run out.\n\tmax_n_trks = inf;\nend\n\n% It's impossible to preallocate the \"tracks\" variable because we don't\n% know the number of points on each curve ahead of time; we find out by\n% reading the file. The line below suppresses preallocation warnings.\n%#ok<*AGROW>\n\niTrk = 1;\nwhile iTrk <= max_n_trks\n\tpts = fread(fid, 1, 'int');\n\tif feof(fid)\n\t\tbreak;\n\tend\n tracks(iTrk).nPoints = pts;\n tracks(iTrk).matrix = fread(fid, [3+header.n_scalars, tracks(iTrk).nPoints], '*float')';\n if header.n_properties\n tracks(iTrk).props = fread(fid, header.n_properties, '*float');\n end\n \n % Modify orientation of tracks (always LPS) to match orientation of volume\n coords = tracks(iTrk).matrix(:,1:3);\n coords = coords(:,[ix iy iz]);\n if header.image_orientation_patient(ix) < 0\n coords(:,ix) = header.dim(ix)*header.voxel_size(ix) - coords(:,ix);\n end\n if header.image_orientation_patient(3+iy) < 0\n coords(:,iy) = header.dim(iy)*header.voxel_size(iy) - coords(:,iy);\n end\n tracks(iTrk).matrix(:,1:3) = coords;\n\tiTrk = iTrk + 1;\nend\n\nif header.n_count == 0\n\theader.n_count = length(tracks);\nend\n\nfclose(fid);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction header = get_header(fid)\n\nheader.id_string = fread(fid, 6, '*char')';\nheader.dim = fread(fid, 3, 'short')';\nheader.voxel_size = fread(fid, 3, 'float')';\nheader.origin = fread(fid, 3, 'float')';\nheader.n_scalars = fread(fid, 1, 'short')';\nheader.scalar_name = fread(fid, [20,10], '*char')';\nheader.n_properties = fread(fid, 1, 'short')';\nheader.property_name = fread(fid, [20,10], '*char')';\nheader.vox_to_ras = fread(fid, [4,4], 'float')';\nheader.reserved = fread(fid, 444, '*char');\nheader.voxel_order = fread(fid, 4, '*char')';\nheader.pad2 = fread(fid, 4, '*char')';\nheader.image_orientation_patient = fread(fid, 6, 'float')';\nheader.pad1 = fread(fid, 2, '*char')';\nheader.invert_x = fread(fid, 1, 'uchar');\nheader.invert_y = fread(fid, 1, 'uchar');\nheader.invert_z = fread(fid, 1, 'uchar');\nheader.swap_xy = fread(fid, 1, 'uchar');\nheader.swap_yz = fread(fid, 1, 'uchar');\nheader.swap_zx = fread(fid, 1, 'uchar');\nheader.n_count = fread(fid, 1, 'int')';\nheader.version = fread(fid, 1, 'int')';\nheader.hdr_size = fread(fid, 1, 'int')';\n", "meta": {"author": "yetianmed", "repo": "subcortex", "sha": "76179cf552b773e79b06a54568eae1fdd13722f4", "save_path": "github-repos/MATLAB/yetianmed-subcortex", "path": "github-repos/MATLAB/yetianmed-subcortex/subcortex-76179cf552b773e79b06a54568eae1fdd13722f4/functions/trk_read.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19451570558812925}} {"text": "clear; clc; close all;\n\nDEVICE_ID = 0; %set gpu id starting from 0\n\n% set paths to Caffe and DeepFool\nPATH_CAFFE = '/path/to/caffe/matlab';\nPATH_DEEPFOOL = '/path/to/DeepFool';\nPATH_IMAGENET_TRAIN = '/path/to/ILSVRC2012/train';\n\naddpath(PATH_CAFFE);\naddpath(PATH_DEEPFOOL);\n\ncaffe.set_mode_gpu();\ncaffe.set_device(DEVICE_ID);\n\nmodel = 'caffenet';\n\nif (strcmp(model, 'vgg_16'))\n fprintf('Loading VGG 16\\n');\n net_model_path = fullfile('data', 'deploy_vgg_16.prototxt');\n net_weights_path = fullfile('data', 'vgg_16.caffemodel');\n net_url = 'http://www.robots.ox.ac.uk/~vgg/software/very_deep/caffe/VGG_ILSVRC_16_layers.caffemodel';\nelseif (strcmp(model, 'vgg_19'))\n fprintf('Loading VGG 19\\n');\n net_model_path = fullfile('data', 'deploy_vgg_19.prototxt');\n net_weights_path = fullfile('data', 'vgg_19.caffemodel');\n net_url = 'http://www.robots.ox.ac.uk/~vgg/software/very_deep/caffe/VGG_ILSVRC_19_layers.caffemodel';\nelseif (strcmp(model, 'googlenet'))\n fprintf('Loading GoogLeNet\\n');\n net_model_path = fullfile('data', 'deploy_googlenet.prototxt');\n net_weights_path = fullfile('data', 'googlenet.caffemodel');\n net_url = 'http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel';\nelseif (strcmp(model, 'vgg_f'))\n fprintf('Loading VGG-F\\n');\n net_model_path = fullfile('data', 'deploy_vgg_f.prototxt');\n net_weights_path = fullfile('data', 'googlenet.caffemodel');\n net_url = 'http://dl.caffe.berkeleyvision.org/bvlc_vgg_f.caffemodel';\nelseif (strcmp(model, 'caffenet'))\n fprintf('Loading CaffeNet\\n');\n net_model_path = fullfile('data', 'deploy_caffenet.prototxt');\n net_weights_path = fullfile('data', 'caffenet.caffemodel');\n net_url = 'http://dl.caffe.berkeleyvision.org/bvlc_reference_caffenet.caffemodel';\nelseif (strcmp(model, 'resnet-152'))\n fprintf('Loading ResNet-152\\n');\n net_model_path = fullfile('data', 'deploy_resnet.prototxt');\n net_weights_path = fullfile('data', 'caffenet.caffemodel');\n net_url = 'https://deepdetect.com/models/resnet/ResNet-152-model.caffemodel';\nelse\n error('Model is not recognized!');\nend\n\nif (~exist(net_weights_path, 'file'))\n fprintf('Downloading model...\\n');\n websave(net_weights_path, net_url);\nend\n \n\nnet = caffe.Net(net_model_path, net_weights_path, 'test'); % run with phase test (so that dropout isn't applied)\nfprintf('Network is loaded\\n');\n\n% Loading the data\nfprintf('Loading the data...\\n');\nim_array = makeImagenetData(PATH_IMAGENET_TRAIN);\nfprintf('Data is loaded\\n');\n\n% set options\nopts.library = 'caffe';\nopts.net = net;\n\nv = universal_perturbation(im_array, opts);\n\n% Test perturbation on a sample image\n\nd = load(fullfile('data', 'ilsvrc_2012_mean.mat'));\nmean_data = d.mean_data;\n\nlabels_file = fullfile('data', 'synset_words.txt');\nfileID = fopen(labels_file);\nC = textscan(fileID, '%c %d %s', 'Delimiter', '\\n');\nsynset_names = C{3};\nsynset_names_short = synset_names;\nfor i = 1:1000\n synset_names_short(i) = strtok(synset_names(i), ',');\nend\n\nim_test = imread(fullfile('data', 'test_img.png'));\nim_test = preprocess_img(im_test, mean_data);\n\noriginal_label = predict_caffe(im_test, net, 1);\nperturbed_label = predict_caffe(im_test+v, net, 1);\n\n% Show original and perturbed images\nim_ = im_test + mean_data(1:224, 1:224, :);\nim_ = permute(im_,[2,1,3]);\nim_ = im_(:,:,[3,2,1],:);\n\nfigure; imshow(uint8(im_));\nxlabel(synset_names_short(original_label));\nset(gca,'xtick',[],'ytick',[])\nset(gcf, 'Color', 'white');\nset(gca, 'FontSize', 15);\ntitle('Original image');\n\nv_ = permute(v,[2,1,3]);\nv_ = v_(:,:,[3,2,1],:);\nfigure; imshow(uint8(im_ + v_));\nxlabel(synset_names_short(perturbed_label));\nset(gca,'xtick',[],'ytick',[])\nset(gcf, 'Color', 'white');\nset(gca, 'FontSize', 15);\ntitle('Perturbed image');\n", "meta": {"author": "LTS4", "repo": "universal", "sha": "2e5ab1544a5c0ea53f07b6c21dbecb6053bb1ca1", "save_path": "github-repos/MATLAB/LTS4-universal", "path": "github-repos/MATLAB/LTS4-universal/universal-2e5ab1544a5c0ea53f07b6c21dbecb6053bb1ca1/matlab/demo_caffe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.19449788401152016}} {"text": "function m = moreland(n)\n%MORELAND Divergent red-white-blue color map\n%\n% Usage: m = moreland([n])\n%\n% Input parameters:\n% n - optional length of colormap (default uses the figure default length)\n%\n% Output parameters:\n% m - colormap [n 3]\n%\n% MORELAND(N) returns an N-by-3 matrix containing a divergent colormap.\n% Without a given N the same length as the current figure's colormap is used.\n% For details on the colormap have a look at:\n% http://www.kennethmoreland.com/color-advice/\n%\n% To change the colormap current figure run: colormap(moreland)\n%\n% Original written by Lewis Marshall.\n%\n% See also: generate_colormap, yellowred, plot_sound_field\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking input parameters =======================================\nnargmin = 0;\nnargmax = 1;\nnarginchk(nargmin,nargmax);\nif nargin < nargmax\n n = size(get(gcf,'colormap'),1);\nend\n\n\n%% ===== Computation =====================================================\ntable = [ 59,76,192\n60,78,194\n61,80,195\n62,81,197\n63,83,198\n64,85,200\n66,87,201\n67,88,203\n68,90,204\n69,92,206\n70,93,207\n71,95,209\n73,97,210\n74,99,211\n75,100,213\n76,102,214\n77,104,215\n79,105,217\n80,107,218\n81,109,219\n82,110,221\n84,112,222\n85,114,223\n86,115,224\n87,117,225\n89,119,226\n90,120,228\n91,122,229\n93,123,230\n94,125,231\n95,127,232\n96,128,233\n98,130,234\n99,131,235\n100,133,236\n102,135,237\n103,136,238\n104,138,239\n106,139,239\n107,141,240\n108,142,241\n110,144,242\n111,145,243\n112,147,243\n114,148,244\n115,150,245\n116,151,246\n118,153,246\n119,154,247\n120,156,247\n122,157,248\n123,158,249\n124,160,249\n126,161,250\n127,163,250\n129,164,251\n130,165,251\n131,167,252\n133,168,252\n134,169,252\n135,171,253\n137,172,253\n138,173,253\n140,174,254\n141,176,254\n142,177,254\n144,178,254\n145,179,254\n147,181,255\n148,182,255\n149,183,255\n151,184,255\n152,185,255\n153,186,255\n155,187,255\n156,188,255\n158,190,255\n159,191,255\n160,192,255\n162,193,255\n163,194,255\n164,195,254\n166,196,254\n167,197,254\n168,198,254\n170,199,253\n171,199,253\n172,200,253\n174,201,253\n175,202,252\n176,203,252\n178,204,251\n179,205,251\n180,205,251\n182,206,250\n183,207,250\n184,208,249\n185,208,248\n187,209,248\n188,210,247\n189,210,247\n190,211,246\n192,212,245\n193,212,245\n194,213,244\n195,213,243\n197,214,243\n198,214,242\n199,215,241\n200,215,240\n201,216,239\n203,216,238\n204,217,238\n205,217,237\n206,217,236\n207,218,235\n208,218,234\n209,219,233\n210,219,232\n211,219,231\n213,219,230\n214,220,229\n215,220,228\n216,220,227\n217,220,225\n218,220,224\n219,220,223\n220,221,222\n221,221,221\n222,220,219\n223,220,218\n224,219,216\n225,219,215\n226,218,214\n227,218,212\n228,217,211\n229,216,209\n230,216,208\n231,215,206\n232,215,205\n232,214,203\n233,213,202\n234,212,200\n235,212,199\n236,211,197\n236,210,196\n237,209,194\n238,209,193\n238,208,191\n239,207,190\n240,206,188\n240,205,187\n241,204,185\n241,203,184\n242,202,182\n242,201,181\n243,200,179\n243,199,178\n244,198,176\n244,197,174\n245,196,173\n245,195,171\n245,194,170\n245,193,168\n246,192,167\n246,191,165\n246,190,163\n246,188,162\n247,187,160\n247,186,159\n247,185,157\n247,184,156\n247,182,154\n247,181,152\n247,180,151\n247,178,149\n247,177,148\n247,176,146\n247,174,145\n247,173,143\n247,172,141\n247,170,140\n247,169,138\n247,167,137\n247,166,135\n246,164,134\n246,163,132\n246,161,131\n246,160,129\n245,158,127\n245,157,126\n245,155,124\n244,154,123\n244,152,121\n244,151,120\n243,149,118\n243,147,117\n242,146,115\n242,144,114\n241,142,112\n241,141,111\n240,139,109\n240,137,108\n239,136,106\n238,134,105\n238,132,103\n237,130,102\n236,129,100\n236,127,99\n235,125,97\n234,123,96\n233,121,95\n233,120,93\n232,118,92\n231,116,90\n230,114,89\n229,112,88\n228,110,86\n227,108,85\n227,106,83\n226,104,82\n225,102,81\n224,100,79\n223,98,78\n222,96,77\n221,94,75\n220,92,74\n218,90,73\n217,88,71\n216,86,70\n215,84,69\n214,82,67\n213,80,66\n212,78,65\n210,75,64\n209,73,62\n208,71,61\n207,69,60\n205,66,59\n204,64,57\n203,62,56\n202,59,55\n200,57,54\n199,54,53\n198,51,52\n196,49,50\n195,46,49\n193,43,48\n192,40,47\n190,37,46\n189,34,45\n188,30,44\n186,26,43\n185,22,41\n183,17,40\n181,11,39\n180,4,38];\nm = generate_colormap(table,n);\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_plotting/colormaps/moreland.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.19422424981873243}} {"text": "classdef grain2d < phaseList & dynProp\n % class representing two dimensional grains\n %\n % Syntax\n % grains = grain2d(V, poly, ori, CSList, phaseId, phaseMap)\n %\n % Input\n % V - n x 2 list of vertices\n % poly - cell array of the polyhedrons\n % ori - array of mean orientations\n % CSList - cell array of symmetries\n % phaseId - list of phaseId for each grain\n % phaseMap -\n %\n % Example\n %\n % V = [0 0; 1 0; 2 0; 0 1; 1 1; 2 1];\n % poly = {[1 2 5 4 1];[2 3 6 5 2]};\n % rot = rotation.rand(2,1);\n % grains = grain2d(V,poly,rot,crystalSymmetry.load('quartz'))\n % plot(grains,grains.meanOrientation)\n %\n % Class Properties\n % phaseId - phase identifier of each grain\n % id - id of each grain\n % poly - cell list of the vertex ids of each grain (index to V)\n % V - list of verticies (x,y coordinates)\n % boundary - @grainBoundary\n % innerBoundary - @grainBoundary\n % triplePoints - @triplePoints\n % grainSize - number if pixels belonging to the grain\n % GOS - grain orientation spread\n % meanOrientation - average grain orientation ()\n %\n % See also\n % GrainReconstruction GrainSpatialPlots SelectingGrains ShapeParameter\n \n % properties with as many rows as data\n properties\n poly={} % cell list of polygons forming the grains\n id=[] % id of each grain \n grainSize = [] % number of measurements per grain\n end\n \n properties (Hidden = true)\n inclusionId = []; % number of elements in poly that model inclusions \n end\n \n % general properties\n properties \n boundary = grainBoundary % boundary of the grains\n innerBoundary = grainBoundary % inner grain boundary\n end\n \n properties (Dependent = true)\n meanOrientation % mean orientation\n V % vertices with x,y coordinates\n scanUnit % unit of the vertice coordinates\n GOS % intragranular average misorientation angle \n x % x coordinates of the vertices of the grains\n y % y coordinates of the vertices of the grains\n triplePoints % triple points\n end\n \n properties (Dependent = true, Access = protected)\n idV % active vertices \n end\n \n methods\n\n function grains = grain2d(V, poly, ori, CSList, phaseId, phaseMap, varargin)\n % constructor\n % \n % Input\n % V - n x 2 list of vertices\n % poly - cell array of the polyhedrons\n % ori - array of mean orientations\n % CSList - cell array of symmetries\n % phaseId - list of phaseId for each grain\n % phaseMap - \n \n if nargin == 0, return;end\n\n grains.poly = poly;\n grains.inclusionId = cellfun(@(p) length(p) - find(p(2:end)==p(1),1),poly)-1;\n\n if nargin>=3 && ~isempty(ori)\n grains.prop.meanRotation = ori;\n else\n grains.prop.meanRotation = rotation.nan(length(poly),1); \n end\n\n if nargin>=4\n grains.CSList = ensurecell(CSList);\n else\n grains.CSList = {'notIndexed'};\n end\n\n if nargin>=5\n grains.phaseId = phaseId;\n else\n grains.phaseId = ones(length(poly),1);\n end\n \n if nargin>=6\n grains.phaseMap = phaseMap;\n else\n grains.phaseMap = 1:length(grains.CSList);\n end\n\n grains.id = (1:numel(grains.phaseId)).';\n grains.grainSize = ones(size(poly));\n \n if isa(V,'grainBoundary') % grain boundary already given\n grains.boundary = V;\n else % otherwise compute grain boundary\n \n % compute boundary segments\n F = arrayfun(@(i) poly{i}([1:end-grains.inclusionId(i)-1;2:end-grains.inclusionId(i)]),...\n 1:length(poly),'uniformOutput',false);\n F = [F{:}].';\n\n lBnd = cellfun(@(p) length(p),poly) - grains.inclusionId -1;\n\n grainIds = repelem(1:length(grains),lBnd);\n\n [~,iF,iG] = unique(sort(F,2),'rows','stable');\n F = F(iF,:);\n \n % compute boundary grainIds\n grainId = zeros(size(F));\n grainId(:,1) = grainIds(iF); % first column - first apperance\n\n % second column - second appearance\n col2 = true(size(iG,1),1);\n col2(iF) = false;\n grainId(iG(col2),2) = grainIds(col2);\n \n % compute misorientation from mean orientations of the grain\n mori = rotation.nan(size(F,1),1);\n isNotBoundary = all(grainId,2);\n mori(isNotBoundary) = ...\n inv(grains.prop.meanRotation(grainId(isNotBoundary,2))) ...\n .* grains.prop.meanRotation(grainId(isNotBoundary,1));\n\n grains.boundary = grainBoundary(V,F,grainId,1:max(grainId),...\n grains.phaseId,mori,grains.CSList,grains.phaseMap);\n \n end\n \n\n end\n \n function V = get.V(grains)\n V = grains.boundary.V;\n end\n \n function x = get.x(grains)\n x = grains.boundary.x;\n end\n \n function y = get.y(grains)\n y = grains.boundary.y;\n end\n \n function grains = set.V(grains,V)\n \n grains.boundary.V = V;\n grains.innerBoundary.V = V;\n \n end\n \n function idV = get.idV(grains)\n \n isCell = cellfun('isclass',grains.poly,'cell');\n polygons = grains.poly;\n polygons(isCell) = cellfun(@(x) [x{:}] ,grains.poly(isCell),'UniformOutput',false);\n idV = unique([polygons{:}]);\n \n end\n \n function varargout = size(grains,varargin)\n [varargout{1:nargout}] = size(grains.id,varargin{:});\n end\n \n function ori = get.meanOrientation(grains)\n if isempty(grains)\n ori = orientation;\n else\n ori = orientation(grains.prop.meanRotation,grains.CS);\n \n % set not indexed orientations to nan\n if ~all(grains.isIndexed), ori(~grains.isIndexed) = NaN; end\n end\n end\n \n function grains = set.meanOrientation(grains,ori)\n \n if ~isempty(grains)\n \n if isnumeric(ori) && all(isnan(ori(:)))\n grains.prop.meanRotation = rotation.nan(size(grains.prop.meanRotation));\n else\n % update rotation\n grains.prop.meanRotation = rotation(ori);\n \n % update phase\n grains.CS = ori.CS;\n end\n end\n \n end\n\n function gos = get.GOS(grains)\n gos = grains.prop.GOS;\n end\n \n function unit = get.scanUnit(grains)\n unit = grains.boundary.scanUnit;\n end\n\n function grains = set.scanUnit(grains,unit)\n grains.boundary.scanUnit = unit;\n grains.innerBoundary.scanUnit = unit;\n end\n \n function tP = get.triplePoints(grains)\n tP = grains.boundary.triplePoints;\n end\n \n function grains = set.triplePoints(grains,tP)\n grains.boundary.triplePoints = tP;\n end\n \n function grains = update(grains)\n \n grains.boundary = grains.boundary.update(grains);\n grains.innerBoundary = grains.innerBoundary.update(grains);\n grains.triplePoints = grains.triplePoints.update(grains);\n \n end\n \n end\n\n methods (Static = true)\n \n [grain2d] = load(fname)\n \n end\n\nend\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/EBSDAnalysis/@grain2d/grain2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.1942242461313857}} {"text": "function [cfg] = ft_multiplotCC(cfg, data)\n\n% FT_MULTIPLOTCC visualises the coherence between channels by using\n% multiple topoplots. The topoplot at a given channel location shows the\n% coherence of that channel with all other channels.\n%\n% Use as\n% ft_multiplotCC(cfg, data)\n%\n% See also FT_PREPARE_LAYOUT, FT_TOPOPLOTCC, FT_CONNECTIVITYPLOT\n\n% Undocumented local options:\n% cfg.layout = layout filename or a structure produced by prepare_layout\n% cfg.xlim\n% cfg.parameter\n% This function requires input from FT_FREQSTATISTICS_SHIFTPREDICT\n% This function should be rewritten, using the clean topoplot implementation\n\n% Copyright (C) 2005-2006, Jan-Mathijs Schoffelen, 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\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 data is valid for this function\ndata = ft_checkdata(data);\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'});\ncfg = ft_checkconfig(cfg, 'deprecated', {'xparam'});\n\n% set the defaults\ncfg.xlim = ft_getopt(cfg, 'xlim', 'all');\ncfg.parameter = ft_getopt(cfg, 'parameter', 'avg.icohspctrm');\ncfg.renderer = ft_getopt(cfg, 'renderer'); % let MATLAB decide on the default\n\nif strcmp(cfg.parameter, 'avg.icohspctrm') && ~issubfield(data, 'avg.icohspctrm')\n data.avg.icohspctrm = abs(imag(data.avg.cohspctrm));\nend\n\nif strcmp(data.dimord, 'chan_chan_freq')\n % reshape input-data, such that ft_topoplotTFR will take it\n cnt = 1;\n siz = size(data.prob);\n data.labelcmb = cell(siz(1)*siz(2),2);\n data.prob = reshape(data.prob, [siz(1)*siz(2) siz(3)]);\n data.stat = reshape(data.stat, [siz(1)*siz(2) siz(3)]);\n for j = 1:length(data.label)\n for k = 1:length(data.label)\n data.labelcmb(cnt,:) = [data.label(k) data.label(j)];\n cnt = cnt + 1;\n end\n end\n tmpdata = data;\nelse\n dat = getsubfield(data, cfg.parameter);\n scale = [0 max(dat(:))-0.2];\nend\n\nif isfield(cfg, 'xparam')\n xparam = getsubfield(data, cfg.xparam);\n if ~strcmp(cfg.xlim, 'all')\n fbin = [nearest(xparam, cfg.xlim(1)) nearest(xparam, cfg.xlim(2))];\n else\n fbin = [xparam(1) xparam(end)];\n end\nend\n\n% read or create the layout that will be used for plotting\ntmpcfg = keepfields(cfg, {'layout', 'channel', 'rows', 'columns', 'commentpos', 'skipcomnt', 'scalepos', 'skipscale', 'projection', 'viewpoint', 'rotate', 'width', 'height', 'elec', 'grad', 'opto', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\nlayout = ft_prepare_layout(tmpcfg);\nft_plot_layout(layout, 'box', false, 'label', 'no', 'point', 'no');\n\nX = layout.pos(:,1);\nY = layout.pos(:,2);\nWidth = layout.width;\nHeight = layout.height;\nLbl = layout.label;\nchNum = numel(layout.label);\n\nxScaleFac = 1/(max(Width)+ max(X) - min(X));\nyScaleFac = 1/(max(Height)+ max(Y) - min(Y));\n\nXpos = xScaleFac*(X-min(X));\nYpos = 0.9*yScaleFac*(Y-min(Y));\n\nfor k=1:length(chNum) - 2\n subplotOL('position',[Xpos(k) Ypos(k)+(Height(k)*yScaleFac) Width(k)*xScaleFac*2 Height(k)*yScaleFac*2])\n tmpcfg = keepfields(cfg, {'parameter', 'layout', 'renderer', 'visible'});\n if exist('tmpdata', 'var')\n tmpcfg.style = 'straight';\n tmpcfg.marker = 'off';\n try\n tmpcfg.refmarker = strmatch(Lbl(k), data.reflabel);\n catch\n tmpcfg.refmarker = strmatch(Lbl(k), data.label);\n end\n tmpcfg.interplimits = 'electrodes';\n if isfield(cfg, 'xparam')\n tmpcfg.xparam = cfg.xparam;\n tmpcfg.xlim = xparam;\n else\n tmpcfg.xparam = 'freq';\n tmpcfg.xlim = [k-0.5 k+0.5];\n end\n tmpcfg.refchannel = Lbl(k);\n tmpcfg.colorbar = 'no';\n tmpcfg.zlim = scale;\n tmpcfg.grid_scale = 30;\n ft_topoplotTFR(tmpcfg, data);\n drawnow\n end\nend\n\n% this is needed for the figure title\nif isfield(cfg, 'dataname') && ~isempty(cfg.dataname)\n dataname = cfg.dataname;\nelseif isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile)\n dataname = cfg.inputfile;\nelseif nargin>1\n dataname = arrayfun(@inputname, 2:nargin, 'UniformOutput', false);\nelse\n dataname = {};\nend\n\n% set the figure window title\nif ~isempty(dataname)\n set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), mfilename, join_str(', ', dataname)));\nelse\n set(gcf, 'Name', sprintf('%d: %s', double(gcf), mfilename));\nend\nset(gcf, 'NumberTitle', 'off');\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous data\nft_postamble provenance\nft_postamble savefig\n\n% add a menu to the figure, but only if the current figure does not have subplots\nmenu_fieldtrip(gcf, cfg, false);\n\nif ~ft_nargout\n % don't return anything\n clear cfg\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_multiplotCC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19401007617453214}} {"text": "function visual_odo_main(visualDataFile,groundTruthFile)\n% NeuroSLAM System Copyright (C) 2018-2019 \n% NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n% Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n% The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n% The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n% Reference:\n% Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n% \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n %% vo\n % for drawing images for estimating pitch and yaw\n global SUB_TRANS_IMG;\n global SUB_YAW_ROT_IMG;\n global SUB_HEIGHT_V_IMG;\n\n global ODO_IMG_TRANS_RESIZE_RANGE;\n global ODO_IMG_YAW_ROT_RESIZE_RANGE;\n global ODO_IMG_HEIGHT_V_RESIZE_RANGE;\n \n global PREV_TRANS_V_IMG_X_SUMS;\n global PREV_YAW_ROT_V_IMG_X_SUMS;\n global PREV_HEIGHT_V_IMG_Y_SUMS;\n \n %% read imgs as VT input\n\n % get the visual data info\n [subFoldersPathSet, numSubFolders] = get_images_data_info(visualDataFile);\n\n % load ground truth data\n [frameId, gt_x, gt_y, gt_z, gt_rx, gt_ry, gt_rz] = load_ground_truth_data(groundTruthFile);\n groundTruthData = [gt_x gt_y gt_z];\n \n % define temp variables of previous profiles\n preProfilesTransImg = zeros(1,ODO_IMG_TRANS_RESIZE_RANGE(2));\n preProfilesYawRotImg = zeros(1,ODO_IMG_YAW_ROT_RESIZE_RANGE(2));\n preProfilesPitchRotImg = zeros(ODO_IMG_HEIGHT_V_RESIZE_RANGE(2), 1);\n \n % For drawing the current rot direction\n curRotDir = [0 0 0];\n curRotDir(1,3) = 0;\n\n \n % The total rotational angle\n sumRotAngle = 0;\n \n \n % for drawing the direction theta (rotational angle)\n theta = [0 0 0 0 0 0];\n rho = [0 0 0 0 0 0];\n startPoint =[0 0];\n endPoint = [0.8 0.8];\n\n % For drawing the velocity\n subRotVel = [];\n transVelVector = [];\n heightVelVector = [];\n sumHeight = [];\n transVelVector(1) = 0;\n heightVelVector(1) = 0;\n subRotVel(1) = 0;\n sumHeight = 0;\n \n % Transform the angle from degree to radian\n global DEGREE_TO_RADIAN;\n DEGREE_TO_RADIAN = pi / 180;\n \n % Transform the angle from radian to degree \n global RADIAN_TO_DEGREE;\n RADIAN_TO_DEGREE = 180 / pi; \n \n RENDER_RATE = 2;\n \n IMG_TYPE = '*.png';\n \n global OFFSET_YAW_ROT; \n offset_yaw_rot_vector = [];\n offset_yaw_rot_vector(1) = 0;\n \n global OFFSET_HEIGHT_V;\n offset_height_V_vector = [];\n offset_height_V_vector(1) = 0;\n \n odoMapTrajectory(1,1) = 0;\n odoMapTrajectory(1,2) = 0;\n odoMapTrajectory(1,3) = 0;\n odoMapTrajectory(1,4) = 0;\n \n ODO_MAP_X_SCALING = 1;\n ODO_MAP_Y_SCALING = 1;\n ODO_MAP_Z_SCALING = 1;\n GT_ODO_X_SCALING = 1;\n GT_ODO_Y_SCALING = 1;\n GT_ODO_Z_SCALING = 1;\n \n curFrame = 0;\n% step = 1;\n\n% % up\n startFrame = 1;\n endFrame = 3000;\n\n % down\n% startFrame = 2484;\n% endFrame = 2621;\n\n % level_2\n% startFrame = 925;\n% endFrame = 2483;\n\n %% processing visual odometry\n for iSubFolder = 1 : numSubFolders\n \n [curFolderPath, imgFilesPathList, numImgs] = get_cur_img_files_path_list(subFoldersPathSet, IMG_TYPE, iSubFolder);\n \n if numImgs > 0\n for indFrame = startFrame : endFrame\n curFrame = curFrame + 1;\n [curImg] = read_current_image(curFolderPath, imgFilesPathList, indFrame);\n\n % visual templates and visual odo uses intensity so convert to grayscale\n curGrayImg = rgb2gray(curImg);\n curGrayImg = im2double(curGrayImg);\n \n % for drawing previous intensity\n preProfilesTransImg = PREV_TRANS_V_IMG_X_SUMS;\n preProfilesYawRotImg = PREV_YAW_ROT_V_IMG_X_SUMS;\n preProfilesHeightVImg = PREV_HEIGHT_V_IMG_Y_SUMS;\n \n %% step2: processing vo\n % get the odometry from the video\n % computing the 3d odometry based on the current image.\n % yawRotV and pitchRotV in degree\n [transV, yawRotV, heightV] = visual_odometry(curGrayImg);\n\n\n subRotVel(curFrame) = yawRotV;\n transVelVector(curFrame) = transV;\n heightVelVector(curFrame) = heightV;\n \n offset_yaw_rot_vector(curFrame) = OFFSET_YAW_ROT;\n offset_height_V_vector(curFrame) = OFFSET_HEIGHT_V;\n \n sumHeight(curFrame + 1) = sumHeight(curFrame) + heightV;\n \n % For drawing the total rotational angle\n if sumRotAngle + yawRotV >= 360\n sumRotAngle = mod(sumRotAngle + yawRotV, 360);\n elseif sumRotAngle + yawRotV <= -360\n sumRotAngle = sumRotAngle + yawRotV + 360;\n else\n sumRotAngle = sumRotAngle + yawRotV;\n end\n\n\n \n % Transform the vrot from degree to radian\n yawRotV = yawRotV * DEGREE_TO_RADIAN; \n\n % Direction by raw odometry\n curRotDir(curFrame + 1, 1) = cos(curRotDir(curFrame, 3) + yawRotV );\n curRotDir(curFrame + 1, 2) = sin(curRotDir(curFrame, 3) + yawRotV );\n curRotDir(curFrame + 1, 3) = curRotDir(curFrame, 3) + yawRotV;\n \n odoMapTrajectory(curFrame + 1,1) = odoMapTrajectory(curFrame,1) + transV * cos(sym(curRotDir(curFrame + 1, 3)));\n odoMapTrajectory(curFrame + 1,2) = odoMapTrajectory(curFrame,2) + transV * sin(sym(curRotDir(curFrame + 1, 3)));\n odoMapTrajectory(curFrame + 1,3) = odoMapTrajectory(curFrame,3) + heightV;\n odoMapTrajectory(curFrame + 1,4) = curRotDir(curFrame + 1, 3);\n \n % render results information\n if (mod(curFrame, RENDER_RATE) == 0)\n\n % computing the normalized profile of horizontal translational image\n profilesTransImg = sum(SUB_TRANS_IMG);\n avgIntensity = sum(profilesTransImg) / size(profilesTransImg, 2);\n profilesTransImg = profilesTransImg / avgIntensity; \n\n \n % computing the normalized profile of rotational image\n profilesYawRotImg = sum(SUB_YAW_ROT_IMG);\n avgIntensity = sum(profilesYawRotImg) / size(profilesYawRotImg, 2);\n profilesYawRotImg = profilesYawRotImg / avgIntensity; \n\n% diffYawRotImgs = profilesYawRotImg - preProfilesYawRotImg;\n % computing the normalized profile of vertical transV image\n profilesHeightVImg = sum(SUB_HEIGHT_V_IMG,2);\n avgIntensity = sum(profilesHeightVImg) / size(profilesHeightVImg, 1);\n profilesHeightVImg = profilesHeightVImg / avgIntensity; \n \n diffHeightVImgs = profilesHeightVImg - preProfilesHeightVImg;\n \n \n figure(1)\n \n % draw odo map\n subplot(1, 1, 1, 'replace');\n hold on\n plot3((odoMapTrajectory(:,2))* ODO_MAP_X_SCALING , ...\n (odoMapTrajectory(:,1)) * ODO_MAP_Y_SCALING, ...\n (odoMapTrajectory(:,3) ) * ODO_MAP_Z_SCALING, '.b');\n \n% plot3((gt_x(1:curFrame) - gt_x(1)) * GT_ODO_X_SCALING, ...\n% (gt_y(1:curFrame) - gt_y(1)) * GT_ODO_Y_SCALING, ...\n% (gt_z(1:curFrame) - gt_z(1)) * GT_ODO_Z_SCALING, '.r');\n hold off;\n view(3);\n grid on;\n% view(0, 90);\n xl = xlabel('odo-map-x');\n yl = ylabel('odo-map-y');\n zlabel('odo-map-z');\n set(xl,'Rotation',15);\n set(yl,'Rotation',-30);\n% title('Multilayered Odometry Map');\n% legend('Result','Truth' ,'1');\n% axis([-5 110 -5 100 -2 5]);\n axis on\n rotate3d on\n \n % draw odo map\n% subplot(1, 2, 2, 'replace');\n% hold on\n% plot3((odoMapTrajectory(:,2))* ODO_MAP_X_SCALING , ...\n% (odoMapTrajectory(:,1)) * ODO_MAP_Y_SCALING, ...\n% (odoMapTrajectory(:,3) ) * ODO_MAP_Z_SCALING, '.b');\n% \n% % plot3((gt_x(1:curFrame) - gt_x(1)) * GT_ODO_X_SCALING, ...\n% % (gt_y(1:curFrame) - gt_y(1)) * GT_ODO_Y_SCALING, ...\n% % (gt_z(1:curFrame) - gt_z(1)) * GT_ODO_Z_SCALING, '.r');\n% hold off;\n% grid on;\n% view(0, 90);\n% xlabel('odo-map-x');\n% ylabel('odo-map-y');\n% zlabel('odo-map-z');\n% % title('Multilayered Odometry Map (top view)');\n% % legend('Result','Truth' ,'1');\n% % axis([-5 110 -5 100]);\n% axis on\n% \n \n figure(2)\n % render the horizontal translational velocity\n subplot(1, 1, 1, 'replace');\n plot(subRotVel);\n% title('Yaw rotational velocity');\n xlabel('Time');\n ylabel('vYawRot');\n axis on\n \n figure(3)\n % render current rot direction \n subplot(1, 1, 1, 'replace');\n polar(theta,rho);\n hold on\n plot([startPoint(1) curRotDir(curFrame,1)],[startPoint(2) curRotDir(curFrame,2)],'linewidth',1,'color',[0.9 0 0]);\n% title('Current rotational direction');\n \n figure(4)\n % render the sub image for estimating horizontal translational velocity\n subplot(3, 4, 1, 'replace');\n imshow(SUB_TRANS_IMG, []);\n title('Sub image (vHoriTrans)');\n xlabel('Width');\n ylabel('Height');\n axis on\n\n % draw the the normalized profile of horizontal translational image\n subplot(3,4,5, 'replace');\n hold on\n plot(1: size(profilesTransImg,2),profilesTransImg, 'r');\n plot(1: size(preProfilesTransImg,2),preProfilesTransImg, 'g');\n hold off\n% legend('curr', 'g: prev');\n title('The intensity profiles');\n xlabel('Width');\n ylabel('Normalized profile');\n axis on\n\n % render the horizontal translational velocity\n subplot(3, 4, 9, 'replace');\n plot(transVelVector);\n title('Translational velocity');\n xlabel('Time');\n ylabel('vTrans');\n axis on\n \n % render the sub image for estimating rotational velocity\n subplot(3, 4, 2, 'replace');\n imshow(SUB_YAW_ROT_IMG, []);\n title('Sub image (vYawRot)');\n xlabel('Width');\n ylabel('Height');\n axis on\n\n \n % draw the the normalized profile of rotational image\n subplot(3,4,6, 'replace');\n hold on \n plot(1: size(profilesYawRotImg,2),profilesYawRotImg, 'r');\n plot(1: size(preProfilesYawRotImg,2),preProfilesYawRotImg, 'g');\n hold off\n% legend('r: curr', 'g: prev');\n title('The intensity profiles');\n xlabel('Width');\n ylabel('Normalized profile');\n axis on\n\n \n \n % render the sub image for estimating pitch velocity\n subplot(3, 4, 3, 'replace');\n imshow(SUB_HEIGHT_V_IMG, []);\n title('Sub image (vPitchRot)');\n xlabel('Width');\n ylabel('Height');\n axis on\n \n % draw the the normalized profile of height v image\n subplot(3,4,7, 'replace');\n hold on \n plot(profilesHeightVImg, 1: size(profilesHeightVImg,1), 'r');\n plot(preProfilesHeightVImg, 1: size(preProfilesHeightVImg,1), 'g');\n hold off\n% legend('r: curr', 'g: prev');\n title('The intensity profiles');\n xlabel('Width');\n ylabel('Normalized profile');\n axis on\n \n % render the horizontal translational velocity\n subplot(3, 4, 11, 'replace');\n plot(heightVelVector);\n title('Vertical translational velocity');\n xlabel('Time');\n ylabel('vVertTrans');\n axis on\n \n \n\n % render the horizontal translational velocity\n subplot(3, 4, 8, 'replace');\n plot(sumHeight);\n title('Height Change');\n xlabel('Time');\n ylabel('Height');\n axis on\n \n % render the horizontal translational velocity\n subplot(3, 4, 12, 'replace');\n hold on\n plot(offset_yaw_rot_vector, 'r');\n plot(offset_height_V_vector, 'g');\n hold off\n title('Offset yaw rotation');\n xlabel('Time');\n ylabel('Offset');\n axis on \n \n% figure(3) \n% \n% subplot(1,1,1, 'replace');\n% hold on \n% plot(1: size(diffHeightVImgs,1),diffHeightVImgs, 'r');\n% hold off\n% % legend('r: curr', 'g: prev');\n% title('The diff between two intensity profiles');\n% xlabel('Width');\n% ylabel('Diff');\n% axis on\n \n drawnow\n end\n end\n end\n end\nend\n", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/03_visual_odometry/visual_odo_main_draw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19401006609120386}} {"text": "function eventLog = ma_executeCoast_goto_func_value(event, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, maData, celBodyData)\n%ma_executeCoast_goto_func_value Summary of this function goes here\n% Detailed explanation goes here\n global number_state_log_entries_per_coast;\n \n old_number_state_log_entries_per_coast = number_state_log_entries_per_coast;\n number_state_log_entries_per_coast = 5; %#ok\n \n bnds = [0, event.maxPropTime];\n funcNoAbs = @(dt) getCoastFuncValue(dt, event.funcHandle, event.coastToValue, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, maData, celBodyData, false);\n funcAbs = @(dt) getCoastFuncValue(dt, event.funcHandle, event.coastToValue, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, maData, celBodyData, true);\n\n odeFunc = @(t,y) odefun(t,y);\n evtFnc = @(t,y) odeEventsFun(t,y,funcNoAbs);\n options = odeset('RelTol',1E-6, 'AbsTol',1E-6, 'Events',evtFnc, 'MaxStep',abs(diff(bnds))/50);\n [~,~,te,~,ie] = ode45(odeFunc, bnds, bnds(1), options);\n \n if(isempty(ie)) %fall back to old way of doing things\n options = optimset('TolX',1E-6);\n [x, fval, exitflag] = fminbnd(funcAbs, bnds(1), bnds(2), options);\n\n if(exitflag == 0 || abs(fval) > 1E-4)\n x = event.maxPropTime;\n end\n else\n x = te(1);\n end\n \n number_state_log_entries_per_coast = old_number_state_log_entries_per_coast;\n eventLog = ma_executeCoast_goto_dt(x, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, celBodyData);\nend\n\nfunction ydot = odefun(~,~)\n ydot = 1;\nend\n\nfunction [value,isterminal,direction] = odeEventsFun(t,~, func)\n value = func(t);\n isterminal = 1;\n direction = 0;\nend\n\nfunction value = getCoastFuncValue(dt, funcHandle, desiredValue, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, maData, celBodyData, useAbs)\n eventLog = ma_executeCoast_goto_dt(dt, initialState, eventNum, considerSoITransitions, soiSkipIds, massLoss, orbitDecay, celBodyData);\n finalState = eventLog(end,:);\n \n [datapt, ~, ~, taskStr, refBodyInfo, otherSC, station] = funcHandle(finalState, false, maData);\n \n if(useAbs)\n value = abs(datapt - desiredValue);\n else\n value = datapt - desiredValue;\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/coast/ma_executeCoast_goto_func_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}} {"text": "function out = PlotPath(state, scalling, mapName)\n% uses B-spline interpolation \n path = state.path';\n path(:,3) = 1;\n path(:,4) = 1;\n\n if nargin <3\n scalling = 1;\n imag = state.map;\n else\n tmp = LoadMap( strcat(mapName, '.png'), 1);\n imag = tmp.map;\n end\n\n \n if scalling ~= 1\n path(:,1) = path(:,1)-2.5;\n path(:,2) = path(:,2)-2.5;\n pathInterpolated = BSpline(path*scalling);\n else\n pathInterpolated = path;\n end\n %%5\n for it = pathInterpolated'\n a = round(it);\n imag(a(1), a(2)) = 0.6;\n end\n figure(100)\n out.handle = imshow(imag);\n out.path = pathInterpolated;\n \nend", "meta": {"author": "LazyFalcon", "repo": "D_star_PathPlanning", "sha": "2e0e97591e4cbaa6c77c0e9b9abcf16916238656", "save_path": "github-repos/MATLAB/LazyFalcon-D_star_PathPlanning", "path": "github-repos/MATLAB/LazyFalcon-D_star_PathPlanning/D_star_PathPlanning-2e0e97591e4cbaa6c77c0e9b9abcf16916238656/PlotPath.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.19394753852655577}} {"text": "function mv = multiVoxelUI(view, roi , scans, dt);\n% mv = multiVoxelUI(view, [roi , scans, dt])\n%\n% multiVoxelUI: user interface for displaying time course / amplitude\n% data across roi within an ROI.\n%\n%\n%\n% ARGS:\n% input:\n% view: mrVista view struct\n% \n% roi : coords (by the current view's conventions) of the roi \n% from which to plot data. May also be a string providing the name of\n% the ROI to plot. Default is view's currently-selected ROI.\n%\n% scans: scans in the current view/data dt to plot. Default is\n% currently-selected scan. For multiple scans, will concatenate\n% together after detrending (using the detrend options saved in the\n% dataTYPES struct in the mrSESSION file).\n%\n% dt: data type to use. Defaults to currently selected data\n% type.\n%\n%output:\n% h: handle to time course interface.\n% \n% data: array containing time course data from selected voxels /scans.\n%\n% More notes:\n% This is currently implemented as a small set of linked analysis tools, \n% all starting with the prefix 'tc_'. This particular piece of code\n% decides, based on the number of input args, whether to open a new\n% mv user interface or just update an existing one, and then refreshes the \n% current mv view according to the time course data and user prefs.\n%\n% Here's how it decides to open a new UI or not: if a view is passed as the\n% first argument, it opens a new one. If there are no input args, it\n% assumes the current figure has the interface and refreshes it. (This is\n% called by all the callbacks on the interface).\n% \n% The time course data, condition information, user prefs, and handles to \n% important controls are all kept in a mv struct stored in the user\n% interface's 'UserData' field. I currently treat each UI as a separate\n% figure; though in time I may find it useful to group several interfaces\n% on multiple axes in the same figure.\n\n% 1/3/04 ras: wrote it.\n% 1/04: added signal to noise ratios, ability to switch off different cond\n% displays, shift onsets, change colors\n% 2/04: added ability to read multiple scans / concat parfiles if it uses\n% them\n% 2/23/04: broke up into several functions, under mrLoadRet sub-section\n% Plots/TimeCourseUI. Also made an offshoot of this, fancyplot2, which\n% doesn't use the mrLoadRet view info, for kalanit. Renamed multiVoxelUI\n% (previously ras_tc -- saved that as an older, stable version).\nmrGlobals\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 1ST DECISION: extract new time course data (w/ corresponding\n% axes figure) or just re-render existing data? This is decided by \n% the # args: if 1, update data; otherwise, just render.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin >= 1\n openFigFlag = 1;\nelse\n openFigFlag = 0;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Open the figure if needed %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif openFigFlag\n if notDefined('dt')\n dt = viewGet(view, 'curDataType');\n end\n \n if notDefined('scans')\n scans = er_getScanGroup(view); %viewGet(view, 'curScan');\n end\n \n if notDefined('roi')\n r = viewGet(view, 'curRoi');\n if r==0\n myErrorDlg('Sorry, you need to load an ROI first.')\n end\n roi = view.ROIs(r);\n end\n \n % want roi to be a struct: parse\n % how it's passed in and make a struct\n roi = tc_roiStruct(view, roi);\n \n % init a voxel data struct from params \n % (this includes loading the data)\n mv = mv_init(view, roi, scans, dt);\n \n % put up the interface window\n mv = mv_openFig(mv);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% RENDER TIME COURSE (taking into account prefs as specified in the\n% ui)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% get the data struct -- in the current axes' UserData\nmv = get(gcf, 'UserData');\n\n% clear previous axes in the figure\nold = findobj('Type', 'axes', 'Parent', gcf);\nold = [old; findobj('Type', 'uicontrol', 'Parent', gcf)];\ndelete(old);\n\n% legend (kind of a hack -- legends are tricky)\nif mv.params.legend==1\n sel = find(tc_selectedConds(mv));\n co = [];\n for i = 1:length(sel)\n % The legend text should be the specified condition names\n leg{i} = mv.condNames{sel(i)};\n % remove underscores -- the teX interpreter is weird about em\n leg{i}(findstr(leg{i}, '_')) = ' ';\n % also get appropriate colors\n co = [co; mv.condColors{sel(i)}];\n end\n set(gca, 'NextPlot', 'ReplaceChildren');\n if length(sel) > 0\n % Plot some random data, just to get the legend put up \n set(gca, 'ColorOrder', co);\n plot(rand(2, length(sel)), 'LineWidth', 4); \n legend(gca, leg, -1);\n end\nend\n\n% select the current plot type\neval( get(mv.ui.plotHandles(mv.ui.plotType), 'Callback') )\n\n% stash the updated data struct\nset(gcf, 'UserData', mv);\n\nreturn", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/MultiVoxelUI/multiVoxelUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1937835041774695}} {"text": "function ChannelMat = in_channel_besa_eps(ChannelFile)\n% IN_CHANNEL_BESA_EPS: Read 3D cartesian positions for a set of electrodes from an couple .eps/ela BESA file.\n%\n% USAGE: ChannelMat = in_channel_besa_eps(ChannelFile)\n%\n% INPUTS: \n% - ChannelFile : Full path to the file (either .ela or .eps file)\n%\n% FORMAT:\n% - .ELA file: contains the labels\n% - .EPS file: contains the positions of the electrodes\n \n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2009-2012\n\n% Check file extension\n[fPath, fBase, fExt] = bst_fileparts(ChannelFile);\nswitch lower(fExt)\n case '.eps'\n epsFile = ChannelFile;\n elaFile = bst_fullfile(fPath, [fBase, '.ela']);\n case '.ela'\n elaFile = ChannelFile;\n epsFile = bst_fullfile(fPath, [fBase, '.eps']);\nend\n \n% ELP: Get the positions\nif ~isempty(epsFile) && file_exist(epsFile)\n ChannelMat = in_channel_ascii(epsFile, {'-Y','X','Z'}, 0, .01);\n ChannelMat.Comment = 'BESA channels';\nelse\n disp('BESA> Error: EPS file is missing');\n ChannelMat = [];\nend\n\n% ELA: Get the labels/types\nif ~isempty(elaFile) && file_exist(elaFile)\n % === READ FILE ===\n % Open file\n fid = fopen(elaFile, 'r');\n if (fid == -1)\n error('Cannot open .ela file.');\n end\n % Read file\n ela = textscan(fid, '%s %s');\n % Close file\n fclose(fid);\n \n % === FILE TYPE ===\n nChan = length(ela{1});\n % ONE column (channel names)\n if all(cellfun(@isempty, ela{2}))\n chLabels = ela{1};\n % By default, all channels are considered as EEG\n chTypes = repmat({'EEG'}, [nChan, 1]);\n % TWO columns (channel types+names)\n else\n chTypes = ela{1};\n chLabels = ela{2};\n end\n \n % === SET THE LABELS ===\n % Create an empty Channel structure if EPS file is missing\n if isempty(ChannelMat)\n ChannelMat = db_template('channelmat');\n ChannelMat.Comment = 'BESA channels';\n ChannelMat.Channel = repmat(db_template('channeldesc'), [1, nChan]);\n [ChannelMat.Channel.Loc] = deal([0;0;0]);\n end\n % Set the labels\n for i = 1:length(chLabels)\n ChannelMat.Channel(i).Name = chLabels{i};\n end\n % Set the types\n for i = 1:length(chLabels)\n ChannelMat.Channel(i).Type = chTypes{i};\n end\nelse\n disp('BESA> Error: ELA file is missing');\nend\n\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_channel_besa_eps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19378350417746948}} {"text": "% readneuronedata() - Read NeurOne Binary files\n%\n% Usage: >> data = readneuronedata(dataFiles,nChannels,chans)\n%\n% ===================================================================\n% Inputs: \n% dataFiles - A cell structure containing full paths for data \n% files to be read. This is input argument is\n% required.\n% nChannels - Another required input argument:\n% the total number of channels.\n% chans - A vector containing the channel numbers to be\n% read. They have to be arranged in an ascending\n% order. This input argument is optional.\n% ====================================================================\n% Output:\n% data - A matrix where all numerical data is stored.\n% The data is arranged so that the data for each\n% channel is stored in a row according\n% to its number. \n%\n% ========================================================================\n% NOTE:\n% This file is part of the NeurOne data import plugin for EEGLAB.\n% ========================================================================\n% \n% Current version: 1.0.3.4 (2016-06-17)\n% Author: Mega Electronics\n\nfunction data = readneuronedata(dataFiles,nChannels,chans)\n%% Parse input arguments\np = inputParser;\np.addRequired('dataFiles', @iscellstr);\np.addRequired('nChannels', @isnumeric);\np.addOptional('chans', 0, @isnumeric);\n\np.parse(dataFiles, nChannels, chans);\narglist=p.Results;\n\n%% Prepare reading data\nnDataFiles = numel(arglist.dataFiles);\nchans = arglist.chans;\nnChannels = arglist.nChannels;\n\nif chans==0\n chans=1:nChannels;\nend\n\n% Get all file sizes\nfSize=zeros(1,nDataFiles);\ntmp={};\n\nfor k=1:nDataFiles\n tmp{k,1}=dir(dataFiles{k,1});\n fSize(1,k)=tmp{k,1}.bytes;\nend\n\nfSizes=cumsum(fSize);\n\n% Total size of the data\ntotalSize=sum(fSize);\n% Total number of data points (per channel)\ndataPntsTotal=(totalSize/4)/nChannels;\n% Number of data points in each binary file (per channel)\ndataPnts=(fSize./4)./nChannels;\n\n%% Read binary data\n\nfprintf('Allocating memory...\\n')\ndata=zeros(numel(chans),dataPntsTotal);\n\n\n% Option 1: Read all channels at once (faster method)\nif numel(chans)==nChannels\n fprintf('Reading data...');\n data=data(:);\n readidx=[0 (fSizes/4)];\n for n=1:nDataFiles\n fid = fopen([dataFiles{n}], 'rb');\n data((1+readidx(n)):readidx(n+1),1)=fread(fid, ...\n fSize(n)/4,'int32');\n fclose(fid);\n end\n data=reshape(data,nChannels,dataPntsTotal);\n fprintf('%s','Done');\nelse\n % Option 2: Read only specific channels to save memory\n fprintf('Reading data... 0%%');\n readidx=[0 (fSizes/4)./nChannels];\n \n % Read channels one by one\n for k=1:numel(chans)\n for n=1:nDataFiles\n \n fid = fopen([dataFiles{n}], 'rb');\n fseek(fid, 4*(chans(k) - 1), 'bof');\n data(k,(1+readidx(n)):readidx(n+1)) = fread(fid, ...\n dataPnts(n),'int32',4*(nChannels-1))';\n fclose(fid);\n end\n \n % Print progress to the command window\n ii = floor(k/numel(chans)*100);\n if ii<10\n ii = [num2str(ii) '%'];\n fprintf(1,'\\b\\b%s',ii);\n elseif ii==100;\n ii = 'Done';\n fprintf(1,'\\b\\b\\b%s',ii);\n else\n ii = [num2str(ii) '%'];\n fprintf(1,'\\b\\b\\b%s',ii);\n \n end\n end \nend\n\nfprintf('\\n');\n\n%% Convert data from nanovolts to microvolts\ndata=data./1000;\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/neurone/readneuronedata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19373855048955074}} {"text": "function y = conj( x )\n\n%Disciplined convex/geometric programming information for CONJ:\n% CONJ(X) imposes no convexity restrictions on its arguments. However,\n% since CONJ(X)=X when X is real, it is only useful for complex\n% affine expressions.\n\ny = cvx( x.size_, conj( x.basis_ ) );\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/builtins/@cvx/conj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19358781864024524}} {"text": "function y = conj( x )\n\n%Disciplined convex/geometric programming information for CONJ:\n% CONJ(X) imposes no convexity restrictions on its arguments. However,\n% since CONJ(X)=X when X is real, it is only useful for complex\n% affine expressions.\n\ny = cvx( x.size_, conj( x.basis_ ) );\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/conj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}} {"text": "% ------------------------------------------------------------------------\n% Analyze non-linear ROIs that were clicked as 'object points'\n% ------------------------------------------------------------------------\n\n\n%% ENTER PARAMETERS AND FILE LOCATION\n\n% file location of object points\nsave_folder = 'C:\\Drive\\Histology\\for tutorial\\Richards\\processed';\n\n% directory of reference atlas files\nannotation_volume_location = 'C:\\Drive\\Histology\\annotation_volume_10um_by_index.npy'; % from the allen inst (see readme)\nstructure_tree_location = 'C:\\Drive\\Histology\\structure_tree_safe_2017.csv'; % located in github repo\nCCF_to_FP_location = 'C:\\Drive\\Histology\\CCF_to_FP.csv'; % located in github repo\nFP_table_location = 'C:\\Drive\\Histology\\FP_table_Chon_2020.csv'; % located in github repo\nchon_images_loc = 'C:\\Drive\\Histology\\Suppl_File1_Labels'; % from chon et al (supplementary data 4, https://www.nature.com/articles/s41467-019-13057-w)\n\n% name of the saved object points\nobject_save_name_suffix = '';\n\n% either set to 'all' or a list of indices from the clicked objects in this file, e.g. [2,3]\nobjects_to_analyze = 'all';\n\n% plane used to view when points were clicked ('coronal' -- most common, 'sagittal', 'transverse')\nplane = 'coronal';\n\n% brain figure black or white\nblack_brain = true;\n\n\n%% LOAD THE REFERENCE ANNOTATIONS AND PROBE POINTS\n\n% load the reference brain annotations\nif ~exist('av','var') || ~exist('st','var')\n disp('loading reference atlas...')\n av = readNPY(annotation_volume_location);\n st = loadStructureTree(structure_tree_location);\nend\nif ~exist('CCFtoFPtable','var') || ~exist('FPtable','var')\n CCFtoFPtable = loadCCFtoFP(CCF_to_FP_location);\n FPtable = loadFPtable(FP_table_location);\nend\n\n% load object points\nobjectPoints = load(fullfile(save_folder, ['probe_points' object_save_name_suffix]));\n\n% determine which objects to analyze\nif strcmp(objects_to_analyze,'all')\n objects = 1:size(objectPoints.pointList.pointList,1);\nelse\n objects = objects_to_analyze;\nend \n\n\n%% BRING UP THE RELEVANT DATA FOR EACH PROBE POINTS, FOR FURTHER ANALYSIS\n\n% initialize cell array containing info on each clicked point\nif length(objects) > 1\n roi_annotation = cell(length(objects),1);\n roi_location = cell(length(objects),1);\nend\n\n% generate needed values\nbregma = allenCCFbregma(); % bregma position in reference data space\natlas_resolution = 0.010; % mm\n\n% plot brain grid\nProbeColors = [1 1 1; 1 .75 0; .3 1 1; .4 .6 .2; 1 .35 .65; .7 .7 1; .65 .4 .25; .7 .95 .3; .7 0 0; .6 0 .7; 1 .6 0]; \n% order of colors: {'white','gold','turquoise','fern','bubble gum','overcast sky','rawhide', 'green apple','purple','orange','red'};\nfwireframe = plotBrainGrid([], [], [], black_brain); hold on; \nfwireframe.InvertHardcopy = 'off';\n\n\n\nfor object_num = objects\n \n selected_object = objects(object_num);\n \n % get the object points for the currently analyzed object \n if strcmp(plane,'coronal')\n curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [3 2 1]);\n elseif strcmp(plane,'sagittal')\n curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [1 2 3]);\n elseif strcmp(plane,'transverse')\n curr_objectPoints = objectPoints.pointList.pointList{selected_object,1}(:, [1 3 2]);\n end\n\n % plot points on the wire frame brain\n figure(fwireframe); hold on\n hp = plot3(curr_objectPoints(:,1), curr_objectPoints(:,3), curr_objectPoints(:,2), '.','linewidth',2, 'color',[ProbeColors(object_num,:) .2],'markers',10); \n\n % use the point's position in the atlas to get the AP, DV, and ML coordinates\n ap = -(curr_objectPoints(:,1)-bregma(1))*atlas_resolution;\n dv = (curr_objectPoints(:,2)-bregma(2))*atlas_resolution;\n ml = (curr_objectPoints(:,3)-bregma(3))*atlas_resolution;\n\n roi_location_curr = [ap dv ml];\n \n % initialize array of region annotations\n roi_annotation_curr = cell(size(curr_objectPoints,1),3); \n roi_annotation_curr_FP = cell(size(curr_objectPoints,1),3); \n \n % loop through every point to get ROI locations and region annotations\n for point = 1:size(curr_objectPoints,1)\n\n % find the annotation, name, and acronym of the current ROI pixel\n ann = av(curr_objectPoints(point,1),curr_objectPoints(point,2),curr_objectPoints(point,3));\n name = st.safe_name{ann};\n acr = st.acronym{ann};\n\n roi_annotation_curr{point,1} = ann;\n roi_annotation_curr{point,2} = name;\n roi_annotation_curr{point,3} = acr;\n \n % find the annotation, name, and acronym of the current ROI pixel\n [ann_FP, name_FP, acr_FP] = CCF_to_FP(curr_objectPoints(point,1), curr_objectPoints(point,2), curr_objectPoints(point,3), CCFtoFPtable, FPtable, chon_images_loc);\n\n roi_annotation_curr_FP{point,1} = ann_FP;\n roi_annotation_curr_FP{point,2} = name_FP;\n roi_annotation_curr_FP{point,3} = acr_FP;\n\n end\n \n % save results in cell array\n if length(objects) > 1\n roi_annotation{object_num} = roi_annotation_curr;\n roi_location{object_num} = roi_location_curr;\n else\n roi_annotation = roi_annotation_curr;\n roi_location = roi_location_curr;\n end\n \n % display results in a table\n disp(['Clicked points for object ' num2str(selected_object)])\n roi_table = table(roi_annotation_curr(:,2),roi_annotation_curr(:,3), roi_annotation_curr_FP(:,2),roi_annotation_curr_FP(:,3),...\n roi_location_curr(:,1),roi_location_curr(:,2),roi_location_curr(:,3), roi_annotation_curr(:,1), roi_annotation_curr_FP(:,1),...\n 'VariableNames', {'CCF_name', 'CCF_acronym', 'FP_name', 'FP_acronym', 'AP_location', 'DV_location', 'ML_location', 'avIndex', 'fpIndex'});\n disp(roi_table)\n \nend\n\n\n% now, use roi_location and roi_annotation for your further analyses\n\n\n", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/SHARP-Track/Convert_Clicked_Points_to_FP_coords.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.1933420385695957}} {"text": "function [tablePathwayRxns] = runFindSparsePathway(model,modelType,start,stop,via,CandidateSubSystem,specificMetabolites2Ignore);\n% This function takes in a model (either metabolic model or a whole-body\n% model), a start metabolite, and a stop metabolite and finds a shortest\n% pathway\nignoreMetabolites = {'atp','h','coa','pi','h2o','o2','nh4','h2o2','nadph','nadh','nadp','nad','adp','udp','na1','hco3',...\n 'ppi', 'imp','xmp','amp','ppa','fad','fadh2','oh1','co2','gmp','so4','pap','paps','mg2','zn2',...\n 'cl','ca2','cu2','adpcbl','fe3','vitd3','i','caro','mn2','fe2','avite1','btn','ascb_L','phyQ','pnto_R','pydx','k'};\n\n%% do not change hereafter\n\nignoreMetabolites = [specificMetabolites2Ignore';ignoreMetabolites'];\ntablePathwayRxns ='';\ns=' ';\nosenseStr = 'max';\n\nmodel = addReaction(model,['start_', start],'reactionFormula',[start,s,'<=>']);\nmodel = addReaction(model,['stop_', stop],'reactionFormula',[stop,s,'<=>']);\nprintRxnFormula(model,model.rxns(end-1:end))\n\nmodel2 = model;\ncompartments = {'e','c','m','n','p','r','l','g','x'};\nignoreMet = [];\nfor i = 1 : length(compartments)\n ignoreM =strcat(ignoreMetabolites,'[',compartments{i},']');\n ignoreMet = [ignoreMet;ignoreM'];\nend\nif strcmp(modelType,'WBM')\n sex = model.sex;\n % load list of organs\n OrganLists;\n % expand list of compartments for biofluids\n biofluids = {'bc','bcK','bp','d','u','lu','luLI','luSI','fe','csf','luC','a','aL','sw','luI','bpC','bpL'};\n \n for i = 1 : length(biofluids)\n ignoreM =strcat(ignoreMetabolites,'[',biofluids{i},']');\n ignoreMet = [ignoreMet;ignoreM'];\n end\n clear ignoreM\n ignoreMet2 =[ignoreMet];\n for i = 1 : length(OrgansListExt)\n ignoreM =strcat(OrgansListExt{i},'_',ignoreMet);\n ignoreMet2 = [ignoreMet2;ignoreM];\n end\n ignoreMet = ignoreMet2;\nend\n\n[model2, rxnRemoveList] = removeMetabolites(model2, ignoreMet,true,'legacy');\n\n\n%Excl_R = [find(contains(model2.rxns,'DM_'));find(contains(model2.rxns,'sink_'));];\n%model2 = changeRxnBounds(model2,model2.rxns(Excl_R),0,'b');\n\n% needed for WBM\n% set whole\nif strcmp(modelType,'WBM')\n model2 = changeRxnBounds(model2,'Whole_body_objective_rxn',0,'l');\n model2 = changeRxnBounds(model2,'Whole_body_objective_rxn',1,'u');\nend\n%remove all constraints\nmodel2.lb(find(model2.lb<0))=-10000000;\nmodel2.ub(find(model2.ub<0))=0;\nmodel2.lb(find(model2.lb>0))=0;\nmodel2.ub(find(model2.ub>0))=10000000;\n\n% remove coupling constraints if present\nif isfield(model2,'C')\n model2 = rmfield(model2,'C');\n model2 = rmfield(model2,'ctrs');\nend\n\n% does not work for WBM\n\n%model = changeRxnBounds(model,model.rxns(find(contains(model.rxns,'EX_'))),-1,'l');\n\nmodel2 = changeObjective(model2,['stop_', stop]);\nmodel2 = changeRxnBounds(model2,['start_', start],-1000,'b');\nmodel2 = changeRxnBounds(model2,['stop_', stop],1000,'l');\n\nif ~isempty(via)\n % enforce flux through via reactions\n \n % model2 = changeRxnBounds(model2,via,-1*ones(length(via),1),'u');\n model2 = changeRxnBounds(model2,via,1*ones(length(via),1),'l');\nend\n \n\nFBA = optimizeCbModel(model2);\n\nif FBA.origStat == 1 %problem is feasible\n %%\n param.printLevel = 0;\n param.regularizeOuter = 1;\n rxnPenalty = ones(length(model2.rxns),1);\n % not implemented yet \n %RS = findRxnsFromSubSystem(model2,CandidateSubSystem);\n %rxnPenalty(ismember(model2.rxns,RS)) = 0;\n rxnPenalty(ismember(model2.rxns,['stop_', stop])) = -1;\n rxnPenalty(ismember(model2.rxns,['start_', start])) = -1;\n rxnPenalty(ismember(model2.rxns,via)) = -1;\n [solution,sparseRxnBool2] = findSparsePathway(model2,rxnPenalty,param);\n sparse = model2.rxns(sparseRxnBool2)\n nnz(sparseRxnBool2)\n nnz(solution.v)\n pathwayRxnsAbbr = sparse;\n pathwayRxnsFormulae = printRxnFormula(model,'rxnAbbrList',sparse,'printFlag',0);\n tablePathwayRxns = table(pathwayRxnsAbbr,pathwayRxnsFormulae);\n nnz(solution.v)\n if 1\n % without ignore metabolites\n [involvedMets, deadEnds] = draw_by_rxn(model2, sparse, 'true');\n else\n % with ignored metabolites\n [involvedMets, deadEnds] = draw_by_rxn(model, sparse, 'true');\n end\nelse\n fprintf('Problem is infeasible.\\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/analysis/wholeBody/PSCMToolbox/runFindSparsePathway.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.19330883435945118}} {"text": "function [cls,M1] = spm_preproc_write8(res,tc,bf,df,mrf,cleanup,bb,vx)\n% Write out VBM preprocessed data\n% FORMAT [cls,M1] = spm_preproc_write8(res,tc,bf,df,mrf,cleanup,bb,vx)\n%__________________________________________________________________________\n% Copyright (C) 2008-2016 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_preproc_write8.m 6881 2016-09-19 09:48:54Z john $\n\n% Prior adjustment factor.\n% This is a fudge factor to weaken the effects of the tissue priors. The\n% idea here is that the bias from the tissue priors probably needs to be\n% reduced because of the spatial smoothing typically used in VBM studies.\n% Having the optimal bias/variance tradeoff for each voxel is not the same\n% as having the optimal tradeoff for weighted averages over several voxels.\n\nif isfield(res,'mg')\n lkp = res.lkp;\n Kb = max(lkp);\nelse\n Kb = size(res.intensity(1).lik,2);\nend\nN = numel(res.image);\n\nif nargin<2, tc = true(Kb,4); end % native, import, warped, warped-mod\nif nargin<3, bf = false(N,2); end % field, corrected\nif nargin<4, df = false(1,2); end % inverse, forward\nif nargin<5, mrf = 1; end % MRF parameter\nif nargin<6, cleanup = 1; end % Run the ad hoc cleanup\n\n% Read essentials from tpm (it will be cleared later)\ntpm = res.tpm;\nif ~isstruct(tpm) || ~isfield(tpm, 'bg1'),\n tpm = spm_load_priors8(tpm);\nend\nd1 = size(tpm.dat{1});\nd1 = d1(1:3);\nM1 = tpm.M;\n\n% Define orientation and field of view of any \"normalised\" space\n% data that may be generated (wc*.nii, mwc*.nii, rc*.nii & y_*.nii).\nif nargin>=7 && any(isfinite(bb(:)))\n % If a bounding box is supplied, combine this with the closest\n % bounding box derived from the dimensions and orientations of\n % the tissue priors.\n if nargin<7, bb = NaN(2,3); end % Default to TPM bounding box\n if nargin<8, vx = NaN; end % Default to TPM voxel size\n [bb1,vx1] = spm_get_bbox(tpm.V(1), 'old');\n bb(~isfinite(bb)) = bb1(~isfinite(bb));\n if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end\n bb(1,:) = vx*round(bb(1,:)/vx);\n bb(2,:) = vx*round(bb(2,:)/vx);\n odim = abs(round((bb(2,1:3)-bb(1,1:3))/vx))+1;\n\n mm = [[bb(1,1) bb(1,2) bb(1,3)\n bb(2,1) bb(1,2) bb(1,3)\n bb(1,1) bb(2,2) bb(1,3)\n bb(2,1) bb(2,2) bb(1,3)\n bb(1,1) bb(1,2) bb(2,3)\n bb(2,1) bb(1,2) bb(2,3)\n bb(1,1) bb(2,2) bb(2,3)\n bb(2,1) bb(2,2) bb(2,3)]'; ones(1,8)];\n vx3 = [[1 1 1\n odim(1) 1 1\n 1 odim(2) 1\n odim(1) odim(2) 1\n 1 1 odim(3)\n odim(1) 1 odim(3)\n 1 odim(2) odim(3)\n odim(1) odim(2) odim(3)]'; ones(1,8)];\n mat = mm/vx3;\nelse\n % Use the actual dimensions and orientations of\n % the tissue priors.\n odim = tpm.V(1).dim;\n mat = tpm.V(1).mat;\nend\n\n\n[pth,nam] = fileparts(res.image(1).fname);\nind = res.image(1).n;\nd = res.image(1).dim(1:3);\n\n[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);\nx3 = 1:d(3);\n\nchan(N) = struct('B1',[],'B2',[],'B3',[],'T',[],'Nc',[],'Nf',[],'ind',[]);\nfor n=1:N\n d3 = [size(res.Tbias{n}) 1];\n chan(n).B3 = spm_dctmtx(d(3),d3(3),x3);\n chan(n).B2 = spm_dctmtx(d(2),d3(2),x2(1,:)');\n chan(n).B1 = spm_dctmtx(d(1),d3(1),x1(:,1));\n chan(n).T = res.Tbias{n};\n\n % Need to fix writing of bias fields or bias corrected images, when the data used are 4D.\n [pth1,nam1] = fileparts(res.image(n).fname);\n chan(n).ind = res.image(n).n;\n\n if bf(n,2)\n chan(n).Nc = nifti;\n chan(n).Nc.dat = file_array(fullfile(pth1,['m', nam1, '.nii']),...\n res.image(n).dim(1:3),...\n [spm_type('float32') spm_platform('bigend')],...\n 0,1,0);\n chan(n).Nc.mat = res.image(n).mat;\n chan(n).Nc.mat0 = res.image(n).mat;\n chan(n).Nc.descrip = 'Bias corrected';\n create(chan(n).Nc);\n end\n\n if bf(n,1),\n chan(n).Nf = nifti;\n chan(n).Nf.dat = file_array(fullfile(pth1,['BiasField_', nam1, '.nii']),...\n res.image(n).dim(1:3),...\n [spm_type('float32') spm_platform('bigend')],...\n 0,1,0);\n chan(n).Nf.mat = res.image(n).mat;\n chan(n).Nf.mat0 = res.image(n).mat;\n chan(n).Nf.descrip = 'Estimated Bias Field';\n create(chan(n).Nf);\n end\nend\n\ndo_cls = any(tc(:)) || nargout>=1;\ntiss(Kb) = struct('Nt',[]);\nfor k1=1:Kb\n if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1,\n do_cls = true;\n end\n if tc(k1,1),\n tiss(k1).Nt = nifti;\n tiss(k1).Nt.dat = file_array(fullfile(pth,['c', num2str(k1), nam, '.nii']),...\n res.image(n).dim(1:3),...\n [spm_type('uint8') spm_platform('bigend')],...\n 0,1/255,0);\n tiss(k1).Nt.mat = res.image(n).mat;\n tiss(k1).Nt.mat0 = res.image(n).mat;\n tiss(k1).Nt.descrip = ['Tissue class ' num2str(k1)];\n create(tiss(k1).Nt);\n do_cls = true;\n end\nend\n\nprm = [3 3 3 0 0 0];\nCoef = cell(1,3);\nCoef{1} = spm_bsplinc(res.Twarp(:,:,:,1),prm);\nCoef{2} = spm_bsplinc(res.Twarp(:,:,:,2),prm);\nCoef{3} = spm_bsplinc(res.Twarp(:,:,:,3),prm);\n\ndo_defs = any(df);\ndo_defs = do_cls | do_defs;\nif do_defs\n if df(1)\n [pth,nam] =fileparts(res.image(1).fname);\n Ndef = nifti;\n Ndef.dat = file_array(fullfile(pth,['iy_', nam, '.nii']),...\n [res.image(1).dim(1:3),1,3],...\n [spm_type('float32') spm_platform('bigend')],...\n 0,1,0);\n Ndef.mat = res.image(1).mat;\n Ndef.mat0 = res.image(1).mat;\n Ndef.descrip = 'Inverse Deformation';\n create(Ndef);\n end\n if df(2) || any(any(tc(:,[2,3,4]))) || nargout>=1,\n y = zeros([res.image(1).dim(1:3),3],'single');\n end\nend\n\nspm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');\nM = M1\\res.Affine*res.image(1).mat;\n\nif do_cls\n Q = zeros([d(1:3),Kb],'single');\nend\n\nfor z=1:length(x3)\n\n % Bias corrected image\n cr = cell(1,N);\n for n=1:N\n f = spm_sample_vol(res.image(n),x1,x2,o*x3(z),0);\n bf = exp(transf(chan(n).B1,chan(n).B2,chan(n).B3(z,:),chan(n).T));\n cr{n} = bf.*f;\n if ~isempty(chan(n).Nc),\n % Write a plane of bias corrected data\n chan(n).Nc.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = cr{n};\n end\n if ~isempty(chan(n).Nf),\n % Write a plane of bias field\n chan(n).Nf.dat(:,:,z,chan(n).ind(1),chan(n).ind(2)) = bf;\n end\n end\n\n\n if do_defs\n % Compute the deformation (mapping voxels in image to voxels in TPM)\n [t1,t2,t3] = defs(Coef,z,res.MT,prm,x1,x2,x3,M);\n\n if exist('Ndef','var')\n % Write out the deformation to file, adjusting it so mapping is\n % to voxels (voxels in image to mm in TPM)\n tmp = M1(1,1)*t1 + M1(1,2)*t2 + M1(1,3)*t3 + M1(1,4);\n Ndef.dat(:,:,z,1,1) = tmp;\n tmp = M1(2,1)*t1 + M1(2,2)*t2 + M1(2,3)*t3 + M1(2,4);\n Ndef.dat(:,:,z,1,2) = tmp;\n tmp = M1(3,1)*t1 + M1(3,2)*t2 + M1(3,3)*t3 + M1(3,4);\n Ndef.dat(:,:,z,1,3) = tmp;\n end\n\n if exist('y','var')\n % If needed later, save in variable y\n y(:,:,z,1) = t1;\n y(:,:,z,2) = t2;\n y(:,:,z,3) = t3;\n end\n\n if do_cls\n % Generate variable Q if tissue classes are needed\n %msk = (f==0) | ~isfinite(f);\n\n if isfield(res,'mg')\n % Parametric representation of intensity distributions\n q = zeros([d(1:2) Kb]);\n q1 = likelihoods(cr,[],res.mg,res.mn,res.vr);\n q1 = reshape(q1,[d(1:2),numel(res.mg)]);\n b = spm_sample_priors8(tpm,t1,t2,t3);\n wp = res.wp;\n s = zeros(size(b{1}));\n for k1 = 1:Kb\n b{k1} = wp(k1)*b{k1};\n s = s + b{k1};\n end\n for k1=1:Kb\n q(:,:,k1) = sum(q1(:,:,lkp==k1),3).*(b{k1}./s);\n end\n else\n % Nonparametric representation of intensity distributions\n q = spm_sample_priors8(tpm,t1,t2,t3);\n wp = res.wp;\n s = zeros(size(q{1}));\n for k1 = 1:Kb\n q{k1} = wp(k1)*q{k1};\n s = s + q{k1};\n end\n for k1 = 1:Kb\n q{k1} = q{k1}./s;\n end\n q = cat(3,q{:});\n\n for n=1:N\n tmp = round(cr{n}*res.intensity(n).interscal(2) + res.intensity(n).interscal(1));\n tmp = min(max(tmp,1),size(res.intensity(n).lik,1));\n for k1=1:Kb\n likelihood = res.intensity(n).lik(:,k1);\n q(:,:,k1) = q(:,:,k1).*likelihood(tmp);\n end\n end\n end\n Q(:,:,z,:) = reshape(q,[d(1:2),1,Kb]);\n end\n end\n spm_progress_bar('set',z);\nend\nspm_progress_bar('clear');\n\n\ncls = cell(1,Kb);\nif do_cls\n P = zeros([d(1:3),Kb],'uint8');\n if mrf==0\n % Normalise to sum to 1\n sQ = (sum(Q,4)+eps)/255;\n for k1=1:size(Q,4)\n P(:,:,:,k1) = uint8(round(Q(:,:,:,k1)./sQ));\n end\n clear sQ\n else\n % Use a MRF cleanup procedure\n nmrf_its = 10;\n spm_progress_bar('init',nmrf_its,['MRF: Working on ' nam],'Iterations completed');\n G = ones([Kb,1],'single')*mrf;\n vx2 = 1./single(sum(res.image(1).mat(1:3,1:3).^2));\n %save PQG P Q G tiss Kb x3 ind\n for iter=1:nmrf_its\n spm_mrf(P,Q,G,vx2);\n spm_progress_bar('set',iter);\n end\n end\n clear Q\n\n if cleanup\n % Use an ad hoc brain cleanup procedure\n if size(P,4)>5\n P = clean_gwc(P,cleanup);\n else\n warning('Cleanup not done.');\n end\n end\n\n % Write tissues if necessary\n for k1=1:Kb\n if ~isempty(tiss(k1).Nt)\n for z=1:length(x3)\n tmp = double(P(:,:,z,k1))/255;\n tiss(k1).Nt.dat(:,:,z,ind(1),ind(2)) = tmp;\n end\n end\n end\n spm_progress_bar('clear');\n\n % Put tissue classes into a cell array...\n for k1=1:Kb\n if tc(k1,4) || any(tc(:,3)) || tc(k1,2) || nargout>=1\n cls{k1} = P(:,:,:,k1);\n end\n end\n clear P % ...and remove the original 4D array\nend\n\nclear tpm\nM0 = res.image(1).mat;\n\nif any(tc(:,2))\n % \"Imported\" tissue class images\n\n % Generate mm coordinates of where deformations map from\n x = affind(rgrid(d),M0);\n\n % Generate mm coordinates of where deformation maps to\n y1 = affind(y,M1);\n\n % Procrustes analysis to compute the closest rigid-body\n % transformation to the deformation, weighted by the\n % interesting tissue classes.\n ind = find(tc(:,2)); % Saved tissue classes\n [dummy,R] = spm_get_closest_affine(x,y1,single(cls{ind(1)})/255);\n clear x y1\n\n mat0 = R\\mat; % Voxel-to-world of original image space\n\n [pth,nam] = fileparts(res.image(1).fname);\n fwhm = max(vx./sqrt(sum(res.image(1).mat(1:3,1:3).^2))-1,0.01);\n for k1=1:size(tc,1)\n if tc(k1,2)\n\n % Low pass filtering to reduce aliasing effects in downsampled images,\n % then reslice and write to disk\n tmp1 = decimate(single(cls{k1}),fwhm);\n Ni = nifti;\n Ni.dat = file_array(fullfile(pth,['rc', num2str(k1), nam, '.nii']),...\n odim,...\n [spm_type('float32') spm_platform('bigend')],...\n 0,1,0);\n Ni.mat = mat;\n Ni.mat_intent = 'Aligned';\n Ni.mat0 = mat0;\n Ni.mat0_intent = 'Aligned';\n Ni.descrip = ['Imported Tissue ' num2str(k1)];\n create(Ni);\n\n for i=1:odim(3)\n tmp = spm_slice_vol(tmp1,M0\\mat0*spm_matrix([0 0 i]),odim(1:2),[1,NaN])/255;\n Ni.dat(:,:,i) = tmp;\n end\n clear tmp1\n end\n end\nend\n\nif any(tc(:,3)) || any(tc(:,4)) || nargout>=1 || df(2)\n % Adjust stuff so that warped data (and deformations) have the\n % desired bounding box and voxel sizes, instead of being the same\n % as those of the tissue probability maps.\n M = mat\\M1;\n for i=1:size(y,3)\n t1 = y(:,:,i,1);\n t2 = y(:,:,i,2);\n t3 = y(:,:,i,3);\n y(:,:,i,1) = M(1,1)*t1 + M(1,2)*t2 + M(1,3)*t3 + M(1,4);\n y(:,:,i,2) = M(2,1)*t1 + M(2,2)*t2 + M(2,3)*t3 + M(2,4);\n y(:,:,i,3) = M(3,1)*t1 + M(3,2)*t2 + M(3,3)*t3 + M(3,4);\n end\n M1 = mat;\n d1 = odim;\nend\n\n\nif any(tc(:,3)) || any(tc(:,4)) || nargout>=1\n\n if any(tc(:,3))\n C = zeros([d1,Kb],'single');\n end\n\n spm_progress_bar('init',Kb,'Warped Tissue Classes','Classes completed');\n for k1 = 1:Kb\n if ~isempty(cls{k1})\n c = single(cls{k1})/255;\n if any(tc(:,3))\n [c,w] = spm_diffeo('push',c,y,d1(1:3));\n vx = sqrt(sum(M1(1:3,1:3).^2));\n spm_field('boundary',1);\n C(:,:,:,k1) = spm_field(w,c,[vx 1e-6 1e-4 0 3 2]);\n clear w\n else\n c = spm_diffeo('push',c,y,d1(1:3));\n end\n if nargout>=1\n cls{k1} = c;\n end\n if tc(k1,4)\n N = nifti;\n N.dat = file_array(fullfile(pth,['mwc', num2str(k1), nam, '.nii']),...\n d1,...\n [spm_type('float32') spm_platform('bigend')],...\n 0,1,0);\n N.mat = M1;\n N.mat0 = M1;\n N.descrip = ['Jac. sc. warped tissue class ' num2str(k1)];\n create(N);\n N.dat(:,:,:) = c*abs(det(M0(1:3,1:3))/det(M1(1:3,1:3)));\n end\n spm_progress_bar('set',k1);\n end\n end\n spm_progress_bar('Clear');\n\n if any(tc(:,3))\n spm_progress_bar('init',Kb,'Writing Warped Tis Cls','Classes completed');\n C = max(C,eps);\n s = sum(C,4);\n for k1=1:Kb\n if tc(k1,3)\n N = nifti;\n N.dat = file_array(fullfile(pth,['wc', num2str(k1), nam, '.nii']),...\n d1,'uint8',0,1/255,0);\n N.mat = M1;\n N.mat0 = M1;\n N.descrip = ['Warped tissue class ' num2str(k1)];\n create(N);\n N.dat(:,:,:) = C(:,:,:,k1)./s;\n end\n spm_progress_bar('set',k1);\n end\n spm_progress_bar('Clear');\n clear C s\n end\nend\n\nif df(2)\n y = spm_diffeo('invdef',y,d1,eye(4),M0);\n y = spm_extrapolate_def(y,M1);\n N = nifti;\n N.dat = file_array(fullfile(pth,['y_', nam, '.nii']),...\n [d1,1,3],'float32',0,1,0);\n N.mat = M1;\n N.mat0 = M1;\n N.descrip = 'Deformation';\n create(N);\n N.dat(:,:,:,:,:) = reshape(y,[d1,1,3]);\nend\n\nreturn;\n\n\n%==========================================================================\n% function [x1,y1,z1] = defs(sol,z,MT,prm,x0,y0,z0,M)\n%==========================================================================\nfunction [x1,y1,z1] = defs(sol,z,MT,prm,x0,y0,z0,M)\niMT = inv(MT);\nx1 = x0*iMT(1,1)+iMT(1,4);\ny1 = y0*iMT(2,2)+iMT(2,4);\nz1 = (z0(z)*iMT(3,3)+iMT(3,4))*ones(size(x1));\nx1a = x0 + spm_bsplins(sol{1},x1,y1,z1,prm);\ny1a = y0 + spm_bsplins(sol{2},x1,y1,z1,prm);\nz1a = z0(z) + spm_bsplins(sol{3},x1,y1,z1,prm);\nx1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);\ny1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);\nz1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);\nreturn;\n\n\n%==========================================================================\n% function t = transf(B1,B2,B3,T)\n%==========================================================================\nfunction t = transf(B1,B2,B3,T)\nif ~isempty(T)\n d2 = [size(T) 1];\n t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));\n t = B1*t1*B2';\nelse\n t = zeros(size(B1,1),size(B2,1),size(B3,1));\nend\nreturn;\n\n\n%==========================================================================\n% function p = likelihoods(f,bf,mg,mn,vr)\n%==========================================================================\nfunction p = likelihoods(f,bf,mg,mn,vr)\nK = numel(mg);\nN = numel(f);\nM = numel(f{1});\ncr = zeros(M,N);\nfor n=1:N\n if isempty(bf)\n cr(:,n) = double(f{n}(:));\n else\n cr(:,n) = double(f{n}(:).*bf{n}(:));\n end\nend\np = ones(numel(f{1}),K);\nfor k=1:K\n amp = mg(k)/sqrt((2*pi)^N * det(vr(:,:,k)));\n d = bsxfun(@minus,cr,mn(:,k)')/chol(vr(:,:,k));\n p(:,k) = amp*exp(-0.5*sum(d.*d,2)) + eps;\nend\nreturn;\n\n\n%==========================================================================\n% function dat = decimate(dat,fwhm)\n%==========================================================================\nfunction dat = decimate(dat,fwhm)\n% Convolve the volume in memory (fwhm in voxels).\nlim = ceil(2*fwhm);\nx = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);\ny = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);\nz = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);\ni = (length(x) - 1)/2;\nj = (length(y) - 1)/2;\nk = (length(z) - 1)/2;\nspm_conv_vol(dat,dat,x,y,z,-[i j k]);\nreturn;\n\n\n%==========================================================================\n% function y1 = affind(y0,M)\n%==========================================================================\nfunction y1 = affind(y0,M)\ny1 = zeros(size(y0),'single');\nfor d=1:3\n y1(:,:,:,d) = y0(:,:,:,1)*M(d,1) + y0(:,:,:,2)*M(d,2) + y0(:,:,:,3)*M(d,3) + M(d,4);\nend\nreturn;\n\n\n%==========================================================================\n% function x = rgrid(d)\n%==========================================================================\nfunction x = rgrid(d)\nx = zeros([d(1:3) 3],'single');\n[x1,x2] = ndgrid(single(1:d(1)),single(1:d(2)));\nfor i=1:d(3)\n x(:,:,i,1) = x1;\n x(:,:,i,2) = x2;\n x(:,:,i,3) = single(i);\nend\nreturn;\n\n\n%==========================================================================\n% function [P] = clean_gwc(P,level)\n%==========================================================================\nfunction [P] = clean_gwc(P,level)\nif nargin<2, level = 1; end\n\nb = P(:,:,:,2);\n\n% Build a 3x3x3 seperable smoothing kernel\n%--------------------------------------------------------------------------\nkx=[0.75 1 0.75];\nky=[0.75 1 0.75];\nkz=[0.75 1 0.75];\nsm=sum(kron(kron(kz,ky),kx))^(1/3);\nkx=kx/sm; ky=ky/sm; kz=kz/sm;\n\nth1 = 0.15;\nif level==2, th1 = 0.2; end\n% Erosions and conditional dilations\n%--------------------------------------------------------------------------\nniter = 32;\nniter2 = 32;\nspm_progress_bar('Init',niter+niter2,'Extracting Brain','Iterations completed');\nfor j=1:niter\n if j>2, th=th1; else th=0.6; end % Dilate after two its of erosion\n for i=1:size(b,3)\n gp = double(P(:,:,i,1));\n wp = double(P(:,:,i,2));\n bp = double(b(:,:,i))/255;\n bp = (bp>th).*(wp+gp);\n b(:,:,i) = uint8(round(bp));\n end\n spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);\n spm_progress_bar('Set',j);\nend\n\n% Also clean up the CSF.\nif niter2 > 0\n c = b;\n for j=1:niter2\n for i=1:size(b,3)\n gp = double(P(:,:,i,1));\n wp = double(P(:,:,i,2));\n cp = double(P(:,:,i,3));\n bp = double(c(:,:,i))/255;\n bp = (bp>th).*(wp+gp+cp);\n c(:,:,i) = uint8(round(bp));\n end\n spm_conv_vol(c,c,kx,ky,kz,-[1 1 1]);\n spm_progress_bar('Set',j+niter);\n end\nend\n\nth = 0.05;\nfor i=1:size(b,3)\n slices = cell(1,size(P,4));\n for k1=1:size(P,4)\n slices{k1} = double(P(:,:,i,k1))/255;\n end\n bp = double(b(:,:,i))/255;\n bp = ((bp>th).*(slices{1}+slices{2}))>th;\n slices{1} = slices{1}.*bp;\n slices{2} = slices{2}.*bp;\n\n if niter2>0\n cp = double(c(:,:,i))/255;\n cp = ((cp>th).*(slices{1}+slices{2}+slices{3}))>th;\n slices{3} = slices{3}.*cp;\n end\n slices{5} = slices{5}+1e-4; % Add a little to the soft tissue class\n tot = zeros(size(bp))+eps;\n for k1=1:size(P,4)\n tot = tot + slices{k1};\n end\n for k1=1:size(P,4)\n P(:,:,i,k1) = uint8(round(slices{k1}./tot*255));\n end \nend\nspm_progress_bar('Clear');\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm12/spm_preproc_write8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19330882161492413}} {"text": "function [interp] = ft_sourceinterpolate(cfg, functional, anatomical)\n\n% FT_SOURCEINTERPOLATE interpolates source activity or statistical maps onto the\n% voxels or vertices of an anatomical description of the brain. Both the functional\n% and the anatomical data can either describe a volumetric 3D regular grid, a\n% triangulated description of the cortical sheet or an arbitrary cloud of points.\n%\n% The functional data in the output data will be interpolated at the locations at\n% which the anatomical data are defined. For example, if the anatomical data was\n% volumetric, the output data is a volume-structure, containing the resliced source\n% and the anatomical volume that can be visualized using FT_SOURCEPLOT or written to\n% file using FT_SOURCEWRITE.\n%\n% The following scenarios can be considered:\n%\n% - Both functional data and anatomical data are defined on 3D regular grids, for\n% example with a low-res grid for the functional data and a high-res grid for the\n% anatomy.\n%\n% - The functional data is defined on a 3D regular grid and the anatomical data is\n% defined on an irregular point cloud, which can be a 2D triangulated surface mesh.\n%\n% - The functional data is defined on an irregular point cloud, which can be a 2D\n% triangulated surface mesh, and the anatomical data is defined on a 3D regular grid.\n%\n% - Both the functional and the anatomical data are defined on an irregular point\n% cloud, which can be a 2D triangulated mesh.\n%\n% - The functional data is defined on a low-resolution 2D triangulated surface mesh and the\n% anatomical data is defined on a high-resolution 2D triangulated surface mesh, where the\n% low-res vertices form a subset of the high-res vertices. This allows for mesh-based\n% interpolation. The algorithm currently implemented is so-called 'smudging' as it is\n% also applied by the MNE-suite software.\n%\n% Use as\n% [interp] = ft_sourceinterpolate(cfg, source, anatomy)\n% [interp] = ft_sourceinterpolate(cfg, stat, anatomy)\n% where\n% source is the output of FT_SOURCEANALYSIS\n% stat is the output of FT_SOURCESTATISTICS\n% anatomy is the output of FT_READ_MRI, or one of the FT_VOLUMExxx functions,\n% or a cortical sheet that was read with FT_READ_HEADSHAPE,\n% or a regular 3D grid created with FT_PREPARE_SOURCEMODEL.\n%\n% The configuration should contain:\n% cfg.parameter = string or cell-array with the functional parameter(s) to be interpolated\n% cfg.downsample = integer number (default = 1, i.e. no downsampling)\n% cfg.interpmethod = string, can be 'nearest', 'linear', 'cubic', 'spline', 'sphere_avg', 'sphere_weighteddistance', or 'smudge' (default = 'linear for interpolating two 3D volumes, 'nearest' for all other cases)\n%\n% For interpolating two 3D regular grids or volumes onto each other the supported\n% interpolation methods are 'nearest', 'linear', 'cubic' or 'spline'. For all other\n% cases the supported interpolation methods are 'nearest', 'sphere_avg',\n% 'sphere_weighteddistance' or 'smudge'.\n%\n% The functional and anatomical data should be expressed in the same\n% coordinate sytem, i.e. either both in MEG headcoordinates (NAS/LPA/RPA)\n% or both in SPM coordinates (AC/PC).\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_READ_MRI, FT_READ_HEADSHAPE, FT_SOURCEPLOT, FT_SOURCEANALYSIS,\n% FT_SOURCEWRITE\n\n% Copyright (C) 2003-2007, Robert Oostenveld\n% Copyright (C) 2011-2014, Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% 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 functional anatomical\nft_preamble provenance functional anatomical\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n return\nend\n\n% this is not supported any more as of 26/10/2011\nif ischar(anatomical)\n ft_error('please use cfg.inputfile instead of specifying the input variable as a sting');\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'unused', {'keepinside' 'voxelcoord'});\ncfg = ft_checkconfig(cfg, 'deprecated', {'sourceunits', 'mriunits'});\ncfg = ft_checkconfig(cfg, 'required', 'parameter');\ncfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.pow', 'pow'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.coh', 'coh'});\ncfg = ft_checkconfig(cfg, 'renamedval', {'parameter', 'avg.mom', 'mom'});\n\n% set the defaults\ncfg.downsample = ft_getopt(cfg, 'downsample', 1);\ncfg.feedback = ft_getopt(cfg, 'feedback', 'text');\ncfg.interpmethod = ft_getopt(cfg, 'interpmethod', []); % cfg.interpmethod depends on how the interpolation should be done and actual defaults will be specified below\n\n% replace pnt by pos\nanatomical = fixpos(anatomical);\nfunctional = fixpos(functional);\n\n% ensure the functional data to be in double precision, the maxdepth parameter ensure double precision up to the content of functional.avg.mom{:}, avoiding too much recursion\nfunctional = ft_struct2double(functional, 3);\n\nif (strcmp(cfg.interpmethod, 'nearest') || strcmp(cfg.interpmethod, 'mode')) && (ft_datatype(functional, 'volume+label') || ft_datatype(functional, 'source+label') || ft_datatype(functional, 'mesh+label'))\n % the first input argument describes a parcellation or segmentation with tissue labels\n isAtlasFun = true;\nelse\n isAtlasFun = false;\nend\n\nif isfield(anatomical, 'transform') && isfield(anatomical, 'dim')\n % anatomical volume\n isUnstructuredAna = false;\nelseif isfield(anatomical, 'pos') && isfield(anatomical, 'dim')\n % positions that can be mapped onto a 3D regular grid\n isUnstructuredAna = false;\nelseif isfield(anatomical, 'pos')\n % anatomical data that consists of a mesh, but no smudging possible\n isUnstructuredAna = true;\nend\n\nif isfield(functional, 'transform') && isfield(functional, 'dim')\n % functional volume\n isUnstructuredFun = false;\nelseif isfield(functional, 'pos') && isfield(functional, 'dim')\n % positions that can be mapped onto a 3D regular grid\n isUnstructuredFun = false;\nelse\n isUnstructuredFun = true;\nend\n\nif isUnstructuredAna\n anatomical = ft_checkdata(anatomical, 'datatype', {'source', 'source+label', 'mesh'}, 'insidestyle', 'logical', 'feedback', 'yes', 'hasunit', 'yes');\nelse\n anatomical = ft_checkdata(anatomical, 'datatype', {'volume', 'volume+label'}, 'insidestyle', 'logical', 'feedback', 'yes', 'hasunit', 'yes');\nend\n\nif isUnstructuredFun\n functional = ft_checkdata(functional, 'datatype', 'source', 'insidestyle', 'logical', 'feedback', 'yes', 'hasunit', 'yes');\nelse\n functional = ft_checkdata(functional, 'datatype', 'volume', 'insidestyle', 'logical', 'feedback', 'yes', 'hasunit', 'yes');\nend\n\n% select the parameters from the data, this needs to be done here, because after running checkdata, the parameterselection fails if the numeric data has nfreq/ntime/etc>1\ncfg.parameter = parameterselection(cfg.parameter, functional);\n\n% ensure that the functional data has the same unit as the anatomical data\nfunctional = ft_convert_units(functional, anatomical.unit);\n\nif isfield(functional, 'coordsys') && isfield(anatomical, 'coordsys') && ~isequal(functional.coordsys, anatomical.coordsys)\n % FIXME is this different when smudged or not?\n % ft_warning('the coordinate systems are not aligned');\n % ft_error('the coordinate systems are not aligned');\nend\n\nif ~isUnstructuredAna && cfg.downsample~=1\n % downsample the anatomical volume\n tmpcfg = keepfields(cfg, {'downsample', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\n tmpcfg.parameter = 'anatomy';\n anatomical = ft_volumedownsample(tmpcfg, anatomical);\n % restore the provenance information and put back cfg.parameter\n tmpparameter = cfg.parameter;\n [cfg, anatomical] = rollback_provenance(cfg, anatomical);\n cfg.parameter = tmpparameter;\nend\n\n% collect the functional volumes that should be converted\ndat_name = {};\ndat_array = {};\nfor i=1:length(cfg.parameter)\n if ~iscell(getsubfield(functional, cfg.parameter{i}))\n dat_name{end+1} = cfg.parameter{i};\n dat_array{end+1} = getsubfield(functional, cfg.parameter{i});\n else\n fprintf('not interpolating %s, since it is represented in a cell-array\\n', cfg.parameter{i});\n end\nend\n\n% hmmmm, if the input data contains a time and/or freq dimension, then the output\n% may be terribly blown up; most convenient would be to output only the\n% smudging matrix, and project the data when plotting\n\nif isUnstructuredFun && isUnstructuredAna && isfield(anatomical, 'orig') && isfield(anatomical.orig, 'pos') && isfield(anatomical.orig, 'tri')\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % functional data defined on subset of vertices in an anatomical mesh\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % FIXME this should not be decided on the basis of the data structures but on the basis of the cfg.interpmethod option\n % FIXME the distribution of 3 geometries over the 2 structures is weird\n % FIXME a (perhaps extreme) application of this would be to interpolate data from parcels on the sheet, i.e. an inverse parcellation\n\n % anatomical data consists of a decimated triangulated mesh, containing\n % the original description, allowing for smudging.\n\n % smudge the low resolution functional data according to the strategy in\n % MNE-suite (chapter 8.3 of the manual)\n\n interpmat = interp_ungridded(anatomical.pos, anatomical.orig.pos, 'projmethod', 'smudge', 'triout', anatomical.orig.tri);\n interpmat(~anatomical.inside(:), :) = 0;\n\n % start with an empty structure, keep only some fields\n interp = keepfields(functional, {'time', 'freq'});\n interp = copyfields(anatomical, interp, {'coordsys', 'unit'});\n interp = copyfields(anatomical.orig, interp, {'pos', 'tri'});\n\n % identify the inside voxels after interpolation\n nzeros = sum(interpmat~=0,2);\n newinside = (nzeros~=0);\n newoutside = (nzeros==0);\n\n interp.inside = false(size(anatomical.pos,1),1);\n interp.inside(newinside) = true;\n\n % interpolate all functional data\n for i=1:length(dat_name)\n fprintf('interpolating %s\\n', dat_name{i});\n\n dimord = getdimord(functional, dat_name{i});\n dimtok = tokenize(dimord, '_');\n dimf = getdimsiz(functional, dat_name{i});\n dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions\n\n % should be 3-D array, can have trailing singleton dimensions\n if numel(dimf)<2\n dimf(2) = 1;\n end\n if numel(dimf)<3\n dimf(3) = 1;\n end\n\n allav = zeros([size(anatomical.orig.pos,1), dimf(2:end)]);\n for k=1:dimf(2)\n for m=1:dimf(3)\n fv = double_ifnot(dat_array{i}(:,k,m));\n av = interpmat*fv;\n av(newoutside) = nan;\n allav(:,k,m) = av;\n end\n end\n interp = setsubfield(interp, dat_name{i}, allav);\n end\n\n\nelseif isUnstructuredFun && isUnstructuredAna\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % functional data defined on a point cloud/mesh, anatomy on a point cloud/mesh\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % set default interpmethod for this situation\n cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');\n cfg.sphereradius = ft_getopt(cfg, 'sphereradius', 0.5);\n cfg.power = ft_getopt(cfg, 'power', 1);\n\n interpmat = interp_ungridded(functional.pos, anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'power', cfg.power); % FIXME include other key-value pairs as well\n interpmat(~anatomical.inside(:), :) = 0;\n\n % start with an empty structure, keep only some fields\n interp = keepfields(functional, {'time', 'freq'});\n interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit'});\n\n % identify the inside voxels after interpolation\n nzeros = sum(interpmat~=0,2);\n newinside = (nzeros~=0);\n newoutside = (nzeros==0);\n\n interp.inside = false(size(anatomical.pos,1),1);\n interp.inside(newinside) = true;\n\n % interpolate all functional data\n for i=1:length(dat_name)\n fprintf('interpolating %s\\n', dat_name{i});\n\n dimord = getdimord(functional, dat_name{i});\n dimtok = tokenize(dimord, '_');\n dimf = getdimsiz(functional, dat_name{i});\n dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions\n\n % should be 3-D array, can have trailing singleton dimensions\n if numel(dimf)<2\n dimf(2) = 1;\n end\n if numel(dimf)<3\n dimf(3) = 1;\n end\n\n allav = zeros([size(anatomical.pos,1), dimf(2:end)]);\n for k=1:dimf(2)\n for m=1:dimf(3)\n fv = double_ifnot(dat_array{i}(:,k,m));\n av = interpmat*fv;\n av(newoutside) = nan;\n allav(:,k,m) = av;\n end\n end\n interp = setsubfield(interp, dat_name{i}, allav);\n end\n\n\nelseif isUnstructuredFun && ~isUnstructuredAna\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % functional data defined on a point cloud/mesh, anatomy on a volume\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % set default interpmethod for this situation\n cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');\n cfg.sphereradius = ft_getopt(cfg, 'sphereradius', 0.5);\n cfg.power = ft_getopt(cfg, 'power', 1);\n\n [ax, ay, az] = voxelcoords(anatomical.dim, anatomical.transform);\n anatomical.pos = [ax(:) ay(:) az(:)];\n clear ax ay az\n\n tmp = interp_ungridded(functional.pos, anatomical.pos(anatomical.inside,:), 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'power', cfg.power); % FIXME include other key-value pairs as well\n interpmat( anatomical.inside(:), :) = tmp;\n interpmat(~anatomical.inside(:), :) = 0;\n \n % start with an empty structure, keep only some fields\n interp = keepfields(functional, {'time', 'freq'});\n interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit', 'anatomy'});\n\n % identify the inside voxels after interpolation\n nzeros = sum(interpmat~=0,2);\n newinside = (nzeros~=0);\n newoutside = (nzeros==0);\n\n interp.inside = false(anatomical.dim);\n interp.inside(newinside) = true;\n\n % interpolate all functional data\n for i=1:length(dat_name)\n fprintf('interpolating %s\\n', dat_name{i});\n\n dimord = getdimord(functional, dat_name{i});\n dimtok = tokenize(dimord, '_');\n dimf = getdimsiz(functional, dat_name{i});\n dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions\n\n % should be 3-D array, can have trailing singleton dimensions\n if numel(dimf)<2\n dimf(2) = 1;\n end\n if numel(dimf)<3\n dimf(3) = 1;\n end\n\n av = zeros([anatomical.dim ]);\n allav = zeros([anatomical.dim dimf(2:end)]);\n\n for k=1:dimf(2)\n for m=1:dimf(3)\n fv = double_ifnot(dat_array{i}(:,k,m));\n av(:) = interpmat*fv;\n av(newoutside) = nan;\n allav(:,:,:,k,m) = av;\n end\n end\n if isfield(interp, 'freq') || isfield(interp, 'time')\n % the output should be a source representation, not a volume\n allav = reshape(allav, prod(anatomical.dim), dimf(2), dimf(3));\n end\n interp = setsubfield(interp, dat_name{i}, allav);\n end\n\n if ~isfield(interp, 'freq') && ~isfield(interp, 'time')\n % the output should be a volume representation, not a source\n interp = rmfield(interp, 'pos');\n end\n\nelseif ~isUnstructuredFun && isUnstructuredAna\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % functional data defined on a volume, anatomy on a point cloud/mesh\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % set default interpmethod for this situation\n cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');\n cfg.sphereradius = ft_getopt(cfg, 'sphereradius', []);\n cfg.power = ft_getopt(cfg, 'power', 1);\n\n % interpolate the 3D volume onto the anatomy\n if ~strcmp(cfg.interpmethod, 'project')\n % use interp_gridded\n [interpmat, dummy] = interp_gridded(functional.transform, zeros(functional.dim), anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'inside', functional.inside, 'power', cfg.power);\n\n % use interp_ungridded\n % interpmat = interp_ungridded(functional.pos, anatomical.pos, 'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius, 'inside', functional.inside, 'power', cfg.power);\n else\n % do the interpolation below, the current implementation of the\n % 'project' method does not output an interpmat (and is therefore quite\n % inefficient\n\n % set the defaults\n cfg.projvec = ft_getopt(cfg, 'projvec', 1);\n cfg.projweight = ft_getopt(cfg, 'projweight', ones(size(cfg.projvec)));\n cfg.projcomb = ft_getopt(cfg, 'projcomb', 'mean'); % or max\n cfg.projthresh = ft_getopt(cfg, 'projthresh', []);\n end\n\n % start with an empty structure, keep some fields\n interp = keepfields(functional, {'time', 'freq'});\n interp = copyfields(anatomical, interp, {'pos', 'tri', 'dim', 'transform', 'coordsys', 'unit'});\n\n % identify the inside voxels after interpolation\n interp.inside = true(size(anatomical.pos,1),1);\n\n % interpolate all functional data\n for i=1:length(dat_name)\n fprintf('interpolating %s\\n', dat_name{i});\n\n dimord = getdimord(functional, dat_name{i});\n dimtok = tokenize(dimord, '_');\n dimf = getdimsiz(functional, dat_name{i});\n dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions\n\n if prod(functional.dim)==dimf(1)\n % convert into 3-D, 4-D or 5-D array\n dimf = [functional.dim dimf(2:end)];\n dat_array{i} = reshape(dat_array{i}, dimf);\n end\n\n % should be 5-D array, can have trailing singleton dimensions\n if numel(dimf)<4\n dimf(4) = 1;\n end\n if numel(dimf)<5\n dimf(5) = 1;\n end\n\n allav = zeros([size(anatomical.pos,1), dimf(4:end)]);\n if ~strcmp(cfg.interpmethod, 'project')\n for k=1:dimf(4)\n for m=1:dimf(5)\n fv = double_ifnot(dat_array{i}(:,:,:,k,m)); % ensure double precision to allow sparse multiplication\n fv = fv(functional.inside(:));\n av = interpmat*fv;\n allav(:,k,m) = av;\n end\n end\n else\n for k=1:dimf(4)\n for m=1:dimf(5)\n fv = double_ifnot(dat_array{i}(:,:,:,k,m));\n av = interp_gridded(functional.transform, fv, anatomical.pos, 'dim', functional.dim, 'projmethod', 'project', 'projvec', cfg.projvec, 'projweight', cfg.projweight, 'projcomb', cfg.projcomb, 'projthresh', cfg.projthresh);\n allav(:,k,m) = av;\n end\n end\n end\n interp = setsubfield(interp, dat_name{i}, allav);\n end\n\nelseif ~isUnstructuredFun && ~isUnstructuredAna\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % functional data defined on a volume, anatomy on a differently sampled volume\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % set default interpmethod for this situation\n cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'linear');\n if isequal(cfg.interpmethod, 'mode') && isAtlasFun\n % use a mode-based interpolation, i.e. a majority vote of the nearby\n % voxel locations.\n \n % first to a nearest interpolation of the voxel coordinates the other\n % way around\n tmp = anatomical;\n [tx, ty, tz] = voxelcoords(tmp.dim, tmp.transform);\n tmp.tx = tx;\n tmp.ty = ty;\n tmp.tz = tz;\n \n tmpcfg = [];\n tmpcfg.interpmethod = 'nearest';\n tmpcfg.parameter = {'tx' 'ty' 'tz'};\n tmpint = ft_sourceinterpolate(tmpcfg, tmp, functional);\n \n [ix,i1,i2] = intersect([tx(:) ty(:) tz(:)],[tmpint.tx(:) tmpint.ty(:) tmpint.tz(:)],'rows');\n \n interp = keepfields(anatomical, {'pos', 'dim', 'transform', 'coordsys', 'unit', 'anatomy'});\n interp.inside = false(interp.dim);\n interp.inside(i1) = true;\n \n for k = 1:numel(cfg.parameter)\n interp.(cfg.parameter{k}) = nan(interp.dim);\n fun = functional.(cfg.parameter{k});\n for m = 1:numel(i1)\n values = reshape(fun(tmpint.tx==tx(i1(m)) & tmpint.ty==ty(i1(m)) & tmpint.tz==tz(i1(m))),[],1);\n [M,f,c] = mode(values);\n if numel(c)==1\n interp.(cfg.parameter{k})(i1(m)) = M;\n else\n ft_warning('multiple modes per voxel, returning NaN');\n interp.(cfg.parameter{k})(i1(m)) = nan;\n end\n end\n end\n \n elseif isequal(cfg.interpmethod, 'mode') && ~isAtlasFun\n ft_error('the interpolation method ''mode'' is only supported for parcellations');\n\n else\n % start with an empty structure, keep some fields\n interp = keepfields(functional, {'time', 'freq'});\n interp = copyfields(anatomical, interp, {'pos', 'dim', 'transform', 'coordsys', 'unit', 'anatomy'});\n \n % convert the anatomical voxel positions into voxel indices into the functional volume\n anatomical.transform = functional.transform \\ anatomical.transform;\n functional.transform = eye(4);\n \n [fx, fy, fz] = voxelcoords(functional.dim, functional.transform);\n [ax, ay, az] = voxelcoords(anatomical.dim, anatomical.transform);\n \n % estimate the subvolume of the anatomy that is spanned by the functional volume\n minfx = 1;\n minfy = 1;\n minfz = 1;\n maxfx = functional.dim(1);\n maxfy = functional.dim(2);\n maxfz = functional.dim(3);\n sel = ax(:)>=minfx & ...\n ax(:)<=maxfx & ...\n ay(:)>=minfy & ...\n ay(:)<=maxfy & ...\n az(:)>=minfz & ...\n az(:)<=maxfz;\n fprintf('selecting subvolume of %.1f%%\\n', 100*sum(sel)./prod(anatomical.dim));\n \n if all(functional.inside(:))\n % keep all voxels marked as inside\n interp.inside = true(anatomical.dim);\n else\n % reslice and interpolate inside\n interp.inside = zeros(anatomical.dim);\n % interpolate with method nearest\n interp.inside( sel) = my_interpn(double(functional.inside), ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);\n interp.inside(~sel) = 0;\n interp.inside = logical(interp.inside);\n end\n \n % prepare the grid that is used in the interpolation\n fg = [fx(:) fy(:) fz(:)];\n clear fx fy fz\n \n % reslice and interpolate all functional volumes\n for i=1:length(dat_name)\n fprintf('reslicing and interpolating %s\\n', dat_name{i});\n \n dimord = getdimord(functional, dat_name{i});\n dimtok = tokenize(dimord, '_');\n dimf = getdimsiz(functional, dat_name{i});\n dimf(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions\n \n if prod(functional.dim)==dimf(1)\n % convert into 3-D, 4-D or 5-D array\n dimf = [functional.dim dimf(2:end)];\n dat_array{i} = reshape(dat_array{i}, dimf);\n end\n \n % should be 5-D array, can have trailing singleton dimensions\n if numel(dimf)<4\n dimf(4) = 1;\n end\n if numel(dimf)<5\n dimf(5) = 1;\n end\n \n av = zeros([anatomical.dim ]);\n allav = zeros([anatomical.dim dimf(4:end)]);\n functional.inside = functional.inside(:,:,:,1,1);\n \n if any(dimf(4:end)>1) && ~strcmp(cfg.feedback, 'none')\n % this is needed to prevent feedback to be displayed for every time-frequency point\n ft_warning('disabling feedback');\n cfg.feedback = 'none';\n end\n \n for k=1:dimf(4)\n for m=1:dimf(5)\n fv = double_ifnot(dat_array{i}(:,:,:,k,m));\n % av( sel) = my_interpn(fx, fy, fz, fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);\n if islogical(dat_array{i})\n % interpolate always with method nearest\n av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);\n av = logical(av);\n else\n if ~all(functional.inside(:))\n % extrapolate the outside of the functional volumes for better interpolation at the edges\n fv(~functional.inside) = griddatan(fg(functional.inside(:), :), fv(functional.inside(:)), fg(~functional.inside(:), :), 'nearest');\n end\n % interpolate functional onto anatomical grid\n av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);\n av(~sel) = nan;\n av(~interp.inside) = nan;\n end\n allav(:,:,:,k,m) = av;\n end\n end\n if isfield(interp, 'freq') || isfield(interp, 'time')\n % the output should be a source representation, not a volume\n allav = reshape(allav, prod(anatomical.dim), dimf(4), dimf(5));\n end\n interp = setsubfield(interp, dat_name{i}, allav);\n % keep the description of the labels in the segmentation/parcellation\n if strcmp(cfg.interpmethod, 'nearest') && isfield(functional, [dat_name{i} 'label'])\n interp.([dat_name{i} 'label']) = functional.([dat_name{i} 'label']);\n end\n end\n \n end\n\nend % computing the interpolation according to the input data\n\nif isfield(interp, 'freq') || isfield(interp, 'time')\n % the output should be a source representation, not a volumetric representation\n if ~isfield(interp, 'pos')\n [x, y, z] = voxelcoords(interp.dim, interp.transform);\n interp.pos = [x(:) y(:) z(:)];\n end\nend\n\nif isAtlasFun\n for i=1:numel(dat_name)\n % keep the labels that describe the different tissue types\n interp = copyfields(functional, interp, [dat_name{i} 'label']);\n % replace NaNs that fall outside the labeled area with zero\n tmp = interp.(dat_name{i});\n tmp(isnan(tmp)) = 0;\n interp.(dat_name{i}) = tmp;\n end\n % remove the inside field if present\n interp = removefields(interp, 'inside');\nend\n\nif exist('interpmat', 'var')\n cfg.interpmat = interpmat;\n cfg.interpmat; % access it once to fool the cfg-tracking\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous functional anatomical\nft_postamble provenance interp\nft_postamble history interp\nft_postamble savevar interp\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION this function computes the location of all voxels in head\n% coordinates in a memory efficient manner\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [x, y, z] = voxelcoords(dim, transform)\n\nxgrid = 1:dim(1);\nygrid = 1:dim(2);\nzgrid = 1:dim(3);\nnpix = prod(dim(1:2)); % number of voxels in a single slice\n\nx = zeros(dim);\ny = zeros(dim);\nz = zeros(dim);\nX = zeros(1,npix);\nY = zeros(1,npix);\nZ = zeros(1,npix);\nE = ones(1,npix);\n% determine the voxel locations per slice\nfor i=1:dim(3)\n [X(:), Y(:), Z(:)] = ndgrid(xgrid, ygrid, zgrid(i));\n tmp = transform*[X; Y; Z; E];\n x((1:npix)+(i-1)*npix) = tmp(1,:);\n y((1:npix)+(i-1)*npix) = tmp(2,:);\n z((1:npix)+(i-1)*npix) = tmp(3,:);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION for memory efficient interpolation\n% the only reason for this function is that it does the interpolation in smaller chuncks\n% this prevents memory problems that I often encountered here\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function [av] = my_interpn(fx, fy, fz, fv, ax, ay, az, interpmethod, feedback);\nfunction [av] = my_interpn(fv, ax, ay, az, interpmethod, feedback)\n\nnum = numel(ax); % total number of voxels\nblocksize = floor(num/20); % number of voxels to interpolate at once, split it into 20 chuncks\nlastblock = 0; % boolean flag for while loop\nsel = 1:blocksize; % selection of voxels that are interpolated, this is the first chunck\nav = zeros(size(ax));\nft_progress('init', feedback, 'interpolating');\nwhile (1)\n ft_progress(sel(1)/num, 'interpolating %.1f%%\\n', 100*sel(1)/num);\n if sel(end)>=num\n sel = sel(1):num;\n lastblock = 1;\n end\n av(sel) = interpn(fv, ax(sel), ay(sel), az(sel), interpmethod);\n if lastblock\n break\n end\n sel = sel + blocksize;\nend\nft_progress('close');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION to cast array to double precision, only if needed\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction out = double_ifnot(in)\n\nif ~isa(in, 'double')\n out = double(in);\nelse\n out = in;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_sourceinterpolate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1931686762426628}} {"text": "function [out] = spm_eeg_displayECD(Pos,Orient,Var,Names,options)\n% Plot dipole positions onto the SPM canonical mesh\n% FORMAT [out] = spm_eeg_displayECD(Pos,Orient,Var,Names,options)\n%\n% IN (admissible choices):\n% - Pos: a 3xndip matrix containing the positions of the dipoles in\n% the canonical frame of reference\n% - Orient: the same with dipole orientations\n% - Var: the same with position variance\n% - Names: the same with dipole names\n% - options: an optional structure containing\n% .hfig: the handle of the display figure\n% .tag: the tag to be associated with the created UI objects\n% .add: binary variable ({0}, 1: just add dipole in the figure .hfig)\n%\n% OUT:\n% - out: a structure containing the handles of the object in the figure\n% (including the mesh, the dipoles, the transparency slider, etc...)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Jean Daunizeau\n% $Id: spm_eeg_displayECD.m 5737 2013-11-10 20:23:49Z karl $\n\n\n% checks and defaults\n%--------------------------------------------------------------------------\nhfig = [];\nParentAxes = [];\nquery = [];\nhandles = [];\ntag = '';\ntry, options; catch, options = []; end\ntry, hfig = options.hfig; end\ntry, tag = options.tag; end\ntry, ParentAxes = options.ParentAxes; end\ntry, query = options.query; end\ntry, handles = options.handles; end\ntry\n figure(hfig);\ncatch\n hfig = spm_figure('GetWin','Graphics');\n spm_figure('Clear',hfig);\n ParentAxes = axes('parent',hfig);\nend\ntry\n markersize = options.markersize;\ncatch\n markersize = 20;\nend\ntry\n meshsurf = options.meshsurf;\ncatch\n meshsurf = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');\nend\n\nif isscalar(Var), Var = Pos*0 + Var^2; end\ntry, Pos{1}; catch, Pos = {Pos}; end\ntry, Orient{1}; catch, Orient = {Orient};end\ntry, Var{1}; catch, Var = {Var}; end\n\nndip = size(Pos{1},2);\nif ~exist('Names','var') || isempty(Names)\n for i=1:ndip\n Names{i} = num2str(i);\n end\nend\n\n\ncol = ['b','g','r','c','m','y','k','w'];\ntmp = ceil(ndip./numel(col));\ncol = repmat(col,1,tmp);\npa = get(ParentAxes,'position');\n\nif ndip > 0\n \n if isempty(query)\n opt.hfig = hfig;\n opt.ParentAxes = ParentAxes;\n opt.visible = 'off';\n pos2 = [pa(1),pa(2)+0.25*pa(4),0.03,0.5*pa(4)];\n out = spm_eeg_render(meshsurf,opt);\n handles.mesh = out.handles.p;\n handles.BUTTONS.transp = out.handles.transp;\n handles.hfig = out.handles.fi;\n handles.ParentAxes = out.handles.ParentAxes;\n set(handles.mesh,...\n 'facealpha',0.1,...\n 'visible','on')\n set(handles.BUTTONS.transp,...\n 'value',0.1,...\n 'position',pos2,...\n 'visible','on')\n end\n \n set(ParentAxes,'nextplot','add')\n for j=1:length(Pos)\n for i =1:ndip\n try\n set(handles.hp(j,i),...\n 'xdata',Pos{j}(1,i),...\n 'ydata',Pos{j}(2,i),...\n 'zdata',Pos{j}(3,i));\n catch\n handles.hp(j,i) = plot3(handles.ParentAxes,...\n Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n [col(i),'.'],...\n 'markerSize',markersize,...\n 'visible','off');\n end\n try\n no = sqrt(sum(Orient{j}(:,i).^2));\n if no > 0\n Oi = 1e1.*Orient{j}(:,i)./no;\n else\n Oi = 1e-5*ones(3,1);\n end\n try\n set(handles.hq(j,i),...\n 'xdata',Pos{j}(1,i),...\n 'ydata',Pos{j}(2,i),...\n 'zdata',Pos{j}(3,i),...\n 'udata',Oi(1),...\n 'vdata',Oi(2),...\n 'wdata',Oi(3))\n catch\n handles.hq(j,i) = quiver3(handles.ParentAxes,...\n Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n Oi(1),Oi(2),Oi(3),col(i),...\n 'lineWidth',2,'visible','off');\n end\n if isequal(query,'add')\n set(handles.hq(j,i),...\n 'LineStyle','--',...\n 'lineWidth',1)\n end\n end\n [x,y,z]= ellipsoid(Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n 1.*sqrt(Var{j}(1,i)),1.*sqrt(Var{j}(2,i)),1.*sqrt(Var{j}(1,i)),20);\n try\n set(handles.hs(j,i),...\n 'xdata',x,...\n 'ydata',y,...\n 'zdata',z);\n catch\n handles.hs(j,i) = surf(handles.ParentAxes,...\n x,y,z,...\n 'edgecolor','none',...\n 'facecolor',col(i),...\n 'facealpha',0.2,...\n 'visible','off');\n end\n try\n set(handles.ht(j,i),...\n 'position',Pos{j}(:,i));\n catch\n handles.ht(j,i) = text(...\n Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...\n Names{i},...\n 'Parent',handles.ParentAxes,...\n 'visible','off');\n end\n end\n end\n \n if length(Pos) > 1\n \n try, set(handles.hp(end,:),'visible','on'); end\n try, set(handles.hq(end,:),'visible','on'); end\n try, set(handles.hs(end,:),'visible','on'); end\n try, set(handles.ht(end,:),'visible','on'); end\n \n handles.uic(1) = uicontrol(handles.fi,...\n 'units','normalized',...\n 'position',[0.45,0.5,0.2,0.03],...\n 'style','radio','string','Show priors',...\n 'callback',@doChange1,...\n 'BackgroundColor',[1 1 1],...\n 'tooltipstring','Display prior locations',...\n 'userdata',handles,'value',0,...\n 'BusyAction','cancel',...\n 'Interruptible','off',...\n 'tag','plotEEG');\n\n handles.uic(2) = uicontrol(handles.fi,...\n 'units','normalized',...\n 'position',[0.45,0.53,0.2,0.03],...\n 'style','radio','string','Show posteriors',...\n 'callback',@doChange2,...\n 'BackgroundColor',[1 1 1],...\n 'tooltipstring','Display posterior locations',...\n 'userdata',handles,'value',1,...\n 'BusyAction','cancel',...\n 'Interruptible','off',...\n 'tag','plotEEG');\n \n else\n \n try, set(handles.hp(1,:),'visible','on'); end\n try, set(handles.hq(1,:),'visible','on'); end\n try, set(handles.hs(1,:),'visible','on'); end\n try, set(handles.ht(1,:),'visible','on'); end\n \n end\n \nend\n\ntry\n clear out\n out.handles = handles;\ncatch\n out = []; \nend\n\n%==========================================================================\nfunction doChange1(i1,i2)\nval = get(i1,'value');\nhandles = get(i1,'userdata');\nif ~val\n try, set(handles.hp(1,:),'visible','off'); end\n try, set(handles.hq(1,:),'visible','off'); end\n try, set(handles.hs(1,:),'visible','off'); end\n try, set(handles.ht(1,:),'visible','off'); end\nelse\n try, set(handles.hp(1,:),'visible','on'); end\n try, set(handles.hq(1,:),'visible','on'); end\n try, set(handles.hs(1,:),'visible','on'); end\n try, set(handles.ht(1,:),'visible','on'); end\nend\n\n\n%==========================================================================\nfunction doChange2(i1,i2)\nval = get(i1,'value');\nhandles = get(i1,'userdata');\nif ~val\n try, set(handles.hp(2,:),'visible','off'); end\n try, set(handles.hq(2,:),'visible','off'); end\n try, set(handles.hs(2,:),'visible','off'); end\n try, set(handles.ht(2,:),'visible','off'); end\nelse\n try, set(handles.hp(2,:),'visible','on'); end\n try, set(handles.hq(2,:),'visible','on'); end\n try, set(handles.hs(2,:),'visible','on'); end\n try, set(handles.ht(2,:),'visible','on'); end\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_eeg_displayECD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.19288825407208837}} {"text": "function dicomrt_plotgammamap2dvol(gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,ct,ct_xmesh,ct_ymesh,ct_zmesh,VOI,voi2use)\n% dicomrt_plotgammamap2dvol(gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,ct,ct_xmesh,ct_ymesh,ct_zmesh,VOI,voi2use)\n%\n% Plot gamma maps.\n% \n% gamma is the ganmma matrix\n% gamma_xmesh,gamma_ymesh,gamma_zmesh are x-y-z coordinates of the center of the gamma-pixel \n% ct is the 3D CT dataset (OPTIONAL)\n% ct_xmesh, ct_ymesh, ct_zmesh are the coordinates of the ct voxels (OPTIONAL)\n% VOI is an OPTIONAL cell array which contain the patients VOIs as read by dicomrt_loadVOI\n% voi2use is an OPTIONAL number pointing to the number of VOIs to be displayed\n%\n% Example:\n%\n% dicomrt_plotgammamap2dvol(gamma2dvol,xmesh,ymesh,zmesh,demo1_ct,ct_xmesh,ct_ymesh,ct_zmesh,demo1_voi,9);\n%\n% plot the gamma map in gamma2dvol on top of a ct slice and with contour of VOI 9.\n%\n% See also dicomrt_GAMMAcal2D, dicomrt_GAMMAcal2DVol, dicomrt_rendervoi\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument and set-up some parameters and variables\nerror(nargchk(4,11,nargin))\n\nif size(gamma,3)==1 \n error('dicomrt_plotgammamap2dvol: Format not supported, try dicomrt_plotgammamap. Exit now !');\nend\n\nif exist('VOI')==1 & exist('voi2use')==1\n [mask_gamma]=dicomrt_mask(VOI,gamma,gamma_xmesh,gamma_ymesh,gamma_zmesh,voi2use,'n');\nelse\n mask_gamma=gamma;\nend\n\nif size(gamma,3)~=length(VOI{voi2use,2})\n disp('Warning: the size of gamma does not match the size of the VOI!');\n disp('There is the possibility that the gamma map was calculated for a different VOI.');\n goahead=input('dicomrt_plotgammamap2dvol: Do you want to continue (y/n) ? (n=default)','s');\n if goahead~='y' | goahead~='Y' \n error('dicomrt_plotgammamap2dvol: Exiting as requested');\n elseif isempty(goahead)==1\n error('dicomrt_plotgammamap2dvol: Exiting as requested');\n end\nend\n\nif length(size(ct))==2 & ct==0\n for k=1:size(gamma,3) % Loop over gamma slices\n % plot ct map\n figure;\n set(gcf,'Name',['dicomrt_plotgammamap2dvol: ',inputname(1),', Z= ',num2str(gamma_zmesh(k))]);\n set(gcf,'NumberTitle','off');\n if exist('VOI')==1 & exist('voi2use')==1\n % plot voi on the same slice \n p=plot3(VOI{voi2use,2}{k,1}(:,1),VOI{voi2use,2}{k,1}(:,2),...\n VOI{voi2use,2}{k,1}(:,3));\n % set VOI contour to Z=-1 to display together with gamma map\n p_handle=get(p);\n ZData_temp_2=p_handle.ZData;\n for i=1:length(ZData_temp_2)\n ZData_temp_2(i)=-1;\n end\n set(p, 'Color', 'k','LineWidth', 1.5);\n set(p,'ZData',ZData_temp_2); \n end\n hold;\n % plot gamma map\n %mesh(mask_gamma(:,:,k),'XData',gamma_xmesh,'YData',gamma_ymesh);\n % ms=surf(mask_gamma(:,:,k));\n ms=surfl(mask_gamma(:,:,k));\n shading interp;\n set(ms,'XData',gamma_xmesh,'YData',gamma_ymesh);\n % add labels\n xlabel('X axis (cm)','Fontsize',12);\n ylabel('Y axis (cm)','Fontsize',12);\n zlabel('\\gamma','Fontsize',14);\n title(['\\gamma map slice: ',num2str(k)],'Fontsize',18);\n axis tight;\n end\nelse\n % rebuilding mesh matrices\n [xmin,xmax,ymin,ymax,zmin,zmax]=dicomrt_voiboundaries(ct_xmesh,ct_ymesh, ct_zmesh,VOI,voi2use);\n [ct3d_xmesh,ct3d_ymesh,ct3d_zmesh]=dicomrt_rebuildmatrix(ct_xmesh(xmin:xmax),ct_ymesh(ymin:ymax),ct_zmesh);\n for k=1:size(gamma,3) % Loop over gamma slices\n % plot ct map\n figure;\n set(gcf,'Name',['dicomrt_plotgammamap2dvol: ',inputname(1),', Z= ',num2str(ct_zmesh(dicomrt_findsliceVECT(gamma_zmesh,k,ct_zmesh)))]);\n set(gcf,'NumberTitle','off');\n handle=slice(ct3d_xmesh,ct3d_ymesh,ct3d_zmesh,ct(ymin:ymax,xmin:xmax,:),[],[],ct_zmesh(dicomrt_findsliceVECT(gamma_zmesh,k,ct_zmesh)));\n % set ct map to Z=-1 to display together with gamma map\n set(handle,'FaceColor','interp','EdgeColor','none','DiffuseStrength',.8);\n gco_handle=get(handle);\n ZData_temp_1=gco_handle.ZData;\n for i=1:size(ZData_temp_1,1)\n for j=1:size(ZData_temp_1,2)\n ZData_temp_1(i,j)=-1;\n end\n end\n set(handle,'ZData',ZData_temp_1); \n hold;\n if exist('VOI')==1 & exist('voi2use')==1\n % plot voi on the same slice \n if k==23\n disp(num2str(k));\n end\n p=plot3(VOI{voi2use,2}{k,1}(:,1),VOI{voi2use,2}{k,1}(:,2),...\n VOI{voi2use,2}{k,1}(:,3));\n % set VOI contour to Z=-1 to display together with gamma map\n p_handle=get(p);\n ZData_temp_2=p_handle.ZData;\n for i=1:length(ZData_temp_2)\n ZData_temp_2(i)=-1;\n end\n set(p, 'Color', 'w','LineWidth', 1.5);\n set(p,'ZData',ZData_temp_2); \n end\n % plot gamma map\n mesh(mask_gamma(:,:,k),'XData',gamma_xmesh,'YData',gamma_ymesh);\n % add labels\n xlabel('X axis (cm)','Fontsize',12);\n ylabel('Y axis (cm)','Fontsize',12);\n zlabel('\\gamma','Fontsize',14);\n title(['\\gamma map slice: ',num2str(k)],'Fontsize',18);\n axis tight;\n end\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/display/dicomrt_plotgammamap2dvol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19281265153914087}} {"text": "function run_demoTracklets(base_dir,calib_dir)\n% KITTI RAW DATA DEVELOPMENT KIT\n% \n% This tool displays the images and the object labels for the benchmark and\n% provides an entry point for writing your own interface to the data set.\n% Before running this tool, set root_dir to the directory where you have\n% downloaded the dataset. 'root_dir' must contain the subdirectory\n% 'training', which in turn contains 'image_2', 'label_2' and 'calib'.\n% For more information about the data format, please look into readme.txt.\n%\n% Input arguments:\n% base_dir .... absolute path to sequence base directory (ends with _sync)\n% calib_dir ... absolute path to directory that contains calibration files\n%\n% Usage:\n% SPACE: next frame\n% '-': last frame\n% 'x': +10 frames\n% 'y': -10 frames\n% 'q': quit\n%\n% Occlusion Coding:\n% green: not occluded\n% yellow: partly occluded\n% red: fully occluded\n% white: unknown\n\n% clear and close everything\nclear all; close all; dbstop error; clc;\ndisp('======= KITTI DevKit Demo =======');\n\n% options (modify this to select your sequence)\n% the base_dir must contain:\n% - the data directories (image_00, image_01, ..)\n% - the tracklet file (tracklet_labels.xml)\n% the calib directory must contain:\n% - calib_cam_to_cam.txt\n% - calib_velo_to_cam.txt\n% cameras:\n% - 0 = left grayscale\n% - 1 = right grayscale\n% - 2 = left color\n% - 3 = right color\nif nargin<1\n base_dir = '/mnt/karlsruhe_dataset/2011_09_26/2011_09_26_drive_0009_sync';\nend\nif nargin<2\n calib_dir = '/mnt/karlsruhe_dataset/2011_09_26';\nend\ncam = 2; % 0-based index\n\n% get image sub-directory\nimage_dir = fullfile(base_dir, sprintf('/image_%02d/data', cam));\n\n% get number of images for this dataset\nnimages = length(dir(fullfile(image_dir, '*.png')));\n\n% set up figure\ngh = visualization('init',image_dir);\n\n% read calibration for the day\n[veloToCam, K] = loadCalibration(calib_dir);\n\n% read tracklets for the selected sequence\ntracklets = readTrackletsMex([base_dir '/tracklet_labels.xml']);\n\n% extract tracklets\n% LOCAL OBJECT COORDINATE SYSTEM:\n% x -> facing right\n% y -> facing forward\n% z -> facing up\nfor it = 1:numel(tracklets)\n \n % shortcut for tracklet dimensions\n w = tracklets{it}.w;\n h = tracklets{it}.h;\n l = tracklets{it}.l;\n\n % set bounding box corners\n corners(it).x = [l/2, l/2, -l/2, -l/2, l/2, l/2, -l/2, -l/2]; % front/back\n corners(it).y = [w/2, -w/2, -w/2, w/2, w/2, -w/2, -w/2, w/2]; % left/right\n corners(it).z = [0,0,0,0,h,h,h,h];\n \n % get translation and orientation\n t{it} = [tracklets{it}.poses(1,:); tracklets{it}.poses(2,:); tracklets{it}.poses(3,:)];\n rz{it} = wrapToPi(tracklets{it}.poses(6,:));\n occlusion{it} = tracklets{it}.poses(8,:);\nend\n\n% 3D bounding box faces (indices for corners)\nface_idx = [ 1,2,6,5 % front face\n 2,3,7,6 % left face\n 3,4,8,7 % back face\n 4,1,5,8]; % right face\n\n% main loop (start at first image of sequence)\nimg_idx = 0;\nwhile 1\n \n % visualization update for next frame\n visualization('update',image_dir,gh,img_idx,nimages);\n \n % compute bounding boxes for visible tracklets\n for it = 1:numel(tracklets)\n \n % get relative tracklet frame index (starting at 0 with first appearance; \n % xml data stores poses relative to the first frame where the tracklet appeared)\n pose_idx = img_idx-tracklets{it}.first_frame+1; % 0-based => 1-based MATLAB index\n\n % only draw tracklets that are visible in current frame\n if pose_idx<1 || pose_idx>(size(tracklets{it}.poses,2))\n continue;\n end\n\n % compute 3d object rotation in velodyne coordinates\n % VELODYNE COORDINATE SYSTEM:\n % x -> facing forward\n % y -> facing left\n % z -> facing up\n R = [cos(rz{it}(pose_idx)), -sin(rz{it}(pose_idx)), 0;\n sin(rz{it}(pose_idx)), cos(rz{it}(pose_idx)), 0;\n 0, 0, 1];\n\n % rotate and translate 3D bounding box in velodyne coordinate system\n corners_3D = R*[corners(it).x;corners(it).y;corners(it).z];\n corners_3D(1,:) = corners_3D(1,:) + t{it}(1,pose_idx);\n corners_3D(2,:) = corners_3D(2,:) + t{it}(2,pose_idx);\n corners_3D(3,:) = corners_3D(3,:) + t{it}(3,pose_idx);\n corners_3D = (veloToCam{cam+1}*[corners_3D; ones(1,size(corners_3D,2))]);\n \n % generate an orientation vector and compute coordinates in velodyneCS\n orientation_3D = R*[0.0, 0.7*l; 0.0, 0.0; 0.0, 0.0];\n orientation_3D(1,:) = orientation_3D(1,:) + t{it}(1, pose_idx);\n orientation_3D(2,:) = orientation_3D(2,:) + t{it}(2, pose_idx);\n orientation_3D(3,:) = orientation_3D(3,:) + t{it}(3, pose_idx);\n orientation_3D = (veloToCam{cam+1}*[orientation_3D; ones(1,size(orientation_3D,2))]);\n \n % only draw 3D bounding box for objects in front of the image plane\n if any(corners_3D(3,:)<0.5) || any(orientation_3D(3,:)<0.5) \n continue;\n end\n\n % project the 3D bounding box into the image plane\n corners_2D = projectToImage(corners_3D, K);\n orientation_2D = projectToImage(orientation_3D, K);\n drawBox3D(gh,occlusion{it}(pose_idx),corners_2D,face_idx,orientation_2D)\n \n % compute and draw the 2D bounding box from the 3D box projection\n box.x1 = min(corners_2D(1,:));\n box.x2 = max(corners_2D(1,:));\n box.y1 = min(corners_2D(2,:));\n box.y2 = max(corners_2D(2,:));\n drawBox2D(gh,box,occlusion{it}(pose_idx),tracklets{it}.objectType)\n end\n\n % force drawing and tiny user interface\n waitforbuttonpress; \n key = get(gcf,'CurrentCharacter');\n switch lower(key) \n case 'q', break; % quit\n case '-', img_idx = max(img_idx-1, 0); % previous frame\n case 'x', img_idx = min(img_idx+100,nimages-1); % +100 frames\n case 'y', img_idx = max(img_idx-100,0); % -100 frames\n otherwise, img_idx = min(img_idx+1, nimages-1); % next frame\n end\n\nend\n\n% clean up\nclose all;\n", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/kitti_extraction/utils/devkit/run_demoTracklets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.19268160125697498}} {"text": "function out = mtimes( a,b )\n%MTIMES for nested cells\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\n% determine input types\ninType = {class(a), class(b)};\nif(strcmp(inType{1},'TRAFO') && strcmp(inType{2},'TRAFO')) \n [outA, idx] = flattenCellMatrix(a.data);\n [outB, idxB] = flattenCellMatrix(b.data);\n meta = a.meta;\n meta_b = b.meta;\n clear 'a' 'b'\n\n if(~isempty(idx) && ~isempty(idxB) && ~all(cellfun(@(x,y) isequal(x,y), idx, idxB)))\n error('TRAFO::mtimes: Nested cells must have the same size');\n end\n if(iscell(meta) && iscell(meta_b))\n if(~isempty(meta) && ~isempty(meta_b))\n if(iscell(meta{1}) && iscell(meta_b{1}))\n if(~all(cellfun(@(x,y) isequal(x,y), flattenCellMatrix(meta), flattenCellMatrix(meta_b))))\n error('TRAFO::mtimes: Unequal reconstruction information');\n end\n else\n if(~all(cellfun(@(x,y) isequal(x,y), meta, meta_b)))\n error('TRAFO::mtimes: Unequal reconstruction information');\n end\n end\n end\n else \n if ~isequal(meta, meta_b)\n error('TRAFO::mtimes: Unequal reconstruction information');\n end\n end\n \n out = cellfun(@(x,y) x*y, outA, outB, 'UniformOutput', false);\n\nelseif(strcmp(inType{1},'TRAFO')) % assume b is double/uint/int\n [out, idx] = flattenCellMatrix(a.data);\n meta = a.meta; \n clear 'a'\n \n out = cellfun(@(x) x * b, out, 'UniformOutput', false);\n \nelseif(strcmp(inType{2},'TRAFO'))\n [out, idx] = flattenCellMatrix(b.data);\n meta = b.meta;\n clear 'b'\n \n out = cellfun(@(x) a * x, out, 'UniformOutput', false);\n \nelse\n error('TRAFO::mtimes: Impossible constellation!');\nend\n\nout = reconFlatCellMatrix(out,idx);\nout = TRAFO(out,meta); % return TRAFO object again without modifying input\n\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@TRAFO/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19268158866320392}} {"text": "% USERDATAPNT User data for SLAMTB - Example with points.\n% This is a particular case of USERDATA.M. It is intended for\n% demonstration of the SLAM toolbox with points. Try the following point\n% types in Opt.init.initType:\n% 'idpPnt' Inverse depth points\n% 'ahmPnt' Anchored homogeneous points\n% 'hmgPnt' Homogeneous points\n%\n% See also USERDATA.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n\n% Time variables \n% - sampling time, first and last frames\nTime = struct(...\n 'dt', .1,... % sampling time, seconds\n 'firstFrame', 1,... % first frame #\n 'lastFrame', 400); % last frame #\n\n% Simulated world\n% - Simulation landmark sets, playground dimensions\nWorld = struct(...\n 'points', thickCloister(-6,6,-6,6,1,7),... % 3d point landmarks - see THICKCLOISTER. \n 'segments', []); % 3D segments - see HOUSE. \n \n% Robot things with their controls\n% - each robot's type and initial configuration, and controls.\n% - motion models (add new model strings if you need more):\n% 'constVel' 6D Constant velocity model\n% 'odometry' 6D Odometry model\n% - See EULERANGLES for orientations specifications.\nRobot{1} = struct(... % ODOMETRY EXAMPLE\n 'id', 1,... % robot identifier\n 'name', 'Dala',... % robot name\n 'type', 'atrv',... % type of robot\n 'motion', 'odometry',... % motion model\n 'position', [0;-5;0],... % robot position in map\n 'orientationDegrees', [0;0;0],... % orientation, in degrees, roll pitch yaw.\n 'positionStd', [0;0;0],... % position error, std\n 'orientationStd', [0;0;0],... % orient. error, std, in degrees\n 'dx', [.08;0;0],... % position increment 8\n 'daDegrees', [0;0;0.9],... % angle increment, degrees 9\n 'dxStd', 0.005*[1;1;1],... % odo linear error std\n 'daStd', 0.05*[1;1;1]); % odo ang error std, degrees\n\n% Robot{2} = struct(... % CONSTANT VELOCITY EXAMPLE\n% 'id', 3,... % robot identifier\n% 'name', 'Dala',... % robot name\n% 'type', 'atrv',... % type of robot\n% 'motion', 'constVel',... % motion model\n% 'position', [1;0;0],... % robot position in map\n% 'orientationDegrees', [0;0;45],... % orientation, in degrees, roll pitch yaw.\n% 'positionStd', [0;0;0],... % position error, std\n% 'orientationStd', [0;0;0],... % orient. error, std, degrees\n% 'velocity', [1;0;0],... % lin. velocity\n% 'angularVelDegrees', [0;0;10],... % ang. velocity, in degrees\n% 'velStd', [0;0;0],... % lin. vel. error, std\n% 'angVelStd', [0;0;0],... % ang. vel. error, std, degrees\n% 'dv', [0;0;0],... % veolcity increment\n% 'dwDegrees', [0;0;0],... % ang. vel. increment, degrees\n% 'dvStd', [0;0;0],... % vel perturbation std\n% 'dwStd', [0;0;1]); % ang vel pert. std, degrees\n\n\n\n% Sensor things \n% - each sensor's type and parameters, noise, non-measurable prior.\n% - Sensor types (add new type strings if you need more):\n% 'pinHole' Pin-hole camera\n% - See EULERANGLES for orientations specifications.\nSensor{1} = struct(...\n 'id', 1,... % sensor identifier\n 'name', 'Micropix',... % sensor name\n 'type', 'pinHole',... % type of sensor\n 'robot', 1,... % robot where it is mounted\n 'position', [0;0;.6],... % position in robot\n 'orientationDegrees', [-90;0;-90],... % orientation in robot, roll pitch yaw\n 'positionStd', [0;0;0],... % position error std\n 'orientationStd', [0;0;0],... % orient. error std\n 'imageSize', [640;480],... % image size\n 'pixErrorStd', 1.0,... % pixel error std\n 'intrinsic', [320;240;320;320],... % intrinsic params [u0 v0 au av]\n 'distortion', [],... % distortion params\n 'frameInMap', false,... % add sensor frame in slam map?\n 'imGrid', struct(... % grid for Active Search\n 'numCells', [8;6],... % number of H and V grid cells\n 'skipOuter', true)); % skip outer cells for initialization?\n\n% Sensor{2} = struct(...\n% 'id', 2,... % sensor identifier\n% 'name', 'Micropix',... % sensor name\n% 'type', 'pinHole',... % type of sensor\n% 'robot', 1,... % robot where it is mounted\n% 'position', [0;-0.15;.6],... % position in robot\n% 'orientationDegrees', [-90;0;-90],... % orientation in robot, roll pitch yaw\n% 'positionStd', [0;0;0],... % position error std\n% 'orientationStd', [1.5;1.5;1.5],... % orient. error std\n% 'imageSize', [640;480],... % image size\n% 'pixErrorStd', 1.0,... % pixel error std\n% 'intrinsic', [320;240;320;320],... % intrinsic params\n% 'distortion', [],... % distortion params\n% 'frameInMap', false); % add sensor frame in slam map?\n\n% Omnidirectional camera model -> MegaPixel Fish Eye lens as example (FoV is ~190 deg )\n% k = [668 438 1 0 0]'; \n% invProjDist = [4.473e+2 -0.000e+0 -1.068e-3 1.184e-6 -1.856e-9]';\n% projDist = [6.447e+2 -3.410e+2 -2.901e+1 -5.770e+1 1.849e+1 5.415e+0 5.065e+1 -5.614e+1 1.591e+1 0 0]';\n% Sensor{1} = struct(...\n% 'id', 1,... % sensor identifier\n% 'name', 'FrontCam',... % sensor name\n% 'type', 'omniCam',... % type of sensor\n% 'robot', 1,... % robot where it is mounted\n% 'position', [0.2;0;1.2],... % position in robot\n% 'orientationDegrees', [-120;0;-90],...% orientation in robot, roll pitch yaw. \n% 'positionStd', [0;0;0],... % position error std\n% 'orientationStd', [0;0;0],... % orient. error std\n% 'imageSize', [1280;800],... % image size\n% 'pixErrorStd', 1.0,... % pixel error std\n% 'intrinsic', k,... % intrinsic params: [xc yc c d e]'; \n% 'distortion', projDist,... % distortion params -> polynom for projection to cam sensor\n% 'invDistortion', invProjDist,... % distortion params -> polynom for inv proj from cam sensor\n% 'frameInMap', false,... % add sensor frame in slam map?\n% 'imGrid', struct(... % grid for Active Search\n% 'numCells', [8;6],... % number of H and V grid cells\n% 'skipOuter', true)); % skip outer cells for initialization?\n\n\n% Estimation options \nOpt = struct(...\n 'map', struct(... % options for the map\n 'numLmks', 73,... % number of 3d landmarks\n 'lmkSize', 7),... % Size of landmark\n 'correct', struct(... % options for lmk correction\n 'reprojectLmks', true,... % reproject lmks after active search?\n 'reparametrize', true,... % reparametrize lmk?\n 'nUpdates', 10,... % max simultaneus updates\n 'MD2th', 9,... % Threshold on Mahalanobis distance squared\n 'linTestIdp', 0.1,... % threshold on IDP linearity test\n 'lines', struct(... % options for line corrections\n 'innType', 'ortDst',... % innovation type for lines\n 'extPolicy', false,... % line extending policy ?\n 'extSwitch', 10)),... % extension policy switch point in pixels\n 'init', struct(... % Options for initialization\n 'nbrInits', [10 1],... % number of inits [firstFrame, otherFrames]\n 'initType', 'ahmPnt',... % Type of lmk to use for init\n 'idpPnt', struct(... % inverse-distance prior\n 'nonObsMean', 0.01,... % mean of non obs\n 'nonObsStd', 0.5),... % std of non obs\n 'plkLin', struct(... % Plucker prior\n 'nonObsMean', [.1;0],... % mean of non obs\n 'nonObsStd', [.25;1])),... % std of non obs\n 'obs', struct(... % Observation options\n 'lines', struct(... % lines options\n 'minLength', 20))); % minimum segment length\n \n\n% Simulation options\n% - random\nSimOpt = struct(... \n 'random', struct(... % random generator options\n 'newSeed', true,... % select new random seed?\n 'fixedSeed', 1,... % random seed for non-random runs\n 'seed', []),... % current seed\n 'obs', Opt.obs); % Observation options\n\n\n\n% Figure options \n% - view, projection, video, ellipses.\n% - figure projections - mapProj:\n% 'persp' Perspective\n% 'ortho' Orthographic\n% - 3D figure views - mapView - see MAPOBSERVER.\n% [a,e,f] Custom azimuth/elevation/FOV vector. Distance automatic\n% [a,e,f,d] custom az/el/fov/distance vector.\n% - 3D figure predefined views (edit mapObserver.m to create/edit views):\n% 'top' Top view\n% 'side' Side view\n% 'view' Generic view\n% 'normal' Normal view\n% - objects colors - two options for color specification:\n% 'rgbcmykw' 1-char predifined Matlab colors\n% [r g b] RGB color vector. [0 0 0] is black, [1 1 1] is white.\nFigOpt = struct(...\n 'renderer', 'opengl',... % renderer\n 'rendPeriod', 1,... % frames to skip for faster processing\n 'createVideo', false,... % create video sequences?\n 'map', struct(... % map figure options\n 'size', [320 240],... % map figure size\n 'lims', struct(... % playground limits\n 'xMin', -10,... \n 'xMax', 10,...\n 'yMin', -10,...\n 'yMax', 10,...\n 'zMin', -10,...\n 'zMax', 10),...\n 'proj', 'persp',... % projection of the 3d figure\n 'view', 'view',... % viewpoint of the 3d figure [30 45 40 20]\n 'orbit', [0 0],... % AZ and EL orbit angle increments\n 'showSimLmk', false,... % show simulated landmarks?\n 'showEllip', true,... % show ellipsoids?\n 'colors', struct(... % map figure colors\n 'border', [1 1 1],... % [r g b] \n 'axes', [0 0 0],... % with:\n 'bckgnd', [1 1 1],... % [0 0 0] black\n 'simLmk', .3*[1 1 1],... % [1 1 1] white\n 'defPnt', struct(... % euclidean point colors\n 'mean', 'b',... % mean dot\n 'ellip', [.7 .7 1]),... % ellipsoid\n 'othPnt', struct(... % other point colors\n 'mean', 'r',... % mean dot\n 'ellip', [1 .7 .7]),... % ellipsoid\n 'defLin', struct(... % Plucker line colors\n 'mean', [0 .8 0],... % mean line\n 'ellip', [.6 1 .6]),... % ellipsoid\n 'othLin', struct(... % Plucker line colors\n 'mean', [.8 0 0],... % mean line\n 'ellip', [1 .6 .6]),... % ellipsoid\n 'simu', 'b',... % or 'r', 'b', etc. \n 'est', 'g',... % estimated robots and sensors\n 'ground', [.8 .8 .8],... % simulated robots and sensors\n 'label', [.0 .5 0])),... % landmark ID labels\n 'sensor', struct(... % sensor figures options\n 'size', [320 240],... % sensor figure size\n 'showEllip', false,... % show ellipses?\n 'colors', struct(... % Sensor figure colors:\n 'border', .8*[1 1 1],... % \n 'axes', [0 0 0],... % \n 'bckgnd', [1 1 1],... %\n 'raw', .3*[1 1 1],... % \n 'defPnt', struct(... % Default point colors\n 'updated', 'c',... % updated\n 'predicted','b'),... % predicted\n 'othPnt', struct(... % other point colors\n 'updated', 'r',... % updated\n 'predicted','m'),... % predicted\n 'defLin', struct(... % Default line colors\n 'meas', 'b',... % measurement\n 'mean', 'g',... % mean line\n 'ellip', 'y'),... % ellipsoid\n 'othLin', struct(... % other line colors\n 'meas', 'b',... % measurement\n 'mean', 'm',... % mean line\n 'ellip', 'r'),... % ellipsoid\n 'label', [.5 .5 .5]))); %\n\n\n% Experiment options \n% - site name, series gathered, estimation run number \nExpOpt = struct(...\n 'root', '~/SLAM/',... % root directory\n 'site', 'simu',... % Name of the site\n 'dataRun', 1,... % Run # on this site\n 'estimateRun', 1,... % slam run for data and site\n 'lmkTypes', Opt.init.initType,... % types of landmarks used\n 'sensingType', 'mono',... % sensing mode\n 'mappingType', 'single'); % mapping mode\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/HighLevel/userDataPnt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19268158866320392}} {"text": "function [sDataCT] = correctPatient30_HN(pathDATA)\n% -------------------------------------------------------------------------\n% function [sDataCT] = correctPatient30_HN(pathDATA)\n% -------------------------------------------------------------------------\n% DESCRIPTION: \n% Reason of existence of the function: the RTstruct of the CT scan of\n% patient 30 is incomplete (most probably it was previously incorrectly \n% processed by MIM). The problem is solved by copying and processing the \n% 'contour' structure of the PET scan.\n% -------------------------------------------------------------------------\n% INPUTS:\n% - pathDATA: Full path to the 'DATA' folder of the HN workspace.\n% -------------------------------------------------------------------------\n% OUTPUTS:\n% - sData: Corrected sData.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: July 2015\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\ncd(pathDATA)\nload('Patient30_CT'), sDataCT = sData;\nload('Patient30_PET'), sDataPET = sData;\n\n% ADJUSTING CT CONTOURS ACCORDING TO PET CONTOURS.\nsDataCT{2}.scan.contour = sDataPET{2}.scan.contour;\nnContour = length(sDataPET{2}.scan.contour);\ndownF = sDataCT{2}.scan.pixelW/sDataPET{2}.scan.pixelW;\noffsetStart = round(abs(sDataPET{3}(1).ImagePositionPatient(2)-sDataCT{3}(1).ImagePositionPatient(2))*sDataCT{2}.scan.pixelW);\noffsetEnd = round((size(sDataCT{2}.scan.volume,1)*sDataCT{2}.scan.pixelW - size(sDataPET{2}.scan.volume,1)*sDataPET{2}.scan.pixelW)/sDataCT{2}.scan.pixelW)-offsetStart;\nfor i = 1:nContour\n sDataCT{2}.scan.contour(i).boxBound(1:2,1) = round((sDataPET{2}.scan.contour(i).boxBound(1:2,1)/downF + offsetStart)); sDataCT{2}.scan.contour(i).boxBound(1:2,2) = round((sDataPET{2}.scan.contour(i).boxBound(1:2,2)/downF + offsetEnd));\n boxBound = sDataCT{2}.scan.contour(i).boxBound;\n nSlices = size(sDataCT{2}.scan.contour(i).boxMask,3);\n sDataCT{2}.scan.contour(i).boxMask = zeros(boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1,nSlices);\n for j = 1:nSlices\n sDataCT{2}.scan.contour(i).boxMask(:,:,j) = imresize(sDataPET{2}.scan.contour(i).boxMask(:,:,j),[boxBound(1,2)-boxBound(1,1)+1,boxBound(2,2)-boxBound(2,1)+1],'nearest');\n end\nend\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/READ_DATA/Archives/correctPatient30_HN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19268158114192288}} {"text": "%% Demo: White balancing all images in a directory\n%\n% Copyright (c) 2018-present, Mahmoud Afifi\n% York University, Canada\n% mafifi@eecs.yorku.ca | m.3afifi@gmail.com\n%\n% This source code is licensed under the license found in the\n% LICENSE file in the root directory of this source tree.\n% All rights reserved.\n%\n% Please cite the following work if this program is used:\n% Mahmoud Afifi, Brian Price, Scott Cohen, and Michael S. Brown,\n% \"When color constancy goes wrong: Correcting improperly white-balanced\n% images\", CVPR 2019.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%\n\n%% input and options\nin_image_dir = fullfile('..', 'example_images');\nout_image_dir = fullfile('..', 'example_images_WB');\ndevice = 'cpu'; %'cpu' or 'gpu'\ngamut_mapping = 2; % use 1 for scaling, 2 for clipping (our paper's results\n% reported using clipping). If the image is over-saturated, scaling is\n% recommended.\nupgraded_model = 0; % use 1 to load our new model that is upgraded with new\n% training examples.\n\n%% \nswitch lower(device)\n case 'cpu'\n if upgraded_model == 1\n load(fullfile('models','WB_model+.mat'));\n elseif upgraded_model == 0\n load(fullfile('models','WB_model.mat'));\n else\n error('Wrong upgraded_model value; please use 0 or 1');\n end\n case 'gpu'\n try\n gpuDevice();\n catch\n error('Cannot find a GPU device');\n end\n if upgraded_model == 1\n load(fullfile('models','WB_model+_gpu.mat'));\n elseif upgraded_model == 0\n load(fullfile('models','WB_model_gpu.mat'));\n else\n error('Wrong upgraded_model value; please use 0 or 1');\n end\n otherwise\n error('Wrong device; please use ''gpu'' or ''cpu''')\nend\nmodel.gamut_mapping = gamut_mapping;\nif exist(out_image_dir,'dir')==0\n mkdir(out_image_dir);\nend\nimds = imageDatastore(in_image_dir);\nfiles = imds.Files;\nfor f = 1 : length(files)\n fprintf('Processing image: %s\\n',files{f});\n infileName = files{f};\n [~,name,ext] = fileparts(infileName);\n outfileName = fullfile(out_image_dir, [name, '_', 'WB', ext]);\n I_in = imread(infileName);\n I_corr = model.correctImage(I_in);\n if strcmpi(device,'gpu')\n imwrite(gather(I_corr),outfileName);\n else\n imwrite(I_corr,outfileName);\n end\n disp('Done!');\nend\n", "meta": {"author": "mahmoudnafifi", "repo": "WB_sRGB", "sha": "98340313cc7d1728e286ad9ba03e8f9a0e8b82c5", "save_path": "github-repos/MATLAB/mahmoudnafifi-WB_sRGB", "path": "github-repos/MATLAB/mahmoudnafifi-WB_sRGB/WB_sRGB-98340313cc7d1728e286ad9ba03e8f9a0e8b82c5/WB_sRGB_Matlab/demo_images.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.1926541330390224}} {"text": "% im2pointsLocally computes image statistics from several images\n% and finds the projections of laser points\n%\n% The version for local computation on each machine\n%\n% The computation core is taken from im2points.m\n% computes average image and image of standard deviations\n% requires read_configuration.m\n% The name of the experiment has to be specified\n% it determines the location of files etc ...\n%\n% the scripts serves as a template for a multiprocessing\n% it assumes a vector of camera IDs CamIds to be known\n% indexes in the CamIds are supposed to be correct\n%\n\ndonefile = '.done';\n\naddpath /home/svoboda/Work/BlueCCal/BlueCFindingPoints\n\n% config = localconfig('BlueCHoengg')\n\n% Read configuration from whatever is specified on command-line (via --config=FILENAME)\nconfig = read_configuration();\n\nSTEP4STAT = 5; % step for computing average and std images, if 1 then all images taken\n\nim.dir = config.paths.data;\nim.ext = config.files.imgext;\n\n% get the information about machine\nmachinename = getenv('HOST');\nCamsIds = str2num(machinename(find(machinename>47 & machinename<58)));\n\nNoCams = size(CamsIds,2);\nCamsIds\n\n% load image names\nfor i=1:NoCams,\n seq(i).camId = CamsIds(i);\n if seq(i).camId > -1\n\tseq(i).data = dir([sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]);\n\t[sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]\n else\n\tseq(i).data = dir([im.dir,sprintf(config.files.imnames),im.ext]);\n end\n seq(i).size = size(seq(i).data,1);\n if seq(i).size<4\n\ti, seq\n\terror('Not enough images found. Wrong image path or name pattern?');\n end\nend\n\n% Expected number of 3D points is equal to the number of frames.\n% In fact, some frames might be without any calibration point\n\n% Because of non-consistent stopping of capturing, the sequences might\n% have different number of images, select the minimal value as the right one\nNoPoints = min([seq.size]);\n\n% compute the average images that will be used for finding LEDs\n% if not already computed\n\npointsIdx = [1:STEP4STAT:NoPoints];\n\nt = cputime;\nfor i=1:NoCams,\n if ~exist(sprintf(config.files.avIM,seq(i).camId)),\n\tdisp(sprintf('The average image of the camera %d is being computed',seq(i).camId));\n\tavIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tfor j=pointsIdx,\n\t IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t avIM = avIM + double(IM);\n\tend\n\tavIM = uint8(round(avIM./size(pointsIdx,2)));\n\timwrite(avIM,sprintf(config.files.avIM,seq(i).camId));\n else\tdisp('Average files already exist');\n end\nend\ndisp(sprintf('Elapsed time for average images: %d [sec]',cputime-t))\n% compute the standard deviations images that will be used for finding LEDs\n% if not already computed\nt = cputime;\nfor i=1:NoCams,\n if ~exist(sprintf(config.files.stdIM,seq(i).camId)),\n\tavIM = double(imread(sprintf(config.files.avIM,seq(i).camId)));\n\tdisp(sprintf('The image of standard deviations of the camera %d is being computed',seq(i).camId));\n\tstdIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tfor j=pointsIdx,\n\t IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t stdIM = stdIM + (double(IM)-avIM).^2;\n\tend\n\tstdIM = uint8(round(sqrt(stdIM./(size(pointsIdx,2)-1))));\n\timwrite(stdIM,sprintf(config.files.stdIM,seq(i).camId));\n else\n\tdisp('Image of standard deviations already exist')\n end\nend\ndisp(sprintf('Elapsed time for computation of images [sec]: %d',cputime-t))\n\n% find points in the images\nWs = [];\nIdWs = [];\nRes\t = [];\n\nIdMat = ones(NoCams,NoPoints);\n% IdMat is very important for Martinec&Pajdla filling [ECCV2002]\n% it is a NoCams x NoPoints matrix,\n% IdMat(i,j) = 0 -> no j-th point in i-th\n% IdMat(i,j) = 1 -> point successfully detected\n\nfor i=1:NoCams,\n Points = [];\n avIM = imread(sprintf(config.files.avIM,seq(i).camId));\n stdIM\t= imread(sprintf(config.files.stdIM,seq(i).camId));\n for j=1:NoPoints,\n\t[pos,err] = getpoint([sprintf(im.dir,seq(i).camId),seq(i).data(j).name], 0, config.imgs, avIM, stdIM);\n\tif err\n\t IdMat(i,j) = 0;\n\t Points = [Points, [NaN; NaN; NaN]];\n\telse\n\t Points = [Points, [pos; 1]];\n\tend\n end\n Ws = [Ws; Points];\n Res= [Res; size(avIM,2), size(avIM,1)];\nend\n\nidx = '.';\nfor i=CamsIds,\n idx = sprintf('%s%02d',idx,i);\nend\n\nsave([config.files.points,idx], 'Ws','-ASCII')\n% save(config.files.IdPoints,'IdWs','-ASCII')\nsave([config.files.Res,idx], 'Res', '-ASCII')\nsave([config.files.IdMat,idx], 'IdMat', '-ASCII')\n\n% write auxiliary file that is done\ndone=1;\nsave(donefile,'done','-ascii');\n\n% exit the Matlab\n% this script is to be used in the batch mode\n% hence exit at the end is necessary\nexit;\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/BlueCFindingPoints/im2pointsLocally.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19256215516013492}} {"text": "%% DEMO_febio_0065_clamp_tension_test\n% Below is a demonstration for: \n% 1) The creation of an FEBio model for clamped tensile testing\n% 2) The use of multiple steps\n% 4) Running an FEBio job with MATLAB\n% 5) Importing FEBio results into MATLAB\n\n%% Keywords\n%\n% * febio_spec version 3.0\n% * febio, FEBio\n% * tension, tensile\n% * displacement control, displacement boundary condition\n% * Hexahedral hex8\n% * static, solid\n% * hyperelastic, Ogden\n% * displacement logfile\n% * stress logfile\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\nfontSize=25;\n\n%% Control parameters\n\n% Path names\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\n\n% Defining file names\nfebioFebFileNamePart='tempModel';\nfebioFebFileName=fullfile(savePath,[febioFebFileNamePart,'.feb']); %FEB file name\nfebioLogFileName=fullfile(savePath,[febioFebFileNamePart,'.txt']); %FEBio log file name\nfebioLogFileName_disp=[febioFebFileNamePart,'_disp_out.txt']; %Log file name for exporting displacement\nfebioLogFileName_strain=[febioFebFileNamePart,'_energy_out.txt']; %Log file name for exporting strain energy density\n\n%Specifying dimensions and number of elements\npointSpacing=1; \nsampleWidth=10;\nsampleThickness=2; \nsampleClampedHeight=sampleWidth;\nsampleGripGripHeight=sampleWidth.*2;\nappliedLinearStrain=0.3;\nclampCompressiveLinearStrain=0.3;\n\n%Initial material parameter set\nc1=1e-3;\nm1=2;\nk_factor=100;\nk=c1*k_factor;\n\n% FEA control settings\nnumTimeSteps=10; %Number of time steps desired\nmax_refs=25; %Max reforms\nmax_ups=0; %Set to zero to use full-Newton iterations\nopt_iter=12; %Optimum number of iterations\nmax_retries=25; %Maximum number of retires\ndtmin=(1/numTimeSteps)/100; %Minimum time step size\ndtmax=1/numTimeSteps; %Maximum time step size\n\nmin_residual=1e-20;\nsymmetric_stiffness=0;\nrunMode='external'; %'internal' or 'external'\n\n%% Computing derived parameters\nnumElementsWidth=ceil(sampleWidth/pointSpacing);\nnumElementsWidth=numElementsWidth+iseven(numElementsWidth); %Force uneven so there is a middle element\nnumElementsThickness=ceil(sampleThickness/pointSpacing)+1;\nnumElementsGripGripHeight=ceil(sampleGripGripHeight/pointSpacing);\nnumElementsGripGripHeight=numElementsGripGripHeight+iseven(numElementsGripGripHeight); %Force uneven so there is a middle element\nnumElementsClampedHeight=ceil(sampleClampedHeight/pointSpacing);\n\nclampCompressiveDisplacement=(sampleThickness.*clampCompressiveLinearStrain)/2;\nclampTensionDisplacement=(sampleGripGripHeight.*appliedLinearStrain);\n\n%% Creating strip region\n% The region consists of three \"boxes\" which define the upper and lower\n% clamped regions as well as the central region. \n\n%Create box 1\nboxDim=[sampleWidth sampleThickness sampleClampedHeight]; %Dimensions\nboxEl=[numElementsWidth numElementsThickness numElementsClampedHeight]; %Number of elements\n[box1]=hexMeshBox(boxDim,boxEl);\nE1=box1.E;\nV1=box1.V;\nF1=box1.F;\nFb1=box1.Fb;\nfaceBoundaryMarker1=box1.faceBoundaryMarker;\n\n%Create box 3 by copying the first\nE3=E1; \nV3=V1; \nF3=F1;\nFb3=Fb1;\nfaceBoundaryMarker3=faceBoundaryMarker1;\n\n%Shift first box up\nV1(:,3)=V1(:,3)+sampleGripGripHeight/2+sampleClampedHeight/2;\n\n%Shift third box down\nV3(:,3)=V3(:,3)-sampleGripGripHeight/2-sampleClampedHeight/2;\n\n%Create box 2\nboxDim=[sampleWidth sampleThickness sampleGripGripHeight]; %Dimensions\nboxEl=[numElementsWidth numElementsThickness numElementsGripGripHeight]; %Number of elements\n[box2]=hexMeshBox(boxDim,boxEl);\nE2=box2.E;\nV2=box2.V;\nF2=box2.F;\nFb2=box2.Fb;\nfaceBoundaryMarker2=box2.faceBoundaryMarker;\n\n%% Merging box sets\n\n%Join color data\nfaceBoundaryMarker_all=[faceBoundaryMarker1; faceBoundaryMarker2; faceBoundaryMarker3;];\nfaceBoundaryMarker_ind=[ones(size(Fb1,1),1);2*ones(size(Fb2,1),1); 3*ones(size(Fb3,1),1);];\n\n%Join nodes, elements, and faces\nV=[V1;V2;V3];\nE=[E1;E2+size(V1,1);E3+size(V1,1)+size(V2,1)];\nF=[F1;F2+size(V1,1);F3+size(V1,1)+size(V2,1)];\nFb=[Fb1;Fb2+size(V1,1);Fb3+size(V1,1)+size(V2,1)];\n\n%Merge nodes\n[F,V,ind1,ind2]=mergeVertices(F,V);\nE=ind2(E);\nFb=ind2(Fb);\n\n%%\n% Plotting surface models\ncFigure; \nsubplot(1,2,1); hold on;\ntitle('Merged box sets','FontSize',fontSize);\ngpatch(Fb,V,faceBoundaryMarker_all);\naxisGeom(gca,fontSize);\ncolormap(gca,gjet(250)); icolorbar; \n\nsubplot(1,2,2); hold on;\ntitle('Merged box sets','FontSize',fontSize);\ngpatch(Fb,V,faceBoundaryMarker_ind);\naxisGeom(gca,fontSize);\ncolormap(gca,gjet(250)); icolorbar; \ndrawnow; \n\n%% Define clamping surfaces\n\nlogicContactSurf1=faceBoundaryMarker_all==3 & faceBoundaryMarker_ind==1;\nFc1=Fb(logicContactSurf1,:);\n\nlogicContactSurf2=faceBoundaryMarker_all==4 & faceBoundaryMarker_ind==1;\nFc2=Fb(logicContactSurf2,:);\n\nlogicContactSurf3=faceBoundaryMarker_all==4 & faceBoundaryMarker_ind==3;\nFc3=Fb(logicContactSurf3,:);\n\nlogicContactSurf4=faceBoundaryMarker_all==3 & faceBoundaryMarker_ind==3;\nFc4=Fb(logicContactSurf4,:);\n\n%% \n% Visualize clamping surfaces \n\ncFigure; hold on;\ntitle('Clamping surfaces','FontSize',fontSize);\ngpatch(Fb,V,'kw','none',0.25);\nhp(1)=gpatch(Fc1,V,'rw','k',1);\nhp(2)=gpatch(Fc2,V,'gw','k',1);\nhp(3)=gpatch(Fc3,V,'bw','k',1);\nhp(4)=gpatch(Fc4,V,'yw','k',1);\nlegend(hp,{'Surf. 1','Surf. 2','Surf. 3','Surf. 4'})\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow; \n\n%% Define BC's\n\nbcPrescribeList1=unique(Fc1(:)); % Nodes of surface 1\nbcPrescribeList2=unique(Fc2(:)); % Nodes of surface 2\nbcPrescribeList3=unique(Fc3(:)); % Nodes of surface 3\nbcPrescribeList4=unique(Fc4(:)); % Nodes of surface 4\n\n%%\n% Visualize boundary conditions\n\ncFigure; hold on;\ntitle('Complete model','FontSize',fontSize);\n\ngpatch(Fb,V,'kw','none',0.25);\n\nhp(1)=plotV(V(bcPrescribeList1,:),'r.','MarkerSize',25);\nhp(2)=plotV(V(bcPrescribeList2,:),'g.','MarkerSize',25);\nhp(3)=plotV(V(bcPrescribeList3,:),'b.','MarkerSize',25);\nhp(4)=plotV(V(bcPrescribeList4,:),'y.','MarkerSize',25);\nlegend(hp,{'Node set 1','Node set 2','Node set 3','Node set 4'})\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow; \n\n%% Get logic for middle elements (to help investigate strain in the middle)\n\nsearchTol=pointSpacing/1000; \nVE=patchCentre(E,V);\nlogicMiddleElements= VE(:,3)-searchTol;\n\n[FM]=element2patch(E(logicMiddleElements,:),[],'hex8');\n\n%%\ncFigure; hold on;\ngpatch(Fb,V,'kw','none',0.25);\n\ngpatch(FM,V,'rw','k',1);\n\n% hp(1)=plotV(V(bcPrescribeList1,:),'r.','MarkerSize',25);\n% legend(hp,{'Node set 1','Node set 2','Node set 3','Node set 4'})\naxisGeom(gca,fontSize);\ncamlight headlight;\ndrawnow; \n\n%% Defining the FEBio input structure\n% See also |febioStructTemplate| and |febioStruct2xml| and the FEBio user\n% manual.\n\n%Get a template with default settings \n[febio_spec]=febioStructTemplate;\n\n%febio_spec version \nfebio_spec.ATTR.version='3.0'; \n\n%Module section\nfebio_spec.Module.ATTR.type='solid'; \n\n%Create control structure for use by all steps\nstepStruct.Control.time_steps=numTimeSteps;\nstepStruct.Control.step_size=1/numTimeSteps;\nstepStruct.Control.solver.max_refs=max_refs;\nstepStruct.Control.solver.max_ups=max_ups;\nstepStruct.Control.time_stepper.dtmin=dtmin;\nstepStruct.Control.time_stepper.dtmax=dtmax; \nstepStruct.Control.time_stepper.max_retries=max_retries;\nstepStruct.Control.time_stepper.opt_iter=opt_iter;\n\n%Add template based default settings to proposed control section\n[stepStruct.Control]=structComplete(stepStruct.Control,febio_spec.Control,1); %Complement provided with default if missing\n\n%Remove control field (part of template) since step specific control sections are used\nfebio_spec=rmfield(febio_spec,'Control'); \n\nfebio_spec.Step.step{1}.Control=stepStruct.Control;\nfebio_spec.Step.step{1}.ATTR.id=1;\nfebio_spec.Step.step{2}.Control=stepStruct.Control;\nfebio_spec.Step.step{2}.ATTR.id=2;\n\n%Material section\nmaterialName1='Material1';\nfebio_spec.Material.material{1}.ATTR.name=materialName1;\nfebio_spec.Material.material{1}.ATTR.type='Ogden';\nfebio_spec.Material.material{1}.ATTR.id=1;\nfebio_spec.Material.material{1}.c1=c1;\nfebio_spec.Material.material{1}.m1=m1;\nfebio_spec.Material.material{1}.c2=c1;\nfebio_spec.Material.material{1}.m2=-m1;\nfebio_spec.Material.material{1}.k=k;\n\n% Mesh section\n% -> Nodes\nfebio_spec.Mesh.Nodes{1}.ATTR.name='Object1'; %The node set name\nfebio_spec.Mesh.Nodes{1}.node.ATTR.id=(1:size(V,1))'; %The node id's\nfebio_spec.Mesh.Nodes{1}.node.VAL=V; %The nodel coordinates\n\n% -> Elements\npartName1='Part1';\nfebio_spec.Mesh.Elements{1}.ATTR.name=partName1; %Name of this part\nfebio_spec.Mesh.Elements{1}.ATTR.type='hex8'; %Element type\nfebio_spec.Mesh.Elements{1}.elem.ATTR.id=(1:1:size(E,1))'; %Element id's\nfebio_spec.Mesh.Elements{1}.elem.VAL=E; %The element matrix\n \n% -> NodeSets\nnodeSetName1='bcPrescribeList1';\nfebio_spec.Mesh.NodeSet{1}.ATTR.name=nodeSetName1;\nfebio_spec.Mesh.NodeSet{1}.node.ATTR.id=bcPrescribeList1(:);\n\nnodeSetName2='bcPrescribeList2';\nfebio_spec.Mesh.NodeSet{2}.ATTR.name=nodeSetName2;\nfebio_spec.Mesh.NodeSet{2}.node.ATTR.id=bcPrescribeList2(:);\n\nnodeSetName3='bcPrescribeList3';\nfebio_spec.Mesh.NodeSet{3}.ATTR.name=nodeSetName3;\nfebio_spec.Mesh.NodeSet{3}.node.ATTR.id=bcPrescribeList3(:);\n\nnodeSetName4='bcPrescribeList4';\nfebio_spec.Mesh.NodeSet{4}.ATTR.name=nodeSetName4;\nfebio_spec.Mesh.NodeSet{4}.node.ATTR.id=bcPrescribeList4(:);\n\n%MeshDomains section\nfebio_spec.MeshDomains.SolidDomain.ATTR.name=partName1;\nfebio_spec.MeshDomains.SolidDomain.ATTR.mat=materialName1;\n\n%Boundary condition section \n%STEP 1: Clamping compression\n%Set 1\nfebio_spec.Step.step{1}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{1}.Boundary.bc{1}.dof='x';\nfebio_spec.Step.step{1}.Boundary.bc{1}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{1}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{2}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{2}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{1}.Boundary.bc{2}.dof='y';\nfebio_spec.Step.step{1}.Boundary.bc{2}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{2}.scale.VAL=clampCompressiveDisplacement;\nfebio_spec.Step.step{1}.Boundary.bc{2}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{3}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{3}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{1}.Boundary.bc{3}.dof='z';\nfebio_spec.Step.step{1}.Boundary.bc{3}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{3}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{3}.relative=1;\n\n%Set 2\nfebio_spec.Step.step{1}.Boundary.bc{4}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{4}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{1}.Boundary.bc{4}.dof='x';\nfebio_spec.Step.step{1}.Boundary.bc{4}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{4}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{4}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{5}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{5}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{1}.Boundary.bc{5}.dof='y';\nfebio_spec.Step.step{1}.Boundary.bc{5}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{5}.scale.VAL=-clampCompressiveDisplacement;\nfebio_spec.Step.step{1}.Boundary.bc{5}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{6}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{6}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{1}.Boundary.bc{6}.dof='z';\nfebio_spec.Step.step{1}.Boundary.bc{6}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{6}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{6}.relative=1;\n\n%Set 3\nfebio_spec.Step.step{1}.Boundary.bc{7}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{7}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{1}.Boundary.bc{7}.dof='x';\nfebio_spec.Step.step{1}.Boundary.bc{7}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{7}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{7}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{8}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{8}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{1}.Boundary.bc{8}.dof='y';\nfebio_spec.Step.step{1}.Boundary.bc{8}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{8}.scale.VAL=-clampCompressiveDisplacement;\nfebio_spec.Step.step{1}.Boundary.bc{8}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{9}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{9}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{1}.Boundary.bc{9}.dof='z';\nfebio_spec.Step.step{1}.Boundary.bc{9}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{9}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{9}.relative=1;\n\n%Set 4\nfebio_spec.Step.step{1}.Boundary.bc{10}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{10}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{1}.Boundary.bc{10}.dof='x';\nfebio_spec.Step.step{1}.Boundary.bc{10}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{10}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{10}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{11}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{11}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{1}.Boundary.bc{11}.dof='y';\nfebio_spec.Step.step{1}.Boundary.bc{11}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{11}.scale.VAL=clampCompressiveDisplacement;\nfebio_spec.Step.step{1}.Boundary.bc{11}.relative=1;\n\nfebio_spec.Step.step{1}.Boundary.bc{12}.ATTR.type='prescribe';\nfebio_spec.Step.step{1}.Boundary.bc{12}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{1}.Boundary.bc{12}.dof='z';\nfebio_spec.Step.step{1}.Boundary.bc{12}.scale.ATTR.lc=1;\nfebio_spec.Step.step{1}.Boundary.bc{12}.scale.VAL=0;\nfebio_spec.Step.step{1}.Boundary.bc{12}.relative=1;\n\n%STEP 2 Tension\n%Set 1\nfebio_spec.Step.step{2}.Boundary.bc{1}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{1}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{2}.Boundary.bc{1}.dof='x';\nfebio_spec.Step.step{2}.Boundary.bc{1}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{1}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{1}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{2}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{2}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{2}.Boundary.bc{2}.dof='y';\nfebio_spec.Step.step{2}.Boundary.bc{2}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{2}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{2}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{3}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{3}.ATTR.node_set=nodeSetName1;\nfebio_spec.Step.step{2}.Boundary.bc{3}.dof='z';\nfebio_spec.Step.step{2}.Boundary.bc{3}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{3}.scale.VAL=clampTensionDisplacement;\nfebio_spec.Step.step{2}.Boundary.bc{3}.relative=1;\n\n%Set 2\nfebio_spec.Step.step{2}.Boundary.bc{4}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{4}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{2}.Boundary.bc{4}.dof='x';\nfebio_spec.Step.step{2}.Boundary.bc{4}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{4}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{4}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{5}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{5}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{2}.Boundary.bc{5}.dof='y';\nfebio_spec.Step.step{2}.Boundary.bc{5}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{5}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{5}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{6}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{6}.ATTR.node_set=nodeSetName2;\nfebio_spec.Step.step{2}.Boundary.bc{6}.dof='z';\nfebio_spec.Step.step{2}.Boundary.bc{6}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{6}.scale.VAL=clampTensionDisplacement;\nfebio_spec.Step.step{2}.Boundary.bc{6}.relative=1;\n\n%Set 3\nfebio_spec.Step.step{2}.Boundary.bc{7}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{7}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{2}.Boundary.bc{7}.dof='x';\nfebio_spec.Step.step{2}.Boundary.bc{7}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{7}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{7}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{8}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{8}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{2}.Boundary.bc{8}.dof='y';\nfebio_spec.Step.step{2}.Boundary.bc{8}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{8}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{8}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{9}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{9}.ATTR.node_set=nodeSetName3;\nfebio_spec.Step.step{2}.Boundary.bc{9}.dof='z';\nfebio_spec.Step.step{2}.Boundary.bc{9}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{9}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{9}.relative=1;\n\n%Set 4\nfebio_spec.Step.step{2}.Boundary.bc{10}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{10}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{2}.Boundary.bc{10}.dof='x';\nfebio_spec.Step.step{2}.Boundary.bc{10}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{10}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{10}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{11}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{11}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{2}.Boundary.bc{11}.dof='y';\nfebio_spec.Step.step{2}.Boundary.bc{11}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{11}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{11}.relative=1;\n\nfebio_spec.Step.step{2}.Boundary.bc{12}.ATTR.type='prescribe';\nfebio_spec.Step.step{2}.Boundary.bc{12}.ATTR.node_set=nodeSetName4;\nfebio_spec.Step.step{2}.Boundary.bc{12}.dof='z';\nfebio_spec.Step.step{2}.Boundary.bc{12}.scale.ATTR.lc=2;\nfebio_spec.Step.step{2}.Boundary.bc{12}.scale.VAL=0;\nfebio_spec.Step.step{2}.Boundary.bc{12}.relative=1;\n\n\n%LoadData section\n%LoadData section\n% -> load_controller\nfebio_spec.LoadData.load_controller{1}.ATTR.id=1;\nfebio_spec.LoadData.load_controller{1}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{1}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{1}.points.point.VAL=[0 0; 1 1];\n\nfebio_spec.LoadData.load_controller{2}.ATTR.id=2;\nfebio_spec.LoadData.load_controller{2}.ATTR.type='loadcurve';\nfebio_spec.LoadData.load_controller{2}.interpolate='LINEAR';\nfebio_spec.LoadData.load_controller{2}.points.point.VAL=[0 0; 1 0; 2 1];\n\n%Output section\n% -> log file\nfebio_spec.Output.logfile.ATTR.file=febioLogFileName;\nfebio_spec.Output.logfile.node_data{1}.ATTR.file=febioLogFileName_disp;\nfebio_spec.Output.logfile.node_data{1}.ATTR.data='ux;uy;uz';\nfebio_spec.Output.logfile.node_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.node_data{1}.VAL=1:size(V,1);\n\nfebio_spec.Output.logfile.element_data{1}.ATTR.file=febioLogFileName_strain;\nfebio_spec.Output.logfile.element_data{1}.ATTR.data='Ez';\nfebio_spec.Output.logfile.element_data{1}.ATTR.delim=',';\nfebio_spec.Output.logfile.element_data{1}.VAL=1:1:size(E,1);\n\n%% Quick viewing of the FEBio input file structure\n% The |febView| function can be used to view the xml structure in a MATLAB\n% figure window. \n\n%%\n% |febView(febio_spec); %Viewing the febio file|\n\n%% Exporting the FEBio input file\n% Exporting the febio_spec structure to an FEBio input file is done using\n% the |febioStruct2xml| function. \n\nfebioStruct2xml(febio_spec,febioFebFileName); %Exporting to file and domNode\n\n%% Running the FEBio analysis\n% To run the analysis defined by the created FEBio input file the\n% |runMonitorFEBio| function is used. The input for this function is a\n% structure defining job settings e.g. the FEBio input file name. The\n% optional output runFlag informs the user if the analysis was run\n% succesfully. \n\nfebioAnalysis.run_filename=febioFebFileName; %The input file name\nfebioAnalysis.run_logname=febioLogFileName; %The name for the log file\nfebioAnalysis.disp_on=1; %Display information on the command window\nfebioAnalysis.runMode=runMode;\nfebioAnalysis.maxLogCheckTime=120; %Max log file checking time\n\n[runFlag]=runMonitorFEBio(febioAnalysis);%START FEBio NOW!!!!!!!!\n\n%% Import FEBio results \n\nif runFlag==1 %i.e. a succesful run\n \n %% \n % Importing nodal displacements from a log file\n\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_disp),1,1);\n \n %Access data\n N_disp_mat=dataStruct.data; %Displacement\n timeVec=dataStruct.time; %Time\n \n %Create deformed coordinate set\n V_DEF=N_disp_mat+repmat(V,[1 1 size(N_disp_mat,3)]);\n\n \n %%\n % Importing element strain data from a log file\n dataStruct=importFEBio_logfile(fullfile(savePath,febioLogFileName_strain),1,1);\n \n %Access data\n E_strain=dataStruct.data;\n \n [F,CF]=element2patch(E,E_strain(:,:,end));\n CF_V=faceToVertexMeasure(F,V,CF);\n\n E_strain_middle_mean=squeeze(mean(E_strain(logicMiddleElements,:,:),1));\n\n %% Compute grimp implied strain\n gripStrainLinear=double(timeVec>1).*(timeVec-1).*appliedLinearStrain; \n gripStrain=1/2*((gripStrainLinear+1).^2-1); %Green-Lagrange strain\n maxGridStrain=max(abs(gripStrain));\n %%\n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations\n \n axLim=[min(min(V_DEF,[],3),[],1); max(max(V_DEF,[],3),[],1)];\n indBc=[bcPrescribeList1;bcPrescribeList2;bcPrescribeList3;bcPrescribeList4;];\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; hold on;%Open figure\n gtitle([febioFebFileNamePart,': Press play to animate']);\n title('$E_{zz}$','Interpreter','Latex')\n hp1=gpatch(Fb,V_DEF(:,:,end),CF_V,'k',1);\n hp1.FaceColor='interp';\n hp2=plotV(V(indBc,:),'k.','MarkerSize',25);\n \n axisGeom(gca,fontSize);\n colormap(warmcold(250)); hc=colorbar;\n caxis([-maxGridStrain maxGridStrain]);\n hc.Ticks=linspace(-maxGridStrain,maxGridStrain,7);\n axis(axLim(:)'); %Set axis limits statically\n\n camlight headlight; axis off;\n \n % Set up animation features\n animStruct.Time=timeVec; %The time vector\n for qt=1:1:size(N_disp_mat,3) %Loop over time increments\n V_def=V+N_disp_mat(:,:,qt); %Current nodal coordinates\n \n [~,CF]=element2patch(E,E_strain(:,:,qt));\n CF_V=faceToVertexMeasure(F,V,CF);\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp1 hp1 hp2 hp2 hp2]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData','XData','YData','ZData'}; %Properties of objects to animate\n animStruct.Set{qt}={V_def,CF_V,V_def(indBc,1),V_def(indBc,2),V_def(indBc,3)}; %Property values for to set in order to animate\n end\n anim8(hf,animStruct); %Initiate animation feature\n gdrawnow;\n\n %%\n % Plotting the simulated results using |anim8| to visualize and animate\n % deformations\n \n indBc=[bcPrescribeList1;bcPrescribeList2;bcPrescribeList3;bcPrescribeList4;];\n \n % Create basic view and store graphics handle to initiate animation\n hf=cFigure; \n subplot(1,2,1); hold on;\n title('$E_{zz}$','Interpreter','Latex');\n gtitle([febioFebFileNamePart,': Press play to animate']);\n hp1=gpatch(Fb,V_DEF(:,:,end),CF_V,'none',1,0.5); hp1.FaceColor='interp';\n hp2=plotV(V_DEF(indBc,:,end),'k.','MarkerSize',1); \n hp3=gpatch(FM,V_DEF(:,:,end),CF_V,'k',1,2); hp3.FaceColor='interp';\n \n colormap(warmcold(250)); hc=colorbar;\n caxis([-maxGridStrain maxGridStrain]);\n hc.Ticks=linspace(-maxGridStrain,maxGridStrain,7); \n axisGeom(gca,fontSize); camlight headlight; \n axis(axisLim(V_DEF)); %Set axis limits statically\n view(0,0); axis off;\n \n subplot(1,2,2); hold on; \n xlabel('Time (s)'); ylabel('$E_{zz}$','Interpreter','Latex');\n hpl4=plot(timeVec,E_strain_middle_mean,'g.-','LineWidth',3);\n hpl5=plot(timeVec,gripStrain,'r.-','LineWidth',3);\n hp4=plot(timeVec(end),E_strain_middle_mean(end),'g.','MarkerSize',50);\n hp5=plot(timeVec(end),gripStrain(end),'r.','MarkerSize',50);\n legend([hpl4 hpl5],{'True strain $E_{zz}$','\"Intended applied\" strain $E_{zz}$'},'Location','NorthOutside','Interpreter','Latex');\n axis tight; box on; grid on; set(gca,'FontSize',fontSize);\n\n % Set up animation features\n animStruct.Time=timeVec; %The time vector\n for qt=1:1:size(N_disp_mat,3) %Loop over time increments\n V_def=V_DEF(:,:,qt); %Current nodal coordinates\n \n [~,CF]=element2patch(E,E_strain(:,:,qt));\n CF_V=faceToVertexMeasure(F,V,CF);\n \n %Set entries in animation structure\n animStruct.Handles{qt}=[hp1 hp1 hp2 hp2 hp2 hp3 hp3 hp4 hp4 hp5 hp5]; %Handles of objects to animate\n animStruct.Props{qt}={'Vertices','CData','XData','YData','ZData','Vertices','CData','XData','YData','XData','YData'}; %Properties of objects to animate\n animStruct.Set{qt}={V_def,CF_V,V_def(indBc,1),V_def(indBc,2),V_def(indBc,3),V_def,CF_V,timeVec(qt),E_strain_middle_mean(qt),timeVec(qt),gripStrain(qt)}; %Property values for to set in order to animate\n end\n anim8(hf,animStruct); %Initiate animation feature\n drawnow;\n \nend\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_febio_0065_clamp_tension_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1925621440073831}} {"text": "% LFCalInit - initialize calibration estimate, called by LFUtilCalLensletCam\n%\n% Usage: \n% CalOptions = LFCalInit( InputPath, CalOptions )\n% CalOptions = LFCalInit( InputPath )\n%\n% This function is called by LFUtilCalLensletCam to initialize a pose and camera model estimate\n% given a set of extracted checkerboard corners.\n% \n% Inputs:\n% \n% InputPath : Path to folder containing processed checkerboard images. Checkerboard corners must\n% be identified prior to calling this function, by running LFCalFindCheckerCorners\n% for example. This is demonstrated by LFUtilCalLensletCam.\n% \n% [optional] CalOptions : struct controlling calibration parameters, all fields are optional\n% .SaveResult : Set to false to perform a \"dry run\"\n% .CheckerCornersFnamePattern : Pattern for finding checkerboard corner files, as generated by\n% LFCalFindCheckerCorners; %s is a placeholder for the base filename\n% .CheckerInfoFname : Name of the output file containing the summarized checkerboard\n% information\n% .CalInfoFname : Name of the file containing an initial estimate, to be refined.\n% Note that this parameter is automatically set in the CalOptions\n% struct returned by LFCalInit\n% .ForceRedoInit : Forces the function to overwrite existing results\n%\n% Outputs :\n% \n% CalOptions struct as applied, including any default values as set up by the function.\n% \n% The checkerboard info file and calibration info file are the key outputs of this function.\n% \n% User guide: LFToolbox.pdf\n% See also: LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalRefine\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction CalOptions = LFCalInit( InputPath, CalOptions )\n\n%---Defaults---\nCalOptions = LFDefaultField( 'CalOptions', 'SaveResult', true );\nCalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' );\nCalOptions = LFDefaultField( 'CalOptions', 'CheckerInfoFname', 'CheckerboardCorners.mat' );\nCalOptions = LFDefaultField( 'CalOptions', 'CalInfoFname', 'CalInfo.json' );\nCalOptions = LFDefaultField( 'CalOptions', 'ForceRedoInit', false );\n\n\n%---Start by checking if this step has already been completed---\nfprintf('\\n===Initializing calibration process===\\n');\nCalInfoSaveFname = fullfile(InputPath, CalOptions.CalInfoFname);\nif( ~CalOptions.ForceRedoInit && exist(CalInfoSaveFname, 'file') )\n fprintf(' ---File %s already exists, skipping---\\n', CalInfoSaveFname);\n return;\nend\n\n%---Compute ideal checkerboard geometry - order matters---\nIdealCheckerX = CalOptions.ExpectedCheckerSpacing_m(1) .* (0:CalOptions.ExpectedCheckerSize(1)-1);\nIdealCheckerY = CalOptions.ExpectedCheckerSpacing_m(2) .* (0:CalOptions.ExpectedCheckerSize(2)-1);\n[IdealCheckerY, IdealCheckerX] = ndgrid(IdealCheckerY, IdealCheckerX);\nIdealChecker = cat(3,IdealCheckerX, IdealCheckerY, zeros(size(IdealCheckerX)));\nIdealChecker = reshape(IdealChecker, [], 3)';\n\n%---Crawl folder structure locating corner info files---\nfprintf('\\n===Locating checkerboard corner files in %s===\\n', InputPath);\n[CalOptions.FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.CheckerCornersFnamePattern, '*') );\nfprintf('Found :\\n');\ndisp(CalOptions.FileList)\n\n%---Initial estimate of focal length---\nSkippedFileCount = 0;\nValidSuperPoseCount = 0;\nValidCheckerCount = 0;\n%---Load each checkerboard corner file---\nfprintf('Loading corner observations...\\n');\nfor( iFile = 1:length(CalOptions.FileList) )\n ValidSuperPoseCount = ValidSuperPoseCount + 1;\n CurFname = CalOptions.FileList{iFile};\n [~,ShortFname] = fileparts(CurFname);\n fprintf('---%s [%3d / %3d]...', ShortFname, ValidSuperPoseCount+SkippedFileCount, length(CalOptions.FileList));\n \n load(fullfile(BasePath, CurFname), 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');\n PerImageValidCount = 0;\n for( TIdx = 1:size(CheckerCorners,1) )\n for( SIdx = 1:size(CheckerCorners,2) )\n CurChecker = CheckerCorners{TIdx, SIdx}';\n CurSize = size(CurChecker);\n CurValid = (CurSize(2) == prod(CalOptions.ExpectedCheckerSize));\n CheckerValid(ValidSuperPoseCount, TIdx, SIdx) = CurValid;\n \n %---For valid poses (having expected corner count), compute a homography---\n if( CurValid )\n ValidCheckerCount = ValidCheckerCount + 1;\n PerImageValidCount = PerImageValidCount + 1;\n \n %--- reorient to expected ---\n Centroid = mean( CurChecker,2 );\n IsTopLeft = all(CurChecker(:,1) < Centroid);\n IsTopRight = (CurChecker(1,1) > Centroid(1) && CurChecker(2,1) < Centroid(2));\n\t\t\t\tIsBotLeft = (CurChecker(1,1) < Centroid(1) && CurChecker(2,1) > Centroid(2));\n\t\t\t\tIsBotRight = all(CurChecker(:,1) > Centroid);\n if( IsTopRight )\n CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);\n CurChecker = CurChecker(:, end:-1:1, :);\n CurChecker = permute(CurChecker, [1,3,2]);\n CurChecker = reshape(CurChecker, 2, []);\n\t\t\t\telseif( IsBotLeft )\n CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);\n CurChecker = CurChecker(:, :, end:-1:1);\n CurChecker = permute(CurChecker, [1,3,2]);\n CurChecker = reshape(CurChecker, 2, []);\n\t\t\t\telseif( IsBotRight )\n CurChecker = reshape(CurChecker, [2, CalOptions.ExpectedCheckerSize]);\n CurChecker = CurChecker(:, end:-1:1, end:-1:1);\n CurChecker = reshape(CurChecker, 2, []);\n\t\t\t\tend\n IsTopLeft = all(CurChecker(:,1) < Centroid);\n assert( IsTopLeft, 'Error: unexpected point order from detectCheckerboardPoints' );\n \n CheckerObs{ValidSuperPoseCount, TIdx, SIdx} = CurChecker;\n end\n end\n end\n CalOptions.ValidSubimageCount(iFile) = PerImageValidCount;\n fprintf(' %d / %d valid.\\n', PerImageValidCount, prod(LFSize(1:2)));\nend\n\n%---Compute homography for each subcam pose---\nfprintf('Initial estimate of focal length...\\n');\nValidCheckerCount = 0;\nfor( iFile = 1:length(CalOptions.FileList) )\n for( TIdx = 1:size(CheckerObs,3) )\n for( SIdx = 1:size(CheckerObs,2) )\n\t\t\tCurChecker = CheckerObs{iFile, TIdx, SIdx};\n\t\t\tif( ~isempty(CurChecker) )\n\t\t\t\tValidCheckerCount = ValidCheckerCount + 1;\t\t\t\n\t\t\t\t%---Compute homography for each subcam pose---\n\t\t\t\tCurH = compute_homography( CurChecker, IdealChecker(1:2,:) );\n\t\t\t\tH(ValidCheckerCount, :,:) = CurH;\n\t\t\tend\n end\n end\n fprintf('.');\nend\nfprintf('\\n');\n\nA = [];\nb = [];\n\n%---Initialize principal point at the center of the image---\n% This section of code is based heavily on code from the Camera Calibration Toolbox for Matlab by\n% Jean-Yves Bouguet\nCInit = LFSize([4,3])'/2 - 0.5; \nRecenterH = [1, 0, -CInit(1); 0, 1, -CInit(2); 0, 0, 1];\n\nfor iHomography = 1:size(H,1)\n CurH = squeeze(H(iHomography,:,:));\n CurH = RecenterH * CurH;\n \n %---Extract vanishing points (direct and diagonal)---\n V_hori_pix = CurH(:,1);\n V_vert_pix = CurH(:,2);\n V_diag1_pix = (CurH(:,1)+CurH(:,2))/2;\n V_diag2_pix = (CurH(:,1)-CurH(:,2))/2;\n \n V_hori_pix = V_hori_pix/norm(V_hori_pix);\n V_vert_pix = V_vert_pix/norm(V_vert_pix);\n V_diag1_pix = V_diag1_pix/norm(V_diag1_pix);\n V_diag2_pix = V_diag2_pix/norm(V_diag2_pix);\n \n a1 = V_hori_pix(1);\n b1 = V_hori_pix(2);\n c1 = V_hori_pix(3);\n \n a2 = V_vert_pix(1);\n b2 = V_vert_pix(2);\n c2 = V_vert_pix(3);\n \n a3 = V_diag1_pix(1);\n b3 = V_diag1_pix(2);\n c3 = V_diag1_pix(3);\n \n a4 = V_diag2_pix(1);\n b4 = V_diag2_pix(2);\n c4 = V_diag2_pix(3);\n \n CurA = [a1*a2, b1*b2; a3*a4, b3*b4];\n CurB = -[c1*c2; c3*c4];\n\n if( isempty(find(isnan(CurA), 1)) && isempty(find(isnan(CurB), 1)) )\n A = [A; CurA];\n b = [b; CurB];\n end\nend\n\nFocInit = sqrt(b'*(sum(A')') / (b'*b)) * ones(2,1);\nfprintf('Init focal length est: %.2f, %.2f\\n', FocInit);\n\n%---Initial estimate of extrinsics---\nfprintf('\\nInitial estimate of extrinsics...\\n');\n\nfor( iSuperPoseIdx = 1:ValidSuperPoseCount )\n fprintf('---[%d / %d]', iSuperPoseIdx, ValidSuperPoseCount);\n for( TIdx = 1:size(CheckerCorners,1) )\n fprintf('.');\n for( SIdx = 1:size(CheckerCorners,2) )\n if( ~CheckerValid(iSuperPoseIdx, TIdx, SIdx) )\n continue;\n end\n CurChecker = CheckerObs{iSuperPoseIdx, TIdx, SIdx};\n \n [CurRot, CurTrans] = compute_extrinsic_init(CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0);\n [CurRot, CurTrans] = compute_extrinsic_refine(CurRot, CurTrans, CurChecker, IdealChecker, FocInit, CInit, zeros(1,5), 0,20,1000000);\n \n RotVals{iSuperPoseIdx, TIdx, SIdx} = CurRot;\n TransVals{iSuperPoseIdx, TIdx, SIdx} = CurTrans;\n end\n end\n \n %---Approximate each superpose as the median of its sub-poses---\n % note the approximation in finding the mean orientation: mean of rodrigues... works because all\n % sub-orientations within a superpose are nearly identical.\n MeanRotVals(iSuperPoseIdx,:) = median([RotVals{iSuperPoseIdx, :, :}], 2);\n MeanTransVals(iSuperPoseIdx,:) = median([TransVals{iSuperPoseIdx, :, :}], 2);\n fprintf('\\n');\n \n %---Track the apparent \"baseline\" of the camera at each pose---\n CurDist = bsxfun(@minus, [TransVals{iSuperPoseIdx, :, :}], MeanTransVals(iSuperPoseIdx,:)');\n CurAbsDist = sqrt(sum(CurDist.^2));\n % store as estimated diameter; the 3/2 comes from the mean radius of points on a disk (2R/3)\n BaselineApprox(iSuperPoseIdx) = 2 * 3/2 * mean(CurAbsDist); \nend\n\n%---Initialize the superpose estimates---\nEstCamPosesV = [MeanTransVals, MeanRotVals];\n\n%---Estimate full intrinsic matrix---\nST_IJ_SlopeApprox = mean(BaselineApprox) ./ (LFSize(2:-1:1)-1);\nUV_KL_SlopeApprox = 1./FocInit';\n\nEstCamIntrinsicsH = eye(5);\nEstCamIntrinsicsH(1,1) = ST_IJ_SlopeApprox(1);\nEstCamIntrinsicsH(2,2) = ST_IJ_SlopeApprox(2);\nEstCamIntrinsicsH(3,3) = UV_KL_SlopeApprox(1);\nEstCamIntrinsicsH(4,4) = UV_KL_SlopeApprox(2);\n\n% Force central ray as s,t,u,v = 0, note all indices start at 1, not 0\nEstCamIntrinsicsH = LFRecenterIntrinsics( EstCamIntrinsicsH, LFSize );\n\nfprintf('\\nInitializing estimate of camera intrinsics to: \\n');\ndisp(EstCamIntrinsicsH);\n\n%---Start with no distortion estimate---\nEstCamDistortionV = [];\n\n%---Optionally save the results---\nif( CalOptions.SaveResult )\n TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');\n GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);\n\n CheckerSaveFname = fullfile(BasePath, CalOptions.CheckerInfoFname);\n fprintf('\\nSaving to %s...\\n', CheckerSaveFname);\n save(CheckerSaveFname, 'GeneratedByInfo', 'CalOptions', 'CheckerObs', 'IdealChecker', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');\n \n fprintf('Saving to %s...\\n', CalInfoSaveFname);\n LFWriteMetadata(CalInfoSaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions));\nend\n\nfprintf(' ---Calibration initialization done---\\n');\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/SupportFunctions/LFCalInit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.19256214400738306}} {"text": "function brs = ssr_brs_point_source(X,phi,xs,irs,conf)\n%SSR_BRS_POINT_SOURCE binaural room scanning (BRS) set for use with the\n%SoundScape Renderer\n%\n% Usage: brs = ssr_brs_point_source(X,phi,xs,irs,conf)\n%\n% Input parameters:\n% X - listener position / m\n% phi - azimuthal head orientation / rad\n% xs - source position / m\n% irs - impulse response data set for the second sources\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% brs - conf.N x 2*nangles matrix containing all impulse responses (2\n% channels) for every angle of the BRS set\n%\n% SSR_BRS_POINT_SOURCE(X,phi,xs,irs,conf) prepares a BRS set for a reference\n% source (single point source) for the given listener position. One way to use\n% this BRS set is using the SoundScapeRenderer (SSR), see\n% http://spatialaudio.net/ssr/\n%\n% See also: ir_generic, ir_point_source, get_ir\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 5;\nnargmax = 5;\nnarginchk(nargmin,nargmax);\nisargposition(X);\nisargxs(xs);\nisargscalar(phi);\nisargstruct(conf);\n\n\n%% ===== Computation =====================================================\nbrs = ssr_brs(X,phi,[xs 0 -1 0 1],1,irs,conf);\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_ssr/ssr_brs_point_source.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.1925621425226095}} {"text": "function [rVectB, vVectB] = getPositOfBodyWRTSun(time, bodyInfo, celBodyData) \n try\n if(bodyInfo.propTypeEnum == BodyPropagationTypeEnum.TwoBody || (numel(time) == 1 && time == bodyInfo.epoch))\n chain = bodyInfo.getOrbitElemsChain();\n [rVectB, vVectB] = getPositOfBodyWRTSun_alg_fast_mex(time, chain{:});\n elseif(bodyInfo.propTypeEnum == BodyPropagationTypeEnum.Numerical)\n parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n\n [rVect, vVect] = getStateAtTime(bodyInfo, time, []);\n cartElem = CartesianElementSet(time, rVect, vVect, parentBodyInfo.getBodyCenteredInertialFrame(), true);\n cartElem = convertToFrame(cartElem, celBodyData.getTopLevelBody().getBodyCenteredInertialFrame());\n\n rVectB = [cartElem.rVect];\n vVectB = [cartElem.vVect];\n\n else\n error('Unknown celestial body prop sim type.');\n end\n catch ME %#ok %if bad then use old way\n numTimes = length(time);\n loop = true;\n rVectB = zeros(3,numTimes);\n vVectB = zeros(3,numTimes);\n while(loop)\n try\n parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n catch \n parentBodyInfo = getParentBodyInfo(bodyInfo, celBodyData);\n end\n\n if(isempty(parentBodyInfo))\n break;\n end\n\n try\n parentGM = bodyInfo.getParentGmuFromCache();\n catch\n parentGM = getParentGM(bodyInfo,celBodyData);\n end\n\n [rVect, vVect] = getStateAtTime(bodyInfo, time, parentGM); %getParentGM(bodyInfo, celBodyData)\n rVectB = rVectB + rVect;\n vVectB = vVectB + vVect;\n\n bodyInfo = parentBodyInfo;\n end\n end\n \n% if(numel(time) > 1 && numel(time) == numel(bodyInfo))\n% [uniBodies,~,ic] = unique(bodyInfo,'stable');\n% \n% rVectB = NaN(3, numel(time));\n% vVectB = rVectB;\n% for(i=1:length(uniBodies))\n% subBodyInfo = uniBodies(i);\n% bool = i == ic;\n% subTimes = time(bool);\n% \n% [rVectB(:,bool), vVectB(:,bool)] = getPositOfBodyWRTSun(subTimes, subBodyInfo, celBodyData);\n% end\n% else\n% try %try new way\n% if(bodyInfo.propTypeEnum == BodyPropagationTypeEnum.TwoBody || (numel(time) == 1 && time == bodyInfo.epoch))\n% % if(numel(time) == 1 && numel(bodyInfo.lastComputedTime) > 0 && bodyInfo.lastComputedTime == time)\n% % rVectB = bodyInfo.lastComputedRVect;\n% % vVectB = bodyInfo.lastComputedVVect;\n% % else\n% % chain = bodyInfo.getOrbitElemsChain();\n% % [rVectB, vVectB] = getPositOfBodyWRTSun_alg(time, chain{:});\n% % \n% % if(numel(time) == 1)\n% % bodyInfo.lastComputedTime = time;\n% % bodyInfo.lastComputedRVect = rVectB;\n% % bodyInfo.lastComputedVVect = vVectB;\n% % end\n% % end\n% \n% if(numel(time) == 1)\n% bool = time == bodyInfo.lastComputedTime;\n% \n% if(any(bool))\n% rVectVVectB = bodyInfo.lastComputedRVectVVect(:,bool);\n% rVectB = rVectVVectB(1:3,1);\n% vVectB = rVectVVectB(4:6,1);\n% \n% else\n% chain = bodyInfo.getOrbitElemsChain();\n% try\n% [rVectB, vVectB] = getPositOfBodyWRTSun_alg_fast_mex(time, chain{:});\n% catch ME %#ok\n% [rVectB, vVectB] = getPositOfBodyWRTSun_alg(time, chain{:});\n% end\n% \n% bodyInfo.lastComputedTime = horzcat(bodyInfo.lastComputedTime, time);\n% bodyInfo.lastComputedRVectVVect = horzcat(bodyInfo.lastComputedRVectVVect, [rVectB;vVectB]);\n% \n% [bodyInfo.lastComputedTime,ia,~] = unique(bodyInfo.lastComputedTime,'stable');\n% bodyInfo.lastComputedRVectVVect = bodyInfo.lastComputedRVectVVect(:, ia);\n% end\n% else\n% chain = bodyInfo.getOrbitElemsChain();\n% try\n% [rVectB, vVectB] = getPositOfBodyWRTSun_alg_fast_mex(time, chain{:});\n% catch ME %#ok\n% [rVectB, vVectB] = getPositOfBodyWRTSun_alg(time, chain{:});\n% end\n% \n% bodyInfo.lastComputedTime = horzcat(bodyInfo.lastComputedTime, time);\n% bodyInfo.lastComputedRVectVVect = horzcat(bodyInfo.lastComputedRVectVVect, [rVectB;vVectB]);\n% \n% [bodyInfo.lastComputedTime,ia,~] = unique(bodyInfo.lastComputedTime,'stable');\n% bodyInfo.lastComputedRVectVVect = bodyInfo.lastComputedRVectVVect(:, ia);\n% end\n% \n% elseif(bodyInfo.propTypeEnum == BodyPropagationTypeEnum.Numerical)\n% parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n% \n% [rVect, vVect] = getStateAtTime(bodyInfo, time, []);\n% cartElem = CartesianElementSet(time, rVect, vVect, parentBodyInfo.getBodyCenteredInertialFrame(), true);\n% cartElem = convertToFrame(cartElem, celBodyData.getTopLevelBody().getBodyCenteredInertialFrame());\n% \n% rVectB = [cartElem.rVect];\n% vVectB = [cartElem.vVect];\n% \n% else\n% error('Unknown celestial body prop sim type.');\n% end\n% catch ME %if bad then use old way\n% numTimes = length(time);\n% loop = true;\n% rVectB = zeros(3,numTimes);\n% vVectB = zeros(3,numTimes);\n% while(loop)\n% try\n% parentBodyInfo = bodyInfo.getParBodyInfo(celBodyData);\n% catch \n% parentBodyInfo = getParentBodyInfo(bodyInfo, celBodyData);\n% end\n% \n% if(isempty(parentBodyInfo))\n% break;\n% end\n% \n% try\n% parentGM = bodyInfo.getParentGmuFromCache();\n% catch\n% parentGM = getParentGM(bodyInfo,celBodyData);\n% end\n% \n% [rVect, vVect] = getStateAtTime(bodyInfo, time, parentGM); %getParentGM(bodyInfo, celBodyData)\n% rVectB = rVectB + rVect;\n% vVectB = vVectB + vVect;\n% \n% bodyInfo = parentBodyInfo;\n% end\n% end\n% end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/astrodynamics/getPositOfBodyWRTSun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.19255321015764554}} {"text": "function overlay_background(src_folder, dst_folder, bkgFilelist, bkgFolder, clutteredBkgRatio, single_thread)\n\nif nargin < 6\n single_thread = 0;\nend\nif single_thread\n num_workers = 0;\nelse\n num_workers = 24;\nend\n\nimage_files = rdir(fullfile(src_folder,'*/*.png'));\nimage_num = length(image_files);\nfprintf('%d images in total.\\n', image_num);\nif image_num == 0\n return;\nend\nsunImageList = importdata(bkgFilelist);\nrng('shuffle');\n\nfprintf('Start overlaying images at time %s, it takes for a while...\\n', datestr(now, 'HH:MM:SS'));\nreport_num = 80;\nfprintf([repmat('.',1,report_num) '\\n\\n']);\nreport_step = floor((image_num+report_num-1)/report_num);\nt_begin = clock;\n%for i = 1:image_num\nparfor(i = 1:image_num, num_workers)\n src_image_file = image_files(i).name;\n try\n [I, ~, alpha] = imread(src_image_file); \n catch\n fprintf('Failed to read %s\\n', src_image_file);\n end\n \n s = size(I);\n fh = s(1); fw = s(2);\n mask = double(alpha) / 255;\n mask = repmat(mask,1,1,3);\n \n if rand() > clutteredBkgRatio\n I = uint8(double(I) .* mask + double(rand()*255) * (1 - mask));\n else\n while true\n id = randi(length(sunImageList));\n bg = imread(fullfile(bkgFolder, sunImageList{id}));\n s = size(bg);\n bh = s(1); bw = s(2);\n if bh < fh || bw < fw\n %fprintf(1, '.');\n continue;\n end\n if length(s) < 3\n continue;\n end\n break;\n end\n by = randi(bh - fh + 1);\n bx = randi(bw - fw + 1);\n bgcrop = bg(by:(by+fh-1), bx:(bx+fw-1), :);\n\n I = uint8(double(I) .* mask + double(bgcrop) .* (1 - mask));\n end\n\n if numel(I) == 0\n fprintf('Failed to overlay %s (empty image after crop)\\n', src_image_file);\n else\n dst_image_file = strrep(src_image_file, src_folder, dst_folder);\n dst_image_file = strrep(dst_image_file, '.png', '.jpg');\n [dst_image_file_folder, ~, ~] = fileparts(dst_image_file);\n if ~exist(dst_image_file_folder, 'dir')\n mkdir(dst_image_file_folder);\n end\n %imwrite(I, dst_image_file, 'png', 'Alpha', alpha);\n imwrite(I, dst_image_file, 'jpg');\n end\n \n if mod(i, report_step) == 0\n fprintf('\\b|\\n');\n end\nend\nt_end = clock;\nfprintf('%f seconds spent on background overlay!\\n', etime(t_end, t_begin));\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/render_pipeline/overlay_background.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.19248093569357408}} {"text": "function rcnn_make_window_file(imdb, out_dir, mode)\n% rcnn_make_window_file(imdb, out_dir)\n% Makes a window file that can be used by the caffe WindowDataLayer \n% for finetuning.\n%\n% The window file format contains repeated blocks of:\n%\n% # image_index \n% img_path\n% channels \n% height \n% width\n% num_windows\n% class_index overlap x1 y1 x2 y2\n% <... num_windows-1 more windows follow ...>\n\n% AUTORIGHTS\n% ---------------------------------------------------------\n% Copyright (c) 2014, Ross Girshick\n% \n% This file is part of the R-CNN code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% ---------------------------------------------------------\nif nargin<3\n mode = 'cnn';\nend\n\nroidb = imdb.roidb_func(imdb);\n\nwindow_file = sprintf('%s/window_file_%s.txt', ...\n out_dir, imdb.name);\nfid = fopen(window_file, 'wt');\n\nchannels = 3; % three channel images\n\nfor i = 1:length(imdb.image_ids)\n tic_toc_print('make window file: %d/%d\\n', i, length(imdb.image_ids));\n img_path = imdb.image_at(i);\n \n roi = roidb.rois(i);\n \n switch mode\n case 'cnn'\n % do nothing\n case 'ctx'\n roi.boxes = roi.ctx;\n otherwise\n disp('Unspecified mode!');\n keyboard;\n end\n\n num_boxes = size(roi.boxes, 1);\n fprintf(fid, '# %d\\n', i-1);\n fprintf(fid, '%s\\n', img_path);\n fprintf(fid, '%d\\n%d\\n%d\\n', ...\n channels, ...\n imdb.sizes(i, 1), ...\n imdb.sizes(i, 2));\n fprintf(fid, '%d\\n', num_boxes);\n for j = 1:num_boxes\n [ov, label] = max(roi.overlap(j,:));\n % zero overlap => label = 0 (background)\n if ov < 1e-5\n label = 0;\n ov = 0;\n end\n bbox = roi.boxes(j,:)-1;\n fprintf(fid, '%d %.3f %d %d %d %d\\n', ...\n label, ov, bbox(1), bbox(2), bbox(3), bbox(4));\n end\nend\n\nfclose(fid);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/segDeepM-master/finetuning/rcnn_make_window_file.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19229519139412718}} {"text": "function [ncst,Area,k]=mu_coast(optn,varargin)\n% MU_COAST Add a coastline to a given map.\n% MU_COAST draw a coastline as either filled patches (slow) or\n% lines (fast) on a given projection. It uses a coastline database with\n% a resolution of about 1/4 degree. \n%\n% It is not meant to be called directly by the user, instead it contains\n% code common to various functions in the m_map directory.\n%\n% Calling sequence is MU_COAST(option,arguments) where\n%\n% Option string \n% c,l,i,h,f : Accesses various GSHHS databases. Next argument is\n% GSHHS filename.\n%\n% u[ser] : Accesses user-specified coastline file (a mat-file of\n% data saved from a previous MU_COAST call). Next argument\n% is filename\n%\n% v[ector] : Uses input vector of data. Next argument is the \n% data in the form of a nx2 matrix of [longitude latitude].\n% Patches must have first and last points the same. In a vector,\n% different patches can be separated by NaN.\n%\n% d[efault] : Accesses default coastline.\n%\n% The arguments given above are then followed by (optional) arguments \n% specifying lines or patches, in the form:\n%\n% optional arguments: , or\n% 'line',.\n% 'patch',.\n% 'speckle',width,density,.\n%\n% If no or one output arguments are specified then the coastline is drawn, with\n% patch handles returned. \n% If 3 output arguments are specified in the calling sequence, then no drawing\n% is done. This can be used to save subsampled coastlines for future use\n% with the 'u' option, for fast drawing of multiple instances of a particular\n% coastal region.\n%\n%\n% \n% See also M_PROJ, M_GRID \n\n% Rich Pawlowicz (rich@ocgy.ubc.ca) 2/Apr/1997\n%\n% Notes: 15/June/98 - fixed some obscure problems that occured sometimes\n% when using conic projections with large extents that\n% crossed the 180-deg longitude line.\n% 31/Aug/98 - added \"f\" gshhs support (Thanks to RAMO)\n% 17/June/99 - 'line' option as per manual (thanks to Brian Farrelly)\n% 3/Aug/01 - kludge fix for lines to South Pole in Antarctica (response\n% to Matt King).\n% 30/May/02 - fix to get gshhs to work in Antarctica.\n% 15/Dec/05 - speckle additions\n% 21/Mar/06 - handling of gshhs v1.3 (developed from suggestions by\n% Martin Borgh)\n% 26/Nov/07 - changed 'finite' to 'isfinite' after warnings\n% 26/Sep/14 - added hierarchy flag to borders and rivers\n% 13/Nov/14 - suggested matlab2014b graphics fix\n% 8/Mar/17 - conic wrap-around not quite working right in a weird case when\n% 'rectbox' was on.\n% Nov/17 - redid a lot of the gshhs-related stuff\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% its mine, so you can't sell it.\n\n\nglobal MAP_PROJECTION MAP_VAR_LIST\n\n% Have to have initialized a map first\n\nif isempty(MAP_PROJECTION)\n disp('No Map Projection initialized - call M_PROJ first!');\n return;\nend\n\n\n% m_coasts.mat contains 3 variables:\n% ncst: a Nx2 matrix of [LONG LAT] line segments, each of which form\n% a closed contour (i.e. first and last points are the SAME), \n% separated by NaN\n% k=[find(isnan(ncst(:,1)))];\n% Area: a vector giving the areas of the different patches. Both ncst\n% and Area should be ordered with biggest regions first. Area can\n% be computed as follows:\n%\n% Area=zeros(length(k)-1,1);\n% for i=1:length(k)-1,\n% x=ncst([k(i)+1:(k(i+1)-1) k(i)+1],1);\n% y=ncst([k(i)+1:(k(i+1)-1) k(i)+1],2);\n% nl=length(x);\n% Area(i)=sum( diff(x).*(y(1:nl-1)+y(2:nl))/2 );\n% end;\n%\n% Area should be >0 for land, and <0 for lakes and inland seas.\n\nswitch optn(1)\n case {'c','l','i','h','f'}\n [ncst,k,Area]=get_coasts(optn,varargin{1});\n varargin(1)=[];\n case 'u' \n eval(['load ' varargin{1} ' -mat']);\n varargin(1)=[];\n case 'v'\n ncst=[NaN NaN;varargin{1};NaN NaN];\n varargin(1)=[];\n k=[find(isnan(ncst(:,1)))]; % Get k\n Area=ones(size(k)); % Make dummy Area vector (all positive).\n otherwise\n currloc=mfilename('fullpath'); % Octave has problems finding the file \n load([currloc(1:end-8) 'm_coasts.mat']);\n \nend\n\n \n% If all we wanted was to extract a sub-coastline, return.\nif nargout==3\n return;\nend\n\n% Handle wrap-arounds (not needed for azimuthal and oblique projections)\n\nswitch MAP_PROJECTION.routine\n case {'mp_cyl','mp_conic','mp_tmerc'}\n if MAP_VAR_LIST.longs(2)<-180\n ncst(:,1)=ncst(:,1)-360;\n elseif MAP_VAR_LIST.longs(1)>180\n ncst(:,1)=ncst(:,1)+360;\n elseif MAP_VAR_LIST.longs(1)<-180\n Area=[Area;Area];\n k=[k;k(2:end)+k(end)-1];\n ncst=[ncst;[ncst(2:end,1)-360 ncst(2:end,2)]];\n % This is kinda kludgey - but sometimes adding all these extra points\n % causes wrap-around in the conic projection, so we want to limit the\n % longitudes to the range needed. However, we don't just clip them to\n % min long because that can cause problems in trying to decide which way\n % curves are oriented when doing the fill algorithm below. So instead\n % I sort of crunch the scale, preserving topology.\n %\n % 12/Sep/2006 - in the gsshs_crude database we have a lot of long skinny\n % things which interact badly with this - so I offset the scrunch 2 degrees\n % away from the bdy\n %\n % Mar/2017 - OK, so somebody used a rectbox 'on' which gave a really wide range of\n % lat/long, and it turns out I need to scale the *other* side as well!\n nn=ncst(:,1)>MAP_VAR_LIST.longs(2)+2; % added 2017\n ncst(nn,1)=(ncst(nn,1)-MAP_VAR_LIST.longs(2)-2)/100+MAP_VAR_LIST.longs(2)+2; % \"\n nn=ncst(:,1)180\n Area=[Area;Area];\n k=[k;k(2:end)+k(end)-1];\n ncst=[ncst;[ncst(2:end,1)+360 ncst(2:end,2)]];\n % Ditto.\n nn=ncst(:,1)>MAP_VAR_LIST.longs(2)+2;\n ncst(nn,1)=(ncst(nn,1)-MAP_VAR_LIST.longs(2)-2)/100+MAP_VAR_LIST.longs(2)+2;\n nn=ncst(:,1)xl(2),Y);\n [Y,X]=mu_util('clip','on',Y,yl(1),Yyl(2),X);\n oncearound=4;\n case 'circle'\n rl=MAP_VAR_LIST.rhomax;\n [X,Y]=m_ll2xy(ncst(:,1),ncst(:,2),'clip','on');\n oncearound=2*pi; \n end\n\n if ~MAP_PROJECTION.newgraphics \n p_hand=zeros(length(k)-1,1); % Patch handles\n else\n p_hand=gobjects(length(k)-1,1); % Patch handles\n end\n \n \n for i=1:length(k)-1\n x=X(k(i)+1:k(i+1)-1);\n fk=isfinite(x);\n if any(fk)\n y=Y(k(i)+1:k(i+1)-1);XX=x;YY=y;\n%% if i>921, disp('pause 1'); pause; end; \n nx=length(x);\n if Area(i)<0, x=flipud(x);y=flipud(y); fk=flipud(fk); end\n%clf\n%line(x,y,'color','m');\n st=find(diff(fk)==1)+1;\n ed=find(diff(fk)==-1);\n%length(x),\n%ed,\n%st\n if length(st)0\n p_hand(i)=m_hatch(xx,yy,'speckle',varargin{2:end});\n if ishandle(p_hand(i)),set(p_hand(i),'tag',[get(p_hand(i),'tag') '_lake']); end\n else \n\t p_hand(i)=m_hatch(xx,yy,'outspeckle',varargin{2:end});\n if ishandle(p_hand(i)),set(p_hand(i),'tag',[ get(p_hand(i),'tag') '_land']); end\n end\n end \n%%%if i>921, disp(['paused-2 ' int2str(i)]);pause; end;\n ed(1)=[];st(1)=[];edge2(1)=[];edge1(1)=[];\n else\n xx=[xx;x(st(mi):ed(mi))];\n yy=[yy;y(st(mi):ed(mi))];\n ed(1)=ed(mi);st(mi)=[];ed(mi)=[];\n edge2(1)=edge2(mi);edge2(mi)=[];edge1(mi)=[];\n end\n%%if i>921, disp(['paused-2 ' int2str(i)]);pause; end;\n end\n end \n end\n \n otherwise\n \n % This handles the odd points required at the south pole by any Antarctic\n % coastline by setting them to NaN (for lines only)\n ii=ncst(:,2)<=-89.9;\n if any(ii), ncst(ii,:)=NaN; end\n \n [X,Y]=m_ll2xy(ncst(:,1),ncst(:,2),'clip','on');\n \n % Get rid of 2-point lines (these are probably clipped lines spanning the window)\n fk=isfinite(X); \n st=find(diff(fk)==1)+1;\n ed=find(diff(fk)==-1);\n k=find((ed-st)==1);\n X(st(k))=NaN;\n\n p_hand=line(X,Y,varargin{:}); \n \nend\n\nncst=p_hand;\n\nend\n%-----------------------------------------------------------------------\nfunction edg=c_edge(x,y)\n% C_EDGE tests if a point is on the edge or not. If it is, it is\n% assigned a value representing it's position oon the perimeter\n% in the clockwise direction. For x/y or lat/long boxes, these\n% values are\n% 0 -> 1 on left edge\n% 1 -> 2 on top\n% 2 -> 3 on right edge\n% 3 -> 4 on bottom\n% For circular boxes, these values are the -ve of the angle\n% from center.\n\nglobal MAP_VAR_LIST\n\nswitch MAP_VAR_LIST.rectbox\n case 'on'\n xl=MAP_VAR_LIST.xlims;\n yl=MAP_VAR_LIST.ylims;\n case 'off'\n xl=MAP_VAR_LIST.longs;\n yl=MAP_VAR_LIST.lats;\n case 'circle'\n rl2=MAP_VAR_LIST.rhomax^2;\nend\n\nedg=9999+zeros(length(x),1);\ntol=1e-10;\n\nswitch MAP_VAR_LIST.rectbox\n case {'on','off'}\n i=abs(x-xl(1))=2\n flaglim=str2num(optn(2));\nend\n \n\nfid=fopen(file,'r','ieee-be');\n\nif fid==-1\n warning(['Coastline file ' file ...\n ' not found \\n(Have you installed it? See the M_Map User''s Guide for details)' ...\n '\\n ---Using default coastline instead']);\n load m_coasts\n return\nend\n\n \nArea2=Area;\n\n% Read the File header\n\n[cnt,g]=get_gheader(fid);\n\n\nl=0;\nwhile cnt>0\n \n C=fread(fid,g.N*2,'int32'); % Read all points in the current segment.\n \n % For versions > 12 there are 2 Antarctics - ice-line and grounding line,\n % also they changed the limits from 0-360 to -180 to 180.\n if g.ver>14 \n switch g.level\n case 6 \n g.level=flaglim+1; % ice line - don't show\n case 5 \n g.level=1; % grounding line - use this.\n end\n else\n %For Antarctica the lime limits are 0 to 360 (exactly), thus c==0 and the\n %line is not chosen for (e.g. a conic projection of part of Antarctica)\n % Fix 30may/02 \n if g.extentE==360e6, g.extentE=g.extentE-1; end \n end \n \n a=rlim>llim; % Map limits cross longitude jump? (a==1 is no)\n b=g.greenwich<65536; % Cross boundary? (b==1 if no).\n c=llimrem(g.extentW+360e6,360e6);\n e=tlim>g.extentS & blim180;(dx>356) - (dx<-356)]);\n\n % Antarctic is a special case - extend contour to make nice closed polygon\n % that doesn't surround the pole. \n if g.ver<15\n % Range from 0-360\n if abs(x(1))<1 && abs(y(1)+68.9)<1\n y=[-89.9;-78.4;y(x<=-180);y(x>-180); -78.4;-89.9*ones(18,1)];\n x=[ 180; 180 ;x(x<=-180)+360;x(x>-180);-180; [-180:20:160]'];\n end\n else\n % new version is from -180 to 180\n if abs(x(1))==180 && y(1)<-76\n y=[-89.9;-78.4;y; -78.4;-89.9*ones(19,1)];\n x=[ 180; 180 ;x; -180; [-180:20:180]'];\n end\n end \n \n \n %plot(x,y);pause;\n \n % First and last point should be the same IF THIS IS A POLYGON\n % if the Area=0 then this is a line, and don't add points!\n \n if g.area>0\n \n if x(end)~=x(1) || y(end)~=y(1) % First and last points should be the same\n x=[x;x(1)];y=[y;y(1)]; \n end\n \n % get correct curve orientation for patch-fill algorithm.\n \n Area2(l)=sum( diff(x).*(y(1:(end-1))+y(2:end))/2 ); % Area \"on the page\"\n Area(l)=g.area/10; % Area \"on the globe\"\n\n if rem(g.level,2)==0 % Make lakes (2) and islands (1) differently oriented\n Area(l)=-abs(Area(l)); \n if Area2(l)>0, x=x(end:-1:1);y=y(end:-1:1); end\n else\n if Area2(l)<0, x=x(end:-1:1);y=y(end:-1:1); end \n end\n \n else\n % Later on 2 point lines are clipped so we want to avoid that\n if length(x)==2\n x=[x(1);mean(x);x(2)];\n y=[y(1);mean(y);y(2)];\n end \n end\n \n % Here we try to reduce the number of points and clip them\n % close to map limits (if they are too far away this can cause\n % problems with some projections as they wrap around into the\n % wrong place)\n \n [cx,cy]=clip_to_lims(x,y,m,decfac);\n\n k(l+1)=k(l)+length(cx)+1;\n ncst(k(l)+1:k(l+1),:)=[cx,cy;NaN NaN];\n \n % This is a little tricky...the filling algorithm expects data to be in the\n % range -180 to 180 deg long. However, there are some land parts that cut across\n % this divide so they appear at +190 but not -170. This causes problems later...\n % so as a kludge I replicate some of the problematic features at 190-360=-170.\n % I cut out the problematic points only, make sure the first and last\n % points are the same, and then add this curve to ncst\n if max(x)>180\n ii=find(x>179);ii=[ii;ii(1)];\n [cx,cy]=clip_to_lims(x(ii)-360,y(ii),m,decfac);\n l=l+1;\n k(l+1)=k(l)+length(cx)+1;\n ncst(k(l)+1:k(l+1),:)=[cx,cy;NaN NaN];\n end\n \n %plot(ncst(:,1),ncst(:,2));drawnow; \n end\n [cnt,g]=get_gheader(fid);\nend\n\nfclose(fid);\n\n%plot(ncst(:,1),ncst(:,2));pause;clf;\n\nncst((k(l+1)+1):end,:)=[]; % get rid of unused part of data matrices\nArea((l+1):end)=[];\nk((l+2):end)=[];\n%%%fprintf('Size ncst: %d, Area: %d, k %d\\n',length(ncst),length(Area),length(k))\n \n\nend\n\nfunction [x,y]=clip_to_lims(x,y,m,decfac)\n% Look for points outside the lat/long boundaries, and then decimate them\n % by a factor of about 'decfac' (don't get rid of them completely because that\n % can sometimes cause problems when polygon edges cross curved map edges).\n \n tol=.2; \n \n % Do y limits, then x so we can keep corner points.\n \n nn=(y>m.tlim+tol) | (y0)+([diff(nn);0]<0)));\n nn([1 end])=0;\n % decimate vigorously\n nn=nn & rem(1:length(nn),decfac)'~=0;\n x(nn)=[];y(nn)=[];\n \n if m.rlim>m.llim % no wraparound\n % sections of line outside lat/long limits\n nn=(x>m.rlim+tol | xm.blim;\n else % wraparound case\n nn=(x>m.rlim+tol & xm.blim;\n end\n nn=logical(nn-min(1,([0;diff(nn)]>0)+([diff(nn);0]<0)));nn([1 end])=0;\n nn=nn & rem(1:length(nn),decfac)'~=0;\n x(nn)=[];y(nn)=[];\n \n % Move all points \"near\" to map boundaries.\n % I'm not sure about the wisdom of this - it might be better to clip\n % to the boundaries instead of moving. Hmmm. \n \n y(y>m.tlim+tol)=m.tlim+tol;\n y(ym.llim % Only clip long bdys if I can tell I'm on the right\n % or left (i.e. not in wraparound case)\n x(x>m.rlim+tol)=m.rlim+tol;\n x(x> 8) & 255: Values: Should be 7 for GSHHS release 7 (i.e., version 2.0)\n% 12 for version 2.2\n% 15 for 2.3.6\n%\t * 3rd byte:\tgreenwich = (flag >> 16) & 1: Values: Greenwich is 1 if Greenwich is crossed\n%\t * 4th byte:\tsource = (flag >> 24) & 1: Values: 0 = CIA WDBII, 1 = WVS\n%\t * 4th byte:\triver = (flag >> 25) & 1: Values: 0 = not set, 1 = river-lake and level = 2\n%\t */\n%\tint west, east, south, north;\t/* min/max extent in micro-degrees */\n%\tint area;\t/* Area of polygon in 1/10 km^2 */\n%\tint area_full;\t/* Area of original full-resolution polygon in 1/10 km^2 */\n%\tint container;\t/* Id of container polygon that encloses this polygon (-1 if none) */\n%\tint ancestor;\t/* Id of ancestor polygon in the full resolution set that was the source of this polygon (-1 if none) \n\n\n% Now, in the calling code I have to use A(2),A(3),A(5-7), A(8), A(9) from original.\n\n[A,cnt]=fread(fid,8,'int32');\n\nif cnt<8 % This gets triggered by the EOF\n g=[];\n return;\nend\n \ng.ver=bitand(bitshift(A(3),-8),255);\n\nif g.ver==0 % then its an old version, fake it to look new\n\n % This works for version 1.2, but not 1.3.\n\n [A2,cnt2]=fread(fid,1,'int32');\n A=[A;A2];\n\n if (cnt+cnt2)==9 && A(9)==3 % we have version 1.3, this would be one of 0,1,65535,65536 in v 1.2\n % Read one more byte\n A2=fread(fid,1,'int32');\n % This is the easiest way not to break existing code.\n A(9)=A2; % one of 0,1,65536,65537\n end\n \nelseif g.ver>=7 % After v2.0 some more bytes around for original area and container/ancerstor IDs\n \n A2=fread(fid,3,'int32');\n\nend\n\n% a newest versions\ng.id=A(1);\ng.N=A(2);\ng.level=bitand(A(3),255);\ng.greenwich=bitand(bitshift(A(3),-16),255)*65536;\ng.source=bitand(bitshift(A(3),-24),255);\nA(3)=g.level;\nA(9)=g.greenwich;\n\ng.extentW=A(4);\ng.extentE=A(5);\ng.extentS=A(6);\ng.extentN=A(7);\ng.area=A(8);\n \n \n \nend\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/thirdParty/m_map/private/mu_coast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19229518405136004}} {"text": "%%\n% calculates the loglikelihood scores for random simulations\n%%\n\nglobal no1 bo1 inb1 inb2\n\n\ncompflag = 'on';\ntmp_newt2 = newt2;\n\n\n%%\n% get the name of the p value grid file and load it\n%%\n\nprompt = {'Enter the name of the random simulation file',...\n 'Enter the name of the real data file (p value estimation)',...\n 'Enter the forecast start time (days from mainshock)',...\n 'Enter the forecast end time (days from mainshock)'...\n 'Enter the number of random simulations'};\ntitle = 'Filename Input';\nlines = 1;\ndef = {'','','10','15','100'};\nanswer = inputdlg(prompt,title,lines,def);\nrand_in = answer{1,1};\nreal_in = answer{2,1};\nfore_sday = str2double(answer{3,1});\nfore_eday = str2double(answer{4,1});\nnumrand = str2double(answer{5,1});\n\nreal_in = 'test.mat';\nload(real_in);\n\n%%\n% get a b c p and k from input file (in that order) for spatially varying models\n%%\ntvg(:,1) = bpvg(:,16);\ntvg(:,2) = bpvg(:,18);\ntvg(:,3) = bpvg(:,14);\ntvg(:,4) = bpvg(:,11);\ntvg(:,5) = bpvg(:,3);\ntvg(:,6) = bpvg(:,4);\n\nrand_in = '100rand.mat';\nload(rand_in)\nnodes = tmpgri;\n\n%bpvg = rpvg;\n\n%if(bpvg(1,15) == 1)\n% % this grid was not calculated with constant area so stop.\n% disp('%%%%ERROR%%%% This input grid was NOT calculated with constant radius please use one that is.')\n% return\n%end\n\n%%\n% cut cat to only forecast time period\n%%\nfore_start = maepi(:,3) + fore_sday/365;\nfore_end = maepi(:,3) + fore_eday/365;\nll = tmp_newt2.Date >= fore_start & tmp_newt2.Date <= fore_end;\nfore_cat = tmp_newt2(ll,:);\n\ndt = .1\ncalc_mag = [];\ncalc_cummag = [];\n\n%%\n% call distofault to get the distance from each grid node to the estimated fault\n% gx and gy come from the input file\n%%\n\nfaultdist\n\nlt1 = fdkm < 1;\nfdkm(lt1) = 1;\n\n\ndisp('values for sequence specific model');\npvalcat\nssa = rja;\nssb = rjb;\nssc = cv;\nssp = pv;\n\n%%\n% use the distance to taper the a value for the Generic calculation\n% and the sequence specific calculation\n%%\n\n%totd = sum(1./(fdkm.^2));\ntotd = sum(fdkm.^2);\nda = -1.67-log(totd);\ndssa = ssa/totd;\nnumevents = length(fore_cat);\nfor i = 1:length(fdkm)\n id(i) = totd/(fdkm(i)^2);\nend\nsid = sum(id);\nsler = id/sid;\n%%\n% gevents is the number of events scaled with distance from fault\n% this is not actually observed but is only the number of total\n% obs events distributed over the entire grid with number of events\n% taper as 1/r^2\n%\n% a is scaled by subtracting the log of the ratio of number of\n% events at the node to the entire number of events from the\n% overall a value.\n%%\ngevents = sler*numevents;\nfor i = 1:length(gevents)\n tapera(i) = -1.67-log(numevents/gevents(i));\n sstapera(i) = ssa-log(numevents/gevents(i));\nend\n\n\n%plot_tapera(tapera,s1x,s1y,s2x,s2y,tmpgri,xvect,yvect)\nmagco_fixed = 1.0\nlvary_a = [];\nlvary_ab = [];\nlgca = [];\n\n%%\n% calculate the overall b-value\n%%\n[magml bo1 stanml, avml] = bmemag(newt2);\n\n%%\n% loop over all grid nodes and calculate various forecasts\n%%\n\nallcount = 0;\nitotal = length(bpvg);\nwait = waitbar(0,'Thinking...');\n[lgl dum, dum] = size(bpvg);\nfor gloop = 1:itotal\n allcount=allcount+1;\n\n %%\n % Calculate the forecast for varying a & b and varying a w/constant b\n %\n % select the events within the radius used for the parameter calc. (rd) from\n % the forecast time period, to compare the calculated number of events with\n %%\n xg = bpvg(gloop,3);\n yg = bpvg(gloop,4);\n l = sqrt(((fore_cat(:,1)-xg)*cos(pi/180*yg)*111).^2 + ((fore_cat(:,2)-yg)*111).^2) ;\n [s,is] = sort(l);\n fore_cat = fore_cat(is(:,1),:) ; % re-orders matrix to agree row-wise\n\n %%\n % get fore events w/in the original radius\n %%\n l3 = l <= bpvg(1,5);\n obs_events = fore_cat(l3,:); % obs_events is the events at the node w/in the radius of the original\n\n\n for rand_loop = 1:numrand+1\n if rand_loop == 1 % only calculate these the first time thru -- not for each rand loop\n\n\n %%\n % Calculate forecast for:\n % Sequence Specific model with a-values smoothed as 1/r^2 from fault and calculate the PDF\n %%\n\n\n mag_events = [];\n ct=1;\n for m = magco_fixed-0.1:0.1:7\n tct = 1;\n for t = fore_sday:dt:fore_eday\n mag_events_ss(tct,ct) = 10^(sstapera(gloop)+ssb*(maepi(1,6)-m))*(t+ssc).^(-ssp);\n tct = tct + 1;\n end\n ct = ct + 1;\n end\n\n\n %%\n % calculate the PDF and the log likelihood score for the ss model -- a tapered away from fault\n %%\n sum_mag = sum(mag_events_ss,1)';\n diff_mag = -diff(sum_mag,1);\n ss_pdf = poisspdf(obs_mag',diff_mag);\n\n lss(:,gloop) = log(ss_pdf);\n l = isinf(lss(:,gloop));\n lss(l,gloop) = -350;\n\n\n %%\n % get a b c p and k from input file (in that order) for spaitally varying models\n %%\n x(1) = tvg(gloop,1);\n x(2) = tvg(gloop,2);\n x(3) = tvg(gloop,3);\n x(4) = tvg(gloop,4);\n\n else %% if rand_loop ~= 1\n x(1) = rpvg(gloop, 1, rand_loop-1);\n x(2) = rpvg(gloop, 2, rand_loop-1);\n x(4) = rpvg(gloop, 3, rand_loop-1);\n x(3) = rpvg(gloop, 4, rand_loop-1);\n end\n\n %%\n % Calculate forecast for:\n % Generic CA model with a-values smoothed as 1/r^2 from fault and calculate the PDF\n %%\n\n num_nodes = length(nodes);\n gen_b = .91;\n gen_p = 1.08;\n gen_c = .05;\n\n mag_events = [];\n ct=1;\n for m = magco_fixed-0.1:0.1:7\n tct = 1;\n for t = fore_sday:dt:fore_eday\n mag_events_gca(tct,ct) = 10^(tapera(gloop)+gen_b*(maepi(1,6)-m))*(t+gen_c).^(-gen_p);\n tct = tct + 1;\n end\n ct = ct + 1;\n end\n\n %%\n % calculate the PDF and the log likelihood score for Generic model -- a tapered away from fault\n %%\n sum_mag = sum(mag_events_gca,1)';\n diff_mag = -diff(sum_mag,1);\n [obs_mag,gca_magbin] = hist(obs_events(:,6),magco_fixed-0.05:0.1:7);\n gca_pdf = poisspdf(obs_mag',diff_mag);\n\n lgca(:,gloop) = log(gca_pdf);\n l = isinf(lgca(:,gloop));\n lgca(l,gloop) = -350;\n\n %%\n % calculate the forecast for each magnitude bin for varying a and constant b\n % bo1 is the constant b value calculated above using max likelihood\n %%\n mag_events = [];\n ct=1;\n for m = magco_fixed-0.1:0.1:7\n tct = 1;\n for t = fore_sday:dt:fore_eday\n mag_events_ab(tct,ct) = 10^(x(1)+x(2)*(maepi(1,6)-m))*(t+x(3)).^(-x(4));\n mag_events_a(tct,ct) = 10^(x(1)+bo1*(maepi(1,6)-m))*(t+x(3)).^(-x(4));\n tct = tct + 1;\n end\n ct = ct + 1;\n end\n %%\n % calculate the PDF and the log likelihood score for varying a & b\n %%\n sum_mag = sum(mag_events_ab,1)';\n diff_mag = -diff(sum_mag,1);\n [obs_mag,magbin] = hist(obs_events(:,6),magco_fixed-0.05:0.1:7);\n vary_abpdf = poisspdf(obs_mag',diff_mag);\n\n lvary_ab(:,gloop,rand_loop) = log(vary_abpdf);\n l = isinf(lvary_ab(:,gloop,rand_loop));\n lvary_ab(l,gloop,rand_loop) = -350;\n\n\n %%\n % calculate the PDF and the log likelihood score for varying a & constant b\n %%\n sum_mag = sum(mag_events_a,1)';\n diff_mag = -diff(sum_mag,1);\n [obs_mag,vary_amagbin] = hist(obs_events(:,6),magco_fixed-0.05:0.1:7);\n vary_apdf = poisspdf(obs_mag',diff_mag);\n\n lvary_a(:,gloop,rand_loop) = log(vary_apdf);\n l = isinf(lvary_a(:,gloop,rand_loop));\n lvary_a(l,gloop,rand_loop) = -350;\n\n\n\n waitbar(allcount/itotal);\n end\nend\n\nclose(wait);\n\nslvary_ab=[];\nslvary_a=[];\ngdiffab=[];\ngdiffa=[];\n\n%%\n% sum the scores\n%%\nslgca = sum(lgca(:,gloop),2);\nslss = sum(lss(:,gloop),2);\n[dum numm, dum] = size(lvary_ab);\nfor rloop2 = 1:numrand+1\n %%\n % sum the scores at each node\n %%\n slgca(rloop2,1:numm) = sum(lgca(:,:,rloop2),1);\n slvary_ab(rloop2,1:numm) = sum(lvary_ab(:,:,rloop2),1);\n slvary_a(rloop2,1:numm) = sum(lvary_a(:,:,rloop2),1);\n if rloop2 >= 2\n gdiffab(rloop2,1:length(slvary_ab(1,:))) = slvary_ab(rloop2,:) - slgca.subset(rloop2);\n gdiffa(rloop2,1:length(slvary_a(1,:))) = slvary_a(rloop2,:) - slgca.subset(rloop2);\n end\nend\n\nmeanab = mean(gdiffab,2);\nmeana = mean(gdiffa,2);\n\n[xll, yll] =size(slvary_ab);\ngcatot = sum(slgca);\nsstot = sum(slss);\nabtot = sum(slvary_ab(2:numrand+1,:));\natot = sum(slvary_a(2:numrand+1,:));\n\nrdabtot = sum(slvary_ab(1,:));\nrdatot = sum(slvary_a(1,:));\n\ntdiff = gcatot - abtot;\n\ncompflag = 'of';\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/pvals/simu_lls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.61878043374385, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.19225160125787258}} {"text": "function [nKeq, nGC, nNone] = standardGibbsFormationEnergyStats(modelT, figures)\n% Generate the stats +/- pie chart on the provinence of the metabolite standard Gibbs energies.\n%\n% USAGE:\n%\n% [nKeq, nGC, nNone] = standardGibbsFormationEnergyStats(modelT, figures)\n%\n% INPUTS:\n% modelT:\n% figures:\n%\n% OUTPUTS:\n% nKeq:\n% nGC:\n% nNone:\n%\n% .. Author: - Ronan M.T. Fleming\n\n[nMet,nRxn]=size(modelT.S);\n\nnKeq=eps;\nnGC=eps;\nnNone=eps;\n\nnoneBool=false(nMet,1);\np=1;\nnoneAbbr=[];\nfor m=1:nMet\n if strcmp(modelT.met(m).dGft0Source,'Keq')\n nKeq=nKeq+1;\n else\n if isnan(modelT.met(m).dGft0Source)\n nNone=nNone+1;\n noneBool(m,1)=1;\n abbr=modelT.mets{m};\n abbr=abbr(1:end-3);\n noneAbbr{p,1}=abbr;\n p=p+1;\n else\n nGC=nGC+1;\n end\n end\nend\n\nif figures\n figure1=figure;\n h=pie([nKeq,nGC,nNone],{{'K_{eq}',int2str(nKeq)},{'Group Contribution',int2str(nGC)},{'None',int2str(nNone)}});\n textObjs = findobj(h,'Type','text');\n set(textObjs,'FontSize',16);\n title('Provinence of reactant \\Delta_{f}G^{\\o} data','FontSize',16);\n saveas(figure1,'dfG0provinencePieChart','fig');\n\nend\n\nfprintf('%s\\n',['Number of unique reactants without dGf0: ' int2str(length(unique(noneAbbr))) ]);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/directionalityReport/standardGibbsFormationEnergyStats.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19209889176289363}} {"text": "function saveHDF5(fileName, model, params)\n %hdf5write(fileName, 'params', params)\n hdf5write(fileName, 'dec_wordvec', model.W_emb_tgt);\n hdf5write(fileName, 'dec_vocab', params.tgtVocab, 'WriteMode', 'append');\n \n if params.isBi\n hdf5write(fileName, 'enc_wordvec', model.W_emb_src, 'WriteMode', 'append');\n hdf5write(fileName, 'enc_vocab', params.tgtVocab, 'WriteMode', 'append');\n end\n \n % ip weight\n hdf5write(fileName, 'ip_weight', model.W_soft, 'WriteMode', 'append');\n \n % recurrent params\n input_col_ranges = 1:params.lstmSize;\n hidden_col_ranges = params.lstmSize+1:2*params.lstmSize;\n for dd=1:params.numLayers\n prefix_tgt = ['dec_d', num2str(dd), '_lstm:'];\n \n % input\n row_ranges = 1:params.lstmSize; \n hdf5write(fileName, [prefix_tgt 'input_gate'], [model.W_tgt{dd}(row_ranges,hidden_col_ranges) model.W_tgt{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n \n % forget\n row_ranges = params.lstmSize+1:2*params.lstmSize; \n hdf5write(fileName, [prefix_tgt 'forget_gate'], [model.W_tgt{dd}(row_ranges,hidden_col_ranges) model.W_tgt{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n \n % output\n row_ranges = 2*params.lstmSize+1:3*params.lstmSize; \n hdf5write(fileName, [prefix_tgt 'output_gate'], [model.W_tgt{dd}(row_ranges,hidden_col_ranges) model.W_tgt{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n \n % signal\n row_ranges = 3*params.lstmSize+1:4*params.lstmSize; \n hdf5write(fileName, [prefix_tgt 'input_value'], [model.W_tgt{dd}(row_ranges,hidden_col_ranges) model.W_tgt{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n \n if params.isBi\n prefix_src = ['enc_d', num2str(dd), '_lstm:'];\n \n % input\n row_ranges = 1:params.lstmSize; \n hdf5write(fileName, [prefix_src 'input_gate'], [model.W_src{dd}(row_ranges,hidden_col_ranges) model.W_src{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n\n % forget\n row_ranges = params.lstmSize+1:2*params.lstmSize; \n hdf5write(fileName, [prefix_src 'forget_gate'], [model.W_src{dd}(row_ranges,hidden_col_ranges) model.W_src{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n\n % output\n row_ranges = 2*params.lstmSize+1:3*params.lstmSize; \n hdf5write(fileName, [prefix_src 'output_gate'], [model.W_src{dd}(row_ranges,hidden_col_ranges) model.W_src{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n\n % signal\n row_ranges = 3*params.lstmSize+1:4*params.lstmSize; \n hdf5write(fileName, [prefix_src 'input_value'], [model.W_src{dd}(row_ranges,hidden_col_ranges) model.W_src{dd}(row_ranges, input_col_ranges)], 'WriteMode', 'append');\n end\n end\n \nend", "meta": {"author": "lmthang", "repo": "nmt.hybrid", "sha": "50d5c025f18ed280ff0fd2e2adce327f4170a2c3", "save_path": "github-repos/MATLAB/lmthang-nmt.hybrid", "path": "github-repos/MATLAB/lmthang-nmt.hybrid/nmt.hybrid-50d5c025f18ed280ff0fd2e2adce327f4170a2c3/code/misc/saveHDF5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1920988917628936}} {"text": "function model = model_add_parts(model, lhs, ruleind, partner, ...\n filterind, numparts, psize, ...\n scale, coef_scale)\n% Add a deformable parts to a rule.\n% model = model_add_parts(model, lhs, ruleind, partner, ...\n% filterind, numparts, psize, ...\n% scale, coef_scale)\n%\n% Return value\n% model Object model\n%\n% Arguments\n% model Object model\n% lhs Parts are added to:\n% ruleind model.rules{lhs}(ruleind)\n% partner Partner ruleind: \n% model.rules{lhs}(ruleind) and \n% model.rules{lhs}(partner) are l/r mirror images of each other\n% Or, if length(partner) == 2:\n% model.rules{lhs}(ruleind) and \n% model.rules{partner(1)}(partner(2)) are l/r mirror images\n% filterind Filter that parts are initialize from\n% numparts Number of parts to add\n% psize Size of each part\n% scale Number of octaves down from lhs to place parts \n% (only scale = 0,1 have been tested)\n% coef_scale Part filter coeficients are scaled by this value\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\n% if the filter is mirrored, find its partner so mirrored\n% parts can be added to it as well\nif ~isempty(partner)\n if length(partner) == 2\n partner_lhs = partner(1);\n partner = partner(2);\n else\n partner_lhs = lhs;\n end\nend\n\nif nargin < 9\n coef_scale = 1;\nend\n\nsource = model_get_block(model, model.filters(filterind));\npfilters = mkpartfilters(source, psize, numparts, scale);\n\nfor i = 1:numparts\n [model, symbolf] = model_add_terminal(model, 'w', coef_scale*pfilters(i).w);\n [model, N1] = model_add_nonterminal(model);\n\n % add deformation rule\n defoffset = 0;\n defparams = pfilters(i).alpha*[0.1 0 0.1 0];\n\n [model, rule] = model_add_def_rule(model, N1, symbolf, 'def_w', defparams);\n\n % add deformation symbols to rhs of rule\n anchor1 = pfilters(i).anchor;\n model.rules{lhs}(ruleind).rhs = [model.rules{lhs}(ruleind).rhs N1];\n model.rules{lhs}(ruleind).anchor = [model.rules{lhs}(ruleind).anchor anchor1];\n\n if ~isempty(partner)\n [model, symbolfp] = model_add_terminal(model, 'mirror_terminal', symbolf);\n [model, N2] = model_add_nonterminal(model);\n\n % add mirrored deformation rule\n model = model_add_def_rule(model, N2, symbolfp, 'mirror_rule', rule);\n\n x = pfilters(i).anchor(1);\n y = pfilters(i).anchor(2);\n % add deformation symbols to rhs of rule\n x2 = 2^scale*size(source, 2) - x - psize(2);\n anchor2 = [x2 y scale];\n model.rules{partner_lhs}(partner).rhs = ...\n [model.rules{partner_lhs}(partner).rhs N2];\n model.rules{partner_lhs}(partner).anchor = ...\n [model.rules{partner_lhs}(partner).anchor anchor2];\n end\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/model/model_add_parts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.19202964676190412}} {"text": "function[labelImage] = imageInsertBlobLabels(labelImage, labelMap, labelNames, varargin)\n% [labelImage] = imageInsertBlobLabels(labelImage, labelMap, labelNames, varargin)\n%\n% Uses insertText (from Vision Toolbox) to insert a cell of strings into\n% the image. Each label is positioned at the center of mass of its blob.\n%\n% Test case (should output a red 'c' on a white image):\n% labelImage = ones(256, 256, 3);\n% labelMap = zeros(256, 256);\n% labelMap(100, 100) = 3;\n% labelMap(101, 100) = 3;\n% labelNames = {'a', 'b', 'c'};\n% outImage = imageInsertBlobLabels(labelImage, labelMap, labelNames, 'fontColor', [255, 0, 0], 'minComponentSize', 1);\n% imshow(outImage);\n%\n% Copyright by Holger Caesar, 2016\n\n% Parse input\np = inputParser;\naddParameter(p, 'fontSize', 15);\naddParameter(p, 'fontWidth', 8);\naddParameter(p, 'fontColor', [26, 232, 222]);\naddParameter(p, 'minComponentSize', 100); % at least 2px\naddParameter(p, 'skipLabelInds', []); % labels that are ignored\nparse(p, varargin{:});\n\nfontSize = p.Results.fontSize;\nfontWidth = p.Results.fontWidth;\nfontColor = p.Results.fontColor;\nminComponentSize = p.Results.minComponentSize;\nskipLabelInds = p.Results.skipLabelInds;\n\n% Check inputs\nassert(~isa(labelMap, 'gpuArray'));\n\n% Get unique list of labels\nlabelList = double(unique(labelMap(:)));\nlabelList(labelList == 0) = [];\nlabelListCount = numel(labelList);\nif labelListCount == 0\n % Don't do anything if there are no labels\n return;\nend\n\n% Init\npixelIdxLists = cell(labelListCount, 1);\npixelIdxLabels = cell(labelListCount, 1);\nusedMap = false(size(labelMap));\n\n% Get the indices for all blobs\nfor labelMapUnIdx = 1 : labelListCount\n labelIdx = labelList(labelMapUnIdx);\n \n % Get connected components of that label\n components = bwconncomp(labelMap == labelIdx);\n pixelIdxList = components.PixelIdxList(:);\n sel = cellfun(@(x) numel(x), pixelIdxList) >= minComponentSize;\n pixelIdxList = pixelIdxList(sel);\n pixelIdxLabels{labelMapUnIdx} = ones(numel(pixelIdxList), 1) .* labelIdx;\n pixelIdxLists{labelMapUnIdx} = pixelIdxList;\nend\n\n% Convert cell to matrix\npixelIdxLists = flattenCellArray(pixelIdxLists);\npixelIdxLabels = cell2mat(pixelIdxLabels);\nassert(numel(pixelIdxLists) == numel(pixelIdxLabels));\ncompCount = numel(pixelIdxLists);\n\n% Sort by size\n[~, sortOrder] = sort(cellfun(@numel, pixelIdxLists), 'descend');\npixelIdxLists = pixelIdxLists(sortOrder);\npixelIdxLabels = pixelIdxLabels(sortOrder);\n\nfor compIdx = 1 : compCount\n labelIdx = pixelIdxLabels(compIdx);\n if ismember(labelIdx, skipLabelInds)\n continue;\n end\n labelName = labelNames{labelIdx};\n \n % Get list of relevant pixels\n pixInds = pixelIdxLists{compIdx};\n pixInds = setdiff(pixInds, find(usedMap(:)));\n if isempty(pixInds)\n continue;\n end\n \n % Compute center of mass\n [y, x] = ind2sub(size(labelMap), pixInds);\n yCenter = median(y);\n xCenter = median(x);\n \n height = fontSize;\n width = fontWidth * numel(labelName);\n yStart = max(1, round(yCenter - height / 2));\n xStart = max(1, round(xCenter - width / 2));\n yEnd = min(yStart + height - 1, size(usedMap, 1));\n xEnd = min(xStart + width - 1, size(usedMap, 2));\n \n if any(any(usedMap(yStart:yEnd, xStart:xEnd)))\n continue;\n end\n \n % Place label here\n labelImage = insertText(labelImage, [xStart, yStart], labelName, 'Font', 'LucidaSansDemiBold', 'FontSize', fontSize, 'TextColor', fontColor, 'BoxOpacity', 0.0, 'AnchorPoint', 'LeftTop');\n \n % Mark those pixels as used\n usedMap(yStart:yEnd, xStart:xEnd) = true;\nend;", "meta": {"author": "nightrome", "repo": "cocostuff10k", "sha": "5fe3850d547ae4b21d73307dd156dfc5c5c61c5c", "save_path": "github-repos/MATLAB/nightrome-cocostuff10k", "path": "github-repos/MATLAB/nightrome-cocostuff10k/cocostuff10k-5fe3850d547ae4b21d73307dd156dfc5c5c61c5c/dataset/code/utils/imageInsertBlobLabels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19196657947290122}} {"text": "% Change to your downloaded location\nclear\naddpath('C:\\liblinear\\matlab')\naddpath('../training_code/');\naddpath('../utilities/');\naddpath('../../data extraction/');\n\n%% load shared definitions and AU data\nall_dataset_aus = [1, 2, 4, 5, 6, 7, 9, 10, 12, 14, 15, 17, 20, 23, 25, 26, 28, 45];\n\n% Set up the hyperparameters to be validated\nhyperparams.c = 10.^(-7:0.5:1);\nhyperparams.e = 10.^(-3);\n\nhyperparams.validate_params = {'c', 'e'};\n\n% Set the training function\nsvm_train = @svm_train_linear;\n \n% Set the test function (the first output will be used for validation)\nsvm_test = @svm_test_linear;\n\nBP4D_aus = [1, 2, 4, 6, 7, 10, 12, 14, 15, 17, 23];\nSEMAINE_aus = [2, 12, 17, 25, 28, 45];\nFERA2011_aus = [1, 2, 4, 6, 7, 10, 12, 15, 17, 25, 26];\nUNBC_aus = [6, 7, 9, 12, 25, 26];\nDISFA_aus = [1, 2, 4, 5, 6, 9, 12, 15, 17, 20, 25, 26];\nBosphorus_aus = [1, 2, 4, 5, 6, 7, 9, 10, 12, 14, 15, 17, 20, 23, 25, 26, 45];\n\nfor a=1:numel(all_dataset_aus)\n \n au = all_dataset_aus(a);\n\n train_samples = [];\n valid_samples = [];\n \n train_labels = [];\n valid_labels = [];\n \n % Keeping track which validation sample came from which dataset, as we\n % will be validating based on which hyperparam leads to best\n % performance on all datasets (mean F1)\n eval_ids = []; \n dataset_ids = {};\n \n if(~isempty(find(BP4D_aus == au, 1)))\n op = cd('../BP4D/');\n rest_aus = setdiff(BP4D_aus, au); \n shared_defs;\n % load the training and testing data for the current fold\n [train_samples_bp4d, train_labels_bp4d, valid_samples_bp4d, valid_labels_bp4d, ~, PC, means, scaling] = Prepare_HOG_AU_data_generic_dynamic(train_recs, devel_recs, au, BP4D_dir, hog_data_dir);\n\n train_samples = cat(1, train_samples, train_samples_bp4d);\n valid_samples = cat(1, valid_samples, valid_samples_bp4d);\n\n train_labels = cat(1, train_labels, train_labels_bp4d);\n valid_labels = cat(1, valid_labels, valid_labels_bp4d);\n \n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_bp4d,1), 1); \n end\n \n clear 'train_samples_bp4d' 'train_labels_bp4d' 'valid_samples_bp4d' 'valid_labels_bp4d'\n \n dataset_ids = cat(1, dataset_ids, {'BP4D'});\n \n cd(op);\n \n end\n \n if(~isempty(find(FERA2011_aus == au, 1)))\n op = cd('../FERA2011/');\n rest_aus = setdiff(FERA2011_aus, au); \n shared_defs;\n all_recs = cat(2, train_recs, devel_recs);\n [users_train, users_valid_fera] = get_balanced_fold(FERA2011_dir, all_recs, au, 1/3, 1);\n \n % load the training and testing data for the current fold\n [train_samples_f2011, train_labels_f2011, valid_samples_f2011, valid_labels_f2011, ~, PC, means, scaling] = Prepare_HOG_AU_data_generic_dynamic(users_train, users_valid_fera, au, rest_aus, FERA2011_dir, features_dir);\n\n train_samples = cat(1, train_samples, train_samples_f2011);\n valid_samples = cat(1, valid_samples, valid_samples_f2011);\n\n train_labels = cat(1, train_labels, train_labels_f2011);\n valid_labels = cat(1, valid_labels, valid_labels_f2011);\n \n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_f2011,1), 1); \n else\n eval_ids = cat(1, eval_ids, (eval_ids(end)+1)*ones(size(valid_labels_f2011,1), 1)); \n end\n \n clear 'train_samples_f2011' 'train_labels_f2011' 'valid_samples_f2011' 'valid_labels_bp4d'\n \n dataset_ids = cat(1, dataset_ids, {'FERA2011'});\n \n cd(op);\n \n end \n \n if(~isempty(find(SEMAINE_aus == au, 1)))\n op = cd('../SEMAINE/');\n rest_aus = setdiff(SEMAINE_aus, au); \n shared_defs;\n % load the training and testing data for the current fold\n [train_samples_sem, train_labels_sem, valid_samples_sem, valid_labels_sem, ~, PC, means, scaling] = Prepare_HOG_AU_data_generic_dynamic(train_recs, devel_recs, au, rest_aus, SEMAINE_dir, hog_data_dir);\n\n train_samples = cat(1, train_samples, train_samples_sem);\n valid_samples = cat(1, valid_samples, valid_samples_sem);\n\n train_labels = cat(1, train_labels, train_labels_sem);\n valid_labels = cat(1, valid_labels, valid_labels_sem);\n \n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_sem,1), 1); \n else\n eval_ids = cat(1, eval_ids, (eval_ids(end)+1)*ones(size(valid_labels_sem,1), 1)); \n end\n \n clear 'train_samples_sem' 'train_labels_sem' 'valid_samples_sem' 'valid_labels_sem'\n dataset_ids = cat(1, dataset_ids, {'SEMAINE'});\n cd(op);\n\n end \n \n if(~isempty(find(Bosphorus_aus == au, 1)))\n op = cd('../Bosphorus/');\n rest_aus = setdiff(DISFA_aus, au); \n shared_defs;\n\n % make sure validation data's labels are balanced\n [users_train, users_valid_bosph] = get_balanced_fold(Bosphorus_dir, all_recs, au, 1/3, 1);\n\n % need to split the rest\n [train_samples_bosph, train_labels_bosph, valid_samples_bosph, valid_labels_bosph, ~, PC, means, scaling, valid_ids, valid_success] = Prepare_HOG_AU_data_dynamic(users_train, users_valid_bosph, au, rest_aus, Bosphorus_dir, hog_data_dir);\n\n train_labels_bosph(train_labels_bosph > 1) = 1;\n valid_labels_bosph(valid_labels_bosph > 1) = 1;\n\n % As there are only a few Bosphorus images (it being an image dataset)\n % we oversample it quite a bit \n train_samples_bosph = repmat(train_samples_bosph, 10, 1);\n train_labels_bosph = repmat(train_labels_bosph, 10, 1); \n \n train_samples = cat(1, train_samples, train_samples_bosph);\n valid_samples = cat(1, valid_samples, valid_samples_bosph);\n\n train_labels = cat(1, train_labels, train_labels_bosph);\n valid_labels = cat(1, valid_labels, valid_labels_bosph);\n\n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_bosph, 1), 1); \n else\n eval_ids = cat(1, eval_ids, (eval_ids(end)+1)*ones(size(valid_labels_bosph, 1), 1)); \n end\n\n clear 'train_samples_bosph' 'train_labels_bosph' 'valid_samples_bosph' 'valid_labels_bosph' \n dataset_ids = cat(1, dataset_ids, {'Bosphorus'});\n cd(op);\n \n end \n \n if(~isempty(find(DISFA_aus == au, 1)))\n op = cd('../DISFA/');\n rest_aus = setdiff(DISFA_aus, au); \n shared_defs;\n\n % make sure validation data's labels are balanced\n [users_train, users_valid_disfa] = get_balanced_fold(DISFA_dir, users, au, 1/3, 1);\n\n % need to split the rest\n [train_samples_disf, train_labels_disf, valid_samples_disf, valid_labels_disf, ~, PC, means, scaling, valid_ids, valid_success] = Prepare_HOG_AU_data_generic_dynamic(users_train, users_valid_disfa, au, rest_aus, DISFA_dir, hog_data_dir);\n\n train_labels_disf(train_labels_disf > 1) = 1;\n valid_labels_disf(valid_labels_disf > 1) = 1;\n\n train_samples = cat(1, train_samples, train_samples_disf);\n valid_samples = cat(1, valid_samples, valid_samples_disf);\n\n train_labels = cat(1, train_labels, train_labels_disf);\n valid_labels = cat(1, valid_labels, valid_labels_disf);\n\n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_disf,1), 1); \n else\n eval_ids = cat(1, eval_ids, (eval_ids(end)+1)*ones(size(valid_labels_disf,1), 1)); \n end\n\n clear 'train_samples_disf' 'train_labels_disf' 'valid_samples_disf' 'valid_labels_disf' \n dataset_ids = cat(1, dataset_ids, {'DISFA'});\n cd(op);\n \n end \n \n if(~isempty(find(UNBC_aus == au, 1)))\n op = cd('../UNBC/');\n rest_aus = setdiff(UNBC_aus, au); \n shared_defs;\n \n [users_train, users_valid_unbc] = get_balanced_fold(UNBC_dir, all_recs, au, 1/3, 1);\n \n % load the training and testing data for the current fold\n [train_samples_unbc, train_labels_unbc, valid_samples_unbc, valid_labels_unbc, ~, PC, means, scaling] = Prepare_HOG_AU_data_dynamic(users_train, users_valid_unbc, au, rest_aus, UNBC_dir, features_dir);\n\n % Binarizing the data\n train_labels_unbc(train_labels_unbc > 1) = 1;\n valid_labels_unbc(valid_labels_unbc > 1) = 1;\n \n train_samples = cat(1, train_samples, train_samples_unbc);\n valid_samples = cat(1, valid_samples, valid_samples_unbc);\n\n train_labels = cat(1, train_labels, train_labels_unbc);\n valid_labels = cat(1, valid_labels, valid_labels_unbc);\n \n if(isempty(eval_ids))\n eval_ids = ones(size(valid_labels_unbc,1), 1); \n else\n eval_ids = cat(1, eval_ids, (eval_ids(end)+1)*ones(size(valid_labels_unbc,1), 1)); \n end \n \n clear 'train_samples_unbc' 'train_labels_unbc' 'valid_samples_unbc' 'valid_labels_unbc' \n dataset_ids = cat(1, dataset_ids, {'UNBC'});\n cd(op);\n\n end \n \n train_samples = sparse(train_samples);\n dataset_ids\n %% Cross-validate here \n hyperparams.eval_ids = eval_ids;\n [ best_params, ~ ] = validate_grid_search_no_par(svm_train, svm_test, false, train_samples, train_labels, valid_samples, valid_labels, hyperparams);\n model = svm_train(train_labels, train_samples, best_params); \n \n model.eval_ids = eval_ids;\n \n [~, predictions_all] = svm_test(valid_labels, valid_samples, model);\n \n name = sprintf('mat_models/AU_%d_dynamic.mat', au);\n\n eval_ids_uq = unique(eval_ids)';\n F1s = [];\n for i=eval_ids_uq \n F1s = cat(2, F1s, compute_F1(valid_labels(eval_ids==i), predictions_all(eval_ids==i)));\n end\n \n meanF1 = mean(F1s);\n \n save(name, 'model', 'F1s', 'meanF1', 'predictions_all', 'valid_labels', 'eval_ids', 'dataset_ids'); \n \n % Write out the model\n name = sprintf('classifiers/AU_%d_dynamic.dat', au);\n\n pos_lbl = model.Label(1);\n neg_lbl = model.Label(2);\n \n w = model.w(1:end-1)';\n b = model.w(end);\n\n svs = bsxfun(@times, PC, 1./scaling') * w;\n \n write_lin_dyn_svm(name, means, svs, b, pos_lbl, neg_lbl);\n \n clear 'train_samples' 'train_labels' 'valid_samples' 'valid_labels' \nend\n\n\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/AU_training/experiments/full_model_training/train_dynamic_classifiers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19196657202003395}} {"text": "function info = cnn_imagenet_evaluate(varargin)\n% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet\n\nrun(fullfile(fileparts(mfilename('fullpath')), ...\n '..', '..', 'matlab', 'vl_setupnn.m')) ;\n\nopts.dataDir = fullfile('data', 'ILSVRC2012') ;\nopts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;\nopts.imdbPath = fullfile(opts.expDir, 'imdb.mat');\nopts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;\nopts.networkType = [] ;\nopts.lite = false ;\nopts.numFetchThreads = 12 ;\nopts.train.batchSize = 128 ;\nopts.train.numEpochs = 1 ;\nopts.train.gpus = [] ;\nopts.train.prefetch = true ;\nopts.train.expDir = opts.expDir ;\n\nopts = vl_argparse(opts, varargin) ;\ndisplay(opts);\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\n\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;\n mkdir(opts.expDir) ;\n save(opts.imdbPath, '-struct', 'imdb') ;\nend\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n\nnet = load(opts.modelPath) ;\nif isfield(net, 'net') ;\n net = net.net ;\nend\n% Cannot use isa('dagnn.DagNN') because it is not an object yet\nisDag = isfield(net, 'params') ;\n\nif isDag\n opts.networkType = 'dagnn' ;\n net = dagnn.DagNN.loadobj(net) ;\n trainfn = @cnn_train_dag ;\n\n % Drop existing loss layers\n drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;\n for n = {net.layers(drop).name}\n net.removeLayer(n) ;\n end\n\n % Extract raw predictions from softmax\n sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;\n predVar = 'prediction' ;\n for n = {net.layers(sftmx).name}\n % check if output\n l = net.getLayerIndex(n) ;\n v = net.getVarIndex(net.layers(l).outputs{1}) ;\n if net.vars(v).fanout == 0\n % remove this layer and update prediction variable\n predVar = net.layers(l).inputs{1} ;\n net.removeLayer(n) ;\n end\n end\n\n % Add custom objective and loss layers on top of raw predictions\n net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...\n {predVar,'label'}, 'objective') ;\n net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...\n {predVar,'label'}, 'top1err') ;\n net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...\n 'opts', {'topK',5}), ...\n {predVar,'label'}, 'top5err') ;\n\n % Make sure that the input is called 'input'\n v = net.getVarIndex('data') ;\n if ~isnan(v)\n net.renameVar('data', 'input') ;\n end\n\n % Swtich to test mode\n net.mode = 'test' ;\nelse\n opts.networkType = 'simplenn' ;\n net = vl_simplenn_tidy(net) ;\n trainfn = @cnn_train ;\n net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss\nend\n\n% Synchronize label indexes used in IMDB with the ones used in NET\nimdb = cnn_imagenet_sync_labels(imdb, net);\n\n% Run evaluation\n[net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...\n opts.train, ...\n 'train', NaN, ...\n 'val', find(imdb.images.set==2)) ;\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchFn(opts, meta)\n% -------------------------------------------------------------------------\nuseGpu = numel(opts.train.gpus) > 0 ;\nbopts = meta.normalization ;\nbopts.numThreads = opts.numFetchThreads ;\n\n% Most networks are trained by resizing images to 256 pixels and then\n% cropping a slightly smaller subarea. Reproduce this effect (center\n% crop) for a more accurate evaluation (it also avoids resizing the\n% images if these have been pre-processed to be of this size, which\n% accelerates everything).\n\nbopts.border = 256 - meta.normalization.imageSize ;\n\nswitch lower(opts.networkType)\n case 'simplenn'\n fn = @(x,y) getSimpleNNBatch(bopts,x,y) ;\n case 'dagnn'\n fn = @(x,y) getDagNNBatch(bopts,useGpu,x,y) ;\nend\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getSimpleNNBatch(opts, imdb, batch)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nlabels = imdb.images.label(batch) ;\n\n% -------------------------------------------------------------------------\nfunction inputs = getDagNNBatch(opts, useGpu, imdb, batch)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nim = cnn_imagenet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nif nargout > 0\n if useGpu\n im = gpuArray(im) ;\n end\n inputs = {'input', im, 'label', imdb.images.label(batch)} ;\nend\n", "meta": {"author": "willard-yuan", "repo": "cnn-for-image-retrieval", "sha": "2e3e8ab76e2c971314be55b5ae44e02884003261", "save_path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-cnn-for-image-retrieval/cnn-for-image-retrieval-2e3e8ab76e2c971314be55b5ae44e02884003261/matconvnet-1.0-beta18/examples/imagenet/cnn_imagenet_evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.19194673019564581}} {"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 varargout = process_mne_maxwell( varargin )\n% PROCESS_MNE_MAXWELL: MNE-Python call to mne.preprocessing.maxwell_filter: Maxwell filtering / SSS /tSSS\n%\n% USAGE: sProcess = process_mne_maxwell('GetDescription')\n% sInput = process_mne_maxwell('Run', sProcess, sInput, method=[])\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2020\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok\n % Description the process\n sProcess.Comment = 'MNE-Python: maxwell_filter (SSS/tSSS)';\n sProcess.FileTag = 'sss';\n sProcess.Category = 'File';\n sProcess.SubGroup = 'Pre-process';\n sProcess.Index = 85;\n % Definition of the input accepted by this process\n sProcess.InputTypes = {'raw'};\n sProcess.OutputTypes = {'raw'};\n sProcess.nInputs = 1;\n sProcess.nMinFiles = 1;\n sProcess.processDim = []; % Do not split matrix\n sProcess.Description = 'https://www.nmr.mgh.harvard.edu/mne/stable/generated/mne.preprocessing.maxwell_filter.html';\n % Definition of the options\n % Help\n sProcess.options.help.Comment = 'mne.preprocessing.maxwell_filter
For information about the parameters, click on \"Online tutorial\"

';\n sProcess.options.help.Type = 'label';\n % int_order: Order of internal component of spherical expansion\n sProcess.options.int_order.Comment = 'int_order (default=8): ';\n sProcess.options.int_order.Type = 'value';\n sProcess.options.int_order.Value = {8,'',0};\n % ext_order: Order of external component of spherical expansion\n sProcess.options.ext_order.Comment = 'ext_order (default=3): ';\n sProcess.options.ext_order.Type = 'value';\n sProcess.options.ext_order.Value = {3,'',0};\n % origin: Origin of internal and external multipolar moment space in meters\n sProcess.options.origin.Comment = 'origin (auto or 3D point): ';\n sProcess.options.origin.Type = 'text';\n sProcess.options.origin.Value = 'auto';\n % coord_frame: Origin of internal and external multipolar moment space in meters\n sProcess.options.coord_frame.Comment = {'head', 'meg', 'coord_frame (default=head): '; ...\n 'head', 'meg', ''};\n sProcess.options.coord_frame.Type = 'radio_linelabel';\n sProcess.options.coord_frame.Value = 'head';\n % destination: The destination location for the head.\n sProcess.options.destination.Comment = 'destination (empty or 3D-point):';\n sProcess.options.destination.Type = 'value';\n sProcess.options.destination.Value = {[], 'list', 3};\n % regularize\n sProcess.options.regularize.Comment = 'regularize (default=on)';\n sProcess.options.regularize.Type = 'checkbox';\n sProcess.options.regularize.Value = 1;\n % ignore_ref\n sProcess.options.ignore_ref.Comment = 'ignore_ref (default=off)';\n sProcess.options.ignore_ref.Type = 'checkbox';\n sProcess.options.ignore_ref.Value = 0;\n % st_duration: tSSS\n sProcess.options.st_duration.Comment = 'st_duration (0=disable tSSS, default=10): ';\n sProcess.options.st_duration.Type = 'value';\n sProcess.options.st_duration.Value = {0,'s',3};\n % st_correlation\n sProcess.options.st_correlation.Comment = 'st_correlation (default=0.98): ';\n sProcess.options.st_correlation.Type = 'value';\n sProcess.options.st_correlation.Value = {0.98,'',2};\n % st_fixed\n sProcess.options.st_fixed.Comment = 'st_fixed (default=on)';\n sProcess.options.st_fixed.Type = 'checkbox';\n sProcess.options.st_fixed.Value = 1;\n % st_only\n sProcess.options.st_only.Comment = 'st_only (default=off)';\n sProcess.options.st_only.Type = 'checkbox';\n sProcess.options.st_only.Value = 0;\n % mag_scale\n sProcess.options.mag_scale.Comment = 'mag_scale (default=100): ';\n sProcess.options.mag_scale.Type = 'value';\n sProcess.options.mag_scale.Value = {100,'',4};\n % skip_by_annotation\n sProcess.options.skip_by_annotation.Comment = 'skip_by_annotation: ';\n sProcess.options.skip_by_annotation.Type = 'text';\n sProcess.options.skip_by_annotation.Value = 'edge, bad_acq_skip';\n % fine_calibration_file (site specific)\n sProcess.options.calibration.Comment = 'fine-calibration file:';\n sProcess.options.calibration.Type = 'filename';\n sProcess.options.calibration.Value = {...\n '', ... % Filename\n '', ... % FileFormat\n 'open', ... % Dialog type: {open,save}\n 'Import fine-calibration file...', ... % Window title\n 'ImportData', ... % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}\n 'single', ... % Selection mode: {single,multiple}\n 'files', ... % Selection mode: {files,dirs,files_and_dirs}\n {'.dat', 'fine-calibration file (*.dat)', 'calibration'}, ... % Specify file type\n 'DataIn'}; % DefaultFormats: {ChannelIn,DataIn,DipolesIn,EventsIn,MriIn,NoiseCovIn,ResultsIn,SspIn,SurfaceIn,TimefreqIn\n % cross_talk_file (site specific) \n sProcess.options.ctc.Comment = 'cross-talk file:';\n sProcess.options.ctc.Type = 'filename';\n sProcess.options.ctc.Value = {...\n '', ... % Filename\n '', ... % FileFormat\n 'open', ... % Dialog type: {open,save}\n 'Import cross-talk file...', ... % Window title\n 'ImportData', ... % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}\n 'single', ... % Selection mode: {single,multiple}\n 'files', ... % Selection mode: {files,dirs,files_and_dirs}\n {'.fif', 'cross-talk file (*.fif)', 'ctc'}, ... % Specify file type\n 'DataIn'}; % DefaultFormats: {ChannelIn,DataIn,DipolesIn,EventsIn,MriIn,NoiseCovIn,ResultsIn,SspIn,SurfaceIn,TimefreqIn \nend\n\n\n%% ===== RUN =====\nfunction OutputFile = Run(sProcess, sInput) %#ok\n OutputFile = process_mne_maxwell_py('Run', sProcess, sInput);\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_mne_maxwell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1918805277022199}} {"text": "function [ bx, ndim ] = cvx_sparsify( bx, tt, mode )\n\nglobal cvx___\nox = isa( bx, 'cvx' );\nif ox,\n sx = size( bx );\n bx = cvx_basis( bx );\nend\nif isempty( tt ),\n by = bx;\nelseif ~any( tt ),\n return\nelse\n by = bx( :, tt );\nend\nif isempty( mode ),\n by = bx;\nelse\n [ xR, by ] = cvx_bcompress( by, mode, 0 );\nend\nnx = size( by, 2 );\nndim = cvx_newvar( nx, cvx_classify_mex( by, cvx___.classes ) );\nbz = sparse( ndim, 1 : nx, 1 );\nnz = size(bz,1);\nby( nz, end ) = 0;\ncvx_newcnstr( by - bz, true );\nif ~isempty( mode ),\n bz = bz * xR;\nend\nif isempty( tt ),\n bx = bz;\nelse\n bx( 1:nz, tt ) = bz;\nend\nif ox,\n bx = cvx( sx, bx );\nend\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/lib/cvx_sparsify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.1917567016274087}} {"text": "function STResNet_stage1(varargin)\n\nif ~isempty(gcp('nocreate'))\n delete(gcp)\nend\n\nopts.train.gpus = [ 1 ] ;\nopts = cnn_setup_environment(opts);\n\naddpath('network_surgery');\nopts.dataSet = 'ucf101'; \nopts.inputdim = [ 224, 224, 20] ;\ninitMethod = 'sumAB';\nopts.dropOutRatio = 0;\nopts.dataDir = fullfile(opts.dataPath, opts.dataSet) ;\nopts.splitDir = [opts.dataSet '_splits']; \nopts.train.fuseInto = 'spatial'; opts.train.fuseFrom = 'temporal';\nopts.train.removeFuseFrom = 0;\nopts.backpropFuseFrom = 1;\nopts.nSplit = 1 ;\nopts.addConv3D = 1 ;\nopts.addPool3D = 0 ; \nopts.doSum = 1 ;\nopts.doScale = 0 ;\nopts.doBiDirectional = 0 ;\nopts.nFrames = 5 ;\nopts.singleSoftMax = 0;\n\nopts.train.learningRate = 1*[ 1e-3*ones(1,3) 1e-4*ones(1,3) 1e-5*ones(1,3) 1e-6*ones(1,3)] ;\nopts.train.augmentation = 'multiScaleRegular';\nopts.train.augmentation = 'f25noCtr';\nopts.train.epochFactor = 10 ;\nopts.train.batchSize = 128 ;\nopts.train.numSubBatches = 32 ;\nopts.train.cheapResize = 0 ;\nopts.train.fusionLayer = {'res2a_relu', 'res2a'; 'res3a_relu', 'res3a'; 'res4a_relu', 'res4a'; ...\n 'res5a_relu', 'res5a'; };\n\n\nmodel = ['ST-ResNet50-split=' num2str(opts.nSplit)];\nopts.train.numSubBatches = ceil(opts.train.numSubBatches / max(numel(opts.train.gpus),1));\nopts.train.memoryMapFile = fullfile(tempdir, 'ramdisk', ['matconvnet' num2str(opts.nSplit ) '.bin']) ;\n\nopts.modelA = fullfile(opts.modelPath, [opts.dataSet '-img-resnet50-split' num2str(opts.nSplit) '-dr0.mat']) ;\nopts.modelB = fullfile(opts.modelPath, [opts.dataSet '-resnet50-split' num2str(opts.nSplit) '-dr0.8.mat']) ;\n\nopts.expDir = fullfile(opts.dataDir, [opts.dataSet '-' model]) ;\n\nopts.train.startEpoch = 1 ;\nopts.train.epochStep = 1 ;\nopts.train.numEpochs = 8 ;\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\n\nopts.imdbPath = fullfile(opts.dataDir, [opts.dataSet '_split' num2str(opts.nSplit) 'imdb.mat']);\n\nopts.train.saveAllPredScores = 1;\nopts.train.denseEval = 1;\nopts.train.plotDiagnostics = 0 ;\nopts.train.continue = 1 ;\nopts.train.prefetch = 1 ;\nopts.train.expDir = opts.expDir ;\nopts.train.numAugments = 1;\nopts.train.frameSample = 'random';\nopts.train.nFramesPerVid = 1;\n\nopts = vl_argparse(opts, varargin) ;\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\n imdb.flowDir = opts.flowDir;\nelse\n imdb = cnn_setup_data(opts) ;\n save(opts.imdbPath, '-struct', 'imdb', '-v6') ;\nend\nnClasses = length(imdb.classes.name);\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\nfor model = {opts.modelA opts.modelB}\n model = model{:};\n if ~exist(model,'file')\n [~, baseModel] = fileparts(model);\n fprintf('Downloading base model file: %s ...\\n', baseModel);\n mkdir(fileparts(model)) ;\n urlwrite(...\n ['http://ftp.tugraz.at/pub/feichtenhofer/st-res/ts-base/' baseModel '.mat'], ...\n model) ;\n end\nend\nnetA = load(opts.modelA) ;\nnetB = load(opts.modelB) ;\nif isfield(netA, 'net'), netA=netA.net;end\nif isfield(netB, 'net'), netB=netB.net;end\n\nif ~isfield(netA, 'meta')\n netA = update_legacy_net(netA);\n netA = dagnn.DagNN.fromSimpleNN(netA) ;\n netA = netA.saveobj() ;\nend\nif ~isfield(netB, 'meta'), netB = dagnn.DagNN.fromSimpleNN(netB) ; netB = netB.saveobj() ; end;\n\nif ~isfield(opts.train, 'fusionLayer');\n sum_layersA = find(strcmp({netA.layers(:).type},'dagnn.Sum')) + 1 ; % +1 for relu\n sum_layersB = find(strcmp({netB.layers(:).type},'dagnn.Sum')) + 1 ;\n opts.train.fusionLayer = {netA.layers(sum_layersA).name; netB.layers(sum_layersB).name};\n opts.train.fusionLayer = reshape({opts.train.fusionLayer{:}},2,[])';\nend\n\nf = find(strcmp({netA.layers(:).type}, 'dagnn.Loss'));\nnetA.layers(f(1)-1).name = 'prediction';\nf = find(strcmp({netB.layers(:).type}, 'dagnn.Loss'));\nnetB.layers(f(1)-1).name = 'prediction';\n\nfusionLayerA = []; fusionLayerB = [];\nif ~isempty(opts.train.fusionLayer)\n for i=1:numel(netA.layers)\n if isfield(netA.layers(i),'name') && any(strcmp(netA.layers(i).name,opts.train.fusionLayer(:,1)))\n fusionLayerA = [fusionLayerA i]; \n end \n end\n for i=1:numel(netB.layers)\n if isfield(netB.layers(i),'name') && any(strcmp(netB.layers(i).name,opts.train.fusionLayer(:,2)))\n fusionLayerB = [fusionLayerB i]; \n end \n end\nend\n\nnetNormalization = netB.meta.normalization;\nnetA.meta.normalization.averageImage = mean(mean(netA.meta.normalization.averageImage, 1), 2);\nnetB.meta.normalization.averageImage = mean(mean(netB.meta.normalization.averageImage, 1), 2);\n\n\n\nnetB.meta.normalization.averageImage = gather(cat(3,netB.meta.normalization.averageImage, netA.meta.normalization.averageImage));\n\n% rename layers, params and vars\nfor x=1:numel(netA.layers)\n if isfield(netA.layers(x), 'name'), netA.layers(x).name = [netA.layers(x).name '_spatial'] ; end\nend\nfor x=1:numel(netB.layers)\n if isfield(netB.layers(x), 'name'), netB.layers(x).name = [netB.layers(x).name '_temporal']; end\nend\n \nnetA = dagnn.DagNN.loadobj(netA);\nfor i = 1:numel(netA.vars), if~strcmp(netA.vars(i).name,'label'), netA.renameVar(netA.vars(i).name, [netA.vars(i).name '_spatial']); end; end; \nfor i = 1:numel(netA.params), netA.renameParam(netA.params(i).name, [netA.params(i).name '_spatial']); end; \n\nnetB = dagnn.DagNN.loadobj(netB);\nfor i = 1:numel(netB.vars), if~strcmp(netB.vars(i).name,'label'), netB.renameVar(netB.vars(i).name, [netB.vars(i).name '_temporal']); end;end; \nfor i = 1:numel(netB.params), netB.renameParam(netB.params(i).name, [netB.params(i).name '_temporal']); end; \nif opts.addConv3D & any(~cellfun(@isempty,(strfind(opts.train.fusionLayer, 'prediction'))))\n if strcmp(opts.train.fuseInto,'temporal')\n [ netB ] = insert_conv_layers( netB, fusionLayerB(end), 'initMethod', initMethod, 'batchNormalization', bnormFusion, 'dropOutRatio', 0 );\n else\n [ netA ] = insert_conv_layers( netA, fusionLayerA(end), 'initMethod', initMethod, 'batchNormalization', bnormFusion, 'dropOutRatio', 0 );\n end\nend\nif ~opts.addConv3D && ~opts.doSum\n if strcmp(opts.train.fuseInto,'temporal')\n [ netB ] = insert_conv_layers( netB, fusionLayerB, 'initMethod', initMethod, 'batchNormalization', bnormFusion, 'dropOutRatio', 0 );\n else\n [ netA ] = insert_conv_layers( netA, fusionLayerA, 'initMethod', initMethod, 'batchNormalization', bnormFusion, 'dropOutRatio', 0 );\n end\nend\n\nif opts.train.removeFuseFrom, \n switch opts.train.fuseFrom\n case 'spatial'\n netA.layers = netA.layers(1:fusionLayerA(end)); netA.rebuild;\n case'temporal'\n netB.layers = netB.layers(1:fusionLayerB(end)); netB.rebuild;\n end\nend\n\nnetA = netA.saveobj() ;\nnetB = netB.saveobj() ;\n\nnet.layers = [netA.layers netB.layers] ;\nnet.params = [netA.params netB.params] ; \nnet.meta = netB.meta;\nnet = dagnn.DagNN.loadobj(net);\n\nnet = dagnn.DagNN.setLrWd(net, 'convFiltersLRWD', [1 1], 'convBiasesLRWD', [2 0], ...\n 'fusionFiltersLRWD', [1 1], 'fusionBiasesLRWD', [2 0], ...\n 'filtersLRWD' , [1 1], 'biasesLRWD' , [2 0] ) ;\n\nclear netA netB;\nif opts.doBiDirectional, nFuse = 2; else nFuse=1; end;\nfor s=1:nFuse\n if s==2\n [opts.train.fuseInto, opts.train.fuseFrom] = deal(opts.train.fuseFrom, opts.train.fuseInto);\n end\n for i = 1:size(opts.train.fusionLayer,1)\n if strcmp(opts.train.fuseInto,'spatial')\n i_fusion = find(~cellfun('isempty', strfind({net.layers.name}, ...\n [opts.train.fusionLayer{i,1} '_' opts.train.fuseInto])));\n else\n i_fusion = find(~cellfun('isempty', strfind({net.layers.name}, ...\n [opts.train.fusionLayer{i,2} '_' opts.train.fuseInto])));\n end\n\n if opts.doSum \n inputVars = net.layers(strcmp({net.layers.name},[opts.train.fusionLayer{i,1}, ...\n '_' opts.train.fuseFrom])).outputs;\n\n if opts.doScale\n name = [net.layers(i_fusion(end)).name '_scale'];\n\n block = dagnn.Scale() ;\n for j = i_fusion(end):-1:1\n p_from = net.layers(j).params; \n if numel(p_from) == 1 || numel(p_from) == 2, break; end;\n end\n\n block.size = [1 1 size(net.params(net.getParamIndex(p_from{1})).value,4)];\n\n pars = {[name '_f'], [name '_b']} ;\n net.addLayerAt(i_fusion(end), name, ...\n block, ...\n inputVars, ...\n name, ...\n pars) ;\n params = block.initParams(0.1);\n [net.params(net.getParamIndex(pars)).value] = deal(params{:}) ;\n\n\n inputVars = {name};\n i_fusion(end) = i_fusion(end)+1;\n end\n\n name = [net.layers(i_fusion(end)).name '_sum'];\n \n block = dagnn.Sum() ;\n\n inputVars = [inputVars{:} net.layers(strcmp({net.layers.name},[opts.train.fusionLayer{i,2}, ...\n '_' opts.train.fuseInto])).outputs];\n net.addLayerAt(i_fusion(end), name, block, ...\n inputVars, ...\n name) ; \n % next line is for disabling ReLUshortcut \n net.layers(cellfun(@(x) any(isequal(x,net.getVarIndex(inputVars(end)))), {net.layers.inputIndexes} )).block.useShortCircuit = 0;\n\n else\n name = [net.layers(i_fusion(end)).name '_concat'];\n block = dagnn.Concat() ;\n net.addLayerAt(i_fusion(end), name, block, ...\n [net.layers(strcmp({net.layers.name},[opts.train.fusionLayer{i,1} '_spatial'])).outputs ...\n net.layers(strcmp({net.layers.name},[opts.train.fusionLayer{i,2} '_temporal'])).outputs], ...\n name) ; \n end\n \n net.layers(i_fusion(end)+2).inputs{1} = name;\n\n end\nend\n\nnet.addVar('input_flow')\nnet.vars(net.getVarIndex('input_flow')).fanout = net.vars(net.getVarIndex('input_flow')).fanout + 1 ;\n\n% set input for conv layers\ni_conv1= find(~cellfun('isempty', strfind({net.layers.name},'temporal')));\nnet.layers(i_conv1(1)).inputs = {'input_flow'};\n\nnet.renameVar(net.vars(1).name, 'input');\n\n\nif opts.addConv3D\n conv_layers = find(arrayfun(@(x) isa(x.block,'dagnn.Conv') && isequal(x.block.size(1),1) ... \n && (~isempty(strfind(x.name,'b_branch2a')) || ~isempty(strfind(x.name,'b_branch2c'))) && isequal(x.block.stride(1),1), net.layers ))\n\n for l=conv_layers\n disp(['converting ' net.layers(l).name ' to ConvTime'])\n block = dagnn.ConvTime() ; block.net = net ;\n\n kernel = net.params(net.getParamIndex(net.layers(l).params{1})).value;\n sz = size(kernel); \n kernel = cat(2, kernel/3, kernel/3, kernel/3 );\n\n \n net.params(net.getParamIndex(net.layers(l).params{1})).value = kernel;\n pads = size(kernel); pads = ceil(pads(1:2) / 2) - 1;\n \n block.pad = [pads(1),pads(1), pads(2),pads(2)] ; \n block.size = size(kernel);\n block.hasBias = net.layers(l).block.hasBias;\n\n block.stride(1) = net.layers(l).block.stride(1)*net.layers(l).block.stride(2);\n net.layers(l).block = block; \n end\nend\nif opts.addPool3D\n\n poolLayers = {'pool5'; };\n\n\n for j=1:numel(poolLayers)\n for s = {'spatial', 'temporal'}\n i_pool = find(strcmp({net.layers.name},[poolLayers{j} '_' char(s)])); \n block = dagnn.PoolTime() ;\n block.poolSize = [1 opts.nFrames ]; \n block.pad = [0 0 0 0]; \n block.stride = [1 1]; \n block.method = 'avg'; \n nPool = 1 ;\n if opts.addPool3D == 2\n block.method = 'max'; \n end\n\n name = {};\n outputVars = {};\n inputVars = net.layers(i_pool).outputs;\n for k=1:nPool\n name{end+1} = [poolLayers{j} '_pool_' char(s) num2str(k)];\n disp(['injecting ' name{end} ' as PoolTime'])\n net.addLayerAt(i_pool, name{end}, block, ...\n [inputVars], {name{end}}) ; \n end\n \n % chain input of l that has layer as input\n for l = 1:numel(net.layers) \n if ~strcmp(net.layers(l).name, name)\n sel = find(strcmp(net.layers(l).inputs, net.layers(i_pool).outputs{1})) ;\n if any(sel)\n net.layers(l).inputs{sel} = inputVars;\n end \n end\n end\n\n end\n end\nend % add pool3d\n\nnet = dagnn.DagNN.insertLossLayers(net, 'numClasses', nClasses) ;\n\n\nopts.train.augmentation = 'f25noCtr';\nopts.train.frameSample = 'temporalStrideRandom';\nopts.train.nFramesPerVid = opts.nFrames * 1;\nopts.train.temporalStride = 5:15; \n\nopts.train.valmode = 'temporalStrideRandom';\nopts.train.numValFrames = 25 ;\nopts.train.saveAllPredScores = 1 ;\nopts.train.denseEval = 1;\nopts.train.opts.nFramestack = opts.nFrames;\n\n \n \nnet.meta.normalization.rgbVariance = [];\nopts.train.train = find(ismember(imdb.images.set, [1])) ;\nopts.train.train = repmat(opts.train.train,1,opts.train.epochFactor);\n\n% opts.train.train = NaN; % for testing only\nopts.train.denseEval = 1;\n\n%%\nzero_drs = find(arrayfun(@(x) isa(x.block,'dagnn.DropOut') && x.block.rate == 0, net.layers)) ;\nnet.removeLayer({net.layers(zero_drs).name}, true);\n\nif ~isnan(opts.dropOutRatio)\n dr_layers = find(arrayfun(@(x) isa(x.block,'dagnn.DropOut'), net.layers)) ;\n if opts.dropOutRatio > 0\n net.layers(dr_layers).block.rate = opts.dropOutRatio;\n else\n net.removeLayer({net.layers(dr_layers).name}, true);\n end\nend\n\nif opts.singleSoftMax\n pred_layers = [];\n for l=1:numel(net.layers)\n if isempty( net.layers(l).params ), continue; end;\n if size(net.params(net.getParamIndex(net.layers(l).params{1})).value,4) == nClasses || ...\n size(net.params(net.getParamIndex(net.layers(l).params{1})).value,5) == nClasses % 3D FC layer\n pred_layers = [pred_layers l];\n net.vars(net.layers(l).outputIndexes).precious = 1;\n end\n end\n pred_layers = fliplr(pred_layers) ; % remove the spatial layer\n paramsIdx1 = net.getParamIndex(net.layers(pred_layers(1)).params);\n paramsIdx2 = net.getParamIndex(net.layers(pred_layers(2)).params);\n for p = 1:numel(paramsIdx1)\n sz = size(net.params(paramsIdx1(p)).value);\n if numel(sz) > 2\n net.params(paramsIdx1(p)).value = cat(3,net.params(paramsIdx1(p)).value, net.params(paramsIdx2(p)).value);\n else\n net.params(paramsIdx1(p)).value = net.params(paramsIdx1(p)).value + net.params(paramsIdx2(p)).value;\n end\n end\n block = dagnn.Concat() ;\n newName = ['opts.singleSoftMaxConcat']; \n net.addLayer(newName, block, ...\n [net.layers(pred_layers).inputs], ...\n newName) ; \n net.layers(pred_layers(1)).inputs = newName ; \n % remove layers of the second prediction path\n for l = numel(net.layers):-1:1\n for f = net.layers(pred_layers(2)).outputs\n sel = find(strcmp(f, net.layers(l).inputs )) ;\n if ~isempty(sel)\n fprintf('removing ayer %s \\n', net.layers(l).name);\n net.removeLayer({net.layers(l).name});\n end\n end\n end\n net.removeLayer({net.layers(pred_layers(2)).name});\nend\n\nnet.layers(~cellfun('isempty', strfind({net.layers(:).name}, 'err'))) = [] ;\nnet.rebuild() ;\nopts.train.derOutputs = {} ;\nfor l=1:numel(net.layers)\n if isa(net.layers(l).block, 'dagnn.Loss') && isempty(strfind(net.layers(l).block.loss, 'err'))\n if opts.backpropFuseFrom || ~isempty(strfind(net.layers(l).name, opts.train.fuseInto ))\n fprintf('setting derivative for layer %s \\n', net.layers(l).name);\n opts.train.derOutputs = [opts.train.derOutputs, net.layers(l).outputs, {1}] ;\n end\n net.addLayer(['err1_' net.layers(l).name(end-7:end) ], dagnn.Loss('loss', 'classerror'), ...\n net.layers(l).inputs, 'error') ; \n end\nend\n\nnet.conserveMemory = 1 ;\nfn = getBatchWrapper_rgbflow(net.meta.normalization, opts.numFetchThreads, opts.train) ;\n[info] = cnn_train_dag(net, imdb, fn, opts.train) ;\n", "meta": {"author": "feichtenhofer", "repo": "st-resnet", "sha": "8b4f28431b5abe881c3b5192c309ac7a303b5c9d", "save_path": "github-repos/MATLAB/feichtenhofer-st-resnet", "path": "github-repos/MATLAB/feichtenhofer-st-resnet/st-resnet-8b4f28431b5abe881c3b5192c309ac7a303b5c9d/STResNet_stage1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.19171909626481737}} {"text": "function [varargout] = minDose(planC, varargin)\n%Calculate a minDose metric.\n%Stand alone metric : minDose(planC, structNum, doseNum, 'Percent' or 'Absolute');\n%Request m object : minDose(planC, 'getnewmetric');\n%Evaluate m object : minDose(planC, m, 'evaluate');\n%LM: 4 Jan 06, JOD: changed interface.\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\nindexS = planC{end};\noptS = planC{indexS.CERROptions};\n\nif(nargin > 1)\n call = varargin{end};\nelse\n warning('Incorrect Usage, try: minDose(planC, structNum, doseNum, ''Percent'' or ''Absolute'');');\n return;\nend\n\nswitch upper(call)\n case 'GETNEWMETRIC'\n m.name = 'minDose';\n m.valueV = [];\n m.description = 'Returns the min dose in specified structure';\n m.functionName = @minDose;\n m.note = '';\n m.params(1).name = 'Structure';\n m.params(1).type = 'DropDown';\n m.params(1).list = {planC{indexS.structures}.structureName};\n m.params(1).value = 1;\n m.params(2).name = 'IsTarget?';\n m.params(2).type = 'DropDown';\n m.params(2).list ={'Target', 'Not Target'};\n m.params(2).value = 2;\n m.units = [];\n m.range = [0 inf];\n m.doseSets = [1];\n varargout = {planC,m};\n return;\n\n case 'EVALUATE'\n m = varargin{1};\n structName = planC{indexS.structures}(m.params(1).value).structureName;\n m.note = structName;\n m.valueV = [];\n\n maxD = -inf;\n\t\tfor i=1:length(m.doseSets)\n [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, m.params(1).value, m.doseSets(i));\n ans = calc_minDose(doseBinsV, volsHistV, m.params(2).value);\n m.valueV = [m.valueV ans];\n doseArray = getDoseArray(planC{indexS.dose}(m.doseSets(i)));\n maxD = max(maxD, max(doseArray(:)));\n end\n if m.params(2).value == 1\n %Is target, high dose is best.\n m.range = [0 max(m.valueV)];\n elseif m.params(2).value == 2;\n m.range = [maxD min(m.valueV)];\n end\n m.units = getDoseUnitsStr(i,planC);\n varargout = {planC,m};\n return;\n\n otherwise %No specific call has been made, assume user just wants raw metric.\n if(nargin > 3)\n structNum = varargin{1};\n doseNum = varargin{2};\n volumeTypeString = varargin{3};\n if(strcmp(upper(volumeTypeString), 'ABSOLUTE'))\n volumeType = 2;\n else\n volumeType = 1;\n end\n [planC, doseBinsV, volsHistV] = getDVHMatrix(planC, structNum, doseNum);\n varargout = {calc_minDose(doseBinsV, volsHistV, volumeType)};\n else\n error('Not enough parameters, try: minDose(planC, structNum, doseNum, ''Percent'' or ''Absolute'');')\n return;\n end\nend\n\n ", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/minDose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19170382664914812}} {"text": "% reref() - convert common reference EEG data to some other common reference\n% or to average reference\n% Usage:\n% >> Dataout = reref(data); % convert all channels to average reference\n% >> [Dataout Chanlocs] = reref(data, refchan, 'key', 'val');\n% % convert data to new reference with options\n% Inputs:\n% data - 2-D or 3-D data matrix (chans,frames*epochs) \n% refchan - reference channel number(s). There are three possibilities:\n% 1) [] - compute average reference\n% 2) [X]: re-reference to channel X \n% 2) [X Y Z ...]: re-reference to the average of channel X Y Z ... \n% \n% Optional inputs:\n% 'exclude' - [integer array] channel indices to exclude from re-referencing\n% (e.g., event marker channels, etc.)\n% 'keepref' - ['on'|'off'] keep reference channel in output (only usable \n% when there are several references).\n% 'elocs' - Current data electrode location structure (e.g., EEG.chanlocs).\n% 'refloc' - Reference channel location single element structure or cell array\n% {'label' theta radius} containing the name and polar coordinates \n% of the current channel. Including this entry means that\n% this channel will be included (reconstructed) in the\n% output.\n%\n% Outputs:\n% Dataout - Input data converted to the new reference\n% Chanlocs - Updated channel locations structure\n%\n% Notes: 1) The average reference calculation implements two methods \n% (see www.egi.com/Technotes/AverageReference.pdf)\n% V'i = (Vi-Vref) - sum(Vi-Vref)/number_of_electrodes\n%\n% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2009-\n% previous version: Arnaud Delorme & Scott Makeig, 1999-2002\n\n% Deprecated inputs:\n% These inputs are still accepted but not processed. The function returns\n% accurate results irrespective of the entry of these options.\n% 'refstate ' - ['common'|'averef'|[indices]] Current reference condition,\n% ('averef') = average reference; ('common' or 0) = common\n% reference. [indices] designate the current reference channel \n% or channels if present in the data {default: 'common'}\n% 'method' - ['standard'|'withref'] Do not ('standard') or do ('withref') \n% include reference channel data in output {def: 'standard'}. \n% Note: Option 'withref' not possible when multiple ref channel \n% indices are given as argument to 'refstate' (below).\n%\n% ICA inputs:\n% These inputs are still accepted but not the ICA conversion is now\n% performed from within pop_reref()\n% 'icaweights' - ICA weight matrix. Note: If this is ICA weights*sphere, \n% then the 'icasphere' input below should be [] or identity.\n% 'icasphere' - ICA sphere matrix (if any)\n% 'icachansind' - Indices of the channels used in ICA decomposition\n%\n% Outputs:\n% Wout - ICA weight matrix (former icaweights*icasphere)\n% converted to new data reference\n% Sout - ICA sphere matrix converted to an identity matrix\n% ICAinds - New indices of channels used in ICA decomposition\n% meandata - (1,dataframes) means removed from each data point\n%\n% 2) In conversion of the weight matrix to a new reference\n% where WS = Wts*Sph and ica_act = WS*data, then\n% data = inv(WS)*ica_act;\n% If R*data are the re-referenced data,\n% R*data= R*inv(WS)*ica_act; \n% And Wout = inv(R*inv(WS));\n% Now, Sout = eye(length(ICAinds));\n% The re-referenced ICA component maps are now the \n% columns of inv(Wout), and the icasphere matrix, Sout, \n% is an identity matrix. Note: inv() -> pinv() when \n% PCA dimension reduction is used during ICA decomposition.\n\n% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK\n% 01-25-02 reformated help & license -ad \n\nfunction [data, Elocs, morechans, W, S, icachansind, meandata] = reref(data, ref, varargin)\n\nif nargin<1\n help reref\n return\nend\nif nargin < 2\n ref = [];\nend;\n\n% check inputs\n% ------------\ng = finputcheck(varargin, { 'icaweight' 'real' [] [];\n 'icaweights' 'real' [] [];\n 'icasphere' 'real' [] [];\n 'icachansind' 'integer' [] [];\n 'method' 'string' { 'standard' 'withref' } 'standard';\n 'refstate' { 'string' 'integer' } { { 'common' 'averef' } [1 size(data,1)] } 'common'; % ot used but kept for backward compatib.\n 'exclude' 'integer' [1 size(data,1)] [];\n 'refloc' { 'cell' 'struct' } { [] [] } {};\n 'keepref' 'string' {'on' 'off' } 'off';\n 'elocs' {'integer' 'struct'} [] [] });\nif isstr(g), error(g); end;\nif ~isempty(g.icaweight)\n g.icaweights = g.icaweight;\nend;\nif ~isempty(g.icaweights)\n if isempty(g.icachansind), \n g.icachansind = [1:size(g.icaweights,2)]; \n disp('Warning: reref() output has changed slightly since EEGLAB 5.02');\n disp(' the 4th output argument is the indices of channels used for ICA instead');\n disp(' of the mean reference value (which is now output argument 5)');\n end;\nend;\n\nif ~isempty(ref)\n if ref > size(data,1)\n error('reference channel index out of range');\n end;\nend;\n\n[dim1 dim2 dim3] = size(data);\ndata = reshape(data, dim1, dim2*dim3);\n\n% single reference not present in the data\n% add it as blank data channel at the end\n% ----------------------------------------\nif ~isempty(g.refloc) == 1\n if ~isempty(g.elocs)\n if iscell(g.refloc)\n data(end+1,:) = 0;\n g.elocs(end+1).labels = g.refloc{1};\n g.elocs(end ).theta = g.refloc{2};\n g.elocs(end ).radius = g.refloc{3};\n else\n data(end+length(g.refloc),:) = 0;\n for iLocs = 1:length(g.refloc)\n g.elocs(end+1).labels = g.refloc(iLocs).labels;\n fieldloc = fieldnames(g.refloc);\n for ind = 1:length(fieldloc)\n g.elocs(end) = setfield(g.elocs(end), fieldloc{ind}, getfield(g.refloc(iLocs), fieldloc{ind}));\n end;\n end;\n end;\n end;\n [dim1 dim2 dim3] = size(data);\nend;\n\n% exclude some channels\n% ---------------------\nchansin = setdiff([1:dim1], g.exclude);\nnchansin = length(chansin);\n\n% return mean data\n% ----------------\nif nargout > 4\n meandata = sum(data(chansin,2))/nchansin;\nend;\n\n% generate rereferencing matrix\n% -----------------------------\nif 0 % alternate code - should work exactly the same\n if isempty(ref)\n ref=chansin; % average reference\n end % if \n chansout=chansin; \n data(chansout,:)=data(chansout,:)-ones(nchansin,1)*mean(data(ref,:),1); \nelse\n if ~isempty(ref) % not average reference \n refmatrix = eye(nchansin); % begin with identity matrix\n tmpref = ref;\n for index = 1:length(g.exclude)\n tmpref(find(g.exclude(index) < tmpref)) = tmpref(find(g.exclude(index) < tmpref))-1;\n end;\n for index = 1:length(tmpref)\n refmatrix(:,tmpref(index)) = refmatrix(:,tmpref(index))-1/length(tmpref);\n end;\n else % compute average reference\n refmatrix = eye(nchansin)-ones(nchansin)*1/nchansin;\n end;\n chansout = chansin;\n data(chansout,:) = refmatrix*data(chansin,:);\nend;\n\n% change reference in elocs structure\n% -----------------------------------\nif ~isempty(g.elocs)\n if isempty(ref)\n for ind = chansin\n g.elocs(ind).ref = 'average';\n end;\n else\n reftxt = { g.elocs(ref).labels };\n if length(reftxt) == 1, reftxt = reftxt{1}; \n else\n reftxt = cellfun(@(x)([x ' ']), reftxt, 'uniformoutput', false);\n reftxt = [ reftxt{:} ];\n end;\n for ind = chansin\n g.elocs(ind).ref = reftxt;\n end;\n end;\nend;\n\n% remove reference\n% ----------------\nmorechans = [];\nif strcmpi(g.keepref, 'off')\n data(ref,:) = [];\n if ~isempty(g.elocs)\n morechans = g.elocs(ref);\n g.elocs(ref) = [];\n end;\nend;\n\ndata = reshape(data, size(data,1), dim2, dim3);\n\n% treat optional ica parameters\n% -----------------------------\nW = []; S = []; icachansind = [];\nif ~isempty(g.icaweights) \n disp('Warning: This function does not process ICA array anymore, use the pop_reref function instead');\nend;\nElocs = g.elocs;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/sigprocfunc/reref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.19154873268917746}} {"text": "function outputImage = perform_binary_operation(this, otherImage, ...\n functionHandle)\n% Performs binary operation (i.e. 2 inputs) on this and a second image\n% for given dimension and returns a new output image\n%\n% NOTE: If voxel dimensions of 2nd image do not match - or a scalar is\n% given as 2nd argument - data in the 2nd argument is automatically\n% replicated to match this image geometry.\n%\n% Y = MrDataNd()\n% outputImage = perform_binary_operation(this, otherImage, ...\n% functionHandle)\n%\n% This is a method of class MrDataNd.\n%\n% IN\n% otherImage 2nd operand for binary operation\n% functionHandle handle of function to be applied to images (e.g.\n% @plus, @minus, @times and @rdivide for the 4 \n% arithmetic operations )\n%\n% OUT\n% outputImage new MrDataNd with possibly new image dimensions,\n% output of binary operation performed on this\n% and otherImage\n% EXAMPLE\n%\n% % Compute difference of 2 images\n%\t\tY = MrDataNd();\n%\t\tZ = MrDataNd();\n%\t\tX = Y.perform_binary_operation(Z, @minus);\n%\n%\t% Scale image (multiply) by a factor of 3\n%\t\tY = MrDataNd();\n%\t\tY = Y.perform_binary_operation(3, @mult)\n%\n%\t% Compute ratio of 2 images\n%\t\tY \t\t\t= MrDataNd();\n%\t\tZ \t\t\t= MrDataNd();\n%\t\tratioYZ \t= Y.perform_binary_operation(Z, @rdivide);\n%\t\n%\n%\n% See also MrDataNd perform_unary_operation\n\n% Author: Saskia Bollmann & Lars Kasper\n% Created: 2014-11-13\n% Copyright (C) 2014 Institute for Biomedical Engineering\n% University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public Licence (GPL), version 3. \n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n% .\n%\n\n\n% binary operation with scalar etc. => make MrDataNd first\nif ~isa(otherImage, 'MrDataNd')\n otherData = otherImage;\n otherName = 'dataMatrix';\n % Create image from data matrix with similar dimInfo\n % TODO: include proper dimInfo-adaptation (right now, res is assumed\n % the same, not FOV!)\n nSamplesOther = size(otherData);\n nSamplesOther(end+1:this.dimInfo.nDims) = 1; % avoid singleton dim error!\n dimInfoOther = this.dimInfo.copyobj;\n dimInfoOther.nSamples = nSamplesOther;\n \n otherImage = this.copyobj();\n otherImage.dimInfo = dimInfoOther;\n otherImage.data = otherData;\n otherImage.name = otherName;\nend\n\n%% TODO: FOV first, then adapt matrix sizes?\n% TODO: Check FOVs first, if they don't match crop or zero-fill otherImage\n\noutputImage = otherImage.resize(this.dimInfo);\noutputImage.name = this.name;\n\n%% Perform computation and store!\noutputImage.data \t= functionHandle(this.data, outputImage.data);\n\noutputImage.info{end+1,1} = sprintf('%s( %s, %s )', func2str(functionHandle), ...\n outputImage.name, otherImage.name);", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrDataNd/perform_binary_operation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19139966681589196}} {"text": "% Copyright (C) 2018 Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos\n% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com\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\nfunction CstFR4lossy(mws)\n\n%'@ define material: FR-4 (lossy)\n\nmaterial = invoke(mws,'material');\ninvoke(material,'Reset');\ninvoke(material,'Name','FR-4 (lossy)'); \ninvoke(material,'FrqType','all');\ninvoke(material,'Type','Normal');\ninvoke(material,'SetMaterialUnit','GHz','mm');\ninvoke(material,'Epsilon','4.3');\ninvoke(material,'Mue','1.0');\ninvoke(material,'Kappa','0.0');\ninvoke(material,'TanD','0.025');\ninvoke(material,'TanDFreq','10.0');\ninvoke(material,'TanDGiven','True');\ninvoke(material,'TanDModel','ConstTanD');\ninvoke(material,'KappaM','0.0');\ninvoke(material,'TanDM','0.0');\ninvoke(material,'TanDMFreq','0.0');\ninvoke(material,'TanDMGiven','False');\ninvoke(material,'TanDMModel','ConstKappa');\ninvoke(material,'DispModelEps','None');\ninvoke(material,'DispModelMue','None');\ninvoke(material,'DispersiveFittingSchemeEps','General 1st');\ninvoke(material,'DispersiveFittingSchemeMue','General 1st');\ninvoke(material,'UseGeneralDispersionEps','False');\ninvoke(material,'UseGeneralDispersionMue','False');\ninvoke(material,'Rho','0.0');\ninvoke(material,'ThermalType','Normal');\ninvoke(material,'ThermalConductivity','0.3');\ninvoke(material,'SetActiveMaterial','all');\ninvoke(material,'Colour','0.94','0.82','0.76');\ninvoke(material,'Wireframe','False');\ninvoke(material,'Transparency','0');\ninvoke(material,'Create');\nrelease(material);\nend", "meta": {"author": "simos421", "repo": "CST-MATLAB-API", "sha": "a6019ad6f33fa14ebfd459579b6e7151dd3d4ece", "save_path": "github-repos/MATLAB/simos421-CST-MATLAB-API", "path": "github-repos/MATLAB/simos421-CST-MATLAB-API/CST-MATLAB-API-a6019ad6f33fa14ebfd459579b6e7151dd3d4ece/Materials/CstFR4lossy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19139965954844798}} {"text": "function [image, imageCha, objOut] = CS_reconstruction(path, para)\n% CS_RECONSTRUCTION main function to select the appropriate Compressed\n% Sensing reconstruction\n%\n% input: \n% path - path to file without specifying file extension\n% - path to directory containing files\n% - empty (for file dialog)\n% - kSpace to be reconstructed with dimensionalities:\n% cell array: NSlice x NChannels x NRepetitions x NAverages\n% each cell: 2D: yPhase x xFreq x (nTime/nPhases)\n% 3D: yPhase x xFreq x zPhase\n% 4D: yPhase x xFreq x zPhase x nTime/nPhases\n% para - struct containing to be modified reconstruction parameters\n% and/or struct with handover parameter\n% - path to parameter file\n%\n%\n% output:\n% image reconstructed and sum-of-squared channel combined image\n% imageCha reconstructed individual coil images\n% objOut reconstruction parameters\n%\n%\n% (c) copyright 2012 - 2016 under BSD license\n% Thomas Kuestner, University of Tuebingen and University of Stuttgart, Germany\n% (thomas.kuestner@{med.uni-tuebingen.de,iss.uni-stuttgart.de})\n% \n% Please see license files (./licenses) for accompanied codes (which also \n% include own modifications) of:\n% - ESPIRiT v0.1.8 in @ESPIRiT, utils/utils_ESPIRiT under LICENSE_ESPIRiT \n% - bart v0.2.09 in utils/utils_BART under LICENSE_BART\n% - SPIRiT v0.3 in @SPIRiT, utils/utils_GRAPPA, \n% utils/utils_SPIRiT under LICENSE_SPIRiT\n% - sparseMRI v0.2 in @sparseMRI, @p2DFT, @A_operator,\n% @TVOP under LICENSE_SPARSEMRI\n% - L1Magic v1.11 in @L1_Magic under LICENSE_L1MAGIC\n% - GIST in utils/utils_Proximal/GIST under LICENSE_GIST\n% - Wavelab850 in @Wavelet, utils/utils_Wavelet under LICENSE_WAVELAB\n% - Rice Wavelet v3.0 in utils/utils_WaveletRice under LICENSE_WAVELETRICE\n% - Curvelab v2.1.3 in utils/utils_TRAFO/CurveLab-2.1.3 under LICENSE_CURVELAB\n% - NUFFT in @NUFFT, utils/utils_NUFFT under LICENSE_NUFFT\n% - DTCWT in utils/utils_TRAFO/DTCWT under LICENSE_DTCWT\n% - Shearlet in utils/utils_TRAFO/Shearlet under LICENSE_SHEARLET\n% - Denoising in utils/utils_Proximal/Denoising under LICENSE_DENOISING\n\nwarning('off','MATLAB:dispatcher:nameConflict');\nwarning('off','MATLAB:mat2cell:TrailingUnityVectorArgRemoved');\n\n% global prop\n\n% prepare m-files\ncurrpath = fileparts(mfilename('fullpath'));\naddpath(genpath([currpath,filesep,'utils']));\naddpath(genpath([currpath,filesep,'io']));\naddpath(genpath([currpath,filesep,'preproc']));\naddpath(genpath([currpath,filesep,'postproc']));\n\n% load ADCs\nif(nargin == 0 || ~exist('path','var') || isempty(path))\n if(strcmp(getenv('computername'),'M123PC'))\n defpath = 'K:\\Compressed Sensing\\Rohdaten\\3D';\n else\n defpath = 'S:\\Rohdaten\\Thomas\\ktFOCUSS\\3D';\n end\n [file, path] = uigetfile({'*.mat;*.dat;', 'ADC measdata (*.mat, *.dat)'; '*.h5', 'ISMRMD (*.h5)'} ,'Select measdata file', 'MultiSelect', 'off', defpath);\n if(isequal(file,0))\n error('CS_reconstruction(): User Termination');\n end\n [~,filename,ext] = fileparts(file);\n lReadFromFile = true;\n % in general: [dData, iLC] = fMeasRead(datapath, 'Set', 0, 'Smp', [21 inf]); \nelse\n if(ischar(path))\n if(isdir(path))\n [file, path] = uigetfile({'*.mat;*.dat;', 'ADC measdata (*.mat, *.dat)'; '*.h5', 'ISMRMD (*.h5)'} ,'Select measdata file', 'MultiSelect', 'off', path);\n if(isequal(file,0))\n error('CS_reconstruction(): User Termination');\n end\n [~,filename,ext] = fileparts(file);\n else\n [path, filename, ext] = fileparts(path);\n end\n lReadFromFile = true;\n else\n lReadFromFile = false;\n end\nend\n\n% read inputs\nif(lReadFromFile)\n if(strcmp(ext,'h5')) % ISMRMD\n data = h5read([path,filesep,filename,ext],'dataset/data');\n % convert to processable kSpace\n [ kSpace, measPara ] = convertKSpace_main( data );\n else % ADC measdata (Siemens)\n if(exist(fullfile(path,[filename,'.mat']),'file'))\n matfile = whos('-file', fullfile(path,[filename,'.mat']));\n end\n if(exist(fullfile(path,[filename,'.mat']),'file') && ~ismember('iLC', {matfile.name})) \n % load mat file to check if it contains iLC/iSP or something else\n data = load(fullfile(path,[filename,'.mat']));\n kSpace = data.kSpace;\n measPara.dim = zeros(1,5);\n measPara.LCall = zeros(1,4);\n dimNames = {'y (phase)', 'x (frequency)', 'z (phase)', 't (time)', 'channels'};\n LCallNames = {'slices', 'acquisitions', 'echos', 'repetitions'};\n dimDefault = ones(1,5);\n LCallDefault = [size(kSpace,1), size(kSpace,4), size(kSpace,5), size(kSpace,3)];\n tmp = size(kSpace{1});\n if(LCallDefault(1) > 1 && length(tmp) > 2)\n dimDefault(1:2) = tmp(1:2);\n dimDefault(4) = tmp(3);\n else\n dimDefault(1:length(tmp)) = tmp;\n end\n dimDefault(5) = size(kSpace,2);\n if(isfield(data,'dim') && isfield(data,'LCall'))\n measPara.dim = data.dim;\n measPara.LCall = data.LCall;\n elseif(isfield(data,'dim') && ~isfield(data,'LCall'))\n measPara.dim = data.dim;\n fprintf('Please specify amount of:\\n');\n for i=1:length(measPara.LCall)\n helper = input(sprintf('%s [%d]: ',LCallNames{i}, LCallDefault(i)),'s');\n if(isempty(helper)), helper = LCallDefault(i); end;\n measPara.LCall(i) = helper;\n end\n\n elseif(~isfield(data,'dim') && isfield(data,'LCall'))\n measPara.LCall = data.LCall;\n fprintf('Please specify dimensions:\\n');\n for i=1:length(measPara.dim)\n helper = input(sprintf('%s [%d]: ',dimNames{i}, dimDefault(i)),'s');\n if(isempty(helper)), helper = dimDefault(i); end;\n measPara.dim(i) = helper;\n end\n\n else\n fprintf('Please specify dimensions:\\n');\n for i=1:length(measPara.dim)\n helper = input(sprintf('%s [%d]: ',dimNames{i}, dimDefault(i)),'s');\n if(isempty(helper)), helper = dimDefault(i); end;\n measPara.dim(i) = helper;\n end\n fprintf('Please specify amount of:\\n');\n for i=1:length(measPara.LCall)\n helper = input(sprintf('%s [%d]: ',LCallNames{i}, LCallDefault(i)),'s');\n if(isempty(helper)), helper = LCallDefault(i); end;\n measPara.LCall(i) = helper;\n end\n end\n clear 'LCallDefault' 'dimDefault';\n loadedVars = {'dimension', 'oversampling', 'measPara', 'iLC', 'iLCPositions', 'drecksMDH'};\n for i=1:length(loadedVars)\n if(isfield(data,loadedVars{i}))\n if(any(strcmp(loadedVars{i},{'dimension','oversampling'})))\n eval(sprintf('measPara.%s = data.%s;', loadedVars{i}, loadedVars{i}));\n else\n eval(sprintf('%s = data.%s;', loadedVars{i}, loadedVars{i}));\n end\n else\n if(strcmp(loadedVars{i},'measPara'))\n continue;\n end\n eval(sprintf('%s = [];', loadedVars{i}));\n end\n end\n clear 'data';\n else\n [dData, iLC, iEvalInfoMask, drecksMDH, iLCPositions] = fMeas_main(fullfile(path, [filename, ext]));\n measPara = [];\n end\n end\nelse\n % kSpace was directly handed over\n kSpace = path;\n path = currpath; % for compatibility later\n filename = '';\n if(isstruct(para))\n loadedVars = {'measPara', 'dimension', 'oversampling', 'iLC', 'iLCPositions', 'drecksMDH', 'savePath'};\n for i=1:length(loadedVars)\n if(isfield(para,loadedVars{i}))\n if(any(strcmp(loadedVars{i},{'dimension','oversampling'})))\n eval(sprintf('measPara.%s = para.%s;', loadedVars{i}, loadedVars{i})); \n else\n eval(sprintf('%s = para.%s;', loadedVars{i}, loadedVars{i}));\n end\n eval(sprintf('para = rmfield(para,''%s'');', loadedVars{i}));\n else\n eval(sprintf('%s = [];', loadedVars{i}));\n end\n end\n end\nend\n \n%% save output\nprop.flagSave = false;\n\n\n%% show output in imagine\nprop.flagPlot = true;\n\n\n%% display output\nprop.disp.names = {'Repetitions', 'Averages', 'Slices', 'Channels', 'Time', 'Frequency', 'Extracting K-Space', 'Phase Correction', 'GRAPPA calibration', 'FOCUSS', 'CG', 'ESPReSSo', 'Trafo', 'POCS', 'MC', 'Line Search', 'Log barrier', 'Newton', 'Proximal Average', 'ADMM', 'SENSE - Slice', 'SENSE - Time', 'SENSE - Calibration', 'SENSE - Kernel', 'SENSE - Concatenate'};\nif(usejava('jvm') && ~feature('ShowFigureWindows'))\n % use text-based alternative\n prop.flagDisp = false;\n prop.flagPlot = prop.flagPlot & false;\n \n % initialize some console variables\n prop.maxvals = zeros(1,length(prop.disp.names));\n prop.lastOut = '';\nelse\n % use GUI dialogs\n prop.flagDisp = true;\n prop.flagPlot = prop.flagPlot & true;\n \n % initialize some GUI variables\n prop.disp.openBar = false(1,size(prop.disp.names,2));\n prop.disp.colors = colorGradient(rgb('DarkRed'),rgb('ForestGreen'),100);\n prop.disp.ppm = cell(1,length(prop.disp.names));\n % initialize some console variables\n prop.maxvals = zeros(1,length(prop.disp.names));\n prop.lastOut = '';\nend\n\n\n%% parallel computing\nprop.flagParallel = false;\nprop.openPool = false;\nhelper = ver;\nlFound = false;\nfor i=1:length(helper)\n if(strcmp(helper(i).Name,'Parallel Computing Toolbox'))\n lFound = true;\n prop.flagParallel = prop.flagParallel & true;\n if(verLessThan('matlab','8.4'))\n if(matlabpool('size') > 0)\n % matlabpool close\n prop.openPool = true;\n end\n else\n if(~isempty(gcp('nocreate')))\n prop.openPool = true;\n end\n end\n break;\n end\nend\nif(~lFound), prop.flagParallel = false; end\n \n\n\n%% load reconstruction parameter\nif(nargin > 1 && exist('para', 'var') && ischar(para))\n [pathPara, filenamePara, ~] = fileparts(para);\n cd(pathPara);\n eval([filenamePara,';']);\n cd(currpath);\nelse\n % load default parameter set\n eval('parameters_default;'); \nend\n\n\n%% replace parameters (if necessary)\nif(nargin > 1 && exist('para', 'var') && isstruct(para))\n names = fieldnames(para);\n for i=1:length(names)\n if(isstruct(para.(names{i})))\n innerNames = fieldnames(para.(names{i}));\n for j=1:length(innerNames)\n eval(sprintf('%s.(innerNames{j}) = para.(names{i}).(innerNames{j});',names{i}));\n if(strcmp(innerNames{j},'trafodim') && ~any(strcmp(innerNames,'scrambledim')))\n eval(sprintf('%s.scrambledim = para.(names{i}).(innerNames{j})(1,:);',names{i}));\n end\n end\n clear 'innerNames'\n else\n eval(sprintf('%s = para.%s;',names{i},names{i}));\n end\n end\n clear 'names'\nend\nclear 'para';\n% save MC parameters\nif(exist('savePath','var'))\n mc.savePath = savePath;\nelse\n mc.savePath = '';\nend\n% check for missing necessary parameters\nloadedVars = {'measPara', 'iLC', 'iLCPositions', 'drecksMDH'};\nfor iI=1:length(loadedVars)\n if(eval(sprintf('~exist(''%s'',''var'')',loadedVars{iI})))\n eval(sprintf('%s = [];', loadedVars{iI}));\n end\nend\n\n\n%% initialize dispProgress\ndispProgress('InitDispProgress',prop);\n\n\n%% get data dimension and loop counters\n[measPara, espresso, postproc] = extractMeasPara( iLC, measPara, espresso, postproc, flagOversampling, drecksMDH, iLCPositions );\n\n\n%% check variable consistency and existence\nallPara = { cstype, measPara.dimension, measPara.dim, iNOUTER, iNINNER, p, lambda, epsilon, measPara.oversampling, lambdaCalib, calibTyk, reconTyk, kernelSize, calibSize, opt_problem, postproc, trafo, FFTwindow, espresso, measPara.LCall, lbtol, tvmu, cgtol, cgmaxiter, flagToolbox, flagZeropadding, measPara.aniso, measPara.precision, reconDIM, flags, lambdaGroup, lambdaNLTV, lambdaTV;...\n 'cstype', 'dimension', 'dim', 'iNOUTER', 'iNINNER', 'p', 'lambda', 'epsilon', 'oversampling', 'lambdaCalib', 'calibTyk', 'reconTyk', 'kernelSize', 'calibSize', 'opt_problem', 'postproc', 'trafo', 'FFTwindow', 'espresso', 'LCall', 'lbtol', 'tvmu', 'cgtol', 'cgmaxiter', 'flagToolbox', 'flagZeropadding', 'aniso', 'precision', 'reconDIM', 'flags', 'lambdaGroup', 'lambdaNLTV', 'lambdaTV'}; %#ok<*NODEF>\n\n[consExist, msg, msgWarn, kernelSize, calibSize, FFTwindow, trafo, flagToolbox, measPara.precision, flags, reconDIM] = checkConsExist(allPara);\nif(~consExist)\n error('CS_reconstruction:checkConsExist','%s', msg); \nend\nif(~isempty(msgWarn))\n warning('CS_reconstruction:checkConsExist\\n%s', msgWarn);\nend\nclear 'allPara' 'msg' 'msgWarn' 'consExist';\n \n\n%% initialize recon objects\nif(strcmp(cstype,'FOCUSS'))\n obj = FOCUSS(iNOUTER, iNINNER, p, lambda, epsilon, measPara, lambdaCalib, lambdaTV, lambdaESPReSSo, lambdaMC, kernelSize, calibTyk, calibSize, flagZeropadding, FFTwindow, trafo, espresso, sScaling, mc, lSense);\n \nelseif(strcmp(cstype,'SPIRiT_CG') || strcmp(cstype,'SPIRiT_POCS'))\n obj = SPIRiT_Wrapper(cstype(8:length(cstype)), iNINNER, measPara, lambda, kernelSize, calibTyk, reconTyk, trafo, espresso, FFTwindow, calibSize); %#ok<*COLND>\n \nelseif(strcmp(cstype,'ESPIRiT_CG') || strcmp(cstype,'ESPIRiT_L1'))\n obj = ESPIRiT_Wrapper(cstype(9:length(cstype)), iNINNER, iNIterSplit, measPara, kernelSize, calibTyk, reconTyk, eigThresh_k, eigThresh_im, n_maps, splitWeight, trafo, flagToolbox, path, espresso, FFTwindow, calibSize);\n\nelseif(strcmp(cstype,'BART'))\n obj = BART_Wrapper(lambda, lambdaCalib, lambdaTV, lambdaMC, measPara, kernelSize, n_maps, trafo, espresso, FFTwindow, currpath, mc, calibSize);\n \nelseif(strcmp(cstype,'sparseMRI'))\n obj = sparseMRI(iNOUTER, iNINNER, measPara, lambda, lambdaTV, lambdaESPReSSo, p, trafo, espresso, FFTwindow, l1Smooth, lineSearchItnlim, lineSearchAlpha, lineSearchBeta, lineSearchT0, gradToll);\n \nelseif(strcmp(cstype,'L1_Magic_TV') || strcmp(cstype,'L1_Magic_L1') || strcmp(cstype,'L1_Magic_TVDantzig') || strcmp(cstype,'L1_Magic_L1Dantzig'))\n obj = L1_Magic(cstype(10:length(cstype)), measPara, epsilon, lbtol, tvmu, cgtol, cgmaxiter, pdmaxiter, espresso);\n\nelseif(strcmp(cstype,'Zero'))\n obj = Zero(measPara, espresso);\n \nelseif(strcmp(cstype,'FCSA_WaTMRI') || strcmp(cstype,'FCSA_SLEP') || strcmp(cstype,'FCSA_proxA') || strcmp(cstype,'BFCSA_proxA') || strcmp(cstype,'ADMM_proxA') || strcmp(cstype,'SB_proxA') || ...\n strcmp(cstype,'A_PFISTA') || strcmp(cstype,'A_TDIHT') || strcmp(cstype,'A_ADMM_L1') || strcmp(cstype,'A_ADMM_L0') || strcmp(cstype,'A_ADMM_SCAD') || strcmp(cstype,'A_ADMM_MCP') || strcmp(cstype,'A_ADMM_ATAN') || strcmp(cstype,'A_ADMM_PSHRINK'))\n obj = Proximal(cstype, iNINNER, itrNLTV, iNOUTER, measPara, trafo, lambda, lambdaTV, lambdaGroup, lambdaNLTV, lambdaNLTV_h, mue, regularizerWeights, flags, reconDIM, espresso);\n \nelse\n error('CS_reconstruction(): Undefined reconstruction cstype');\nend\n\n\n%% optimize fft command\nif(prop.flagOptim)\n optimizeFFT(measPara.dimension, measPara.dim, kernelSize, fft_planner_method, trafo.fftdim, lambdaCalib, flagZeropadding, measPara.precision);\nend\n\n\n%% extract kSpace data from measurement file\nif(exist('iLC','var') && ~isempty(iLC) && ~exist('kSpace', 'var'))\n [obj.kSpace, evalMask] = extractKSpace_main(dData, iLC, iEvalInfoMask, measPara);\nelse\n obj.kSpace = kSpace;\n clear 'kSpace';\nend\n\n\n%% correct phase perturbations (echo alignment)\nif(isfield(measPara,'sequenceName') && strcmp(measPara.sequenceName, 'CS_EPI'))\n obj.kSpace = alignEchos(obj.kSpace, evalMask, measPara, dData, iLC, iEvalInfoMask);\nend\n\n\n% clear all unnecessary variables\nclear 'dData' 'iLC' 'dDataRep' 'iLCRep' 'dDataSli' 'iLCSli' 'drecksMDH' 'iLCPositions' 'evalMask' 'helper' 'espresso' 'trafo' 'flagOversampling' 'mc';\nsCallingStack = dbstack;\nif(strcmp(sCallingStack(end).name,'fRetroGateAndRecon') || strcmp(sCallingStack(end).name,'MotionCorrection')) % for 4D CS_Retro\n evalin('caller', 'clear ''kSpace'';'); % ''para''\nend\nclear 'sCallingStack';\n\n\n%% start reconstruction\ncs_time = tic;\nimageCha = cell(size(obj.kSpace));\n\nif(lAutoCheck && ( ((strcmp(measPara.dimension,'3D') || strcmp(measPara.dimension,'4D')) && nnz(obj.kSpace{1,1}) >= 0.95*prod(measPara.dim(1:4))) || ...\n (strcmp(measPara.dimension,'2D') && nnz(obj.kSpace{1,1}) >= 0.95*prod(measPara.dim([1:2,4]))) || ...\n (obj.espresso.state && ~isempty(regexp(filename,'\\w*x1\\D\\w*','once'))) || (obj.espresso.state && isfield(measPara, 'CSAcceleration') && measPara.CSAcceleration == 1)))\n % check for acceleration factor == 1 ==> full acquisition\n if(strcmp(measPara.dimension,'2D'))\n fftdim = 1:2;\n pfdim = [3 1 2];\n subs = {':', ':', ':', ':'}; % y-x-cha\n subsid = 4;\n if(measPara.dim(4) > 1)\n pfdim = [4 1 2 3];\n subs = {':', ':', ':', ':'}; % y-x-t-cha\n subsid = 3;\n end\n elseif(strcmp(measPara.dimension,'3D'))\n fftdim = 1:3;\n pfdim = [4 1 2 3];\n subs = {':', ':', ':', ':', ':'}; % y-x-z-cha\n subsid = 5;\n elseif(strcmp(measPara.dimension,'4D'))\n fftdim = 1:3;\n pfdim = [5 1 2 3 4];\n subs = {':', ':', ':', ':', ':'}; % y-x-z-t-cha\n subsid = 4;\n end\n totalCount = measPara.LCall(2)*measPara.LCall(4)*measPara.LCall(1)*measPara.dim(4);\n dispProgress('Repetitions', 0, measPara.LCall(4));\n dispProgress('Averages', 0, totalCount);\n dispProgress('Time', 0, totalCount);\n for iRep=1:measPara.LCall(4)\n for iAvg=1:measPara.LCall(2)\n if(obj.espresso.state)\n for iSli=1:measPara.LCall(1)\n kSpaceTmp = squeeze(cell2mat(shiftdim(obj.kSpace(iSli,:,iRep,iAvg),-2)));\n imgTmp = zeros(size(kSpaceTmp)); \n for iTime=1:measPara.dim(4)\n subs{subsid} = iTime;\n imgTmp(subs{:}) = ipermute(espresso_recon(permute(kSpaceTmp(subs{:}),pfdim), obj.espresso.iter, false),pfdim);\n dispProgress('Time', ((iRep-1)*measPara.LCall(2)*measPara.LCall(1)*measPara.dim(4) + (iAvg-1)*measPara.LCall(1)*measPara.dim(4) + (iSli-1)*measPara.dim(4) +iTime)/totalCount);\n end\n if(strcmp(measPara.dimension,'2D') && measPara.dim(4) == 1) % 2D\n imageCha(iSli,:,iRep,iAvg) = shiftdim(squeeze(mat2cell(imgTmp, size(obj.kSpace{1,1},1),size(obj.kSpace{1,1},2),ones(1,measPara.dim(5)))),-1);\n else % 2Dt, 3D, 4D\n imageCha(iSli,:,iRep,iAvg) = shiftdim(squeeze(mat2cell(imgTmp, size(obj.kSpace{1,1},1),size(obj.kSpace{1,1},2),size(obj.kSpace{1,1},3),ones(1,measPara.dim(5)))),-1);\n end\n clear 'imgTmp' 'kSpaceTmp';\n end\n else \n imageCha(:,:,iRep,iAvg) = cellfun(@(x) ifftnshift(x,fftdim), obj.kSpace(:,:,iRep,iAvg), 'UniformOutput', false);\n end \n dispProgress('Averages', ((iRep-1)*measPara.LCall(2)*measPara.LCall(1)*measPara.dim(4) + iAvg*measPara.LCall(1)*measPara.dim(4))/totalCount);\n end\n dispProgress('Repetitions', iRep/measPara.LCall(4));\n end\n dispProgress('Time','Close');\nelse\n % Compressed Sensing reconstruction\n dispProgress('Repetitions', 0, measPara.LCall(4));\n dispProgress('Averages', 0, measPara.LCall(4)*measPara.LCall(2));\n for iRep=1:measPara.LCall(4)\n for iAvg=1:measPara.LCall(2)\n imageCha(:,:,iRep,iAvg) = obj.recon_main(iRep,iAvg); % obj.kSpace(:,:,iRep,iAvg)\n dispProgress('Averages', ((iRep-1)*measPara.LCall(2) + iAvg)/(measPara.LCall(4)*measPara.LCall(2)));\n end\n dispProgress('Repetitions', iRep/measPara.LCall(4));\n end\nend \nif(exist('cutOutMask','var')), imageCha = imageCha(cutOutMask); end;\ndispProgress('Averages', 'Close');\ndispProgress('Repetitions', 'Close');\nobj.kSpace = []; % clear kSpace variable\n\ncs_time = toc(cs_time);\ndRecontime(1) = mod(cs_time,60);\ndRecontime(2) = mod((cs_time - dRecontime(1))/60,60);\ndRecontime(3) = mod(((cs_time - dRecontime(1))/60 - dRecontime(2))/60, 24);\nif(cs_time >= 3600) \n fprintf('Execution time: %.2dh %.2dmin %.2ds\\n', dRecontime(3), dRecontime(2), round(dRecontime(1)));\nelseif(cs_time >= 60)\n fprintf('Execution time: %.2dmin %.2ds\\n', dRecontime(2), round(dRecontime(1)));\nelse\n fprintf('Execution time: %.2ds\\n', round(dRecontime(1)));\nend\nobj.dRecontime = dRecontime;\n\n%% postprocessing\nif(isempty(obj.kernelSize))\n obj.kernelSize = kernelSize;\nend\n\nimage = cell(1,measPara.LCall(4));\nfor iRep=1:measPara.LCall(4)\n imageAvg = cell(1,measPara.LCall(2));\n for iAvg=1:measPara.LCall(2)\n % each element: 2D (y-x + one slice), 3D (y-x-t + one slice, y-x + several slices, y-x-z) or\n % 4D (y-x-t + several slices, y-x-z-t)\n imageAvg{1,iAvg} = postproc_main(obj, imageCha(:,:,iRep,iAvg), postproc);\n end\n image{iRep} = squeeze(mean(cell2mat(shiftdim(imageAvg,-4)),6));\nend\nimage = squeeze(cell2mat(shiftdim(image,-3)));\n\n% % average over repetitions\n% image = squeeze(mean(cell2mat(shiftdim(image,-3)),5));\n\n\n%% delete fftw_wisdom variable\nif(prop.flagOptim)\n evalin('base', 'clear ''fftw_wisdom''');\nend\n\n%% save image\nif(nargout > 2 || prop.flagSave)\n % convert obj->struct and reduce size\n objProp = properties(obj);\n for iObj = 1:numel(objProp)\n if(any(strcmp(objProp{iObj},{'kernel','kernelImg','kCalib','A','kSpace'})))\n continue;\n end\n eval(['objOut.',objProp{iObj},' = obj.',objProp{iObj},';']);\n end\nend\nif(prop.flagSave)\n if(exist('filename','var') && ~isempty(filename))\n savename = [filename,'_',cstype,'_',transformation];\n else\n savename = [cstype,'_',transformation];\n end\n dirContent = dir(path);\n occurence = 0;\n for i=1:length(dirContent)\n if(dirContent(i).isdir)\n continue;\n end\n tmp = regexp(dirContent(i).name,[savename,'[_]*\\d*'],'once');\n% if(strcmpi(dirContent(i).name,savename))\n if(~isempty(tmp))\n occurence = occurence + 1;\n end\n end\n if(occurence > 0)\n savename = [savename,'_',num2str(occurence)];\n end\n% save([path,filesep,savename,'.mat'], 'image', 'imageCha', 'objOut');\n save([path,filesep,savename,'.mat'], 'image', 'objOut', '-v7.3');\nend\n\n\n%% plot resulting image\nif(prop.flagPlot && exist('imagine','file'))\n if(iscell(image))\n imagePlot = cell2mat(shiftdim(image,-1));\n else\n imagePlot = image;\n end\n \n % set displayed name\n figname = [cstype,'_',transformation];\n tmp = functions(FFTwindow.type);\n if(~strcmp(tmp.function,'rectwin'))\n figname = [figname,'_',tmp.function];\n end \n if(obj.espresso.state)\n figname = [figname,'_espresso'];\n end\n figname = [figname,'_',postproc.type];\n \n % if imagine is already open, add new image in same window\n hfig = findobj('type','figure','name','IMAGINE 2.0 Belly Jeans');\n if(length(hfig) > 1)\n hfig = max(hfig);\n end\n \n if(~isempty(hfig) && ishandle(hfig))\n fh = get(hfig,'userdata');\n data = fh();\n \n \n oldImage = cell(1,size(data,2));\n oldTitle = oldImage;\n cmd = '';\n for i=1:size(data,2)\n oldImage{i} = data(i).dImg;\n oldTitle{i} = data(i).sName;\n cmd = [cmd, sprintf('oldImage{%d},''Name'',oldTitle{%d},',i,i)];\n end\n\n close(hfig);\n cmd = ['imagine(',cmd, 'imagePlot,''Name'',figname);'];\n eval(cmd);\n clear oldImage oldTitle cmd hfig;\n else\n imagine(imagePlot,'Name',figname);\n end\nend\n\n\nend", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/CS_reconstruction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}} {"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": "function cluster_length = save_declus(catalog) \n \n ZG=ZmapGlobal.Data; % used by get_zmap_globals\n global cluslength %[OUT]\n %FIXME: this is torn to shreds by the updated catalog format\n report_this_filefun();\n storedcat=a;\n hodis = fullfile(hodi, 'external');\n cd(hodis);\n \n str = [];\n \n s = [ ZG.primeCatalog.Date.Year ZG.primeCatalog.Date.Month ZG.primeCatalog.Date.Day ZG.primeCatalog.Date.Hour ZG.primeCatalog.Date.Minute ZG.primeCatalog.Magnitude ZG.primeCatalog.Latitude ZG.primeCatalog.Longitude ZG.primeCatalog.Depth ];\n fid = fopen(['data'],'w') ;\n fprintf(fid,'%4.0f%2.0f%2.0f%2.0f%2.0f %3.1fmb%7.3f%8.3f%5.1fA\\n',s');\n fclose(fid);\n clear s\n \n s = [taumin*60*24 taumax*60*24 P xk xmeff rfact err derr ];\n fid = fopen(['para.dat'],'w') ;\n fprintf(fid,'%5.0f %5.0f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f\\n',s');\n fclose(fid);\n clear s\n \n % This executes the clus.exe FORTRAN code\n unix(['.' filesep 'myclus ']);\n \n %open datafile\n fid = 'outf.clu';\n \n try\n format = ['%12c %3f %f %f %f %d'];\n %[dat,mag,lat,lon,dep,clu] = textread(fid,format,'whitespace',' \\b\\r\\t\\n mb A ');\n C = textscan(fid, format, 'Whitespace',' \\b\\r\\t\\n mb A ');\n dat=C{1}; mag=C{2}; lat = C{3}; lon=C{4}; dep = C{5}; clu = C{6};\n catch ME\n l=ME.message;\n l1 = strfind(l,',');\n anz = str2double(l(53:l1-1));\n %[dat,mag,lat,lon,dep,clu] = textread(fid,format,anz-1,'whitespace',' \\b\\r\\t\\n mb A ');\n C = textscan(fid, format, anz-1, 'Whitespace',' \\b\\r\\t\\n mb A ');\n dat=C{1}; mag=C{2}; lat = C{3}; lon=C{4}; dep = C{5}; clu = C{6};\n \n disp(['Error in Line ' num2str(anz) ' read only lines 1 - ' num2str(anz-1) ]);\n \n end\n \n \n %transform data to ZMAP format\n watchon;\n disp('Reloading data ...')\n \n yr = str2double(dat(:,1:4));\n mo= str2double(dat(:,5:6));\n da= str2double(dat(:,7:8));\n hr= str2double(dat(:,9:10));\n mi= str2double(dat(:,11:12));\n \n replaceMainCatalog([lon lat ZG.primeCatalog.Date mo da mag storedcat.Depth hr mi clu]);\n \n cluslength=[];\n n=0;\n k1=max(clu);\n for j=1:k1 %for all clusters\n cluslength(j)=length(find(clu==j)); %length of each clusters\n end\n \n tmp=find(cluslength); %numbers of clusters that are not empty\n \n %cluslength,bg,mbg only for events which are not zero\n cluslength=cluslength(tmp);\n \n clustnumbers=(1:length(tmp)); %stores numbers of clusters\n l = a(:,10) > 0;\n clus = ZG.primeCatalog.subset(l);\n ZG.primeCatalog(l,:) = [];\n \n % plot the results\n zmap_update_displays();\n set(gca,'NextPlot','add')\n plot(clus(:,1),clus(:,2),'m+');\n \n st1 = [' The declustering found ' num2str(max(clu)) ' clusters of earthquakes, a total of '...\n ' ' num2str(length(clus(:,1))) ' events (out of ' num2str(storedcat.Count) '). '...\n ' The map window now display the declustered catalog containing ' num2str(ZG.primeCatalog.Count) ' events . The individual clusters are displayed as magenta o in the map. ' ];\n \n msgbox(st1,'Declustering Information')\n watchoff;\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/save_declus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.19122010632991643}} {"text": "function dx = pendulumSystem(x,A,P,grid,dyn)\n% dx = pendulumSystem(x,A,P,pendulum)\n%\n% This function computes the closed loop dynamics of the pendulum, using\n% the optimal controller from the MDP solve\n%\n\nth = x(1,:);\nw = x(2,:);\n\nu = pendulumController(x,A,P,grid);\ndw = pendulumDynamics(th,w,u,dyn);\n\ndx = [w;dw];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/MDP_Pendulum/pendulumSystem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19089558572865678}} {"text": "function [mesh, meshCurvature, layerCurvature, gLocs2d, gLocs3d, numNodes] ...\n = mfmAssignGray(mesh, params, insideNodes)\n% Assign gray matter locations to the unfolded positions in a flattened\n% map.\n%\n% [mesh, meshCurvature, layerCurvature, gLocs2d, gLocs3d, numNodes] ...\n% = mfmAssignGray(mesh, params, insideNodes)\n%\n% Author: Winawer\n%\n% Purpose: Assign gray matter locations to the unfolded positions in a flattened\n% map. \n% \n% Sub-routine derived from Alex's unfoldMeshFromGUI code.\n%\n% See Also: unfoldMeshFromGUI\n% Get all the variables we may need\nmeshFileName = params.meshFileName;\ngrayFileName = params.grayFileName;\nflatFileName = params.flatFileName;\nstartCoords = params.startCoords;\nscaleFactor = params.scaleFactor;\nperimDist = params.perimDist;\nstatusHandle = params.statusHandle;\nbusyHandle = params.busyHandle;\nspacingMethod = params.spacingMethod;\nadjustSpacing = params.adjustSpacing;\ngridSpacing = params.gridSpacing;\nshowFigures = params.showFigures;\nsaveExtra = params.saveExtra;\ntruePerimDist = params.truePerimDist;\nhemi = params.hemi;\nnperims = params.NPERIMS;\nsaveIntermeidate = params.SAVE_INTERMEDIATE;\nnumberOfSteps = params.NUMBEROFSTEPS;\n\n% Update status\nstatusStringAdd(statusHandle,'Reading gray graph...');\n[gNodes, gEdges] = readGrayGraph(grayFileName, hemi);\n\n% Do all the gray node stages in a loop so that we can have arbitrary\n% numbers of layers.\nnumGrayLayers=max(gNodes(6,:));\n\n% Get the indices for all the gnodes (all layers)\nfor t=1:numGrayLayers\n grayNodeIndices{t}=find(gNodes(6,:)==t);\nend\n\n% Extract the layer 1 nodes. These are special because they are used to map\n% down to the unfolded boundary mesh.\nl1gNodes=gNodes(:,grayNodeIndices{1});\nl1mesh.vertices=l1gNodes(1:3,:);\nl1mesh.indices=grayNodeIndices{1};\n\n% How many gNodes are there?\nnGnodes=length(gNodes);\n% How many gEdges are there?\nnGedges=length(gEdges);\n\n% We want to make a grey node connection matrix - which grey nodes are connected to which other gnodes?\nstatusStringAdd(statusHandle,'Finding grey connection matrix (slow)');\n\ngrayConMat=makeGrayConMat(gNodes,gEdges,busyHandle);\n\n% We can assign layer 1 grey nodes to the white matter mesh using\n% assignToNearest.dll (see assignToNearest.c) Can't do this for higher\n% levels of grey matter because they might be mis-assigned. (Also, potential\n% problem near very crinkly edges. - Could we accidentally assign a l1\n% grey matter node to the wrong WM point?) (I think the answer is 'yes,\n% rarely'. If a single layer or gray is sandwiched between two sides of a\n% sulcus (say) : It's grown from one side but mrFlatMesh has no way of\n% telling which one. Going deeper into mrGray's source code to determine\n% the parentage of l1 gray nodes might be possible...)\n\n\n% So for higher grey matter points, we have to restrict the possible sub\n% node search space by assigning them >only< to points they are connected\n% to. Note that a single layer2 grey node may be connected to several l1\n% nodes\n\n\n% The gray may be defined over the entire mesh but we only want to deal with gray points over the \n% unfolded part. The strategy should be....\n% 1) do assignToNearest for each mesh point to find the nearest connected l1 node\n% 2) Use the set of l1 nodes found in 1) to build up a list of other connected gray nodes\n% 3) Repeat stage 2 for l3,l4\n\nstatusStringAdd(statusHandle,'Mapping L1 to mesh.');\n\n% Find 3D coords of all the l1 gnodes\nl1GNodeCoords=l1gNodes(1:3,:)';\n\n% Find 3D coords of all the mesh points (not just the unfolded ones) \nmeshCoords=mesh.uniqueVertices;\n\n% Mesh coords are in voxels, gnode coords are in voxels. Bring them into alignment\nl1GNodeCoordsN=l1GNodeCoords-1; % Use this -1 to bring them into perfect alignment. This was the source of an error in V1.0\n\n% Now restrict the mesh coords to just those points in the unfold\nmeshCoordsN=meshCoords(mesh.insideNodes,:);\n\n% And now restrict the set of l1 gray nodes so that only those that are relatively near the \n% mesh are included in the search - this is done first as a simple bounds check\nboundedL1NodeIndices=boundsCheck3D(min(meshCoordsN)-3,max(meshCoordsN)+3,l1GNodeCoordsN);\nboundedL1GNodes=l1GNodeCoordsN(boundedL1NodeIndices,:);\nboundedL1NodeIndices=grayNodeIndices{1}(boundedL1NodeIndices); % This is now a list of indices into the full gNode array\n\nstatusStringAdd(statusHandle,'Finding nearest Ll gray points to mesh (very slow)');\n\n% Find mesh points near the l1 gNodes\n[boundedL1toMeshIndices,sqrDist]=nearpoints(boundedL1GNodes',(meshCoordsN)');\n% This returns a list of indices into the meshCoordsN array that links a single 3D mesh point to each l1Gnode)\n% and then eliminate any l1gNodes that are more than a set distance away from the mesh - here sqrt(0.25)\n\n% *************************\ncloseEnough=find(sqrDist<=0.2501);\n% *************************\n\nboundedL1toMeshNodes = boundedL1GNodes(closeEnough,:); % remember, assignToNearest returns the squared distance\nboundedL1toMeshIndices= boundedL1toMeshIndices(closeEnough);\n\n% For each member of the bounded l1Gnodes, this tells us the index of the full mesh point that it maps to.\nfullBoundedL1toMeshIndices=insideNodes(boundedL1toMeshIndices);\n\nrestNodeIndices{1}=boundedL1NodeIndices(closeEnough);\n\nstatusStringAdd(statusHandle,'Setting L1 glocs');\n% We can start setting gLocs\n% Note the +1 here! Because we subtracted 1 from the original node coords\n% to align them with the mesh. \nlayerGlocs3d{1}=boundedL1toMeshNodes+1; \nlayerGlocs2d{1}=mesh.X(fullBoundedL1toMeshIndices,:);\n\nnumNodes(1)=length(layerGlocs3d{1});\n\nlayerCurvature{1}=mesh.uniqueCols(fullBoundedL1toMeshIndices,1);\n\nif (showFigures)\n h = unfoldPlotL1Mesh(grayConMat(restNodeIndices{1},restNodeIndices{1}), layerGlocs2d{1}); \n statusStringAdd(statusHandle,'Displaying L1 gray mesh.');\n\t\n\t[p f ext] = fileparts(flatFileName);\n\tsavePath = fullfile(p, [f ' Gray Mesh.png']);\n\tsaveas(h, savePath);\n\tfprintf('[%s]: Saved %s.\\n', mfilename, savePath);\t\nend\n\n% Now we have to find l2tol1Indices, l3tol2Indices and l4tol3Indices. This\n% is faster since for each point, we restrict its potential nearest\n% neighbours to points that it is connected to in the previous layer. We\n% also restrict the l2 nodes to just those that are connected to the\n% restricted l1 nodes and the l3 nodes to those connected to the l2 nodes.\n% Use the full connection matrix to find which l2 Gnodes are connected to the restricted l1Gnodes\nstatusStringAdd(statusHandle,'Mapping other gray layers (2,3,4..)');\n\n% Set up the 3 critical arrays curvature, gLocs2d, gLocs3d. These are what\n% eventually get written to the flat.\nmeshCurvature=layerCurvature{1};\ngLocs2d=layerGlocs2d{1};\ngLocs3d=layerGlocs3d{1};\n\nfor t=2:numGrayLayers\n \n layerInterconnect=grayConMat(:, restNodeIndices{t-1}); % Finds all the things connected to the t-1th layer...\n [restNodeIndices{t},dummy]=find(layerInterconnect);\n restNodeIndices{t}=unique(restNodeIndices{t});\n restNodeIndices{t}=intersect(restNodeIndices{t},grayNodeIndices{t}); % Only take potential l2 node indices\n finalConnectIndices{t-1}=findNearestConnected(gNodes', restNodeIndices{t},restNodeIndices{t-1},grayConMat);\n \n % Set glocs3d, glocs2d, meshCurvature\n layerGlocs3d{t}=gNodes(1:3,restNodeIndices{t})';\n numNodes(t)=length(layerGlocs3d{t});\n layerGlocs2d{t}=layerGlocs2d{t-1}(finalConnectIndices{t-1},:);\n layerCurvature{t}=zeros(length(finalConnectIndices{t-1}),1);\n gLocs2d=[gLocs2d;layerGlocs2d{t}];\n gLocs3d=[gLocs3d;layerGlocs3d{t}];\n meshCurvature=[meshCurvature;layerCurvature{t}];\n \nend\n\nif (showFigures), \n\tunfoldPlotgLocs2d(numGrayLayers,layerGlocs2d); \n\t[p f ext] = fileparts(flatFileName);\n\tsavePath = fullfile(p, [f ' Grid Locations.png']);\n\tsaveas(gcf, savePath);\n\tfprintf('[%s]: Saved %s.\\n', mfilename, savePath);\nend\n\nstatusStringAdd(statusHandle,'Creating flat.mat structure');\n\n% We want to transform the curvature to run between 1 to 64 for display\n% purposes. We want the mean, however, to be preserved so that we can\n% calculate the average curvature and also we want to keep the values\n% accurate in terms of real curvature (which is 1/radius in pixels but\n% should be mm; though mrGray may do some unwanted scaling).\n% So, instead of this: \n% meshCurvature=normalize((meshCurvature))*63+1;%\n% we now do this to (a) map to 1 to 64, \n%\n% Note that the curvature values here are pulled from the rgba field of the\n% mesh sturct. This is created by meGray and is the actual RGB (& alpha)\n% value used to color each triangle when the mesh is rendered. If the mesh\n% has no color overlays, then this will be an 8-bit grayscale value (R=G=B)\n% and thus range from 0-255, with curvature=0 at 127. (RFD/BW).\nmeshCurvature = (layerCurvature{1}/255)*63 ;\n\nreturn\n\n%----------------------------------\n% ---- SUBROUTINES\n%----------------------------------\n%----------------------------------\nfunction h = unfoldPlotL1Mesh(x,layer1Glocs2d)\nh = figure;\ngplot(x,layer1Glocs2d);\ntitle('L1 gray mesh'); zoom on;\n\nreturn;\n\n%----------------------------------\nfunction unfoldPlotgLocs2d(numGrayLayers,layerGlocs2d)\n%\nnFigsAcross=ceil(sqrt(numGrayLayers));\nnFigsDown=ceil(sqrt(numGrayLayers));\nfor t=1:numGrayLayers\n if (t<=numGrayLayers)\n subplot(nFigsDown,nFigsAcross,t);\n \n plot(layerGlocs2d{t}(:,1),layerGlocs2d{t}(:,2),'.');\n axis equal;\n end % end check on current layer index\nend % Next image\nreturn;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/mrFlatMesh/mfm/mfmAssignGray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19051555406926693}} {"text": "function output = calllpsolve(interfacedata)\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc = interfacedata.c;\nK = interfacedata.K;\ninteger_variables = interfacedata.integer_variables;\nbinary_variables = interfacedata.binary_variables;\nsemicont_variables = interfacedata.semicont_variables;\nub = interfacedata.ub;\nlb = interfacedata.lb;\n\nn = length(c);\n% Bounded variables converted to constraints\nif ~isempty(ub)\n LB = lb;\n UB = ub;\nelse\n if isempty(integer_variables) & isempty(binary_variables) \n LB = -ones(n,1)*inf;;\n UB = ones(n,1)*inf;;\n else\n %LP_SOLVE FAILS IF BOUNDS NOT EXPLICIT\n [LB,UB,used_rows] = find_lp_bounds(F_struc,K);\n LB(isinf(LB)) = -1e12;\n UB(isinf(UB)) = 1e12;\n F_struc(K.f+used_rows,:)=[];\n K.l = K.l - length(used_rows);\n LB(binary_variables) = max(LB(binary_variables),0);\n UB(binary_variables) = min(UB(binary_variables),0);\n end\nend\n\nif options.showprogress;showprogress('Calling LPSOLVE',options.showprogress);end\n\nf = - full(c); % Must be full\nA = - F_struc(:,2:end);\nb = full(F_struc(:,1)); % Must be full\ne = -ones(size(A,1),1);\ne(1:K.f) = 0;\n\nxint = uniquestripped([integer_variables binary_variables]);\n\n% Call mex-interface\nsolvertime = clock; \n\nif K.f>0\n Aeq = A(1:K.f,:);\n beq = b(1:K.f);\n Alin = A(K.f+1:end,:);\n blin = b(K.f+1:end);\n [LB,UB,Alin,blin] = remove_bounds_from_Ab(Alin,blin,LB,UB);\n A = [Aeq;Alin];\n b = [beq;blin];\n e = -ones(size(A,1),1);\n e(1:K.f) = 0;\n options.saveduals = 0;\nelse\n [LB,UB,A,b] = remove_bounds_from_Ab(A,b,LB,UB);\n e = -ones(size(A,1),1);\n options.saveduals = 0;\nend\nif ~isempty(semicont_variables)\n redundant = find(LB<=0 & UB>=0);\n semicont_variables = setdiff(semicont_variables,redundant);\nend\n\n% LPSOLVE assumes semi-continuous variables only can take negative values so\n% we negate semi-continuous violating this\nNegativeSemiVar = [];\nif ~isempty(semicont_variables)\n NegativeSemiVar = find(UB(semicont_variables) < 0);\n if ~isempty(NegativeSemiVar)\n temp = UB(semicont_variables(NegativeSemiVar));\n UB(semicont_variables(NegativeSemiVar)) = -LB(semicont_variables(NegativeSemiVar));\n LB(semicont_variables(NegativeSemiVar)) = -temp;\n A(:,semicont_variables(NegativeSemiVar)) = -A(:,semicont_variables(NegativeSemiVar));\n f(semicont_variables(NegativeSemiVar)) = -f(semicont_variables(NegativeSemiVar));\n end\nend\nif options.savedebug\n save lpsolvedebug f A b e UB LB xint \nend\n\nlp = create_lp_solve_model(A,b,f,xint,LB,UB,e,options);\nif ~isempty(K.sos)\n for i = 1:length(K.sos.type)\n lp_solve('add_SOS', lp, 'Dummy', str2num(K.sos.type(i)), 1, K.sos.variables{i}, K.sos.weight{i});\n end\nend\nif ~isempty(semicont_variables)\n lp_solve('set_semicont', lp, semicont_variables) \nend\n\ntry \n if options.showprogress;showprogress(['Calling ' interfacedata.solver.tag],options.showprogress);end\n solvertime = tic;\n result=lp_solve('solve', lp);\n solvertime = toc(solvertime);\n if result == 0 | result == 1 | result == 11 | result == 12 \n [obj, x, duals] = lp_solve('get_solution', lp);\n else\n obj = [];\n x = zeros(length(c),1);\n duals = [];\n end\n lp_solve('delete_lp', lp);\ncatch\n obj = [];\n x = zeros(length(c),1);\n duals = [];\n result = -1;\n lp_solve('delete_lp', lp);\nend\n\n\n% LPSOLVE assumes semi-continuous variables only can take negative values so\n% we negate semi-continuous violating this\n if length(x) == length(c)\n if ~isempty(NegativeSemiVar)\n x(NegativeSemiVar) = -x(NegativeSemiVar);\n end\n end\n\nif options.saveduals & isempty(integer_variables)\n D_struc = duals;\nelse\n D_struc = [];\nend\n\nswitch result\n case {0,1}\n problem = 0; % OPTIMAL\n case 2\n problem = 1; % INFEASIBLE\n case 3\n problem = 2; % UNBOUNDED\n case {7,12,13}\n problem = 3; % RUN OUT OF TIME OR SIMILIAR\n case 5\n problem = 4;\n case {-2,10,11}\n problem = 11;\n otherwise\n problem = -1;\nend\n \n% Save all data sent to solver?\nif options.savesolverinput\n\tsolverinput.A = A;\n\tsolverinput.f = f;\n\tsolverinput.b = b;\t\n\tsolverinput.LB = LB;\n\tsolverinput.UB = UB; \n solverinput.xint = xint; \nelse\n\tsolverinput = [];\nend\n\n% Save all data from the solver?\nif options.savesolveroutput\n\tsolveroutput.x = x;\n solveroutput.obj = obj;\n solveroutput.duals = duals; \n solveroutput.result = result; \nelse\n\tsolveroutput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(x,D_struc,[],problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/calllpsolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.19051554111353444}} {"text": "function errores = errors\n\nsource = evalin('base','source');\ndecout = evalin('base','decout');\nN = evalin('base','N');\n\nerrores = sum(abs(source - decout));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18259-turbo-coding-for-generic-rsc-coders/errors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1904511844281577}} {"text": "function hdr = ReadEfileHeader(EfileName)\n% header = ReadEfileHeader(EfileName) \n%\n% Returns header info from Efile produced by G. Glover's auto-recon program.\n% Output is structure having field names corresponding to Glover's parameters.\n%\n% Ress 9/01\n% $Author: sayres $\n% $Date: 2005/08/23 08:06:25 $\nif nargin==0\n if exist('Raw/Pfiles','dir')\n startDir = 'Raw/Pfiles';\n else\n startDir = pwd;\n end\n [f p] = myUiGetfile(startDir,'*.7','Choose an E-file');\n EfileName = fullfile(p,f);\nend\n\nhdr = [];\n\nfid = fopen(EfileName);\nif fid == -1\n Alert(['Could not open file: ' EfileName])\n return\nend\n\nnLine = 0;\nwhile 1\n line = fgetl(fid);\n if ~ischar(line), break, end\n ieq = findstr(line, '=');\n lhs = line(1:ieq-2);\n rhs = line(ieq+2:end);\n switch lhs\n case 'rev'\n % Revision\n hdr.rev = rhs;\n case 'date of scan'\n % Date\n hdr.date = rhs;\n % Make this more reasonable\n hdr.date=[hdr.date(1:6),hdr.date(8:end)];\n case 'time of scan'\n % Time\n hdr.time = rhs;\n case 'patient name'\n % Name\n hdr.name = rhs;\n \n case 'psd'\n % PSD\n hdr.psd = rhs;\n case 'coil'\n % Coil\n hdr.coil = rhs;\n case 'slquant'\n % Number of slices\n hdr.slquant = getNumberFromString(rhs);\n case 'num time frames'\n % Number of frames\n hdr.nframes = getNumberFromString(rhs);\n case 'numextra discards'\n % Number of discarded shots\n hdr.nextra = getNumberFromString(rhs);\n case 'nshot'\n % Number of interleaves\n hdr.nshots = getNumberFromString(rhs);\n case 'FOV'\n % Field of view (mm)\n hdr.FOV = getNumberFromString(rhs);\n case 'slice thick'\n % Slice thickness (mm)\n hdr.sliceThickness = getNumberFromString(rhs);\n case 'skip'\n % Slice spacing (skip)\n hdr.skip = getNumberFromString(rhs);\n case 'TR'\n % Echo time, TR (ms)\n hdr.TR = getNumberFromString(rhs);\n case 'TE'\n % Repetition time, TE (ms)\n hdr.TE = getNumberFromString(rhs);\n case 'time/frame'\n % Acquisition time (ms)\n hdr.tAcq = getNumberFromString(rhs);\n case 'equiv matrix size'\n % Equivalent matrix size\n hdr.equivMatSize = getNumberFromString(rhs);\n case 'imgsize'\n % Image size\n hdr.imgsize = getNumberFromString(rhs);\n case 'pixel size'\n % Pixel size (mm)\n hdr.pixel = getNumberFromString(rhs);\n case 'freq'\n % Frequency (MHz)\n hdr.freq = getNumberFromString(rhs)/1.e6;\n case 'R1, R2, TG (mps)'\n % Gains [R1, R2, TG]\n hdr.R1 = getNumberFromString(rhs, 1);\n hdr.R2 = getNumberFromString(rhs, 2);\n hdr.TG = getNumberFromString(rhs, 3);\n otherwise\n end\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Init/ReadEfileHeader.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.19037458646394367}} {"text": "function script_rfcn_VOC0712_ResNet101_OHEM_ss()\n% script_rfcn_VOC0712_ResNet101_OHEM_ss()\n% RFCN training and testing with OHEM using ResNet101 model and selective\n% search proposals\n% --------------------------------------------------------\n% R-FCN implementation\n% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)\n% Copyright (c) 2016, Jifeng Dai\n% Licensed under The MIT License [see LICENSE for details]\n% --------------------------------------------------------\n\nclc;\nclear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));\n%% -------------------- CONFIG --------------------\nopts.caffe_version = 'caffe_rfcn';\nopts.gpu_id = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\n\n% model\nmodel = Model.ResNet101_for_RFCN_VOC0712_OHEM();\n% cache name\nopts.cache_name = 'rfcn_VOC0712_ResNet101_OHEM_ss';\n% config\nconf = rfcn_config_ohem('image_means', model.mean_image);\n% train/test data\nfprintf('Loading dataset...')\ndataset = [];\ndataset = Dataset.voc0712_trainval_ss(dataset, 'train', conf.use_flipped);\ndataset = Dataset.voc2007_test_ss(dataset, 'test', false);\nfprintf('Done.\\n');\n\n% do validation, or not\nopts.do_val = true; \n\n%% -------------------- TRAINING --------------------\n\nopts.rfcn_model = rfcn_train(conf, dataset.imdb_train, dataset.roidb_train, ...\n 'do_val', opts.do_val, ...\n 'imdb_val', dataset.imdb_test, ...\n 'roidb_val', dataset.roidb_test, ...\n 'solver_def_file', model.solver_def_file, ...\n 'net_file', model.net_file, ...\n 'cache_name', opts.cache_name, ...\n 'caffe_version', opts.caffe_version);\nassert(exist(opts.rfcn_model, 'file') ~= 0, 'not found trained model');\n\n%% -------------------- TESTING --------------------\n rfcn_test(conf, dataset.imdb_test, dataset.roidb_test, ...\n 'net_def_file', model.test_net_def_file, ...\n 'net_file', opts.rfcn_model, ...\n 'cache_name', opts.cache_name,...\n 'ignore_cache', true);\n\nend\n", "meta": {"author": "daijifeng001", "repo": "R-FCN", "sha": "94797e0e8d15998a9ab0a76cbac3281ad907f04a", "save_path": "github-repos/MATLAB/daijifeng001-R-FCN", "path": "github-repos/MATLAB/daijifeng001-R-FCN/R-FCN-94797e0e8d15998a9ab0a76cbac3281ad907f04a/experiments/script_rfcn_VOC0712_ResNet101_OHEM_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19037458118860806}} {"text": "function [epochs] = fiff_read_epochs(fname)\n%\n% [epochs] = fiff_read_epochs(fname,setno)\n%\n% Read eochs from file\n%\n%\n% Author : Martin Luessi, MGH Martinos Center\n% License : BSD 3-clause\n\nglobal FIFF;\nif isempty(FIFF)\n FIFF = fiff_define_constants();\nend\n\nme='MNE:fiff_read_epochs';\n\n%\n% Open the file\n%\nfprintf(1,'Reading %s ...\\n',fname);\n[ fid, tree ] = fiff_open(fname);\n%\n% Read the measurement info\n%\n[ info, meas ] = fiff_read_meas_info(fid,tree);\ninfo.filename = fname;\n\n%\n% Read events\n%\n[ events, mappings ] = fiff_read_events(fid,tree);\n\n%\n% Locate the data of interest\n%\nprocessed = fiff_dir_tree_find(meas, FIFF.FIFFB_PROCESSED_DATA);\nif length(processed) == 0\n fclose(fid);\n error(me,'Could not find epochs data');\nend\n\nep = fiff_dir_tree_find(meas, FIFF.FIFFB_MNE_EPOCHS);\nif length(ep) == 0\n fclose(fid);\n error(me,'Could not find epochs data');\nend\n\ncomment = '';\nselection = '';\ndrop_log = '';\nfor k = 1:ep.nent\n kind = ep.dir(k).kind;\n pos = ep.dir(k).pos;\n switch kind\n case FIFF.FIFF_FIRST_SAMPLE\n tag = fiff_read_tag(fid,pos);\n first = tag.data;\n case FIFF.FIFF_LAST_SAMPLE\n tag = fiff_read_tag(fid,pos);\n last = tag.data;\n case FIFF.FIFF_COMMENT\n tag = fiff_read_tag(fid,pos);\n comment = tag.data;\n case FIFF.FIFF_EPOCH\n tag = fiff_read_tag(fid,pos);\n epoch = tag.data;\n case FIFF.FIFF_MNE_BASELINE_MIN\n tag = fiff_read_tag(fid,pos);\n bmin = tag.data;\n case FIFF.FIFF_MNE_BASELINE_MAX\n tag = fiff_read_tag(fid,pos);\n bmax = tag.data;\n case FIFF.FIFFB_MNE_EPOCHS_SELECTION\n tag = fiff_read_tag(fid,pos);\n selection = tag.data;\n case FIFF.FIFFB_MNE_EPOCHS_DROP_LOG\n tag = fiff_read_tag(fid,pos);\n drop_log = tag.data;\n end\nend\n\nif ~exist('epoch','var')\n fclose(fid);\n error(me,'Epochs data not found');\nend\n\nif ~exist('bmin','var')\n bmin = double(first)/info.sfreq;\nend\n\nif ~exist('bmax','var')\n bmax = double(last)/info.sfreq;\nend\n\nbaseline = [bmin, bmax];\n\nnsamp = last-first+1;\nfprintf(1,'\\tFound the data of interest:\\n');\nfprintf(1,'\\t\\tt = %10.2f ... %10.2f ms (%s)\\n',...\n 1000*double(first)/info.sfreq,1000*double(last)/info.sfreq,comment);\nif ~isempty(info.comps)\n fprintf(1,'\\t\\t%d CTF compensation matrices available\\n',length(info.comps));\nend\n\nif size(epoch,1) ~= size(events,1)\n fclose(fid);\n error(me,'Incorrect number of trials (%d instead of %d)',...\n size(epoch,1),size(events,1));\nend\n\nif size(epoch,2) ~= info.nchan\n fclose(fid);\n error(me,'Incorrect number of channels (%d instead of %d)',...\n size(epoch,2),info.nchan);\nend\n\nif size(epoch,3) ~= nsamp\n fclose(fid);\n error(me,'Incorrect number of samples (%d instead of %d)',...\n size(epoch,3),nsamp);\nend\n\n%\n% Calibrate\n%\nfor k = 1:info.nchan\n cals(k) = info.chs(k).cal;\nend\n\nnepochs = size(epoch, 1);\nepoch = repmat(cals, [nepochs, 1, nsamp]) .* epoch;\n\ntimes = double(first:last) / info.sfreq;\ntmin = times(1);\ntmax = times(end);\n\n%\n% Put it all together\n%\nepochs.info = info;\nepochs.events = events;\nepochs.name = comment;\nepochs.times = times;\nepochs.tmin = tmin;\nepochs.tmax = tmax;\nepochs.data = epoch;\nepochs.baseline = baseline;\nepochs.event_id = mappings;\nepochs.selection = selection;\nepochs.drop_log = drop_log;\n\nfclose(fid);\n\nreturn;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/mne/fiff_read_epochs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19037457915378636}} {"text": "function allMets = evaluateTracking(allSeq, resDir, dataDir)\n%% evaluate CLEAR MOT and other metrics\n% concatenate ALL sequences and evaluate as one!\n%\n% SETUP:\n%\n% define directories for tracking results...\n% resDir = fullfile('res','data',filesep);\n% ... and the actual sequences\n% dataDir = fullfile('..','data','2DMOT2015','train',filesep);\n%\n%\n\nfprintf('Sequences: \\n');\ndisp(allSeq')\n\n% concat gtInfo\ngtInfo=[];\ngtInfo.Xi=[];\nallFgt=zeros(1,length(allSeq));\n\n% Find out the length of each sequence\n% and concatenate ground truth\ngtInfoSingle=[];\nseqCnt=0;\nfor s=allSeq\n seqCnt=seqCnt+1;\n seqName = char(s);\n seqFolder= [dataDir,seqName,filesep];\n \n assert(isdir(seqFolder),'Sequence folder %s missing',seqFolder);\n \n gtFile = fullfile(dataDir,seqName,'gt','gt.txt');\n gtI = convertTXTToStruct(gtFile,seqFolder);\n \n [Fgt,Ngt] = size(gtInfo.Xi);\n [FgtI,NgtI] = size(gtI.Xi);\n newFgt = Fgt+1:Fgt+FgtI;\n newNgt = Ngt+1:Ngt+NgtI;\n \n gtInfo.Xi(newFgt,newNgt) = gtI.Xi;\n gtInfo.Yi(newFgt,newNgt) = gtI.Yi;\n gtInfo.W(newFgt,newNgt) = gtI.W;\n gtInfo.H(newFgt,newNgt) = gtI.H;\n \n gtInfoSingle(seqCnt).wc=0;\n \n % fill in world coordinates if they exist\n if isfield(gtI,'Xgp') && isfield(gtI,'Ygp')\n gtInfo.Xgp(newFgt,newNgt) = gtI.Xgp;\n gtInfo.Ygp(newFgt,newNgt) = gtI.Ygp;\n gtInfoSingle(seqCnt).wc=1;\n end\n \n \n allFgt(seqCnt) = FgtI;\n \n gtInfoSingle(seqCnt).gtInfo=gtI;\n \nend\ngtInfo.frameNums=1:size(gtInfo.Xi,1);\n\nallMets=[];\n\nmcnt=1;\n\n\nfprintf('Evaluating ... \\n');\n\n\nclear stInfo\nstInfo.Xi=[];\n\nevalMethod=1;\n\n% flags for entire benchmark\n% if one seq missing, evaluation impossible\neval2D=1;\neval3D=1;\n\nseqCnt=0;\n\n% iterate over each sequence\nfor s=allSeq\n \n seqCnt=seqCnt+1;\n seqName = char(s);\n \n fprintf('\\t... %s\\n',seqName);\n \n % if a result is missing, we cannot evaluate this tracker\n resFile = fullfile(resDir,[seqName '.txt']);\n if ~exist(resFile,'file')\n fprintf('WARNING: result for %s not available!\\n',seqName);\n eval2D=0;\n eval3D=0;\n continue;\n end\n \n \n stI = convertTXTToStruct(resFile);\n% stI.Xi(find(stI.Xi(:)))=-1;\n % check if bounding boxes available in solution\n imCoord=1;\n if all(stI.Xi(find(stI.Xi(:)))==-1)\n imCoord=0;\n end\n \n worldCoordST=0; % state\n if isfield(stI,'Xgp') && isfield(stI,'Ygp')\n worldCoordST=1;\n end\n \n [FI,NI] = size(stI.Xi);\n \n \n % if stateInfo shorter, pad with zeros\n % GT and result must be equal length\n if FI255)||any(inputArray<0))\n error('Hash values can only be obtained from character arrays or arrays of positive integer values from 0 through 255');\nend\n\nif(nargin<2)\n algorithm='simple';\nend\n\n%If the simple aglorithm is chosen. otherwise, a cryptographic has is being\n%used.\nif(strcmp(algorithm,'simple'))\n %Convert the array to a character string.\n if(~ischar(inputArray))\n inputArray=native2unicode(inputArray);\n end\n\n myString=java.lang.String(inputArray);\n hashVal=myString.hashCode;\n %Java's integers are always 32-bits.\n hexVal=dec2hex(typecast(int32(hashVal),'uint32'),8);\n return;\nend\n\n%The cryptographic has functions work on bytes, not strings.\nif(ischar(inputArray))\n inputArray=unicode2native(inputArray);\nend\n\nmyDigest=java.security.MessageDigest.getInstance(algorithm);\n\nmyDigest.update(inputArray);\nhashVal=myDigest.digest;\nhexVal=javax.xml.bind.DatatypeConverter.printHexBinary(hashVal);\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Misc/genHashVal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.19024507616224706}} {"text": "classdef ObjectnessBING < handle\n %OBJECTNESSBING The Binarized normed gradients algorithm for Objectness\n %\n % Implementation of BING for Objectness.\n %\n % ## Saliency API\n %\n % Many computer vision applications may benefit from understanding where\n % humans focus given a scene. Other than cognitively understanding the way\n % human perceive images and scenes, finding salient regions and objects in\n % the images helps various tasks such as speeding up object detection,\n % object recognition, object tracking and content-aware image editing.\n %\n % About the saliency, there is a rich literature but the development is\n % very fragmented. The principal purpose of this API is to give a unique\n % interface, a unique framework for use and plug sever saliency\n % algorithms, also with very different nature and methodology, but they\n % share the same purpose, organizing algorithms into three main\n % categories:\n %\n % * Static Saliency\n % * Motion Saliency\n % * Objectness\n %\n % Saliency UML diagram:\n %\n % ![image](https://docs.opencv.org/3.3.1/saliency.png)\n %\n % To see how API works, try tracker demo: `computeSaliency_demo.m`.\n %\n % ## Objectness Algorithms\n %\n % Objectness is usually represented as a value which reflects how likely\n % an image window covers an object of any category. Algorithms belonging\n % to this category, avoid making decisions early on, by proposing a small\n % number of category-independent proposals, that are expected to cover all\n % objects in an image. Being able to perceive objects before identifying\n % them is closely related to bottom up visual attention (saliency).\n %\n % Presently, the Binarized normed gradients algorithm [BING] has been\n % implemented.\n %\n % ## References\n % [BING]:\n % > Cheng, Ming-Ming, et al. \"BING: Binarized normed gradients for\n % > objectness estimation at 300fps\". In IEEE CVPR, 2014.\n %\n % See also: cv.StaticSaliencySpectralResidual,\n % cv.MotionSaliencyBinWangApr2014\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % base for window size quantization. default 2\n Base\n % Size for non-maximal suppress. default 2\n NSS\n % As described in the paper: feature window size (W, W). default 8\n W\n end\n\n methods\n function this = ObjectnessBING()\n %OBJECTNESSBING Constructor, creates a specialized saliency algorithm of this type\n %\n % obj = cv.ObjectnessBING()\n %\n % See also: cv.ObjectnessBING.computeSaliency\n %\n this.id = ObjectnessBING_(0, 'new');\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % obj.delete()\n %\n % See also: cv.ObjectnessBING\n %\n if isempty(this.id), return; end\n ObjectnessBING_(this.id, 'delete');\n end\n\n function objectnessValues = getObjectnessValues(this)\n %GETOBJECTNESSVALUES Return the list of the rectangles' objectness value\n %\n % objectnessValues = obj.getObjectnessValues()\n %\n % ## Output\n % * __objectnessValues__ vector of floats in the same order as\n % `objectnessBoundingBox` returned by the algorithm (in\n % `computeSaliency` function). The bigger value these scores\n % are, it is more likely to be an object window.\n %\n % See also: cv.ObjectnessBING.computeSaliency\n %\n objectnessValues = ObjectnessBING_(this.id, 'getobjectnessValues');\n end\n\n function setTrainingPath(this, trainingPath)\n %SETTRAININGPATH This is a utility function that allows to set the correct path from which the algorithm will load the trained model\n %\n % obj.setTrainingPath(trainingPath)\n %\n % ## Input\n % * __trainingPath__ trained model path.\n %\n % See also: cv.ObjectnessBING.setBBResDir\n %\n ObjectnessBING_(this.id, 'setTrainingPath', trainingPath);\n end\n\n function setBBResDir(this, resultsDir)\n %SETBBRESDIR This is a utility function that allows to set an arbitrary path in which the algorithm will save the optional results\n %\n % obj.setBBResDir(resultsDir)\n %\n % ## Input\n % * __resultsDir__ results' folder path.\n %\n % Writes on file the total number and the list of rectangles\n % returned by objectness, one for each row.\n %\n % See also: cv.ObjectnessBING.setTrainingPath\n %\n ObjectnessBING_(this.id, 'setBBResDir', resultsDir);\n end\n end\n\n %% Algorithm\n methods\n function clear(this)\n %CLEAR Clears the algorithm state\n %\n % obj.clear()\n %\n % See also: cv.ObjectnessBING.empty, cv.ObjectnessBING.load\n %\n ObjectnessBING_(this.id, 'clear');\n end\n\n function b = empty(this)\n %EMPTY Checks if detector object is empty\n %\n % b = obj.empty()\n %\n % ## Output\n % * __b__ Returns true if the detector object is empty (e.g in the\n % very beginning or after unsuccessful read).\n %\n % See also: cv.ObjectnessBING.clear, cv.ObjectnessBING.load\n %\n b = ObjectnessBING_(this.id, 'empty');\n end\n\n function save(this, filename)\n %SAVE Saves the algorithm parameters to a file\n %\n % obj.save(filename)\n %\n % ## Input\n % * __filename__ Name of the file to save to.\n %\n % This method stores the algorithm parameters in the specified\n % XML or YAML file.\n %\n % See also: cv.ObjectnessBING.load\n %\n ObjectnessBING_(this.id, 'save', filename);\n end\n\n function load(this, fname_or_str, varargin)\n %LOAD Loads algorithm from a file or a string\n %\n % obj.load(fname)\n % obj.load(str, 'FromString',true)\n % obj.load(..., 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __fname__ Name of the file to read.\n % * __str__ String containing the serialized model you want to\n % load.\n %\n % ## Options\n % * __ObjName__ The optional name of the node to read (if empty,\n % the first top-level node will be used). default empty\n % * __FromString__ Logical flag to indicate whether the input is a\n % filename or a string containing the serialized model.\n % default false\n %\n % This method reads algorithm parameters from the specified XML or\n % YAML file (either from disk or serialized string). The previous\n % algorithm state is discarded.\n %\n % See also: cv.ObjectnessBING.save\n %\n ObjectnessBING_(this.id, 'load', fname_or_str, varargin{:});\n end\n\n function name = getDefaultName(this)\n %GETDEFAULTNAME Returns the algorithm string identifier\n %\n % name = obj.getDefaultName()\n %\n % ## Output\n % * __name__ This string is used as top level XML/YML node tag\n % when the object is saved to a file or string.\n %\n % See also: cv.ObjectnessBING.save, cv.ObjectnessBING.load\n %\n name = ObjectnessBING_(this.id, 'getDefaultName');\n end\n end\n\n %% Saliency, Objectness\n methods\n function objectnessBoundingBox = computeSaliency(this, img)\n %COMPUTESALIENCY Compute the saliency\n %\n % objectnessBoundingBox = obj.computeSaliency(img)\n %\n % ## Input\n % * __img__ The input image, 8-bit color.\n %\n % ## Output\n % * __objectnessBoundingBox__ objectness Bounding Box vector.\n % According to the result given by this specialized algorithm,\n % the `objectnessBoundingBox` is a cell array of 4-element\n % vectors. Each bounding box is represented by\n % `[minX, minY, maxX, maxY]`.\n %\n % Performs all the operations and calls all internal functions\n % necessary for the accomplishment of the Binarized normed\n % gradients algorithm.\n %\n % See also: cv.ObjectnessBING.ObjectnessBING\n %\n objectnessBoundingBox = ObjectnessBING_(this.id, 'computeSaliency', img);\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.Base(this)\n value = ObjectnessBING_(this.id, 'get', 'Base');\n end\n function set.Base(this, value)\n ObjectnessBING_(this.id, 'set', 'Base', value);\n end\n\n function value = get.NSS(this)\n value = ObjectnessBING_(this.id, 'get', 'NSS');\n end\n function set.NSS(this, value)\n ObjectnessBING_(this.id, 'set', 'NSS', value);\n end\n\n function value = get.W(this)\n value = ObjectnessBING_(this.id, 'get', 'W');\n end\n function set.W(this, value)\n ObjectnessBING_(this.id, 'set', 'W', value);\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/ObjectnessBING.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.19024506910387576}} {"text": "function PPI = spm_peb_ppi(varargin)\n% Bold deconvolution to create physio- or psycho-physiologic interactions\n% FORMAT PPI = spm_peb_ppi(SPMname,ppiflag,VOI,Uu,ppiname,showGraphics)\n%\n% SPM - Structure containing generic details about the analysis or\n% the fully qualified filename of such a structure.\n% ppiflag - Type of analysis. Must be one of:\n% 'simple deconvolution' or 'sd'\n% 'psychophysiologic interaction' or 'ppi'\n% 'physiophysiologic interaction' or 'phipi'\n% VOI - Structure containing details about a VOI (as produced by\n% spm_regions) or the fully qualified filename of such a\n% structure. If a structure, then VOI should be of size 1x1\n% in the case of simple deconvolution, and psychophysiologic \n% interactions) or 1x2, in the case of physiophysiologic\n% interactions. If a file name it should be 1xN or 2xN.\n% Uu - Matrix of input variables and contrast weights. This is an\n% [n x 3] matrix. The first column indexes SPM.Sess.U(i). The\n% second column indexes the name of the input or cause, see\n% SPM.Sess.U(i).name{j}. The third column is the contrast\n% weight. Unless there are parametric effects the second\n% column will generally be a 1.\n% ppiname - Basename of the PPI file to save. The saved file will be:\n% /PPI_.mat\n% showGraphics - empty or 1 = yes, 0 = no.\n%\n%\n% PPI.ppi - (PSY*xn or xn1*xn2) convolved with the HRF\n% PPI.Y - Original BOLD eigenvariate. Use as covariate of no interest\n% PPI.P - PSY convolved with HRF for psychophysiologic interactions,\n% or in the case of physiophysologic interactions contains\n% the eigenvariate of the second region. \n% PPI.name - Name of PPI\n% PPI.xY - Original VOI information\n% PPI.xn - Deconvolved neural signal(s)\n% PPI.psy.u - Psychological variable or input function (PPIs only)\n% PPI.psy.w - Contrast weights for psychological variable (PPIs only)\n% PPI.psy.name - Names of psychological conditions (PPIs only)\n%__________________________________________________________________________\n%\n% This routine is effectively a hemodynamic deconvolution using full priors\n% and EM to deconvolve the HRF from a hemodynamic time series to give a \n% neuronal time series [that can be found in PPI.xn]. This deconvolution \n% conforms to Wiener filtering. The neuronal process is then used to form \n% PPIs. See help text within function for more details.\n%__________________________________________________________________________\n% Copyright (C) 2002-2014 Wellcome Trust Centre for Neuroimaging\n\n% Darren Gitelman\n% $Id: spm_peb_ppi.m 6556 2015-09-15 15:42:04Z guillaume $\n\n\n% SETTING UP A PPI THAT ACCOUNTS FOR THE HRF\n% =========================================================================\n% PPI's were initially conceived as a means of identifying regions whose\n% reponses can be explained in terms of an interaction between activity in\n% a specified source (the physiological factor) and some experimental\n% effect (the psychological factor). However, a problem in setting up PPI's\n% is that in order to derive a proper estimate of the interaction between\n% a psychological variable (P) and measured hemodynamic signal (x), one \n% cannot simply convolve the psychological variable with the hrf (HRF) and \n% multiply by the signal. Thus:\n% \n% conv(P,HRF).* x ~= conv((P.*xn),HRF)\n%\n% P = psychological variable\n% HRF = hemodynamic response function\n% xn = underlying neural signal which in fMRI is convolved with the hrf to\n% give the signal one measures -- x.\n% x = measured fmri signal\n%\n% It is actually the right hand side of the equation one wants.\n% Thus one has to work backwards, in a sense, and deconvolve the hrf\n% from x to get xn. This can then be multiplied by P and the resulting\n% vector (or matrix) reconvolved with the hrf.\n%\n% This algorithm uses a least squares strategy to solve for xn.\n%\n% The source's hemodynamics are x = HRF*xn;\n%\n% Using the constraint that xn should have a uniform spectral density \n% we can expand x in terms of a discrete cosine set (xb)\n%\n% xn = xb*B\n% B = parameter estimate\n%\n% The estimator of x is then\n%\n% x = HRF(k,:)*xn\n% x = HRF(k,:) * xb * B\n%\n% This accounts for different time resolutions between our hemodynamic \n% signal and the discrete representation of the psychological variable. In \n% this case k is a vector representing the time resolution of the scans.\n%\n% Conditional estimates of B allow for priors that ensure uniform variance \n% over frequencies.\n%\n% PPI STATISTICAL MODEL\n% =========================================================================\n% Once the PPI.ppi interaction term has been calculated a new GLM must be\n% setup to search for the interaction effects across the brain. This is\n% done using a standard, first level, fMRI model, which must include 3\n% covariates, PPI.ppi (interaction), PPI.Y (main effect: source region bold\n% signal) and PPI.P (main effect: \"psychological\" condition), plus any\n% nuisance regressors according to the particular design.\n%\n% NB: Designs that include only the interaction term without the main\n% effects are not proper as inferences on the interaction will include a\n% mixture of both main and interaction effects. \n%\n% Once the model has been setup and run, a contrast of [1 0 0] over the\n% PPI.ppi, PPI.Y and PPI.P columns respectively, will show regions with a\n% positive relationship to the interaction term, discounting any main\n% effects. Negative regressions can be examined with [-1 0 0]. A PPI random\n% effects analysis would involve taking the con* files from the [1 0 0]\n% t-contrast for each subject and forwarding them to a second level\n% analysis.\n\n\n% Shortcut for PPI display\n%--------------------------------------------------------------------------\nif nargin && ischar(varargin{1}) && strcmpi(varargin{1},'display')\n if nargin > 1\n PPI = varargin{2};\n else\n [PPI, sts] = spm_select(1,'^PPI.*\\.mat$');\n if ~sts, return; end\n end\n if ischar(PPI), load(PPI); end\n display_ppi(PPI);\n return;\nend\n\n% Set up the graphical interface\n%--------------------------------------------------------------------------\nFinter = spm_figure('FindWin','Interactive');\nif ~nargin, Finter = spm_figure('GetWin','Interactive'); end\nheader = get(Finter,'Name');\nspm_clf(Finter); set(Finter,'name','PPI Setup');\n\n% Check inputs\n%--------------------------------------------------------------------------\nif nargin && isstruct(varargin{1})\n SPM = varargin{1};\n try, swd = SPM.pwd; catch, swd = pwd; end\nelse\n try\n P = varargin{1};\n catch\n [P, sts] = spm_select(1,'^SPM\\.mat$','Select SPM.mat');\n if ~sts, PPI = []; return; end\n end\n swd = spm_file(P,'fpath');\n load(fullfile(swd,'SPM.mat'));\nend\nSPM.swd = spm_file(swd,'cpath');\ncwd = pwd;\ncd(SPM.swd)\n\n\n% Ask whether to perform physiophysiologic or psychophysiologic interactions\n%--------------------------------------------------------------------------\ntry\n ppiflag = varargin{2};\ncatch\n ppiflag = {'simple deconvolution',...\n 'psychophysiologic interaction',...\n 'physiophysiologic interaction'};\n i = spm_input('Analysis type?',1,'m',ppiflag);\n ppiflag = ppiflag{i};\nend\n\n\nswitch lower(ppiflag)\n \n case {'simple deconvolution','sd'}\n %======================================================================\n if nargin>2 && isstruct(varargin{3})\n p.xY = varargin{3};\n else\n try\n VOI = varargin{3};\n p = load(deblank(VOI(1,:)),'xY');\n catch\n spm_input('physiological variable:... ',2,'d');\n [VOI,sts] = spm_select(1,'^VOI.*\\.mat$',{'select VOI'});\n if ~sts, PPI = []; return; end\n p = load(VOI,'xY');\n end\n end\n xY(1) = p.xY;\n Sess = SPM.Sess(xY(1).Sess);\n\n case {'physiophysiologic interaction','phipi'}\n %======================================================================\n if nargin>2 && isstruct(varargin{3})\n xY = varargin{3};\n xY = xY(:)';\n if numel(xY) ~= 2\n error('Must include 2 VOI structures for physiophysiologic interactions')\n end\n else\n try\n VOI = varargin{3};\n if size(VOI,1) ~= 2\n error('Must include 2 VOI filenames for physiophysiologic interactions')\n end\n for i = 1:2\n p = load(deblank(VOI(i,:)),'xY');\n xY(i) = p.xY;\n end\n catch\n spm_input('physiological variables:... ',2,'d');\n [VOI,sts] = spm_select(2,'^VOI.*\\.mat$',{'select VOIs'});\n if ~sts, PPI = []; return; end\n for i = 1:2\n p = load(deblank(VOI(i,:)),'xY');\n xY(i) = p.xY;\n end\n end\n end\n Sess = SPM.Sess(xY(1).Sess);\n\n case {'psychophysiologic interaction','ppi'}\n %======================================================================\n if nargin>2 && isstruct(varargin{3})\n p.xY = varargin{3};\n else\n try\n VOI = varargin{3};\n p = load(deblank(VOI(1,:)),'xY');\n catch\n spm_input('physiological variable:... ',2,'d');\n [VOI,sts] = spm_select(1,'^VOI.*\\.mat$',{'select VOI'});\n if ~sts, PPI = []; return; end\n p = load(VOI,'xY');\n end\n end\n xY(1) = p.xY;\n Sess = SPM.Sess(xY(1).Sess);\n\n % get 'causes' or inputs U\n %----------------------------------------------------------------------\n U.name = {};\n U.u = [];\n U.w = [];\n try\n Uu = varargin{4};\n for i = 1:size(Uu,1)\n U.u = [U.u Sess.U(Uu(i,1)).u(33:end,Uu(i,2))];\n U.name{end+1} = Sess.U(Uu(i,1)).name{Uu(i,2)};\n U.w = [U.w Uu(i,3)];\n end\n catch\n spm_input('Psychological variable:... ',2,'d');\n u = length(Sess.U);\n for i = 1:u\n for j = 1:length(Sess.U(i).name)\n str = ['include ' Sess.U(i).name{j} '?'];\n if spm_input(str,3,'y/n',[1 0])\n str = 'Contrast weight';\n tmpw = spm_input(str,4,'e',[],1);\n % if tmpw==0 then don't include the column in the\n % design. This takes care of the possibility that the\n % user would select to include the column but then give\n % it a 0 weight.\n %------------------------------------------------------\n if tmpw ~= 0\n U.w = [U.w tmpw];\n U.u = [U.u Sess.U(i).u(33:end,j)];\n U.name{end + 1} = Sess.U(i).name{j};\n end\n end\n end\n end\n end\n\n otherwise\n %======================================================================\n error('Unknown type of analysis');\n \nend % (switch setup)\n\n\n% Name of PPI file to be saved\n%--------------------------------------------------------------------------\ntry\n PPI.name = varargin{5};\ncatch\n PPI.name = spm_input('Name of PPI',3,'s','PPI');\nend\n\n\n% Check if Graphical output should be shown\n%--------------------------------------------------------------------------\ntry\n showGraphics = varargin{6};\ncatch\n showGraphics = 1;\nend\n\n\n% Setup variables\n%--------------------------------------------------------------------------\nRT = SPM.xY.RT;\ndt = SPM.xBF.dt;\nNT = round(RT/dt);\nfMRI_T0 = SPM.xBF.T0;\nN = length(xY(1).u);\nk = 1:NT:N*NT; % microtime to scan time indices\n\n\n% Setup other output variables\n%--------------------------------------------------------------------------\nPPI.xY = xY;\nPPI.RT = RT;\nPPI.dt = dt;\n\n\n% Create basis functions and hrf in scan time and microtime\n%--------------------------------------------------------------------------\nhrf = spm_hrf(dt);\n\n\n% Create convolved explanatory {Hxb} variables in scan time\n%--------------------------------------------------------------------------\nxb = spm_dctmtx(N*NT + 128,N);\nHxb = zeros(N,N);\nfor i = 1:N\n Hx = conv(xb(:,i),hrf);\n Hxb(:,i) = Hx(k + 128);\nend\nxb = xb(129:end,:);\n\n\n% Get confounds (in scan time) and constant term\n%--------------------------------------------------------------------------\nX0 = xY(1).X0;\nM = size(X0,2);\n\n\n% Get response variable\n%--------------------------------------------------------------------------\nfor i = 1:size(xY,2)\n Y(:,i) = xY(i).u;\nend\n\n\n% Remove confounds and save Y in ouput structure\n%--------------------------------------------------------------------------\nYc = Y - X0*inv(X0'*X0)*X0'*Y;\nPPI.Y = Yc(:,1);\nif size(Y,2) == 2\n PPI.P = Yc(:,2);\nend\n\n\n% Specify covariance components; assume neuronal response is white\n% treating confounds as fixed effects\n%--------------------------------------------------------------------------\nQ = speye(N,N)*N/trace(Hxb'*Hxb);\nQ = blkdiag(Q, speye(M,M)*1e6 );\n\n\n% Get whitening matrix (NB: confounds have already been whitened)\n%--------------------------------------------------------------------------\nW = SPM.xX.W(Sess.row,Sess.row);\n\n\n% Create structure for spm_PEB\n%--------------------------------------------------------------------------\nclear P\nP{1}.X = [W*Hxb X0]; % Design matrix for lowest level\nP{1}.C = speye(N,N)/4; % i.i.d assumptions\nP{2}.X = sparse(N + M,1); % Design matrix for parameters (0's)\nP{2}.C = Q;\n\n\nswitch ppiflag\n\n case {'simple deconvolution','sd'}\n %======================================================================\n C = spm_PEB(Y,P);\n xn = xb*C{2}.E(1:N);\n xn = spm_detrend(xn);\n\n % Save variables (NOTE: xn is in microtime and does not account for\n % slice timing shifts). To convert to BOLD signal convolve with a hrf.\n % Use a microtime to scan time index to convert to scan time: e.g.,\n % k = 1:NT:N*NT; where NT = number of bins per TR = TR/dt or SPM.xBF.T\n % and N = number of scans in the session. Finally account for slice\n % timing effects by shifting the index accordingly.\n %----------------------------------------------------------------------\n PPI.xn = xn;\n\n case {'physiophysiologic interaction','phipi'}\n %======================================================================\n C = spm_PEB(Y(:,1),P);\n xn1 = xb*C{2}.E(1:N);\n C = spm_PEB(Y(:,2),P);\n xn2 = xb*C{2}.E(1:N);\n xn1 = spm_detrend(xn1);\n xn2 = spm_detrend(xn2);\n xnxn = xn1.*xn2;\n\n % Convolve, convert to scan time, and account for slice timing shift\n %----------------------------------------------------------------------\n ppi = conv(xnxn,hrf);\n ppi = ppi((k-1) + fMRI_T0);\n\n % Save variables\n %----------------------------------------------------------------------\n PPI.xn = [xn1 xn2];\n PPI.ppi = spm_detrend(ppi);\n\n case {'psychophysiologic interaction','ppi'}\n %======================================================================\n\n % COMPUTE PSYCHOPHYSIOLOGIC INTERACTIONS\n % use basis set in microtime\n %----------------------------------------------------------------------\n % get parameter estimates and neural signal; beta (C) is in scan time\n % This clever trick allows us to compute the betas in scan time which\n % is much quicker than with the large microtime vectors. Then the betas\n % are applied to a microtime basis set generating the correct neural\n % activity to convolve with the psychological variable in microtime\n %----------------------------------------------------------------------\n C = spm_PEB(Y,P);\n xn = xb*C{2}.E(1:N);\n xn = spm_detrend(xn);\n\n % Setup psychological variable from inputs and contrast weights\n %----------------------------------------------------------------------\n PSY = zeros(N*NT,1);\n for i = 1:size(U.u,2)\n PSY = PSY + full(U.u(:,i) * U.w(i));\n end\n PSY = spm_detrend(PSY);\n\n % Multiply psychological variable by neural signal\n %----------------------------------------------------------------------\n PSYxn = PSY.*xn;\n\n % Convolve, convert to scan time, and account for slice timing shift\n %----------------------------------------------------------------------\n ppi = conv(PSYxn,hrf);\n ppi = ppi((k-1) + fMRI_T0);\n\n % Convolve psych effect, convert to scan time, and account for slice\n % timing shift\n %----------------------------------------------------------------------\n PSYHRF = conv(PSY,hrf);\n PSYHRF = PSYHRF((k-1) + fMRI_T0);\n\n % Save psychological variables\n %----------------------------------------------------------------------\n PPI.psy = U;\n PPI.P = PSYHRF;\n PPI.xn = xn;\n PPI.ppi = spm_detrend(ppi);\n \nend % (switch)\n\n% Display\n%--------------------------------------------------------------------------\nif showGraphics\n display_ppi(PPI);\nend\n\n% Save\n%--------------------------------------------------------------------------\nstr = ['PPI_' PPI.name '.mat'];\n\nsave(fullfile(SPM.swd,str),'PPI', spm_get_defaults('mat.format'))\n\ncmd = 'spm_peb_ppi(''display'',''%s'')';\nfprintf(' PPI saved as %s\\n',spm_file(fullfile(SPM.swd,str),'link',cmd));\n\n% Clean up\n%--------------------------------------------------------------------------\nset(Finter,'name',header);\ncd(cwd);\n\n\n%==========================================================================\n% function display_ppi(PPI)\n%==========================================================================\nfunction display_ppi(PPI)\n\nFgraph = spm_figure('GetWin','PPI');\nFS = spm('FontSizes');\nspm_clf(Fgraph);\n\ntry\n RT = PPI.RT;\ncatch\n RT = spm_get_defaults('stats.fmri.t')*PPI.dt; % backward compatibility\nend\nN = length(PPI.xY(1).u);\nNT = round(RT/PPI.dt);\nt = PPI.RT*[1:N];\nT = PPI.dt*[1:(N*NT)];\n\n%-Simple deconvolution\n%--------------------------------------------------------------------------\nif numel(PPI.xY) == 1 && ~isfield(PPI,'psy')\n \n ax = subplot(1,1,1);\n plot(t,PPI.Y,T,PPI.xn)\n title('hemodynamic and neuronal responses')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n legend('BOLD','neuronal')\n \n str = sprintf('Simple Deconvolution: %s\\n',PPI.name);\n str = [str sprintf('VOI file: %s',PPI.xY.name)];\n \n%-Physiophysiologic interaction\n%--------------------------------------------------------------------------\nelseif numel(PPI.xY) == 2\n \n ax = subplot(2,1,1);\n plot(t,PPI.ppi)\n title('PPI')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n \n subplot(2,2,3)\n plot(t,PPI.Y(:,1),T,PPI.xn(:,1))\n title('hemodynamic and neuronal responses (1st)')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n legend('BOLD','neuronal')\n \n subplot(2,2,4)\n plot(t,PPI.P,T,PPI.xn(:,2))\n title('hemodynamic and neuronal responses (2nd)')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n legend('BOLD','neuronal')\n \n str = sprintf('Physiophysiologic Interaction: %s\\n',PPI.name);\n str = [str, sprintf('VOI File 1: %s\\n',PPI.xY(1).name)];\n str = [str, sprintf('VOI File 2: %s',PPI.xY(2).name)];\n \n%-Psychophysiologic interaction\n%--------------------------------------------------------------------------\nelseif isfield(PPI,'psy')\n \n PSY = zeros(N*NT,1);\n for i = 1:size(PPI.psy.u,2)\n PSY = PSY + full(PPI.psy.u(:,i)*PPI.psy.w(:,i));\n end\n \n ax = subplot(2,1,1);\n plot(t,PPI.Y,T,PPI.xn(:,1))\n title('hemodynamic and neuronal responses')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n legend('BOLD','neuronal')\n \n subplot(2,2,3)\n plot(T,PSY,'LineStyle','--','Color',[0 .65 0]);\n hold on\n plot(t,PPI.P,'LineStyle','-','LineWidth',1,'Color','b');\n hold off\n title('[convolved] psych. variable')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n \n subplot(2,2,4)\n plot(t,PPI.ppi)\n title('PPI')\n xlabel(['time (secs)'])\n axis tight square\n grid on\n \n str = sprintf('Psychophysiologic Interaction: %s\\n',PPI.name);\n str = [str, sprintf('VOI File: %s\\n',PPI.xY(1).name)];\n str = [str, sprintf('Factors: ')];\n for i = 1:numel(PPI.psy.name)\n str = [str, sprintf('%s [%0.0f]',PPI.psy.name{i},PPI.psy.w(i))];\n if i < numel(PPI.psy.name)\n str = [str, sprintf('; ')];\n end\n end\n \nelse\n error('Unknown PPI type.');\nend\n\nhAx = axes('Position',[0 0.90 1 0.1],...\n 'DefaultTextFontSize',FS(8),...\n 'DefaultTextInterpreter','None',...\n 'DefaultTextVerticalAlignment','Baseline',...\n 'Parent',Fgraph,...\n 'Units','points',...\n 'Visible','off');\nAxPos = get(hAx,'Position');\nset(hAx,'XLim',[0,AxPos(3)]); set(hAx,'YLim',AxPos(2)+[0,AxPos(4)])\ndy = FS(9);\nh = text(dy,floor(AxPos(2)+AxPos(4))-2*dy,str);\nset(h,'Parent',hAx);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_peb_ppi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.19016394028127234}} {"text": "%\n% a script to show and sample default colors on the X windows system\n% default colors are read from /usr/lib/X11/rgb.txt if it exists, else from myrgb.txt\n% see also ROIcmap\n%\n\nNmax = 2000;\nname(Nmax).s = '';\nname(Nmax).r = 0;\nname(Nmax).g = 0;\nname(Nmax).b = 0;\nif (exist('/usr/lib/X11/rgb.txt') == 2),\n Colname = '/usr/lib/X11/rgb.txt';\n fprintf(1,'Using %s\\n', Colname);\n ColFile = fopen (Colname,'r');\n %skip until first number\n tmp = fgets(ColFile);\n i = 0;\n while (tmp ~= -1 )\n tmp = zdeblank(tmp);\n if (afni_isdigit(tmp(1))),\n i = i + 1;\n [name(i).r,name(i).g,name(i).b,s1,s2,s3,s4] = strread(tmp,'%d%d%d %s %s %s %s');\n if (~isempty(s4)) name(i).s = sprintf('%s %s %s %s', char(s1), char(s2), char(s3), char(s4));\n elseif (~isempty(s3)) name(i).s = sprintf('%s %s %s', char(s1), char(s2), char(s3));\n elseif (~isempty(s2)) name(i).s = sprintf('%s %s', char(s1), char(s2));\n else name(i).s = char(s1);\n end\n end\n tmp = fgets(ColFile);\n end\n fclose (ColFile);\n N = i;\nelse\n ColFile = fopen ('myrgb.txt', 'r');\n Colname = 'myrgb.txt';\n fprintf(1,'Using %s\\n', Colname);\n N = 752;\n for (i=1:1:N),\n name(i).r = fscanf(ColFile, '%g ', 1);\n name(i).g = fscanf(ColFile, '%g ', 1);\n name(i).b = fscanf(ColFile, '%g ', 1);\n name(i).s = fgets(ColFile);\n end\n fclose (ColFile);\nend\n\nname = name(1:N);\n\n\n\nMall = zeros (N, 3);\nMall(:,1) = [name(:).r]';\nMall(:,2) = [name(:).g]';\nMall(:,3) = [name(:).b]';\nMall = Mall./255;\n\nif (0),\nfor (i=6:1:N-5),\n M = zeros (11,3);\n for (j=-5:1:5)\n M(j+6,1) = name(i+j).r./255;\n M(j+6,2) = name(i+j).g./255;\n M(j+6,3) = name(i+j).b./255;\n end\n colormap(M);\n subplot 211;\n\timage ([1:1:length(M(:,1))]);\n input ('Hit Enter:', 's');\nend\n\nend\nfigure(1), clf;\nsubplot (211);\nstr = sprintf('Colors in %s\\nPick colors (background then foreground) with mouse\\nHit \"enter\" to quit', Colname);\ncolormap(Mall); image ([1:1:N]); title (str, 'fontsize',14);\ndrawnow;\ni = 0;\nsubplot (269);cla\n\nx1 = 1;\nwhile (~isempty(x1)),\n [x1,y] = ginput (1);\n if (~isempty(x1)),\n x1 = floor(x1(1)-0.5)+1;\n subplot (269);\n addsquare([0 i], [2.5 1+i], Mall(x1,:)); hold on\n plot (-0.2, i+0.5, 'k*');\n axis ([-1 3 -1 11]);\n str = sprintf ('back: %s', name(x1).s);\n title (str);\n [x2,y] = ginput (1);\n x2 = floor(x2(1)-0.5)+1;\n subplot (269);\n str = sprintf ('SUMA (%g %g)', x1, x2 );\n ht = text (0.3, 0.3+i, 0, str, 'fontsize',14, 'color', Mall(x2,:));\n str = sprintf ('back: %s (%g), fore: %s (%g)', name(x1).s, x1, name(x2).s, x2);\n title (str);\n i = rem(i +1, 10);\n end\nend\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/afni/readXcol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.19005901843344739}} {"text": "classdef ExtremumValueConstraint < AbstractConstraint\n %ExtremumValueConstraint Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n normFact = 1;\n event LaunchVehicleEvent\n eventNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n extremum LaunchVehicleExtrema\n \n lb(1,1) double = 0;\n ub(1,1) double = 0;\n \n evalType(1,1) ConstraintEvalTypeEnum = ConstraintEvalTypeEnum.FixedBounds;\n stateCompType(1,1) ConstraintStateComparisonTypeEnum = ConstraintStateComparisonTypeEnum.Equals;\n stateCompEvent LaunchVehicleEvent\n stateCompNode(1,1) ConstraintStateComparisonNodeEnum = ConstraintStateComparisonNodeEnum.FinalState;\n end\n \n methods\n function obj = ExtremumValueConstraint(event, lb, ub)\n obj.event = event;\n obj.lb = lb;\n obj.ub = ub; \n \n obj.id = rand();\n end\n \n function [lb, ub] = getBounds(obj)\n lb = obj.lb;\n ub = obj.ub;\n end\n \n function [c, ceq, value, lwrBnd, uprBnd, type, eventNum, valueStateComp] = evalConstraint(obj, stateLog, celBodyData) \n type = obj.getConstraintType();\n \n switch obj.eventNode\n case ConstraintStateComparisonNodeEnum.FinalState\n stateLogEntry = stateLog.getLastStateLogForEvent(obj.event);\n \n case ConstraintStateComparisonNodeEnum.InitialState\n stateLogEntry = stateLog.getFirstStateLogForEvent(obj.event);\n \n otherwise\n error('Unknown event node.');\n end\n \n extremaStates = stateLogEntry.getAllExtremaStates();\n extremaState = extremaStates(extremaStates.extrema == obj.extremum);\n \n value = extremaState.value;\n \n if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n switch obj.stateCompNode\n case ConstraintStateComparisonNodeEnum.FinalState\n stateLogEntryStateComp = stateLog.getLastStateLogForEvent(obj.stateCompEvent);\n\n case ConstraintStateComparisonNodeEnum.InitialState\n stateLogEntryStateComp = stateLog.getFirstStateLogForEvent(obj.stateCompEvent);\n\n otherwise\n error('Unknown event node.');\n end\n \n extremaStates = stateLogEntryStateComp.getAllExtremaStates();\n extremaState = extremaStates(extremaStates.extrema == obj.extremum);\n\n valueStateComp = extremaState.value;\n else\n valueStateComp = NaN;\n end\n \n [c, ceq] = obj.computeCAndCeqValues(value, valueStateComp); \n \n lwrBnd = obj.lb;\n uprBnd = obj.ub;\n \n eventNum = obj.event.getEventNum();\n end\n \n function sF = getScaleFactor(obj)\n sF = obj.normFact;\n end\n \n function setScaleFactor(obj, sF)\n obj.normFact = sF;\n end\n \n function tf = usesStage(obj, stage)\n tf = false;\n end\n \n function tf = usesEngine(obj, engine)\n tf = false;\n end\n \n function tf = usesTank(obj, tank)\n tf = false;\n end\n \n function tf = usesEngineToTankConn(obj, engineToTank)\n tf = false;\n end\n \n function tf = usesEvent(obj, event)\n tf = obj.event == event;\n if(obj.evalType == ConstraintEvalTypeEnum.StateComparison)\n tf = tf || obj.stateCompEvent == event;\n end\n end\n \n function tf = usesStopwatch(obj, stopwatch)\n tf = false;\n end\n \n function tf = usesExtremum(obj, extremum)\n tf = [obj.extremum] == extremum;\n end\n \n function tf = canUseSparseOutput(obj)\n tf = false;\n end\n \n function event = getConstraintEvent(obj)\n event = obj.event;\n end\n \n function type = getConstraintType(obj)\n type = 'Extremum Value';\n end\n \n% function name = getName(obj)\n% name = sprintf('%s - Event %i', obj.getConstraintType(), obj.event.getEventNum());\n% end\n \n function [unit, lbLim, ubLim, usesLbUb, usesCelBody, usesRefSc] = getConstraintStaticDetails(obj)\n unit = obj.extremum.unitStr;\n lbLim = -Inf;\n ubLim = Inf;\n usesLbUb = true;\n usesCelBody = false;\n usesRefSc = false;\n end\n \n function addConstraintTf = openEditConstraintUI(obj, lvdData)\n% [listBoxStr, extrema] = lvdData.launchVehicle.getExtremaListBoxStr();\n% \n% if(isempty(extrema))\n% addConstraintTf = false;\n% \n% warndlg('Cannot create extrema value object: no extrema have been created. Create an extremum first.','Extremum Value Constraint','modal');\n% else\n% [Selection,ok] = listdlg('PromptString',{'Select an extremum:'},...\n% 'SelectionMode','single',...\n% 'Name','Extremum',...\n% 'ListString',listBoxStr);\n% \n% if(ok == 0)\n% addConstraintTf = false;\n% else\n% ex = extrema(Selection);\n% obj.extremum = ex;\n% \n% addConstraintTf = lvd_EditGenericMAConstraintGUI(obj, lvdData);\n% end\n% end\n\n ex = obj.selectConstraintObj(lvdData);\n \n if(not(isempty(ex)))\n obj.extremum = ex;\n% addConstraintTf = lvd_EditGenericMAConstraintGUI(obj, lvdData);\n\n output = AppDesignerGUIOutput({false});\n lvd_EditGenericMAConstraintGUI_App(obj, lvdData, output);\n addConstraintTf = output.output{1}; \n else\n addConstraintTf = false;\n end\n end\n \n function ex = selectConstraintObj(obj, lvdData)\n [listBoxStr, extrema] = lvdData.launchVehicle.getExtremaListBoxStr();\n\n ex = [];\n if(isempty(extrema)) \n warndlg('Cannot create extrema value object: no extrema have been created. Create an extremum first.','Extremum Value Constraint','modal');\n else\n [Selection,ok] = listdlg('PromptString',{'Select an extremum:'},...\n 'SelectionMode','single',...\n 'Name','Extremum',...\n 'ListString',listBoxStr);\n \n if(ok == 0)\n ex = [];\n else\n ex = extrema(Selection);\n end\n end\n end\n \n function useObjFcn = setupForUseAsObjectiveFcn(obj,lvdData)\n ex = obj.selectConstraintObj(lvdData);\n \n if(not(isempty(ex)))\n obj.extremum = ex;\n useObjFcn = true;\n else\n useObjFcn = false;\n end\n end\n end\n \n methods(Static)\n function constraint = getDefaultConstraint(~, ~) \n constraint = ExtremumValueConstraint(LaunchVehicleEvent.empty(1,0),0,0);\n end\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Optimization/constraints/@ExtremumValueConstraint/ExtremumValueConstraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19005901093492025}} {"text": "function [imVol, mmPerVox, gradDirs, bVals, xformToCannonical] = dtiAverageRawData(firstDataFile, gradsFile)\n% Intelligent averaging of diffusion-weighted images.\n%\n% [imVol, mmPerVox, gradDirs, bVals, xformToCannonical] = dtiAverageRawData(firstDataFile, gradsFile);\n%\n% Loads a whole directory of raw image files and combines them according to\n% the gradient direction information in gradsFile. All repeated\n% measurements are averaged. If coreg is true (default), it will also try\n% to align each b>0 image to the b=0 image using a 12-parameter\n% mutual-information algorithm (from SPM2). This should remove much of the\n% eddy-current distortion.\n%\n% Also returns the xform that will rotate the images into our cannonical\n% orientation (as close to axial as possible- see\n% computeCannonicalXformFromIfile).\n%\n% TODO:\n% * coreg should also do motion correction. To implement this, we need to\n% do the coregistration step before we combine the repeated measurements.\n% Of course, we should also correct the gradDirs for non-trivial motion.\n%\n%\n% HISTORY:\n% 2005.05.25: RFD (bob@sirl.stanford.edu) wrote it.\n%\n\nif(~exist('gradsFile','var')|isempty(gradsFile))\n % We could also try to infer the file based on info in the dicom\n % header.\n if(isunix)\n default = '/usr/local/dti/diffusion_grads/dwepi.13.grads';\n else\n default = pwd;\n end\n [f,p] = uigetfile({'*.grads';'*.*'},'Select dwepi grads file...',default);\n if(isequal(f,0)||isequal(p,0))\n error('User cancelled.');\n end\n gradsFile = fullfile(p,f);\nend\nif(~exist('firstDataFile','var')|isempty(firstDataFile))\n [f,p] = uigetfile({'*.dcm';'*.*'},'Select the first data file...');\n if(isequal(f,0)||isequal(p,0))\n error('User cancelled.');\n end\n firstDataFile = fullfile(p,f);\nend\n\n% Flag to turn on MI-based coregistration (eddy-current correction)\nif(~exist('coreg','var')|isempty(coreg))\n coreg = false;\nend\n\ngradDirs = dlmread(gradsFile);\nscannerToPhysXform = computeXformFromIfile(firstDataFile);\n[xformToCannonical, baseName, mmPerVox, imDim, notes, sliceSkip] = computeCannonicalXformFromIfile(firstDataFile);\n% *** TODO: may want to include im_hdr.scanspacing!\n%mmPerVox(3) = mmPerVox(3)+sliceSkip;\n\n% *** TODO: We assume that all non-zero b-vals are the same\nhdr = dicominfo(firstDataFile);\nbVals = hdr.Private_0019_10b0;\n\n% HACK! TO deal with our interleaved data:\nimDim(3) = imDim(3)*2;\n\n[dataDir,f,ext] = fileparts(firstDataFile);\nallFiles = dir(fullfile(dataDir, ['*' ext]));\nnDirs = size(gradDirs,1);\nnSlices = imDim(3);\nfilesPerRep = nDirs*nSlices;\nnReps = length(allFiles)/filesPerRep;\nif(nReps~=round(nReps))\n error('Non-integer number of repeats. Something is funky- refusing to go on...');\nend\n\n% TO DO: \n% * motion correction/outlier rejection\n%\ndisp('Loading all the data files...');\nimVol = zeros([imDim nDirs]);\nfor(d=1:nDirs)\n for(n=1:nReps)\n fn = [[1:nSlices]+(d-1)*nSlices+((n-1)*filesPerRep)];\n for s = 1:nSlices;\n curName = sprintf('I%04d.dcm', fn(s));\n tmpImg = readRawImage(fullfile(dataDir,curName), 0, nPix(1:2), 'b');\n imVol(:,:,s,d) = imVol(:,:,s,d)+double(tmpImg);\n end\n end\n %tmpIm = makeCubeIfiles(dataDir, nPix(1:2), fileNums);\nend\nimVol = imVol./nReps;\n\ndisp('Merging duplicate directions...');\n% Merge duplicates\n[gDirs,inds] = unique(gradDirs,'rows');\n% undo unique's sorting\ngDirs = gradDirs(sort(inds),:);\nnDirs = size(gDirs,1);\njunk= [];\nfor(ii=1:nDirs)\n dups = gDirs(ii,1)==gradDirs(:,1)&gDirs(ii,2)==gradDirs(:,2)& ...\n gDirs(ii,3)==gradDirs(:,3);\n dups = find(dups);\n if(length(dups)>1)\n imVol(:,:,:,dups(1)) = mean(imVol(:,:,:,dups),4);\n junk = [junk dups(2:end)];\n end\nend\nimVol(:,:,:,junk) = [];\n\nif(coreg)\n disp('Coregistering...');\n % NOTE: The following MI-based image registration tries to\n % coregister each direction map to the b0. It doen't seem to do\n % anything bad, but isn't particularly effective at removing the\n % eddy-current distortion. I guess it's not a 3d affine xform?\n % But, if we ran it on the individual images before averaging, it\n % would probably be a good way to remove motion.\n b0 = imVol(:,:,:,1);\n b0 = uint8(mrAnatHistogramClip(b0, 0.4, 0.99)*255+0.5);\n h = mrvWaitbar(0,'Performing eddy current correction...');\n for(d=2:nDirs)\n xf{d} = mrAnatRegister(imVol(:,:,:,d), b0);\n tmpIm = mrAnatResliceSpm(imVol(:,:,:,d),xf{d},[],[1 1 1],[7 7 7 0 0 0],0);\n tmpIm(isnan(tmpIm)) = 0;\n tmpIm(tmpIm<0) = 0;\n imVol(:,:,:,d) = tmpIm;\n mrvWaitbar(d/nDirs,h);\n end\n close(h);\nend\nimVol = int16(round(imVol));\nreturn;\n\n% Showing a movie (to see the image mis-alignment)\nfor(d=1:nDirs)\n f = squeeze(imVol(:,:,20,d));\n f = uint8(f./max(f(:)).*255+0.5);\n m(d) = im2frame(f,gray(256)); \nend\nfigure(99); \nimage(f); colormap(gray(256));\ntruesize; axis off\nmovie(m,1,5);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/file/dtiAverageRawData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.19001750036579487}} {"text": "%% Define the objective function.\naddpath(genpath(pwd()));\ncd AC_blackbox_eval/blackbox_eval_source/\nconfig_file = 'config_file.txt';\nnumRun = 1;\nscenario_file = 'scenario-lpsolve-CORLAT-inst.txt';\n[func, obj] = define_func_handle(config_file, scenario_file, numRun);\ncd ../..\n\n%% Optimize.\nyaml = 'lpsolve.yaml';\nmodel = highdim_opt(yaml, obj);", "meta": {"author": "ziyuw", "repo": "rembo", "sha": "7926c00a802ad33e7c7f61e3571a32bacaba3d00", "save_path": "github-repos/MATLAB/ziyuw-rembo", "path": "github-repos/MATLAB/ziyuw-rembo/rembo-7926c00a802ad33e7c7f61e3571a32bacaba3d00/demos/lpsolve/opt_lpsolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18998546820621814}} {"text": "%% --------------------------\n% DRRN_B1U9\n% -------------------------------\nfunction test_DRRN_B1U9()\nsetenv('LC_ALL','C')\naddpath /data2/taiying/MSU_Code/my_caffe/matlab; % change to your caffe path\nsetenv('GLOG_minloglevel','2')\naddpath('../');\naddpath('../evaluation_func/');\naddpath('../evaluation_func/matlabPyrTools-master/');\n\n%% parameters\ngpu_id = 2;\nup_scale = 3;\ndata_set_id = 1;\n\niter_interval = 6536;\nstartNUM = 71;\nendNUM = 71;\nthresh = 1;\nthresh_hei = 150; % threshold patch size for inference, since too big image may cost too much memory\nthresh_wid = 150;\nrf = 16;\n\npathfolder = ['../../data/'];\nif data_set_id == 1\n % Set5\n setTestCur = 'Set5';\n path = [pathfolder setTestCur '/'];\n d = dir([path '*.bmp']);\n filenum = 5;\nend\nif data_set_id == 2\n % Set14\n setTestCur = 'Set14';\n path = [pathfolder setTestCur '/'];\n d = dir([path '*.bmp']);\n filenum = 14;\nend\nif data_set_id == 3\n % B100\n setTestCur = 'B100';\n path = [pathfolder setTestCur '/'];\n d = dir([path '*.jpg']);\n filenum = 100;\nend\nif data_set_id == 4\n % Urban100\n setTestCur = 'Urban100';\n path = [pathfolder setTestCur '/'];\n d = dir([path '*.png']);\n filenum = 100;\nend\n\nsavepath = ['./results/'];\nfolderResultCur = fullfile(savepath, [setTestCur,'_x',num2str(up_scale)]);\n%%% folder to store results\nif ~exist(folderResultCur,'file')\n mkdir(folderResultCur);\nend\n\nmean_bicubic = [];\nmean_drrn = [];\n% caffe.set_mode_cpu(); % for CPU\ncaffe.set_mode_gpu(); % for GPU\ncaffe.set_device(gpu_id);\n\nfor NUM = startNUM:thresh:endNUM\n epochNUM = NUM*iter_interval;\n weights = ['../../model/DRRN_B1U9_20C128_iter_' num2str(epochNUM) '.caffemodel'];\n model_path = './DRRN_B1U9_20C128_deploy';\n \n bicubic_set =[];\n drrn_set = [];\n im_h_set = cell(filenum,1);\n im_gnd_set = cell(filenum,1);\n im_other_set = cell(6,1);\n scaleset = [];\n gatingset = [];\n \n for iii = 1:1:length(d) \n disp(['NUM: ' num2str(NUM) ' id: ' num2str(iii)]);\n imageName = d(iii).name;\n imageName = imageName(1:end-4);\n im = imread([path d(iii).name]);\n \n %% work on luminance only\n im_ycbcr= im;\n if size(im,3)>1\n im_ycbcr = rgb2ycbcr(im);\n im_cb = im2double(im_ycbcr(:, :, 2));\n im_cr = im2double(im_ycbcr(:, :, 3));\n im_cb_gnd = modcrop(im_cb, up_scale);\n im_cr_gnd = modcrop(im_cr, up_scale);\n im_cb_b = imresize(imresize(im_cb_gnd,1/up_scale,'bicubic'),up_scale,'bicubic');\n im_cb_b = single(im_cb_b);\n im_cr_b = imresize(imresize(im_cr_gnd,1/up_scale,'bicubic'),up_scale,'bicubic');\n im_cr_b = single(im_cr_b);\n end\n im_y = im2double(im_ycbcr(:, :, 1));\n im_y_gnd = modcrop(im_y, up_scale);\n \n [hei,wid] = size(im_y_gnd);\n im_y_b = imresize(imresize(im_y_gnd,1/up_scale,'bicubic'),up_scale,'bicubic');\n im_y_b = single(im_y_b);\n \n %% adaptively spilt\n % decide patch numbers\n hei_patch = ceil(hei/(thresh_hei+rf));\n wid_patch = ceil(wid/(thresh_wid+rf));\n hei_stride = ceil(hei/hei_patch);\n wid_stride = ceil(wid/wid_patch);\n use_start_x = 0;\n use_start_y = 0;\n use_end_x = 0;\n use_end_y = 0;\n \n ext_start_x = 0;\n ext_end_x = 0;\n ext_start_y = 0;\n ext_end_y = 0;\n \n posext_start_x = 0;\n posext_start_y = 0;\n posext_end_x = 0;\n posext_end_y = 0;\n \n % extract each patch for inference\n im_y_h = [];\n temp1 = [];\n temp2 = [];\n temp3 = [];\n temp4 = [];\n temp5 = [];\n temp6 = [];\n for x = 1 : hei_stride : hei\n for y = 1 : wid_stride : wid\n % decide the length of hei and wid for each patch\n use_start_x = x;\n use_start_y = y;\n if x - rf > 1 % add border\n ext_start_x = x-rf;\n posext_start_x = rf+1;\n else\n ext_start_x = x;\n posext_start_x = 1;\n end\n if y-rf > 1\n ext_start_y = y-rf;\n posext_start_y = rf+1;\n else\n ext_start_y = y;\n posext_start_y = 1;\n end\n \n use_end_x = use_start_x+hei_stride-1;\n use_end_y = use_start_y+wid_stride-1;\n \n \n if use_start_x+hei_stride+rf-1 <= hei\n hei_length = hei_stride+rf;\n ext_end_x = use_start_x+hei_length-1;\n posext_end_x = hei_length-rf+posext_start_x-1;\n \n else\n hei_length = hei-ext_start_x+1;\n ext_end_x = ext_start_x+hei_length-1;\n posext_end_x = hei_length;\n use_end_x = ext_start_x+hei_length-1;\n end\n if use_start_y+wid_stride+rf-1 <= wid\n wid_length = wid_stride+rf;\n ext_end_y = use_start_y+wid_length-1;\n posext_end_y = wid_length-rf+posext_start_y-1;\n \n else\n wid_length = wid-ext_start_y+1;\n ext_end_y = ext_start_y+wid_length-1;\n posext_end_y = wid_length;\n use_end_y = ext_start_y+wid_length-1;\n end\n \n subim_input = im_y_b(ext_start_x : ext_end_x, ext_start_y : ext_end_y); % input\n data = permute(subim_input,[2, 1, 3]);\n model = [model_path '.prototxt'];\n subim_output = do_cnn(model,weights,data);\n subim_output = subim_output';\n subim_output = subim_output(posext_start_x:posext_end_x,posext_start_y:posext_end_y);\n \n % fill im_h with sub_output\n im_y_h(use_start_x:use_end_x,use_start_y:use_end_y) = subim_output;\n \n end\n end\n \n %% remove border\n im_y_h1 = shave(uint8(single(im_y_h) * 255), [up_scale, up_scale]);\n im_y_gnd1 = shave(uint8(single(im_y_gnd) * 255), [up_scale, up_scale]);\n im_y_b1 = shave(uint8(single(im_y_b) * 255), [up_scale, up_scale]);\n \n if size(im,3) > 1\n im_cb_b1 = shave(uint8(single(im_cb_b) * 255), [up_scale, up_scale]);\n im_cr_b1 = shave(uint8(single(im_cr_b) * 255), [up_scale, up_scale]);\n ycbcr_h = cat(3,(im_y_h1),(im_cb_b1),(im_cr_b1));\n im_h1 = ycbcr2rgb(ycbcr_h);\n \n im_cb_gnd1 = shave(uint8(single(im_cb_gnd) * 255), [up_scale, up_scale]);\n im_cr_gnd1 = shave(uint8(single(im_cr_gnd) * 255), [up_scale, up_scale]);\n ycbcr_gnd = cat(3,(im_y_gnd1),(im_cb_gnd1),(im_cr_gnd1));\n im_gnd1 = ycbcr2rgb(ycbcr_gnd);\n else\n im_h1 = im_y_h1;\n im_gnd1 = im_y_gnd1;\n end\n im_h_set{iii} = im_h1;\n im_gnd_set{iii} = im_gnd1;\n \n %% save images\n imwrite(im_h1,fullfile(folderResultCur,[imageName,'_x',num2str(up_scale),'.png']));\n \n %% compute PSNR and SSIM and IFC\n bic(1) = compute_psnr(im_y_gnd1,im_y_b1);\n drrn(1) = compute_psnr(im_y_gnd1,im_y_h1);\n bic(2) = ssim_index(im_y_gnd1,im_y_b1);\n drrn(2) = ssim_index(im_y_gnd1,im_y_h1);\n bic(3) = ifcvec(double(im_y_gnd1),double(im_y_b1));\n drrn(3) = ifcvec(double(im_y_gnd1),double(im_y_h1));\n \n bicubic_set = [bicubic_set; bic];\n drrn_set = [drrn_set; drrn];\n end\n mean_bicubic = [mean_bicubic; [mean(bicubic_set(:,1)) mean(bicubic_set(:,2)) mean(bicubic_set(:,3))]];\n mean_drrn = [mean_drrn; [mean(drrn_set(:,1)) mean(drrn_set(:,2)) mean(drrn_set(:,3))]];\nend\n\n%%% save PSNR and SSIM metrics\nPSNR_set = drrn_set(:,1);\nSSIM_set = drrn_set(:,2);\nIFC_set = drrn_set(:,3);\nsave(fullfile(folderResultCur,['PSNR_',setTestCur,'_x',num2str(up_scale),'.mat']),['PSNR_set'])\nsave(fullfile(folderResultCur,['SSIM_',setTestCur,'_x',num2str(up_scale),'.mat']),['SSIM_set'])\nsave(fullfile(folderResultCur,['IFC_',setTestCur,'_x',num2str(up_scale),'.mat']),['IFC_set'])\n\ncount = 1;\nfor kk = startNUM:thresh:endNUM\n disp(['epoch: ' num2str(kk) '---- bic = ' num2str(mean_bicubic(count,:)) '---- DRRN = ' num2str(mean_drrn(count,:))]);\n count = count+1;\nend\n\nend\n \n\n\n", "meta": {"author": "tyshiwo", "repo": "DRRN_CVPR17", "sha": "cafe98bc73997c10947911de74279d63cb786b8a", "save_path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17", "path": "github-repos/MATLAB/tyshiwo-DRRN_CVPR17/DRRN_CVPR17-cafe98bc73997c10947911de74279d63cb786b8a/test/DRRN_B1U9_20C128/test_DRRN_B1U9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.18995625247969547}} {"text": "function [dim lf] = readBESAlft(filename, chanid)\n\n% readBESAlft reads the leadfield from the BESA leadfield file format.\n% The leadfield matrix and a vector with the leadfield dimensions are\n% returned.\n%\n% Parameters:\n% [filename]\n% In the case that the current folder is not the folder containing \n% the file it should be the full path including the name of the \n% lft file else only the name of the file should be specified. \n% \n% [chanid]\n% Additional parameter specifying particular channel for which\n% leadfield information should be returned.\n%\n% Return:\n% [dim] \n% Leadfield dimensions {, , }. Please note, in case that\n% the additional parameter is specified, the number of sensors will\n% be set to 1.\n% \n% [lf] \n% Leadfield matrix with rows and x columns. Each row\n% contains first the potentials for sources at all nodes in x-dir,\n% then for sources at all nodes in y-dir, and finally for all\n% nodes in z-dir.\n%\n% Copyright (C) 2013, BESA GmbH\n%\n% File name: readBESAlft.m\n%\n% Author: Benjamin Lanfer/Robert Spangler\n% Created: 2013-11-27\n\n\n% Check additional parameter\nif exist('chanid', 'var')\n % check if chanid is scalar\n if isscalar(chanid)\n % get leadfield info from specific channels\n else\n % error; only scalar values allowed for chanid\n error('Parameter chanid is not a scalar value!');\n end;\nelse\n % get leadfield info all channels\n chanid = [];\nend;\n\n% Try to open file.\nFileID = fopen(filename, 'rb');\nif(FileID < 0)\n\tfprintf('Error opening file.\\n');\n\treturn\nend\n\n% Read version number (int32)\n[VersionNumber NrReadElements] = fread(FileID, 1, 'int32');\nif(NrReadElements ~= 1)\n\tfprintf('Could not read number of elements.\\n');\n\treturn\nend\n\n% Check version number\nExpectedVersionNumber = 1;\nif(VersionNumber ~= ExpectedVersionNumber)\n\tfprintf('Wrong version number. Expected: %d, read %d.\\n', ExpectedVersionNumber, ...\n\t\tVersionNumber);\n\treturn\nend\n\n% Read number of sensors (int32)\n[NumberSensors NrReadElements] = fread(FileID, 1, 'int32');\nif(NrReadElements ~= 1)\n\tfprintf('Could not read number of sensors.\\n');\n\treturn\nend\n\n% In case the leadfield for one specific channel has to be returned, check\n% if chanid is in correct range.\nif ~isempty(chanid)\n if ((chanid > NumberSensors) ||...\n (chanid < 1))\n % error; chanid out of range\n error('Parameter chanid is out of range!'); \n end;\nend;\n\n% Read number of source space nodes (int32)\n[NumberSourceSpaceNodes NrReadElements] = fread(FileID, 1, 'int32');\nif(NrReadElements ~= 1)\n\tfprintf('Could not read number of source space nodes.\\n');\n\treturn\nend\n\n% Read number of source directions per node (int32)\n[NumberDirections NrReadElements] = fread(FileID, 1, 'int32');\nif(NrReadElements ~= 1)\n\tfprintf('Could not read number of source directions.\\n');\n\treturn\nend\n\n% Read maximum LF values for each source (source nodes x directions) (float32)\nNumberColumns = NumberDirections * NumberSourceSpaceNodes;\n[MaxVals NrReadElements] = fread(FileID, NumberColumns, 'float32');\nif(NrReadElements ~= NumberColumns)\n\tfprintf('Could not read maximum leadfield values from file.\\n');\n\treturn\nend\n\nif ~isempty(chanid)\n % Get leadfield for specific channel only\n lf = [];\n NumberSensors = 1;\n \n % Go to correct position in file where leadfield info for current\n % channel is stored\n NumSkippedBytes = (chanid-1)*NumberSourceSpaceNodes*NumberDirections*2;\n status = fseek(FileID, NumSkippedBytes, 0);\n if status ~= 0\n error('Unable to move to specified position in file.');\n end;\n\n % Read compactly stored LF values for channel #chanid (int16)\n NumberLFValues = NumberColumns * 1;\n [CompactLFVals NrReadElements] = fread(FileID, NumberLFValues, 'int16');\n if(NrReadElements ~= NumberLFValues)\n fprintf('Could not read leadfield values from file.\\n');\n return\n end\n \nelse\n % Get leadfield for all channels\n\n % Read compactly stored LF values (int16)\n NumberLFValues = NumberColumns * NumberSensors;\n [CompactLFVals NrReadElements] = fread(FileID, NumberLFValues, 'int16');\n if(NrReadElements ~= NumberLFValues)\n fprintf('Could not read leadfield values from file.\\n');\n return\n end\nend\n\n% Reshape matrix with compact LF values.\nCompactLFVals = reshape(CompactLFVals, NumberColumns, NumberSensors);\nCompactLFVals = CompactLFVals';\n\n% Compute factors for converting compactly stored LF values\n% to float values.\nConversionFactors = MaxVals / 32767.0;\n\n% Clear superfluous parameters\nclear('MaxVals');\n\n% Convert compact LF values to float.\n%lf = CompactLFVals * repmat(ConversionFactors, 1, NumberColumns);\n\n% NOTE RS:\n% * operator in line %lf = CompactLFVals * repmat(...) is a real\n% matrix multiplication, not a scalar multiplication. Is this intended?\n\n% NOTE RS:\n% Use alternative conversion of compact LF values to float LF\n% values due to the extrem memory consumption of the repmat function:\nfor iCol=1:NumberColumns\n CompactLFVals(:,iCol) = CompactLFVals(:,iCol)*ConversionFactors(iCol);\nend\nlf = CompactLFVals;\n\n% Copy dimensions.\ndim = [NumberSensors; NumberSourceSpaceNodes; NumberDirections];\n\n% Close file.\nfclose(FileID);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/besa/readBESAlft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.18985858565612165}} {"text": "function [m, bl] = model_add_block(m, varargin);\n% Add a block of parameters to the model.\n% [m, bl] = model_add_block(m, varargin)\n%\n% Return values\n% m Updated model\n%\n% Arguments\n% m Model to update\n% varargin (key, value) pairs that can specify the following:\n% key value\n% --- -----\n% reg_mult Block regularization cost\n% learn 0 => parameters are not learned; 1 => they are learned\n% lower_bounds Lower-bound box contraints for each parameter in this block\n% shape Dimensions of this block (e.g., [6 6 32])\n% w Block parameter values\n% type Block type from the block_type enumeration\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2009-2012 Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nvalid_opts = {'reg_mult', 'learn', 'lower_bounds', 'shape', 'w', 'type'};\nopts = getopts(varargin, valid_opts);\n\n% OPT: w\nif opts.isKey('w')\n w = opts('w');\nelse\n w = [];\nend\n\n% OPT: shape\nif opts.isKey('shape')\n shape = opts('shape');\n if isempty(w)\n w = zeros(prod(shape), 1);\n end\nelse\n shape = size(w);\nend\n\n% Dimension of the block's parameter vector\ndim = prod(shape);\n\n% OPT: reg_mult\nif opts.isKey('reg_mult')\n reg_mult = opts('reg_mult');\nelse\n reg_mult = 1;\nend\n\n% OPT: learn\nif opts.isKey('learn')\n learn = opts('learn');\nelse\n learn = 1;\nend\n\n% OPT: lower_bounds\nif opts.isKey('lower_bounds')\n lower_bounds = opts('lower_bounds');\nelse\n lower_bounds = -inf*ones(dim, 1);\nend\n\n% OPT: type\nif opts.isKey('type')\n btype = opts('type');\nelse\n btype = block_types.Other;\nend\n\n% Sanity checks\nassert(~isempty(w));\nassert(numel(w) == dim);\nassert(size(lower_bounds,1) == dim);\n\n% Allocate new block \nbl = m.numblocks + 1;\nm.numblocks = bl;\n\n% Install block\nm.blocks(bl).w = w(:);\nm.blocks(bl).lb = lower_bounds;\nm.blocks(bl).learn = learn;\nm.blocks(bl).reg_mult = reg_mult;\nm.blocks(bl).dim = dim;\nm.blocks(bl).shape = shape;\nm.blocks(bl).type = btype;\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/model/model_add_block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.18985857857061667}} {"text": "function deformation_field = PTKSolveMatchedImagesForFluidRegistration(image_to_transform, reference_image, reporting)\n % PTKSolveMatchedImagesForFluidRegistration. \n %\n %\n % Licence\n % -------\n % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n % Author: Tom Doel, 2012. www.tomdoel.com\n % Distributed under the GNU GPL v3 licence. Please see website for details.\n %\n\n MimImageUtilities.MatchSizes(reference_image, image_to_transform);\n \n if ~isequal(image_to_transform.VoxelSize, reference_image.VoxelSize)\n reporting.Error('SolveMatchedImagesForFluidRegistration:UnequalVoxelSize', 'SolveMatchedImagesForFluidRegistration requires images to have the same voxel size');\n end\n \n % Convert to distance transforms\n dt_float = PTKRunForEachComponentAndCombine(@MimImageUtilities.GetNormalisedDT, image_to_transform, image_to_transform, reporting);\n dt_ref = PTKRunForEachComponentAndCombine(@MimImageUtilities.GetNormalisedDT, reference_image, reference_image, reporting);\n \n % Solve to find the deformation field between these images\n [deformation_field, ~] = Solve(dt_float, dt_ref, reporting);\nend\n\nfunction [deformation_field, deformed_image] = Solve(image_1, image_2, reporting)\n deformation_field = image_2.BlankCopy;\n deformed_image = image_2.BlankCopy;\n voxel_size = image_2.VoxelSize;\n if ~isequal(voxel_size, image_1.VoxelSize)\n reporting.Error('PTKGetFluidDeformationField:DifferentVoxelSizes', 'Images must have the same voxel size');\n end\n if ~isequal(image_1.ImageSize, image_2.ImageSize)\n reporting.Error('PTKGetFluidDeformationField:DifferentVoxelSizes', 'Images must have the same image size');\n end\n \n if PTKSoftwareInfo.ShowRegistrationConvergence\n display_value = 'iter';\n else\n display_value = 'off';\n end\n iterations = 200;\n % X corresponds to image columns and Y image rows\n options = npRegSet(...\n 'Display', display_value, ...\n 'Regularizer', 'curvature', ... % elastic | {fluid} | diffusion | curvature\n 'BoundaryCond', 'Neumann', ...\n 'VoxSizeX', voxel_size(2),'VoxSizeY', voxel_size(1), 'VoxSizeZ', voxel_size(3), ...\n 'maxiter', iterations, ...\n 'RegularizerFactor', 1,...\n 'BodyForceTol', PTKSoftwareInfo.RegistrationBodyForceTol, ... % Termination tolerance on the body force [1e-2]\n 'BodyForceDiffTol', PTKSoftwareInfo.RegistrationBodyForceDiffTol, ... % Termination tolerance on the difference between successive body force estimates [1e-2]..\n 'SimMeasPercentDiffTol', 0.001, ... % Termination tolerance on the percentage difference between successive similarity measure estimates [ positive scalar {1e-2} ]\n 'FixedPointMaxFlowDistance', 5 ...\n);\n\n% 'SimilarityMeasure', 'SSD', ... % [ {SSD} | NCC | CR | MI | NMI ]\n%UDiffTol - Fixed point iteration termination tolerance on the maximum sum \n% of squared differences between successive displacement field \n% estimates [ positive scalar {1e-2} ]\n%UDiffTol - Fixed point iteration termination tolerance on the maximum sum \n% of squared differences between successive velocity field estimates\n% [ positive scalar {1e-2} ]\n%SimMeasTol - Fixed point iteration termination tolerance on the similarity\n% measure [ positive scalar {1e-2} ]\n%SimMeasDiffTol - Fixed point iteration termination tolerance on the\n% difference between successive similarity measure estimates\n% [ positive scalar {1e-2} ]\n%SimMeasPercentDiffTol - Fixed point iteration termination tolerance on\n% the percentage difference between successive similarity measure\n% estimates [ positive scalar {1e-2} ]\n%FixedPointMaxFlowDistance - Maximum distance (in voxels) that the\n% deformation field is allowed to flow during each fixed point\n% iteration [ positive scalar {5.0} ]\n%RegridTol - Tolerance on the Jacobian of the deformation field, below which\n% regridding will take place [ positive scalar {0.0025} ]\n%Mu - Lame constant for use with elastic or fluid regularizers\n% [ positive scalar {1.0} ]\n%Lambda - Lame constant for use with elastic or fluid regularizers\n% [ nonnegative scalar {0.0} ]\n [deformed_image_raw, deformation_field_raw, exit_flag] = npReg(image_2.RawImage, image_1.RawImage, options);\n deformed_image.ChangeRawImage(deformed_image_raw);\n \n if (exit_flag ~= 1)\n reporting.ShowWarning('PTKGetFluidDeformationField:RegistrationDidNotConverge', 'npReg registration did not converge.', []);\n end\n \n translation = (image_2.Origin - image_1.Origin).*image_2.VoxelSize;\n deformation_field_raw(:,:,:,1) = deformation_field_raw(:,:,:,1) + translation(1);\n deformation_field_raw(:,:,:,2) = deformation_field_raw(:,:,:,2) + translation(2);\n deformation_field_raw(:,:,:,3) = deformation_field_raw(:,:,:,3) + translation(3);\n \n deformation_field.ChangeRawImage(deformation_field_raw);\nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Registration/PTKSolveMatchedImagesForFluidRegistration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.18983084349040577}} {"text": "function F = cut(varargin)\n%CUT Defines a cut constraint\n% \n% The syntax for CUT is exactly the same as the\n% syntax for ordinary constraints. \n%\n% The difference between a ordinary constraint and \n% a cut constraint is that the CUT will not be used\n% in the solution of the upper bound problem in a\n% global solver, but only in the relaxation for the \n% lower problem.\n\nswitch nargin\ncase 0\n F = lmi;\ncase 1\n F = lmi(varargin{1});\ncase 2\n F = lmi(varargin{1},varargin{2});\ncase 3\n F = lmi(varargin{1},varargin{1},varargin{3});\notherwise\nend\n \nF = setcutflag(F);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/cut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18949865165309507}} {"text": "function binary_image = PTKSkeletonise(binary_image, fixed_points_global, reporting)\n % PTKSkeletonise. Performs a skeletonisation on a segmented airway tree.\n %\n %\n %\n % Licence\n % -------\n % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n % Author: Tom Doel, 2012. www.tomdoel.com\n % Distributed under the GNU GPL v3 licence. Please see website for details.\n % \n\n if ~isa(binary_image, 'PTKImage')\n error('Requires a PTKImage as input');\n end\n \n if ~exist('reporting', 'var')\n reporting = CoreReportingDefault;\n end\n \n if isdeployed || exist('PTKFastIsSimplePoint') == 3 %#ok\n use_mex_simple_point = true;\n else\n use_mex_simple_point = false;\n warning_message = 'Could not find compiled mex file PTKFastIsSimplePoint. Using a slower version PTKIsSimplePoint instead. Increase program speed by running mex PTKFastIsSimplePoint.cpp in the mex folder.';\n reporting.ShowWarning('PTKSkeletonise:PTKFastIsSimplePointnotFound', warning_message, []);\n end\n \n fixed_points = binary_image.GlobalToLocalIndices(fixed_points_global);\n \n % Marks endpoints with 3\n binary_image = binary_image.Copy;\n binary_image.ChangeRawImage(MarkEndpoints(binary_image.RawImage, fixed_points));\n total_number_of_points = sum(binary_image.RawImage(:) > 0);\n\n binary_image.AddBorder(2);\n direction_vectors = CalculateDirectionVectors;\n \n raw_image = binary_image.RawImage;\n\n previous_image = zeros(size(raw_image), 'uint8');\n\n iteration = 0;\n \n while ~isequal(previous_image, raw_image)\n previous_image = raw_image;\n \n iteration = iteration + 1;\n if (iteration > 20)\n if isempty(reporting)\n error('Maximum number of iterations exceeded. This can occur if not all the airway endpoints have been specified correctly.');\n else\n reporting.Error('PTKSkeletonise:MaximumIterationsExceeded', 'Maximum number of iterations exceeded. This can occur if not all the airway endpoints have been specified correctly.');\n end\n end\n \n\n % For each of the 6 principal directions\n for direction = [5, 23, 11, 17, 13, 15]\n \n if ~isempty(reporting)\n number_remaining_points = sum(raw_image(:) > 0);\n progress_value = round(100*(1-number_remaining_points/total_number_of_points));\n reporting.UpdateProgressAndMessage(progress_value, ['Skeletonisation: Iteration ' int2str(iteration)]);\n end\n \n if ~isempty(reporting)\n if reporting.HasBeenCancelled\n error('User cancelled');\n end\n end\n \n direction_vector = direction_vectors(direction,:);\n i = direction_vector(1);\n j = direction_vector(2);\n k = direction_vector(3);\n \n % Detect border points and get their indices\n [b_i, b_j, b_k] = ind2sub(size(raw_image) - [2 2 2], ...\n find((1 == raw_image(2:end-1, 2:end-1, 2:end-1)) & (0 == raw_image(2+i:end-1+i,2+j:end-1+j,2+k:end-1+k))));\n b_i = b_i + 1; b_j = b_j + 1; b_k = b_k + 1;\n \n % Iterate through each border point and delete (set to zero) if\n % it is a simple point\n for i = 1 : length(b_i)\n raw_image(b_i(i), b_j(i), b_k(i)) = ~IsPointSimple(raw_image, b_i(i), b_j(i), b_k(i), use_mex_simple_point);\n end\n end\n end\n binary_image.ChangeRawImage(raw_image);\n binary_image.RemoveBorder(2);\nend\n\nfunction is_simple = IsPointSimple(binary_image, i, j, k, use_mex_simple_point)\n if use_mex_simple_point\n % MEX function (fast)\n is_simple = PTKFastIsSimplePoint((binary_image(i-1:i+1, j-1:j+1, k-1:k+1)));\n else\n % Matlab function (slow)\n is_simple = PTKIsSimplePoint(binary_image(i-1:i+1, j-1:j+1, k-1:k+1));\n end\nend\n\nfunction binary_image = MarkEndpoints(binary_image, fixed_points) \n binary_image = int8(binary_image ~= 0);\n binary_image(fixed_points) = 3;\nend\n\n\nfunction direction_vectors = CalculateDirectionVectors\n [i, j, k] = ind2sub([3 3 3], 1 : 27);\n direction_vectors = [i' - 2, j' - 2, k' - 2];\nend", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Airways/PTKSkeletonise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949864441711325}} {"text": "function rgb = yellow\n\n% This returns a predefined color as [red green blue] values\n% red = [255 0 0]/255;\n% green = [ 0 192 0]/255;\n% blue = [ 0 0 255]/255;\n% magenta = [255 255 0]/255;\n% cyan = [ 0 255 255]/255;\n% yellow = [255 255 0]/255;\n% white = [255 255 255]/255;\n% black = [ 0 0 0]/255;\n%\n% skull = [140 85 85]/255\n% cortex = [255 213 119]/255;\n% cortex_light = [199 194 169]/255;\n% cortex_dark = [100 97 85]/255;\n% skin = [249 223 192]/255;\n% skin_light = [249 223 192]/255;\n% skin_medium_light = [225 194 158]/255;\n% skin_medium = [188 142 106]/255;\n% skin_medium_dark = [155 102\t65]/255;\n% skin_dark = [ 91 71 61]/255;\n\nrgb = [255 255 0]/255;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/yellow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18945048798577616}} {"text": "report_this_filefun(mfilename('fullpath'));\n\nR = 0.3:1:20;\nTw = 0.1:0.1:4.5;\naa = a;\n\n%maepi = [ -116.5 34.25 1992.48 6 6 7.2 10 ];\nM = zeros(length(R),length(Tw))*nan; i1 = 0; i2 = 0;\nmaepi(1,3) = 1992.48;\nan = maepi(1,:);\ny = an(1,2),x = an(1,1); z = an(:,7); Te = an(:,3);\n%figure_w_normalized_uicontrolunits(map)\naxes(hs);\n[x,y] = ginput(1)\nTe = max(a.Date)\nz = 5\n\nl = a.Date < Te;\na = a.subset(l);\n\n\ndT = max(a.Date) - min(a.Date);\ndi = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2 + (a.Depth-z).^2) ;\n\n\nN =[];\nfor i1 = 1:1:length(R)\n ;\n % take first ni points\n %\n l = di <= R(i1);\n b = a.subset(l); % ne\n for i2 = 1:1:length(Tw)\n\n l = b(:,3) >= Te-Tw(i2) & b(:,3) < Te;\n Q = length(b(l,3)) ; % This is the annual rate\n B = length(b(:,1))*Tw(i2)/dT;\n P = poisscdf(Q,B);\n\n\n M(i1,i2) = P;\n\n end\n N =[N ; length(b)];\n i2 = 0;\nend\ni1 = 0;\n\n% plot the results\nplotqmatri;\n\na = aa;\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/orphaned/src/qmatri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18939741231547594}} {"text": "classdef RigidJoint < CoordinateFrame\n % A coordinate frame that is rigidly attached to the origin a rigid\n % joint and the child link of the joint. In addition, this class stores\n % the type, rotation axis, child link, and limit of the rigid joints.\n %\n % Copyright (c) 2016-2017, AMBER Lab\n % All right reserved.\n %\n % Redistribution and use in source and binary forms, with or without\n % modification, are permitted only in compliance with the BSD 3-Clause\n % license, see\n % http://www.opensource.org/licenses/bsd-license.php\n \n \n properties (SetAccess=protected, GetAccess=public)\n % The type of the rigid joint\n %\n % @note valid joint types include: \n % revolute, prismatic, continuous, fixed.\n %\n % @type char\n Type\n \n % The rotation axis vector of the rigid joint\n %\n % @note it must be a 3x1 vector.\n %\n % @type rowvec\n Axis\n \n % The name of the child link\n %\n % @type char\n Child\n \n % The name of the parent link\n %\n % @type char\n Parent\n \n % A structure data stores the physical limits of the rigid joints\n %\n % Required fields of limit:\n % effort: the maximum actuator effort @type double\n % lower: the minimum allowable displacement @type double\n % upper: the maximum allowable displacement @type double\n % velocity: the maximum allowable velocity @type double\n % \n % @type struct \n Limit\n \n % A structure contains information about the actuator for the joint\n %\n % An empty property indicates the joint is not actuated.\n %\n % @type struct\n Actuator\n \n end\n \n properties (Hidden, SetAccess=protected, GetAccess=public)\n \n % The indices of kinematic chains from the base to the current\n % joint\n %\n % @type rowvec\n ChainIndices\n \n % The twist from the base frame\n %\n % @type rowvec\n Twist\n \n % The twist pairs of all precedent joints (coordinate frame)\n %\n % @type SymExpression\n TwistPairs\n end\n methods\n \n function obj = RigidJoint(varargin)\n % The class constructor function\n %\n % Parameters:\n % varargin: variable nama-value pair input arguments, in detail:\n % Name: the name of the frame @type char\n % Reference: the reference frame @type CoordinateFrame\n % Offset: the offset of the origin @type rowvec\n % R: the rotation matrix or the Euler angles @type rowvec\n % Axis: the rotation axis vector @type rowvec\n % Type: the type of the joints @type char\n % Child: the child link frame @type RigidLink\n % Limit: the joint physical limits @type struct\n \n \n \n \n % consruct the superclass object first\n obj = obj@CoordinateFrame(varargin{:});\n if nargin == 0\n return;\n end\n argin = struct(varargin{:});\n \n % validate and assign the joint type\n if isfield(argin, 'Type') && ~isempty(argin.Type)\n obj = obj.setType(argin.Type);\n else\n error('The joint type is not defined.');\n end\n \n % validate and assign the joint axis \n if isfield(argin, 'Axis') && ~isempty(argin.Axis)\n obj = obj.setAxis(argin.Axis);\n elseif strcmp(obj.Type, 'fixed')\n obj = obj.setAxis([0,0,1]);\n else\n error('The joint rotation axis is not defined.');\n end\n \n \n % validate and assign the child link\n if isfield(argin, 'Child') && ~isempty(argin.Child)\n obj = obj.setChild(argin.Child);\n else\n error('The child link is not defined.');\n end\n \n % validate and assign the parent link\n if isfield(argin, 'Parent') && ~isempty(argin.Parent)\n obj = obj.setParent(argin.Parent);\n else\n error('The parent link is not defined.');\n end\n \n % validate and assign the physical limits\n if isfield(argin, 'Limit') && ~isempty(argin.Limit)\n obj = obj.setLimit(argin.Limit);\n else\n warning('The joint limits are not defined. Using default values.');\n default_limit = struct(...\n 'effort',0,...\n 'lower',-inf,...\n 'upper',inf,...\n 'velocity',inf);\n obj = obj.setLimit(default_limit);\n end\n \n % validate and assign the actuator info\n if isfield(argin, 'Actuator') && ~isempty(argin.Actuator)\n obj = obj.setActuator(argin.Actuator);\n end\n end\n \n end\n \n %% methods defined in external files\n methods\n obj = setAxis(obj, axis);\n \n obj = setType(obj, type);\n \n obj = setParent(obj, parent);\n \n obj = setChild(obj, child);\n \n obj = setLimit(obj, varargin);\n \n obj = setActuator(obj, varargin);\n \n obj = setChainIndices(obj, indices);\n \n xi = getTwist(obj);\n \n obj = computeTwist(obj);\n \n obj = setTwistPairs(obj, dofs, q);\n end\nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/matlab/robotics/@RigidJoint/RigidJoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.18939741100233465}} {"text": "function [value,isterminal,direction,eventDesc] = ma_NodeEvents(T,Y, node, bodyInfo, refBody, celBodyData)\n if(strcmpi(T, 'getInfo'))\n value = node;\n isterminal = bodyInfo;\n direction = refBody;\n eventDesc = [];\n \n return\n end\n \n if(~isempty(refBody) && bodyInfo.id ~= refBody.id)\n value = [];\n isterminal = [];\n direction = [];\n eventDesc = {};\n \n return\n end\n \n rVectECI = Y(1:3);\n \n topLevelBodyInfo = getTopLevelCentralBody(celBodyData);\n bodyInfoSun = topLevelBodyInfo;\n [rVectECI,vVectECI] = getAbsPositBetweenSpacecraftAndBody(T, rVectECI, bodyInfoSun, bodyInfo, celBodyData);\n \n [lat, ~, ~] = getLatLongAltFromInertialVect(T, -rVectECI, bodyInfo, vVectECI);\n \n value = lat;\n isterminal = 1;\n \n if(strcmpi(node,'asc'))\n direction = 1;\n else\n direction = -1;\n end\n \n eventDesc = [upper(node), ' Node'];\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/nbody_coast/events/ma_NodeEvents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18939739482348916}} {"text": "function cascade_data(model, data_year, pca)\n\n% cascade_data(model, data_year, pca)\n%\n% Compute score statistics for filters and deformation models\n% using the model and training data associated with the model\n% and dataset year 'data_year'. If PCA is given a value > 0, then\n% the score statistics are computed using a PCA projection of the\n% model and training data.\n%\n% The score statistics are written in to the file \n% class_year_cascade_data_pcaK_data_year.inf, which is used \n% by cascade_model.m.\n%\n% model object detector\n% data_year dataset year as a string (e.g., '2007')\n% pca number of PCA components to project onto (if pca > 0)\n\nsetVOCyear = model.year;\nglobals;\npascal_init;\n\n% if using PCA, project the model\nif pca > 0\n load('pca.mat');\n [ignore, model] = projectmodel(model, coeff, pca);\nend\n\n% files used by scorestat.cc\npca_str = num2str(pca);\nclass_year = [model.class '_' model.year];\ndetfile = [cscdir class_year '_cascade_data_det_' data_year '.inf'];\ninffile = [cscdir class_year '_cascade_data_pca' pca_str '_' data_year '.inf'];\n\n% load training images\npos = pascal_data(model.class, true, data_year);\nif pca == 0\n % file for recording the detection location and component of each detection\n detfid = fopen(detfile, 'w');\n validinfo = [];\nelse\n % read the detection location and component used for each detection by the\n % non-PCA model\n pattern = ['%n%n%n' repmat('%n', 1, model.numblocks)];\n detfid = fopen(detfile);\n D = textscan(detfid, '%d %d %d %d %d', 'Delimiter', ' ');\n fclose(detfid);\n validinfo = [D{2} D{3} D{4} D{5}];\nend\n\n% reserve an int at the beginning of the file\ninffid = fopen(inffile, 'wb');\nfwrite(inffid, 0, 'int32');\n% compute detections on training images\nnum = process(model, pos, validinfo, pca, detfid, inffid);\n% rewind and write sample size\nfrewind(inffid);\nfwrite(inffid, num, 'int32');\nfclose(inffid);\nif pca == 0\n fclose(detfid);\nend\nfprintf('Wrote score statistics for %d examples.\\n', num);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Write detection info file and detection feature vector file.\nfunction num = process(model, pos, validinfo, pca, detfid, inffid)\n\nnumpos = length(pos);\npixels = model.minsize * model.sbin;\nminsize = prod(pixels);\n\nnum = 0;\nbatchsize = 16;\n% process positive examples in parallel batches\nfor j = 1:batchsize:numpos\n % do batches of detections in parallel\n thisbatchsize = batchsize - max(0, (j+batchsize-1) - numpos);\n % data for this batch\n pardata = {};\n parfor k = 1:thisbatchsize\n i = j+k-1;\n fprintf('%s %s: cascade data (PCA=%d): %d/%d', procid(), model.class, pca, i, numpos);\n bbox = [pos(i).x1 pos(i).y1 pos(i).x2 pos(i).y2];\n valid = struct('c',0,'x',0,'y',0,'l',0);\n % skip small examples\n if (bbox(3)-bbox(1)+1)*(bbox(4)-bbox(2)+1) < minsize\n pardata{k}.det = [];\n if pca == 0\n pardata{k}.detinfo = valid;\n end\n fprintf(' (too small)\\n');\n continue;\n end\n % get example\n im = imreadx(pos(i));\n [im, bbox] = croppos(im, bbox);\n pyra = featpyramid(im, model);\n if pca > 0\n pyra = projectpyramid(model, pyra);\n valid.c = validinfo(i,1);\n valid.x = validinfo(i,2);\n valid.y = validinfo(i,3);\n valid.l = validinfo(i,4);\n end\n [det, boxes, info] = gdetectvalid(pyra, model, 0, bbox, 0.5, valid);\n pardata{k}.detinfo = getdetinfo(model, info);\n pardata{k}.det = det;\n pardata{k}.boxes = boxes;\n pardata{k}.info = info;\n pardata{k}.pyra = pyra;\n\n if ~isempty(det)\n fprintf(' (%f)\\n', det(end));\n num = num + 1;\n %showboxes(im, det);\n else\n fprintf(' (skip)\\n');\n end\n end\n % write data to disk sequentially\n for k = 1:thisbatchsize\n i = j+k-1;\n if ~isempty(pardata{k}.det)\n writescores(pardata{k}.pyra, model, pardata{k}.info, inffid);\n end\n if pca == 0\n % record the detection location and component for this detection \n detinfo = pardata{k}.detinfo;\n fprintf(detfid, '%d %d %d %d %d\\n', ...\n i, detinfo.c, detinfo.x, detinfo.y, detinfo.l);\n end\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Retrieve the (x,y,scale) location of the detection in feature\n% pyramid coordinates.\nfunction d = getdetinfo(model, info)\n\nd.c = 0;\nd.x = 0;\nd.y = 0;\nd.l = 0;\n\nif ~isempty(info)\n % See: gdetectwrite.m and getdetections.cc\n DET_IND = 2; % rule index (i.e. component number)\n DET_X = 3; % x coord (filter and deformation)\n DET_Y = 4; % y coord (filter and deformation)\n DET_L = 5; % level (filter)\n\n ruleind = info(DET_IND, model.start, 1);\n d.c = ruleind;\n d.x = info(DET_X, model.start, 1);\n d.y = info(DET_Y, model.start, 1);\n d.l = info(DET_L, model.start, 1);\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/star-cascade-master/cascade_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18932355014276117}} {"text": "% Copyright 2011 Zdenek Kalal\n%\n% This file is part of TLD.\n% \n% TLD 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% TLD 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 TLD. If not, see .\n\nfunction source = tldInitFirstFrame(tld,source,min_win)\n\n% load the first frame into memory\nsource.im0 = img_get(source,source.idx(1));\n\n% set the initial bounding box: \n% - from file\nif source.camera == 0 && exist([source.input '/init.txt'],'file')\n bb = dlmread([source.input '/init.txt']);\n source.bb = bb(:);\n \n % check\n if isempty(source.bb) || min(bb_size(source.bb)) < min_win\n exit('Error: bounding box is incorrectly defined or too small');\n end\n% - by mouse \nelse\n source.bb = bb_click(tld,source.im0.input);\n \n % check\n if isempty(source.bb) || min(bb_size(source.bb)) < min_win\n source = [];\n end\nend\n\n\n", "meta": {"author": "zk00006", "repo": "OpenTLD", "sha": "953e2df96575ba9e3e0720b8f91e936c26c9b2e3", "save_path": "github-repos/MATLAB/zk00006-OpenTLD", "path": "github-repos/MATLAB/zk00006-OpenTLD/OpenTLD-953e2df96575ba9e3e0720b8f91e936c26c9b2e3/tld/tldInitFirstFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18926665017755384}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MoveAbsJ:\n% Moves robot to a particular joint coordinates\n% Example: MoveAbsJ(robot, joint_coord, 'v1000', 'z100', gripper, wobj0);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction MoveAbsJ(joint_coord, speeddata, zonedata, gripper, Wobj)\n\nglobal configuration robot\n\nfprintf('\\nCall to MoveAbsJ');\n\n%obtain current joint coordinates\nq_current=robot.q;\n\n%obtain target joint coordinates\nq_final= joint_coord(1:robot.DOF)';\n\n%test joint limits for the final values\ntest_joints(robot, q_final);\n\nspeed = obtain_joint_speed(robot, speeddata);\n%when fine is specified, the radius is zero, otherwise, \n%the radius represents a sphere around the target where the\n%movement is changed to the next target\nradius = obtain_zone_data(zonedata);\n\n%find time to perform movement\n[actual_speed, tmax]=synchronize(q_current, q_final, speed, robot.accelmax);\n\n%in this case, if the total time for the movement is lower than the\n%configuration.delta_time time then 10 points are interpolated\nif tmax <= configuration.delta_time\n t = [0:tmax/10:tmax]';\nelse\n %local time for the planning, normal case\n t = [0:configuration.delta_time:tmax]';\nend\n\nif radius==0\n %compute a smooth trajectory in q and qd\n %in this case, the final speed is zero\n [q, qd, qdd] = compute_joint_trajectory_indep(robot, q_current, q_final, robot.qd, zeros(1,robot.DOF), t);\nelse\n %in this case, the final speed is selected as the speed selected by the\n %variable speeddata\n [q, qd, qdd] = compute_joint_trajectory_indep(robot, q_current, q_final, robot.qd, actual_speed, t);\nend\n\nT=directkinematic(robot, q_final);\n%finds the first joint coordinates that are inside a radius r of the target\n%point\nindex = find_first_in_zone_data(robot, q, T, radius);\n\n%the robot performs the movement until the index found. The coordinates, joint speed and acceleratin\n%are stored and used in the planning of the next point\nrobot.q=q(:,index);\nrobot.qd=qd(:,index);\nrobot.qdd=qdd(:,index);\n\n%store all the trajectory for plotting\n%the joint trajectories, speeds and acceleration of susequent movements are\n%store here\nrobot.q_vector=[q(:, 1:index)];\nrobot.qd_vector=[qd(:, 1:index)];\nrobot.qdd_vector=[qdd(:, 1:index)];\n\n\n%a global time for the planning is computed.\n%in this way, the total trajectory of different movements can be plotted\nif length(robot.time)==0\n tend = 0;\nelse\n tend = robot.time(end);\nend\nt = t + tend;\n%store total time\n%robot.time=[robot.time t(1:index)'];\nrobot.time=[t(1:index)'];\n\n\n%Test whether there are joints outside mechanical limits\ntest_joint_limits(robot);\n\n%Plot position, velocity and acceleration\n%plot_joint_data(robot);\n%Now, animate the robot in 3D\nanimate(robot, q);\n\n%Plot the trajectory\npp = zeros(3,size(q,2));\nfor i=1:size(q,2),\n T=directkinematic(robot, q(:,i));\n pp(1:3,i)=T(1:3,4);\nend\nplot3(pp(1,:),pp(2,:),pp(3,:), 'k', 'LineWidth', 2)\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/RAPID/functions/MoveAbsJ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.18922692601607075}} {"text": "function MENSRB = readMENSRB(fid)\n%\n% <<<<<<<<<< CLASSIFICATION: UNCLASSIFIED >>>>>>>>>> \n%\n% READMENSRB Create structure for metadata fields.\n% MENSRB = READMENSRB(FID) returns a structure of fields and their\n% associated values.\n\n% Written by Matt Donath, NGA, matthew.b.donath@nga.ic.gov\n% References:\n% > MIL-STD-2500A, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.0\n% > MIL-STD-2500C, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.1\n% > STDI-0001, NATIONAL SUPPORT DATA EXTENSIONS (SDE)(VERSION 1.3/CN2)\n% FOR THE NATIONAL IMAGERY TRANSMISSION FORMAT (NITF)\n% > STDI-0002, THE COMPENDIUM OF CONTROLLED EXTENSIONS (CE) FOR THE \n% NATIONAL IMAGERY TRANSMISSION FORMAT (NITF) VERSION 2.1\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n%% Create the metadata structure for MENSRB.\n\nMENSRB.CETAG = fread(fid,6,'uint8=>char')';\nMENSRB.CEL = str2double(fread(fid,5,'uint8=>char')');\n\nMENSRB.ACFT_LOC = fread(fid,25,'uint8=>char')';\nMENSRB.ACFT_LOC_ACCY = str2double(fread(fid,6,'uint8=>char')');\nMENSRB.ACFT_ALT = str2double(fread(fid,6,'uint8=>char')');\nMENSRB.RP_LOC = fread(fid,25,'uint8=>char')';\nMENSRB.RP_LOC_ACCY = str2double(fread(fid,6,'uint8=>char')');\nMENSRB.RP_ELV = str2double(fread(fid,6,'uint8=>char')');\nMENSRB.OF_PC_R = str2double(fread(fid,7,'uint8=>char')');\nMENSRB.OF_PC_A = str2double(fread(fid,7,'uint8=>char')');\nMENSRB.COSGRZ = str2double(fread(fid,7,'uint8=>char')');\nMENSRB.RGCCRP = str2double(fread(fid,7,'uint8=>char')');\nMENSRB.RLMAP = fread(fid,1,'uint8=>char')';\nMENSRB.RP_ROW = str2double(fread(fid,5,'uint8=>char')');\nMENSRB.RP_COL = str2double(fread(fid,5,'uint8=>char')');\nMENSRB.C_R_NC = str2double(fread(fid,10,'uint8=>char')');\nMENSRB.C_R_EC = str2double(fread(fid,10,'uint8=>char')');\nMENSRB.C_R_DC = str2double(fread(fid,10,'uint8=>char')');\nMENSRB.C_AZ_NC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.C_AZ_EC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.C_AZ_DC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.C_AL_NC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.C_AL_EC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.C_AL_DC = str2double(fread(fid,9,'uint8=>char')');\nMENSRB.TOTAL_TILES_COLS = str2double(fread(fid,3,'uint8=>char')');\nMENSRB.TOTAL_TILES_ROWS = str2double(fread(fid,5,'uint8=>char')');\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/nitf/tre/readMENSRB.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.1890209618110204}} {"text": "function [eeg] = read_ns_eeg(filename, epoch)\n\n% READ_NS_EEG read a NeuroScan 3.x or 4.x EEG File\n%\n% [eeg] = read_ns_eeg(filename, epoch)\n%\n% filename input Neuroscan .eeg file (version 3.x)\n% epoch which epoch to read (default is all)\n% \n% The output data structure eeg has the fields:\n% eeg.data(..) - epoch signal in uV (size: Nepoch x Nchan x Npnt)\n% and\n% eeg.label - electrode labels\n% eeg.nchan - number of channels\n% eeg.npnt - number of samplepoints in ERP waveform\n% eeg.time - time for each sample\n% eeg.rate - sample rate (Hz)\n% eeg.xmin - prestimulus epoch start (e.g., -100 msec)\n% eeg.xmax - poststimulus epoch end (e.g., 900 msec)\n% eeg.nsweeps - number of accepted trials/sweeps\n\n% Copyright (C) 2003, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% read the neuroscan header \neeg = read_ns_hdr(filename);\n\n% clear the variance part which is empty anyway\neeg = rmfield(eeg, 'variance');\n\n% create a time axis\neeg.time = linspace(eeg.xmin, eeg.xmax, eeg.npnt);\n\n% open the file and seek towards the place where the raw data is\nfid = fopen_or_error(filename,'r','ieee-le');\n\n% the default is to read all epochs\nif nargin<2\n epoch = 1:eeg.nsweeps;\nend\n\n% determine whether it is 16 or 32 bit data\nfseek(fid, 0, 'eof');\nheader_size = 900 + 75*eeg.nchan;\nfile_size = ftell(fid);\nsample_size = (file_size-header_size)/(eeg.nchan*eeg.npnt*eeg.nsweeps);\n% note that the V4 format can have some extra information at the end of\n% the file, causing the sample size to be slightly larger than 2 or 4\nif floor(sample_size)==2\n epoch_size = eeg.nchan*eeg.npnt*2 + 13;\n datatype ='int16';\nelseif floor(sample_size)==4\n datatype ='int32';\n epoch_size = eeg.nchan*eeg.npnt*4 + 13;\nelseif floor(sample_size)>4\n % although this is not to be expected, it might be due to a very large \"footer\" compared to the data size\n % Olga Sysoeva reported that this extention to the datatype detection fixed it for her (see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=547)\n datatype ='int32';\n epoch_size = eeg.nchan*eeg.npnt*4 + 13;\nend\n\n% create empty storage for the data\ndata = zeros(length(epoch), eeg.nchan, eeg.npnt);\nsweep = struct();\n\nfor i=1:length(epoch)\n fseek(fid, 900, 'bof'); % skip general header\n fseek(fid, 75*eeg.nchan, 'cof'); % skip channel headers\n status = fseek(fid, (epoch(i)-1)*epoch_size, 'cof'); % skip first epochs\n if status~=0\n ft_error('seek error while reading epoch data');\n end\n\n % fprintf('reading epoch %d at offset %d\\n', epoch(i), ftell(fid));\n \n % read sweep header \n sweep(i).accept = fread(fid, 1, 'uchar');\n sweep(i).type = fread(fid, 1, 'ushort');\n sweep(i).correct = fread(fid, 1, 'ushort');\n sweep(i).rt = fread(fid, 1, 'float32');\n sweep(i).response = fread(fid, 1, 'ushort');\n sweep(i).reserved = fread(fid, 1, 'ushort');\n\n % read raw signal\n raw = fread(fid, eeg.nchan*eeg.npnt, datatype);\n if length(raw)~=eeg.nchan*eeg.npnt\n ft_error('fread error while reading epoch data');\n end\n data(i,:,:) = reshape(raw, [eeg.nchan, eeg.npnt]);\n\nend\n\n% convert raw signal to uV\nfor chan=1:eeg.nchan\n data(:,chan,:) = (data(:,chan,:) - eeg.baseline(chan)) * eeg.factor(chan);\nend\n\n% store the epoch information and data in the output structure\neeg.data = squeeze(data);\neeg.sweep = squeeze(sweep');\n\nfclose(fid);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_ns_eeg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3557749071749626, "lm_q1q2_score": 0.18899096550251815}} {"text": "function GenCrossValidationData()\nSPR = 0;\n\ntag = sprintf('.SPR%d', SPR);\n\npara.local.clean_wav_root = ChoosePath4OS({'D:\\Data\\NoiseData\\Libri\\LibriSpeech\\dev-clean', '/media/xiaoxiong/OS/data1/G/REVERB_Challenge'}); \npara.local.clean_wav_ext = 'flac';\npara.local.rir_wav_root = ChoosePath4OS({'D:\\Data\\NoiseData\\ReverbEstimation\\RIR_T60_1ch', '/media/xiaoxiong/OS/data1/G/REVERB_Challenge'}); \npara.local.rir_wav_ext = 'wav';\npara.local.noise_wav_root = ChoosePath4OS({'D:\\Data\\NoiseData\\musan\\noise', '/media/xiaoxiong/OS/data1/G/REVERB_Challenge'}); \npara.local.noise_wav_ext = 'wav';\npara.local.useFileName = 1; % if set to 0, load all training data to memory. otherwise, only load file names.\npara.local.parallel_wav_root = ChoosePath4OS({'D:\\Data\\NoiseData\\Libri\\LibriSpeech\\dev-separation', '/media/xiaoxiong/OS/data1/G/REVERB_Challenge'}); \npara.local.parallel_wav_root = [para.local.parallel_wav_root tag];\npara.singlePrecision = 1;\n\nfs = 16000;\npara.IO.DynamicMixture.fs = fs;\npara.IO.DynamicMixture.nUtt4Iteration = 100; % dynamically generate 10000 distorted sentences for each training iteration\npara.IO.DynamicMixture.SPR_PDF = 'uniform'; % distribution of the power ratio between the two sources, defined as 10log10(P1/P2), \n % where P1>P2 are the power of the two mixture signals\npara.IO.DynamicMixture.SPR_para = [-1 1] * SPR; % parameters of SPR PDF. If use uniform, it is the lowest and highest SPR allowed. \n % if use normal, it is the mean and variance of SPR. \npara.IO.DynamicMixture.addReverb = 0; % whether to add reverberation to the mixed signal\npara.IO.DynamicMixture.addNoise = 0; % whether to add noise to the mixed signal\npara.IO.DynamicMixture.SNR_PDF = 'uniform'; % distribution of SNR, choose [uniform|normal]. SNR is defined as the energy ratio P1/P2, \n % where P1>P2 are the power of the two mixture signals\npara.IO.DynamicMixture.SNR_para = [0 20]; % parameters of SNR PDF. If use uniform, it is the lowest and highest SNR allowed. \n % if use normal, it is the mean and variance of SNR. \n \n[base_data, para] = LoadWavRIRNoise_Libri(para, 1);\npara.IO.DynamicMixture.inputFeature = para.IO.DynamicDistortion.inputFeature;\npara.IO.DynamicMixture.fileReader = para.IO.DynamicDistortion.fileReader;\n\n[data, para] = GenDynamicMixture(base_data, para);\n\ndistorted = data(1).data;\nclean1 = data(2).data;\nclean2 = data(3).data;\n\nmy_mkdir([para.local.parallel_wav_root '/mixed']);\nmy_mkdir([para.local.parallel_wav_root '/clean1']);\nmy_mkdir([para.local.parallel_wav_root '/clean2']);\nfor i=1:length(distorted)\n PrintProgress(i, length(distorted), 100);\n curr_distorted = double(distorted{i});\n curr_distorted = curr_distorted / max(abs(curr_distorted));\n distorted_filename = [para.local.parallel_wav_root '/mixed/' sprintf('utt%d.wav', i)];\n audiowrite(distorted_filename, curr_distorted, fs);\n\n curr_clean = double(clean1{i});\n curr_clean = curr_clean / max(abs(curr_clean));\n clean_filename = [para.local.parallel_wav_root '/clean1/' sprintf('utt%d.wav', i)];\n audiowrite(clean_filename, curr_clean, fs);\n\n curr_clean = double(clean2{i});\n curr_clean = curr_clean / max(abs(curr_clean));\n clean_filename = [para.local.parallel_wav_root '/clean2/' sprintf('utt%d.wav', i)];\n audiowrite(clean_filename, curr_clean, fs);\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/separation/GenCrossValidationData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.18899095461697665}} {"text": "function organizeExperiments_Radiomics_Old(pathFeatures,pathLR,pathCR,outcomes,timeToEvent,nPatient,nonTextName,fSetNames,paramSEP,baselineSEP,freedomSEP,textType,textName)\n\nstartpath = pwd;\n\npermTrain = randperm(nPatient.HGJ + nPatient.CHUS); permTest = randperm(nPatient.HMR + nPatient.CHUM); % Random permutation of instances.\n\nnNonText = numel(nonTextName);\nnFset = numel(fSetNames);\nnameOutcomes = fieldnames(outcomes.HGJ); nOutcomes = numel(nameOutcomes);\nnTextType = numel(textType);\n\ntraining.nonText = struct; training.text = struct; training.outcomes = struct; training.timeToEvent = struct; \ntesting.nonText = struct; testing.text = struct; testing.outcomes = struct; testing.timeToEvent = struct;\n\n% Organizing non-texture features\ncd(pathFeatures)\ntrain1 = load('nonText_HGJ_GTVtot'); train1 = struct2cell(train1); train1 = train1{1};\ntrain2 = load('nonText_CHUS_GTVtot'); train2 = struct2cell(train2); train2 = train2{1};\ntest1 = load('nonText_HMR_GTVtot'); test1 = struct2cell(test1); test1 = test1{1};\ntest2 = load('nonText_CHUM_GTVtot'); test2 = struct2cell(test2); test2 = test2{1};\nfor i = 1:nNonText\n training.nonText.(nonTextName{i}).Data = [train1.(nonTextName{i}).Data;train2.(nonTextName{i}).Data];\n testing.nonText.(nonTextName{i}).Data = [test1.(nonTextName{i}).Data;test2.(nonTextName{i}).Data];\n training.nonText.(nonTextName{i}).Data = training.nonText.(nonTextName{i}).Data(permTrain);\n testing.nonText.(nonTextName{i}).Data = testing.nonText.(nonTextName{i}).Data(permTest);\nend\n\n% Organizing texture features\nfor f = 1:nFset\n training.text.(fSetNames{f}) = struct; testing.text.(fSetNames{f}) = struct;\n if strcmp(fSetNames{f},'PET') % Using only PET\n train1 = load('text_HGJ_PT_GTVtot'); train1 = struct2cell(train1); train1 = train1{1};\n train2 = load('text_CHUS_PT_GTVtot'); train2 = struct2cell(train2); train2 = train2{1};\n test1 = load('text_HMR_PT_GTVtot'); test1 = struct2cell(test1); test1 = test1{1};\n test2 = load('text_CHUM_PT_GTVtot'); test2 = struct2cell(test2); test2 = test2{1};\n train1 = {train1}; train2 = {train2};\n test1 = {test1}; test2 = {test2};\n training.text.(fSetNames{f}).param = paramSEP; \n training.text.(fSetNames{f}).baseline = baselineSEP; \n training.text.(fSetNames{f}).freedom = freedomSEP;\n training.text.(fSetNames{f}).paramName = {'Scale','Quant.algo','Ng'};\n textCellName = {'PT'};\n elseif strcmp(fSetNames{f},'CT') % Using only CT\n train1 = load('text_HGJ_CT_GTVtot'); train1 = struct2cell(train1); train1 = train1{1};\n train2 = load('text_CHUS_CT_GTVtot'); train2 = struct2cell(train2); train2 = train2{1};\n test1 = load('text_HMR_CT_GTVtot'); test1 = struct2cell(test1); test1 = test1{1};\n test2 = load('text_CHUM_CT_GTVtot'); test2 = struct2cell(test2); test2 = test2{1};\n train1 = {train1}; train2 = {train2};\n test1 = {test1}; test2 = {test2};\n training.text.(fSetNames{f}).param = paramSEP; \n training.text.(fSetNames{f}).baseline = baselineSEP; \n training.text.(fSetNames{f}).freedom = freedomSEP;\n training.text.(fSetNames{f}).paramName = {'Scale','Quant.algo','Ng'};\n textCellName = {'CT'};\n end\n \n for i = 1:numel(train1)\n sizeParam = size(train1{1});\n training.text.(fSetNames{f}).(textCellName{i}) = cell(sizeParam);\n testing.text.(fSetNames{f}).(textCellName{i}) = cell(sizeParam);\n for n = 1:numel(train1{1})\n for type = 1:nTextType\n for text = 1:numel(textName{type})\n training.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = [train1{i}{n}.(textType{type}).(textName{type}{text}).Data;train2{i}{n}.(textType{type}).(textName{type}{text}).Data];\n testing.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = [test1{i}{n}.(textType{type}).(textName{type}{text}).Data;test2{i}{n}.(textType{type}).(textName{type}{text}).Data];\n training.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = training.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data(permTrain);\n testing.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = testing.text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data(permTest);\n end\n end\n end\n end\nend\n\n\n% Organizing outcomes\nfor o = 1:nOutcomes\n training.outcomes.(nameOutcomes{o}) = [outcomes.HGJ.(nameOutcomes{o});outcomes.CHUS.(nameOutcomes{o})];\n testing.outcomes.(nameOutcomes{o}) = [outcomes.HMR.(nameOutcomes{o});outcomes.CHUM.(nameOutcomes{o})];\n training.timeToEvent.(nameOutcomes{o}) = [timeToEvent.HGJ.(nameOutcomes{o});timeToEvent.CHUS.(nameOutcomes{o})];\n testing.timeToEvent.(nameOutcomes{o}) = [timeToEvent.HMR.(nameOutcomes{o});timeToEvent.CHUM.(nameOutcomes{o})];\n training.outcomes.(nameOutcomes{o}) = training.outcomes.(nameOutcomes{o})(permTrain);\n testing.outcomes.(nameOutcomes{o}) = testing.outcomes.(nameOutcomes{o})(permTest);\n training.timeToEvent.(nameOutcomes{o}) = training.timeToEvent.(nameOutcomes{o})(permTrain);\n testing.timeToEvent.(nameOutcomes{o}) = testing.timeToEvent.(nameOutcomes{o})(permTest);\nend\n\n% Re-arranging by outcomes (same features for all outcomes here)\ntempTraining = training; tempTesting = testing; clear training testing\nfor o = 1:nOutcomes\n training.(nameOutcomes{o}).nonText = tempTraining.nonText;\n training.(nameOutcomes{o}).text = tempTraining.text;\n training.(nameOutcomes{o}).outcome = tempTraining.outcomes.(nameOutcomes{o});\n training.(nameOutcomes{o}).timeToEvent = tempTraining.timeToEvent.(nameOutcomes{o});\n testing.(nameOutcomes{o}).nonText = tempTesting.nonText;\n testing.(nameOutcomes{o}).text = tempTesting.text;\n testing.(nameOutcomes{o}).outcome = tempTesting.outcomes.(nameOutcomes{o});\n testing.(nameOutcomes{o}).timeToEvent = tempTesting.timeToEvent.(nameOutcomes{o});\nend\n\ncd(pathLR), save('training','training'), save('testing','testing'), save('permTrain','permTrain'), save('permTest','permTest')\ncd(pathCR), save('training','training'), save('testing','testing'), save('permTrain','permTrain'), save('permTest','permTest')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/organizeExperiments_Radiomics_Old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.18868946532451683}} {"text": "function hash = xVOChash_init(strs)\n% From the PASCAL VOC 2011 devkit\n\nhsize=4999;\nhash.key=cell(hsize,1);\nhash.val=cell(hsize,1);\n\nfor i=1:numel(strs)\n s=strs{i};\n h=mod(str2double(s([4 6:end])),hsize)+1;\n j=numel(hash.key{h})+1;\n hash.key{h}{j}=strs{i};\n hash.val{h}(j)=i;\nend\n\n", "meta": {"author": "ShaoqingRen", "repo": "faster_rcnn", "sha": "49ad0990512a5d6e34f56e3c6596eb5fbf22f651", "save_path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn", "path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn/faster_rcnn-49ad0990512a5d6e34f56e3c6596eb5fbf22f651/utils/xVOChash_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18868221808365662}} {"text": "function engine = jtree_mnet_inf_engine(model, varargin)\n% JTREE_MNET_INF_ENGINE Junction tree inference engine for Markov nets\n% engine = jtree_inf_engine(mnet, ...)\n%\n\n% set default params\nN = length(mnet.graph);\nroot = N;\n\nengine = init_fields;\nengine = class(engine, 'jtree_mnet_inf_engine', inf_engine(bnet));\n\nonodes = bnet.observed;\nif is_mnet(bnet)\n MG = bnet.graph;\nelse\n error('should be a mnet')\nend\n\n%[engine.jtree, dummy, engine.cliques, B, w, elim_order, moral_edges, fill_in_edges, strong] = ...\n% dag_to_jtree(bnet, onodes, stages, clusters);\n\nporder = determine_elim_constraints(bnet, onodes);\nstrong = ~isempty(porder);\nns = bnet.node_sizes(:);\nns(onodes) = 1; % observed nodes have only 1 possible value\n[engine.jtree, root2, engine.cliques, B, w] = ...\n graph_to_jtree(MG, ns, porder, stages, clusters);\n\nengine.cliques_bitv = B;\nengine.clique_weight = w;\nC = length(engine.cliques);\nengine.clpot = cell(1,C);\n\n% Compute the separators between connected cliques.\n[is,js] = find(engine.jtree > 0);\nengine.separator = cell(C,C);\nfor k=1:length(is)\n i = is(k); j = js(k);\n engine.separator{i,j} = find(B(i,:) & B(j,:)); % intersect(cliques{i}, cliques{j});\nend\n\n% A node can be a member of many cliques, but is assigned to exactly one, to avoid\n% double-counting its CPD. We assign node i to clique c if c is the \"lightest\" clique that\n% contains i's family, so it can accomodate its CPD.\n\nengine.clq_ass_to_node = zeros(1, N);\nfor i=1:N\n %c = clq_containing_nodes(engine, family(bnet.dag, i));\n clqs_containing_family = find(all(B(:,family(bnet.dag, i)), 2)); % all selected columns must be 1\n c = clqs_containing_family(argmin(w(clqs_containing_family))); \n engine.clq_ass_to_node(i) = c; \nend\n\n% Make the jtree rooted, so there is a fixed message passing order.\nif strong\n % the last clique is guaranteed to be a strong root\n engine.root_clq = length(engine.cliques);\nelse\n % jtree_dbn_inf_engine requires the root to contain the interface.\n % This may conflict with the strong root requirement! *********** BUG *************\n engine.root_clq = clq_containing_nodes(engine, root);\n if engine.root_clq <= 0\n error(['no clique contains ' num2str(root)]);\n end\nend \n\n[engine.jtree, engine.preorder, engine.postorder] = mk_rooted_tree(engine.jtree, engine.root_clq);\n\n% collect \nengine.postorder_parents = cell(1,length(engine.postorder));\nfor n=engine.postorder(:)'\n engine.postorder_parents{n} = parents(engine.jtree, n);\nend\n% distribute\nengine.preorder_children = cell(1,length(engine.preorder));\nfor n=engine.preorder(:)'\n engine.preorder_children{n} = children(engine.jtree, n);\nend\n\n \n\n%%%%%%%%\n\nfunction engine = init_fields()\n\nengine.jtree = [];\nengine.cliques = [];\nengine.separator = [];\nengine.cliques_bitv = [];\nengine.clique_weight = [];\nengine.clpot = [];\nengine.clq_ass_to_node = [];\nengine.root_clq = [];\nengine.preorder = [];\nengine.postorder = [];\nengine.preorder_children = [];\nengine.postorder_parents = [];\nengine.maximize = [];\nengine.evidence = [];\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/inference/static/@jtree_mnet_inf_engine/jtree_mnet_inf_engine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18857024147945223}} {"text": "function [clusLengths,biggestEvent,mbg,bg,clustnumbers] = funBuildclu(mycat, biggestEvent, clus, mbg)\n% FUNBUILDCLU builds cluster out out of information stored in clus\n% \n% FUNBUILDCLU(mycat, biggestEvent, clus, mbg)\n%\n% mycat : catalog\n% clus: size of catalog, containing cluster index numbers\n% biggestEvent: size nClusters\n% mbg: max mag in cluster\n% bg : size nClusters\n%\n % originally, \"mycat\" was \"newcat\"\n % A.Allmann\n \n% modified by C Reyes 2017\n\n%global mycat clus mbg k1 clust clustnumbers \n%global bgevent bg\n\n % count # events in each cluster\nclusLengths = histcounts(clus,'BinLimits',[1 max(clus)], 'BinMethod','integers');\n\n% cull any clusters that don't have events\nempty_clusters = clusLengths == 0; %numbers of clusters that are empty eg. [1:9 2:0 3: 8 4:0] -> [0 1 0 1]\nclusLengths(empty_clusters)=[];\nbiggestEvent(empty_clusters)=[];\nmbg(empty_clusters)=[];\n\nbg = biggestEvent;\nbiggestEvent = mycat.subset(bg); %biggest event in a cluster(if more than one,take first)\n\nclustnumbers=(1:numel(clusLengths)); % stores numbers of clusters\n\n\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/declus/funBuildclu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.18809850809422762}} {"text": "% Convert bin-epoched EEG to a bin-organized EEG structure\n% may be useful for subsequent decoding scripts\n% axs 2020\n%\n% Inputs:\n% EEG - an EEG set, which must have been processed with ERPLAB, with\n% valid EventList, and be bin-epoched EEG data\n% write_file_path - optional full path to write file to, string\n%\n% Outputs:\n% binorgEEG - reorganisation of the EEG data, around the ERPLAB bins\n% with the data in binorgEEG.binwise_data(bin_n).data(elec,timepoints,trial_n)\nfunction binorgEEG = binepEEG_to_binorgEEG(EEG, write_file_path)\n\ndim_data = numel(size(EEG.data));\nif dim_data ~= 3\n error('binepEEG_to_binorgEEG works on bin-epoched EEG. Please ensure data is epoched (not continuous) and has bin labels');\nend\n\n% Prepare info for averager call\nartif = 1; stderror = 1; excbound = 1;\n\n% Call ERP Averager subfunction, populating the epoch_list\n\n[ERP2, EVENTLISTi, countbiORI, countbinINV, countbinOK, countflags, workfname,epoch_list] = averager(EEG, artif, stderror, excbound);\n\n\n% We now have epoch_list, which has a list of 'good' bepoch indecies to use\n% epoch_list(1).good_bep_indx(:) has those trials for bin 1\n% epoch_list(2).good_bep_indx(:) has those trials for bin 2, etc\nnbin = ERP2.nbin;\n\n% Prepare binorg data structure\nfor bin = 1:nbin\n \n binorgEEG.binwise_data(bin).data = EEG.data(:,:,epoch_list(bin).good_bep_indx);\n binorgEEG.n_trials_this_bin(bin) = numel(epoch_list(bin).good_bep_indx);\n \nend\n\n% Now, the data from each trial is saved, reorganized by bin, such that:\n% for bin X\n% binorgEEG.binwise_data(X).data(:,:,1) gives all elecs and all\n% timepoints for the 1st trial of bin X\n\n\nif ischar(write_file_path)\n % If a string of a full write file path is provided in arg, save it there\n save(write_file_path,'binorgEEG')\n \nelseif write_file_path == 1\n % UI file pick when write_file_path == 1\n [file_name, file_path] = uiputfile('*.mat','Please pick a path to save the Bin-Organized EEG data');\n write_file_path = [file_path file_name];\n save(write_file_path,'binorgEEG');\nend", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/functions/binepEEG_to_binorgEEG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18809850625490437}} {"text": "for model_index=0:0\n caffe.reset_all;\n net=caffe.get_net(param.test_net_file,'test');\n% net.copy_from(strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(65500+model_index*2000),'.caffemodel'));\n net.copy_from(param.fintune_model);\n tic;\n fin=fopen(param.result_save_file,'a');\n str=strcat(param.save_model_file,num2str(split_index),'/',param.save_model_name,'_',num2str(65500+model_index*2000),'.caffemodel');\n fprintf(fin,'model:%s\\n',str);\n fprintf('testing model:%s\\n',str);\n fclose(fin);\n net.blobs('data').reshape([224 224 3 param.test_batch_size]);\n% % contrast fix score\n% net.blobs('sig').reshape([1 1 3 param.test_batch_size]);\n% batch_sig=ones(1,1,3,param.test_batch_size,'single');\n% net.blobs('sig').set_data(batch_sig);\n% %\n load(strcat(param.data_path,param.testdata_filename,num2str(split_index),'/test_data.mat'));\n test_script_for_LPW;\n toc;\nend", "meta": {"author": "liuyuisanai", "repo": "Quality-Aware-Network", "sha": "c1b3dadf5503938782f3c9b4560ec425a597dddb", "save_path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network", "path": "github-repos/MATLAB/liuyuisanai-Quality-Aware-Network/Quality-Aware-Network-c1b3dadf5503938782f3c9b4560ec425a597dddb/train_PQAN/test_network_for_LPW.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1880778451665064}} {"text": "function [fig_handle,tot_image,image_XYYZ,image_YX] = DrawCellsOnAnat(I,ax)\nif exist('ax','var') && isobject(ax) \n axes(ax);\n fig_handle = gcf;\nelse\n fig_handle = figure('Position',[600,50,458.5,608],'color',[1 1 1],...\n 'Name',['Fish#' num2str(I.i_fish)]);\n set(gca,'Position',[0.01, 0.01, 0.98, 0.98]); % right ~subplot \nend\n \n%% load from Input struct that is generated by 'LoadCurrentFishForAnatPlot.m'\nnames = fieldnames(I); % cell of strings\nfor i = 1:length(names),\n eval([names{i} ' = I.',names{i},';']);\nend\n\nif ~isRefAnat, % raw images\n k_zres_ratio = 20; % 8/0.406 = 19.704\n radius_xy = 5;%7;\n width_z = 10;\n thickness_z = 1;\nelse % registered to ZBrain \n k_zres_ratio = 2.5; % 2/0.798 = 2.506\n radius_xy = 3;\n width_z = 5;\n thickness_z = 3;\n z_range_ventral = 40;% round(min(CellXYZ(:,3))*k_zres_ratio);\nend\n\n%% Setup\n[s1,s2] = size(cIX);\nif s2>s1,\n cIX = cIX';\nend\n[s1,s2] = size(gIX);\nif s2>s1,\n gIX = gIX';\nend\n\n% down-sample\nif ~isPopout,\n displaymax = 8000;\n if length(cIX) > displaymax,\n skip = round(length(cIX)/displaymax);\n cIX = cIX(1:skip:end,:);\n gIX = gIX(1:skip:end,:);\n end\nend\n\n% set up anatomical images\n% anat_YX = zeros(size(anat_yx));\n% anat_YZ = zeros(size(anat_yz));\n% anat_ZX = zeros(size(anat_zx));\nanat_YX = anat_yx/4;\nanat_YZ = anat_yz/4;\nanat_ZX = anat_zx/4;\nanat_ZX = flipud(anat_ZX);\ndimv_yx = size(anat_YX);\ndimv_yz = size(anat_YZ);\ndimv_zx = size(anat_ZX);\n\n% adjust size for YZ and ZX view, and combine all 3 view into total-image\n% (including white borders as indicated in dim_totimage)\n\nanat_yz2=zeros(dimv_yz(1),dimv_yz(2)*k_zres_ratio,3);\nanat_zx2=zeros(dimv_zx(1)*k_zres_ratio,dimv_zx(2),3);\n\n% Show cropped version for normalized fish\n% (only for plotting for now, because drawing on GUI relies on the true\n% coordinates)\n\nif isRefAnat && isPopout,\n % crop lengthwise (most of tail), and scale k_zres\n y_range = 81:980;%81:990;% 81:1104; % max 1406\n z_range = z_range_ventral:345; % max 138*k_zres\n dimv_yx3 = size(anat_YX(y_range,:,:));\n dimv_yz3 = [length(y_range),length(z_range),3];\n dimv_zx3 = [length(z_range),size(anat_YX,2),3];\n \n dim_totimage = [dimv_yx3(1)+dimv_zx3(1)+10,dimv_yx3(2)+dimv_yz3(2)+10,3];\nelse\n dim_totimage = [dimv_yx(1)+dimv_zx(1)*k_zres_ratio+10,dimv_yx(2)+dimv_yz(2)*k_zres_ratio+10,3];\nend\ntot_image=ones(dim_totimage);\n\n% create masks (~linearized indices), to draw cells on image (later)\ncirclemaskIX = MakeCircularMask(radius_xy,dimv_yx);\nyzmaskIX = MakeSquareMask(width_z,thickness_z,dimv_yz);\nzxmaskIX = MakeSquareMask(thickness_z,width_z,dimv_zx);\n\n%% Draw each cell on map (all 3 views)\n% main loop\ncIX_abs = absIX(cIX);\nM_xyz = CellXYZ(cIX_abs,:);\n\nif ~isempty(cIX)\n anat_YX = DrawMasksInRGB(anat_YX,M_xyz(:,[1,2]),circlemaskIX,clrmap,gIX,clr_alpha);\n anat_YZ = DrawMasksInRGB(anat_YZ,M_xyz(:,[1,3]),yzmaskIX,clrmap,gIX,clr_alpha/2);\n anat_ZX = DrawMasksInRGB(anat_ZX,M_xyz(:,[3,2]),zxmaskIX,clrmap,gIX,clr_alpha/2);\nend\n\n%% Draw masks on anat projections\nif isShowMasks,\n nMasks = length(Msk_IDs);\n % set params\n rng(1);\n % cmap2 = rand(nMasks,3);\n cmap2 = hsv(nMasks);%jet(nMasks);\n outline_radius = 3;\n msk_alpha = 0.1;%0.15 %0.25 for all projections\n white_alpha = 0.15;%0.25 % 0 for all projections\n for i = 1:nMasks,\n clr = cmap2(i,:);\n % get masks from database\n if Msk_IDs(i)==0,\n msk = full(newMask);\n else\n msk = full(MASKs.MaskDatabase(:,Msk_IDs(i)));\n end\n mask_3D = reshape(msk, [MASKs.height, MASKs.width, MASKs.Zs]);\n \n % Y-X\n masks_XY = max(mask_3D,[],3);\n masks_fit = logical(imresize(masks_XY,[size(anat_yx,1),size(anat_yx,2)]));\n if isShowMskOutline,\n masks_fit = imdilate(edge(masks_fit), strel('disk',outline_radius));\n end\n anat_YX = DrawMasksInRGB(anat_YX,[],masks_fit,clr,1,msk_alpha,white_alpha);\n \n % Y-Z\n masks_YZ = squeeze(max(mask_3D,[],2));\n masks_fit = logical(imresize(masks_YZ,[size(anat_yz,1),size(anat_yz,2)]));\n if isShowMskOutline,\n masks_fit = imdilate(edge(masks_fit), ones(5,2));%strel('line',outline_radius,90));\n end\n anat_YZ = DrawMasksInRGB(anat_YZ,[],masks_fit,clr,1,msk_alpha,white_alpha);\n \n % Z-X\n masks_ZX = squeeze(max(mask_3D,[],1))'; % notice the transpose\n masks_fit = logical(imresize(masks_ZX,[size(anat_zx,1),size(anat_zx,2)]));\n if isShowMskOutline,\n masks_fit = imdilate(edge(masks_fit), ones(2,5));%strel('line',outline_radius,0));\n end\n anat_ZX = DrawMasksInRGB(anat_ZX,[],masks_fit,clr,1,msk_alpha,white_alpha);\n end\nend\n\n%% rescale (low-res) z dimension\nfor k=1:3\n anat_yz2(:,:,k) = imresize(anat_YZ(:,:,k), [dimv_yz(1), dimv_yz(2)*k_zres_ratio],'nearest');\n anat_zx2(:,:,k) = imresize(anat_ZX(:,:,k), [dimv_zx(1)*k_zres_ratio, dimv_zx(2)],'nearest');\nend\n\n% Draw scale bar\nif isRefAnat\n if ~isPopout,\n y_range = 1:size(anat_YX,1);\n end\n k_um = 0.798; % ZBrain: x/y/z = 0.798/0.798/2um\n scalebar_len = round(50/k_um);\n scalebar_x_range = (600-scalebar_len+1):600;\n scalebar_y = y_range(end)-30-y_range(1)+1;\n scalebar_y_range = (scalebar_y-3):(scalebar_y+3);\n \n image_YX = anat_YX(y_range,:,:);\n image_YX(scalebar_y_range,scalebar_x_range,:) = 1;\nelse\n k_um = 0.406; % xy_res\n scalebar_len = round(50/k_um);\n \n x_end = size(anat_YX,2)-30;\n scalebar_x_range = (x_end-scalebar_len+1):x_end;\n scalebar_y = size(anat_YX,1)-30+1;\n scalebar_y_range = (scalebar_y-3):(scalebar_y+3);\n \n image_YX = anat_YX;\n image_YX(scalebar_y_range,scalebar_x_range,:) = 1;\nend\n\n% compile 3 projections to image panel\nif isRefAnat && isPopout,\n tot_image(dimv_zx3(1)+11:end,1:dimv_yx3(2),:) = image_YX;%anat_YX(y_range,:,:);\n tot_image(dimv_zx3(1)+11:end,dimv_yx3(2)+11:end,:) = anat_yz2(y_range,z_range,:);\n tot_image(1:dimv_zx3(1),1:dimv_zx3(2),:) = flipud(anat_zx2(z_range,:,:));\n image_XYYZ = tot_image(dimv_zx3(1)+11:end,1:end,:);\nelse\n tot_image(dimv_zx(1)*k_zres_ratio+11:end,1:dimv_yx(2),:) = image_YX;\n tot_image(dimv_zx(1)*k_zres_ratio+11:end,dimv_yx(2)+11:end,:) = anat_yz2;\n tot_image(1:dimv_zx(1)*k_zres_ratio,1:dimv_zx(2),:) = flipud(anat_zx2);\n image_XYYZ = tot_image(dimv_zx(1)*k_zres_ratio+11:end,1:end,:);\nend\n\n% OPTIONAL BRIGHTENING\n% tot_image = tot_image*2;\n\n\ntot_image(tot_image(:)>1) = 1;\ntot_image(tot_image(:)<0) = 0;\n\nimage(image_XYYZ); % image(tot_image);\naxis image;axis off\n\nset(gcf,'Color','w');\n\nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/GUI functions/DrawCellsOnAnat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.18807783643814135}} {"text": "classdef TextDetectorCNN < handle\n %TEXTDETECTORCNN Class providing functionality of text detection\n %\n % This class provides the functionality of text bounding box detection\n % (finds bounding boxes of text words given an input image).\n %\n % This class uses OpenCV dnn module to load pre-trained model described in\n % [LiaoSBWL17].\n % The original repository with the modified SSD Caffe version:\n % [GitHub](https://github.com/MhLiao/TextBoxes).\n %\n % Model (90.68 MB) can be downloaded from\n % [DropBox](https://www.dropbox.com/s/g8pjzv2de9gty8g/TextBoxes_icdar13.caffemodel?dl=0).\n %\n % Modified `.prototxt` file with the model description can be obtained from\n % [GitHub](https://github.com/opencv/opencv_contrib/raw/3.4.1/modules/text/samples/textbox.prototxt).\n %\n % ## References\n % [LiaoSBWL17]:\n % > Minghui Liao, Baoguang Shi, Xiang Bai, Xinggang Wang, and Wenyu Liu.\n % > \"Textboxes: A fast text detector with a single deep neural network\".\n % > In AAAI, 2017.\n %\n % See also: cv.TextDetectorCNN.TextDetectorCNN, cv.Net\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n %% TextDetectorCNN\n methods\n function this = TextDetectorCNN(varargin)\n %TEXTDETECTORCNN Creates an instance using the provided parameters\n %\n % obj = cv.TextDetectorCNN(modelArchFilename, modelWeightsFilename)\n % obj = cv.TextDetectorCNN(..., 'OptionName', optionValue, ...)\n %\n % ## Input\n % * __modelArchFilename__ path to the prototxt file describing the\n % classifiers architecture (the `.prototxt` file).\n % * __modelWeightsFilename__ path to the file containing the\n % pretrained weights of the model in caffe-binary form\n % (the `.caffemodel` file).\n %\n % ## Options\n % * __DetectionSizes__ a list of sizes for multiscale detection.\n % The values\n % `{[300,300], [700,500], [700,300], [700,700], [1600,1600]}`\n % are recommended in [LiaoSBWL17] to achieve the best quality.\n % default `{[300,300]}`.\n %\n % See also: cv.TextDetectorCNN\n %\n this.id = TextDetectorCNN_(0, 'new', varargin{:});\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % obj.delete()\n %\n % See also: cv.TextDetectorCNN\n %\n if isempty(this.id), return; end\n TextDetectorCNN_(this.id, 'delete');\n end\n end\n\n %% TextDetector\n methods\n function [bbox, conf] = detect(this, img)\n %DETECT Detect text inside an image\n %\n % [bbox, conf] = obj.detect(img)\n %\n % ## Input\n % * __img__ an image to process, expected to be a 8-bit color\n % image of any size.\n %\n % ## Output\n % * __bbox__ a vector of rectangles of the detected word bounding\n % boxes.\n % * __conf__ a vector of float of the confidences the classifier\n % has for the corresponding bounding boxes.\n %\n % See also: cv.TextDetectorCNN.TextDetectorCNN\n %\n [bbox, conf] = TextDetectorCNN_(this.id, 'detect', img);\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/opencv_contrib/+cv/TextDetectorCNN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.18800485387469562}} {"text": "function result = analyzePathDeviationDetection(debug, PerformanceSpec)\n\n% Author: Alexander Wischnewski Date: 01-07-2019\n% \n% Description: \n% scans the debug data and ground truth whether the path deviation\n% detection works as specified\n% \n% Input: \n% debug: Debug structure of the vehicle\n% PerformanceSpec Structure with fields: \n% HighDeviationLat_m \n% VeryHighDeviationLat_m \n% HighDeviationHeading_rad\n% VeryHighDeviationHeading_rad\n% TimeSpec_s\n% \n% Outputs: \n% result: 1 if valid according to spec, 0 otherwise\n\nresult = 1; \n\ndisp(' ');\ndisp('------------------------------');\ndisp('Check High Path Deviation Detection: ');\ndisp('------------------------------');\nidxFailure = find(abs(debug.debug_mvdc_path_matching_debug_PathPos_d_m.Data) >= PerformanceSpec.HighDeviationLat_m | ...\n abs(debug.debug_mvdc_path_matching_debug_PathPos_psi_rad.Data) >= PerformanceSpec.HighDeviationHeading_rad, 1);\nif isempty(idxFailure)\n disp('The vehicle did not deviate enough from the path for high path deviation detection.'); \nelse\n % load time where failure occured\n tFailure = debug.debug_mloc_statemachine_debug_TUMVehicleState.Time(idxFailure); \n % find time where vehicle has gone to emergency\n idxDetect = find(uint16(debug.debug_mloc_statemachine_debug_TUMVehicleState.Data) == 50, 1);\n tFailureDetected_s = debug.debug_mloc_statemachine_debug_TUMVehicleState.Time(idxDetect);\n disp(['The failure was detected within ' num2str(tFailureDetected_s-tFailure) 's.']); \n if(tFailureDetected_s - tFailure > PerformanceSpec.TimeSpec_s)\n disp('The failure was not detected within the specified time window'); \n result = 0; \n return\n end\n disp('The high path deviation failure was detected within the specified time window'); \nend\n\ndisp(' ');\ndisp('------------------------------');\ndisp('Check Very High Path Deviation Detection: ');\ndisp('------------------------------');\nidxFailure = find(abs(debug.debug_mvdc_path_matching_debug_PathPos_d_m.Data) >= PerformanceSpec.VeryHighDeviationLat_m | ...\n abs(debug.debug_mvdc_path_matching_debug_PathPos_psi_rad.Data) >= PerformanceSpec.VeryHighDeviationHeading_rad, 1);\nif isempty(idxFailure)\n disp('The vehicle did not deviate enough from the path for very high path deviation detection.'); \nelse\n % load time where failure occured\n tFailure = debug.debug_mloc_statemachine_debug_TUMVehicleState.Time(idxFailure); \n % find time where vehicle has gone to emergency\n idxDetect = find(uint16(debug.debug_mloc_statemachine_debug_TUMVehicleState.Data) == 60, 1);\n tFailureDetected_s = debug.debug_mloc_statemachine_debug_TUMVehicleState.Time(idxDetect);\n disp(['The failure was detected within ' num2str(tFailureDetected_s-tFailure) 's.']); \n if((tFailureDetected_s - tFailure) > PerformanceSpec.TimeSpec_s)\n disp('The failure was not detected within the specified time window'); \n result = 0; \n return\n end\n disp('The very high path deviation failure was detected within the specified time window'); \nend\n\ndisp(' ');\ndisp('All checks passed.');", "meta": {"author": "TUMFTM", "repo": "mod_vehicle_dynamics_control", "sha": "48b12705b72740b0c1574b0da2eab66fe0c75127", "save_path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control", "path": "github-repos/MATLAB/TUMFTM-mod_vehicle_dynamics_control/mod_vehicle_dynamics_control-48b12705b72740b0c1574b0da2eab66fe0c75127/scripts/analyzePathDeviationDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.18797622522100868}} {"text": "function [data,eid,name] = DBGetValues(query,direction)\n\n%DBGetValues - Group values for all variables that match given criteria.\n%\n% Concatenate individual values for all variables matching the optional query.\n% Values must be scalars, vectors or matrices. Concatenation can be performed\n% horizontally or vertically. Matrices can also be concatenated along the\n% third dimension (z). By default, values of size MxN are concatenated\n% vertically if M<=N, or horizontally otherwise.\n%\n% USAGE\n%\n% [data,eid,name] = DBGetValues(query,direction)\n%\n% query optional list query (WHERE clause; see Example)\n% direction optional concatenation direction ('h', 'v' or 'z')\n%\n% OUTPUT\n%\n% data concatenation of individual values\n% eid experiment ID (identifier string)\n% name descriptive name (identifier string)\n%\n% EXAMPLE\n%\n% In this example, place cells were recorded on successive days while the\n% animal explored a maze, then during sleep. Firing fields were stored in a\n% database using eids like '20120213-Maze-(1,2)' (where 1,2 corresponds to\n% tetrode 1, cluster 2) and named 'FiringFields'. Mean firing rates during\n% sleep were named 'MeanRate'.\n%\n% Get all firing fields (for details on query syntax, see an SQL manual):\n%\n% [fields,eid1] = DBGetValues('eid like \"%Maze%\" and name=\"FiringField\"');\n%\n% Get all firing rates during sleep:\n%\n% [rates,eid2] = DBGetValues('eid like \"%Sleep%\" and name=\"MeanRate\"');\n%\n% SEE\n%\n% See also DBMatchValues, DBGetVariables, DBAddVariable, DBGetFigures.\n%\n\n% Copyright (C) 2007-2013 by Micha\u00ebl Zugaro\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 3 of the License, or\n% (at your option) any later version.\n\n% Make sure MyM is installed and functional\nCheckMyM;\n\ndata = [];\neid = {};\nname = {};\n\n% Parameters\nif nargin < 1,\n\tquery = '';\n\tdirection = [];\nelseif nargin == 1,\n\tif strcmp(lower(query),'h'),\n\t\tquery = '';\n\t\tdirection = 'h';\n\telseif strcmp(lower(query),'v'),\n\t\tquery = '';\n\t\tdirection = 'v';\n\telseif strcmp(lower(query),'z'),\n\t\tquery = '';\n\t\tdirection = 'z';\n\telse\n\t\tdirection = [];\n\tend\nend\n\n% Query database\nresults = DBGetVariables(query,'output','full');\nif isempty(results.v), return; end\neid = results.eid;\nname = results.name;\n\nfirst = results.v{1};\nif ~isnumeric(first),\n\terror('Values are not numerical and cannot be concatenated (type ''help DBGetValues'' for details).');\nend\n\n% Automatic concatenation direction\nif isempty(direction),\n\tif size(first,1) <= size(first,2),\n\t\tdirection = 'v';\n\telse\n\t\tdirection = 'h';\n\tend\nend\n\n% Concatenation\n\n% Determine sizes of retrieved values (arrays)\nsizes = cellfun(@size,results.v,'UniformOutput',false);\n% Make sure they all have the same number of dimensions\nnDims = cellfun(@length,sizes);\nif any(nDims~=nDims(1)),\n\terror('All values should have the same number of dimensions (type ''help DBGetValues'' for details).');\nend\n% Determine 'circumscribed' array size\ns = max(unique(vertcat(sizes{:}),'rows'),[],1);\n% Extend all arrays\nresults.v = cellfun(@(x) ExtendArray(x,s),results.v,'uniformoutput',false);\n% Concatenate in the appropriate direction\nif strcmp(direction,'v'),\n\tdata = vertcat(results.v{:});\nelseif strcmp(direction,'h'),\n\tdata = [results.v{:}];\nelse\n\tdata = cat(3,results.v{:});\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/FMAToolbox/Database/DBGetValues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759006064978404}} {"text": "%%*****************************************************************************\n%% sqlpsummary: print summary\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 sqlpsummary(info,ttime,infeas_org,printlevel)\n\niter = info.iter;\nobj = info.obj;\ngap = info.gap;\nrelgap = info.relgap;\nprim_infeas = info.pinfeas;\ndual_infeas = info.dinfeas;\ntermcode = info.termcode;\nreldist = info.reldist;\nresid = info.resid;\ndimacs = info.dimacs;\ntotaltime = info.cputime;\n%%\npreproctime = ttime.preproc; pcholtime = ttime.pchol; dcholtime = ttime.dchol;\npredtime = ttime.pred; pstep_predtime = ttime.pred_pstep; dstep_predtime = ttime.pred_pstep;\ncorrtime = ttime.corr; pstep_corrtime = ttime.corr_pstep; dstep_corrtime = ttime.corr_dstep;\nmisctime = ttime.misc;\n%%\nif (printlevel >= 2)\n fprintf('\\n------------------------------------------------');\n fprintf('-------------------\\n');\n fprintf(' number of iterations = %2.0f\\n',iter);\nend\nif (termcode <= 0)\n if (printlevel >=2)\n fprintf(' primal objective value = %- 9.8e\\n',obj(1));\n fprintf(' dual objective value = %- 9.8e\\n',obj(2));\n fprintf(' gap := trace(XZ) = %3.2e\\n',gap);\n fprintf(' relative gap = %3.2e\\n',relgap);\n fprintf(' actual relative gap = %3.2e\\n',-diff(obj)/(1+sum(abs(obj))));\n if norm(infeas_org)\n fprintf(' rel. primal infeas (scaled problem) = %3.2e\\n',prim_infeas);\n fprintf(' rel. dual \" \" \" = %3.2e\\n',dual_infeas);\n fprintf(' rel. primal infeas (unscaled problem) = %3.2e\\n',infeas_org(1));\n fprintf(' rel. dual \" \" \" = %3.2e\\n',infeas_org(2));\n else\n fprintf(' rel. primal infeas = %3.2e\\n',prim_infeas);\n fprintf(' rel. dual infeas = %3.2e\\n',dual_infeas);\n end\n fprintf(' norm(X), norm(y), norm(Z) = %3.1e, %3.1e, %3.1e\\n',...\n info.normX,info.normy,info.normZ);\n fprintf(' norm(A), norm(b), norm(C) = %3.1e, %3.1e, %3.1e\\n',...\n info.normA,info.normb,info.normC);\n end\nelseif (termcode == 1)\n if (printlevel >=2)\n fprintf(' residual of primal infeasibility \\n')\n fprintf(' certificate (y,Z) = %3.2e\\n',resid);\n fprintf(' reldist to infeas. <= %3.2e\\n',reldist);\n end\nelseif (termcode == 2)\n if (printlevel >=2)\n fprintf(' residual of dual infeasibility \\n')\n fprintf(' certificate X = %3.2e\\n',resid);\n fprintf(' reldist to infeas. <= %3.2e\\n',reldist);\n end\nend\nif (printlevel >=2)\n fprintf(' Total CPU time (secs) = %3.2f \\n',totaltime);\n fprintf(' CPU time per iteration = %3.2f \\n',totaltime/iter);\n fprintf(' termination code = %2.0f\\n',termcode);\n fprintf(' DIMACS: %.1e %.1e %.1e %.1e %.1e %.1e\\n',dimacs);\n fprintf('------------------------------------------------');\n fprintf('-------------------\\n');\n if (printlevel > 3)\n fprintf(' Percentage of CPU time spent in various parts \\n');\n fprintf('------------------------------------------------');\n fprintf('-------------------\\n');\n fprintf(' preproc Xchol Zchol pred pred_steplen corr corr_steplen misc\\n')\n tt = [preproctime, pcholtime, dcholtime, predtime, pstep_predtime, dstep_predtime];\n tt = [tt, corrtime, pstep_corrtime, dstep_corrtime, misctime];\n tt = tt/sum(tt)*100;\n fprintf(' %3.1f %3.1f %3.1f %3.1f %3.1f %3.1f ',...\n tt(1),tt(2),tt(3),tt(4),tt(5),tt(6));\n fprintf(' %3.1f %3.1f %3.1f %3.1f\\n',tt(7),tt(8),tt(9),tt(10));\n fprintf('------------------------------------------------');\n fprintf('-------------------\\n');\n end\nend\n%%*****************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/sdpt3/Solver/sqlpsummary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017088}} {"text": "function [SACdata,SeisData,sacfiles]=sacpc2mat(varargin)\n% [SACdata,SeisData,filenames] = SACPCMAT('file1','file2',..., 'filen' )\n%\n% reads n SAC files file1, file2, filen (SAC files are assumed to have\n% PC byte order) and converts them to matlab\n% format. The filenames can contain globbing characters (e.g. * and ?).\n% These are expanded and all matching files loaded.\n%\n% SACPCMAT( cellarray ) where cellarray={'file1','file2',...,'filen'}\n% is equivalent to the standard form.\n% \n% SACdata is an n x 1 struct array containing the header variables\n% in the same format as is obtained by using MAT function\n% of SAC2000.\n% SACdata(i).trcLen contains the number of samples.\n%\n% SeisData is an m x n array (where m=max(npts1, npts2, ...) )\n% containing the actual data.\n%\n% filenames is a n x 1 string cell array with the filenames actually read.\n%\n% Note that writing \n%\n% [SACdata,SeisData] = sacsun2mat('file1','file2',..., 'filen' ) \n%\n% is equivalent to the following sequence\n% \n% sac2000\n% READ file1 file2 .. filen\n% MAT\n%\n% (in fact the failure of above sequence to work properly on my\n% system motivated this script).\n%\n%\n% SACPC2MAT was written by F Tilmann (tilmann@esc.cam.ac.uk) \n% based on sac_sun2pc_mat by C. D. Saragiotis (I copied the \n% routines doing the actual work from this code but\n% used a different header structure and made the routine\n% flexible). \n% It was tested on MATLAB5 on a PC but\n% should work on newer versions, too.\n%\n% (C) 2004\n%\n\nF = 4-1; % float byte-size minus 1;\nK = 8-1; % alphanumeric byte-size minus 1\nL = 4-1; % long integer byte-size minus 1;\n\nfnames={};\nfor i=1:nargin\n if ischar(varargin{i})\n fnames=cell([fnames; cellstr(varargin{i})]);\n elseif iscellstr(varargin{i}) & size(varargin{i},1)==1\n fnames=cell([fnames; varargin{i}']);\n elseif iscellstr(varargin{i}) & size(varargin{i},2)==1\n fnames=cell([fnames; varargin{i}]);\n end\nend\n% expand globs\nsacfiles={};k=1;\nfor i=1:length(fnames)\n dirlist=dir(fnames{i});\n for j=1:length(dirlist)\n if ~dirlist(j).isdir\n sacfiles{k,1}=dirlist(j).name;\n k=k+1;\n end\n end\nend\n\nmaxnpts=0;\nfor i=1:length(sacfiles)\n fid=fopen(sacfiles{i},'rb');\n if fid==-1\n error(sprintf('Could not open SAC file %s',fnames{i}))\n end\n SACdata(i,1)=readSacHeader(fid,F,K,L);\n npts=SACdata(i).trcLen;\n if npts>maxnpts\n maxnpts=npts;\n end\n fprintf('Processing file %d: %s\\n',i,sacfiles{i});\n SeisData(npts,i)=0; % Magnify seis matrix if necessary\n SeisData(:,i)=[ readSacData(fid,npts,F+1); zeros(maxnpts-npts,1)]; % Have to pad with zeros if new data have less data points than some previously read file\nend\n\nfunction hdr = readSacHeader(fileId,F,K,L)\n% hdr = readSacHeader(FID)\n% sacReadAlphaNum reads the SAC-format header fields and returns most of them. \n% \n% The output variable, 'hdr' is a structure, whose fields are\n% the fields as in the SACdata structure generated by SAC's\n% matlab command MAT\n% \n% Created by C. D. Saragiotis, August 5th, 2003, modified by F Tilmann\nheaderBytes = 632;\nchrctr = fread(fileId,headerBytes,'uchar');\nchrctr = chrctr(:)';\n% Read floats\nhdr.times.delta = sacReadFloat(chrctr(1:1+F)); % increment between evenly spaced samples\n%hdr.DEPMIN = sacReadFloat(chrctr(5:5+F)); % MINimum value of DEPendent variable\n%hdr.DEPMAX = sacReadFloat(chrctr(9:9+F)); % MAXimum value of DEPendent variable\n% (not currently used) SCALE = sacReadFloat(chrctr(13:13+F)); % Mult SCALE factor for dependent variable\n%hdr.ODELTA = sacReadFloat(chrctr(17:17+F)); % Observd increment if different than DELTA\nhdr.times.b = sacReadFloat(chrctr(21:21+F)); % Begining value of the independent variable\nhdr.times.e = sacReadFloat(chrctr(25:25+F)); % Ending value of the independent variable\nhdr.times.o = sacReadFloat(chrctr(29:29+F)); % event Origin time\nhdr.times.a = sacReadFloat(chrctr(33:33+F)); % first Arrival time\nhdr.times.t0 = sacReadFloat(chrctr(41:41+F));\nhdr.times.t1 = sacReadFloat(chrctr(45:45+F));\nhdr.times.t2 = sacReadFloat(chrctr(49:49+F));\nhdr.times.t3 = sacReadFloat(chrctr(53:53+F));\nhdr.times.t4 = sacReadFloat(chrctr(57:57+F));\nhdr.times.t5 = sacReadFloat(chrctr(61:61+F));\nhdr.times.t6 = sacReadFloat(chrctr(65:65+F));\nhdr.times.t7 = sacReadFloat(chrctr(69:69+F));\nhdr.times.t8 = sacReadFloat(chrctr(73:73+F));\nhdr.times.t9 = sacReadFloat(chrctr(77:77+F));\nhdr.times.f = sacReadFloat(chrctr(81:81+F)); % Fini of event time\n\n\nhdr.response = sacReadFloat(reshape(chrctr(85:85+10*(F+1)-1),F+1,10)');\n\nhdr.station.stla = sacReadFloat(chrctr(125:125+F)); % STation LAttitude\nhdr.station.stlo = sacReadFloat(chrctr(129:129+F)); % STation LOngtitude\nhdr.station.stel = sacReadFloat(chrctr(133:133+F)); % STation ELevation\nhdr.station.stdp = sacReadFloat(chrctr(137:137+F)); % STation DePth below surface \n\nhdr.event.ecla = sacReadFloat(chrctr(141:141+F)); % EVent LAttitude\nhdr.event.evlo = sacReadFloat(chrctr(145:145+F)); % EVent LOngtitude\nhdr.event.evel = sacReadFloat(chrctr(149:149+F)); % EVent ELevation\nhdr.event.evdp = sacReadFloat(chrctr(153:153+F)); % EVent DePth below surface\nhdr.event.mag = sacReadFloat(chrctr(157:157+F)); % EVent DePth below surface\n\nuserdata=sacReadFloat(reshape(chrctr(161:161+10*(F+1)-1),F+1,10)');\n\nhdr.evsta.dist = sacReadFloat(chrctr(201:201+F)); % station to event DISTance (km)\nhdr.evsta.az = sacReadFloat(chrctr(205:205+F)); % event to station AZimuth (degrees)\nhdr.evsta.baz = sacReadFloat(chrctr(209:209+F)); % station to event AZimuth (degrees)\nhdr.evsta.gcarc = sacReadFloat(chrctr(213:213+F)); % station to event Great Circle ARC length (degrees)\n\n%hdr.DEPMEN = sacReadFloat(chrctr(225:225+F)); % MEaN value of DEPendent variable\n\nhdr.station.cmpaz = sacReadFloat(chrctr(229:229+F)); % CoMPonent AZimuth (degrees clockwise from north)\nhdr.station.cmpinc = sacReadFloat(chrctr(233:233+F)); % CoMPonent INCident angle (degrees from vertical)\n\nhdr.llnl.xminimum = sacReadFloat(chrctr(237:237+L));\nhdr.llnl.xmaximum = sacReadFloat(chrctr(241:241+L));\nhdr.llnl.yminimum = sacReadFloat(chrctr(245:245+L));\nhdr.llnl.ymaximum = sacReadFloat(chrctr(249:249+L));\n\n% Read long integers\nhdr.event.nzyear = sacReadLong(chrctr(281:281+L)); % GMT YEAR\nhdr.event.nzjday = sacReadLong(chrctr(285:285+L)); % GMT julian DAY\nhdr.event.nzhour = sacReadLong(chrctr(289:289+L)); % GMT HOUR\nhdr.event.nzmin = sacReadLong(chrctr(293:293+L)); % GMT MINute\nhdr.event.nzsec = sacReadLong(chrctr(297:297+L)); % GMT SECond\nhdr.event.nzmsec = sacReadLong(chrctr(301:301+L)); % GMT MilliSECond\n\nhdr.llnl.norid = sacReadLong(chrctr(309:309+L));\nhdr.llnl.nevid = sacReadLong(chrctr(313:313+L));\n\nhdr.trcLen = sacReadLong(chrctr(317:317+L)); % Number of PoinTS per data component\n\nhdr.llnl.nwfid = sacReadLong(chrctr(325:325+L));\nhdr.llnl.nxsize = sacReadLong(chrctr(329:329+L));\nhdr.llnl.nysize = sacReadLong(chrctr(333:333+L));\n\nhdr.descrip.iftype = sacReadLong(chrctr(341:341+L)); % File TYPE\nhdr.descrip.idep = sacReadLong(chrctr(345:345+L)); % type of DEPendent variable\nhdr.descrip.iztype = sacReadLong(chrctr(349:349+L)); % reference time equivalence\n\nhdr.descrip.iinst = sacReadLong(chrctr(357:357+L)); % type of recording INSTrument\n\n% Before there were floats read here?\nhdr.descrip.istreg = sacReadLong(chrctr(361:361+F)); % STation geographic REGion\nhdr.descrip.ievreg = sacReadLong(chrctr(365:365+F)); % EVent geographic REGion\nhdr.descrip.ievtyp = sacReadLong(chrctr(369:369+F)); % EVent geographic REGion\nhdr.descrip.iqual = sacReadLong(chrctr(373:373+F)); % QUALity of data\nhdr.descrip.isynth = sacReadLong(chrctr(377:377+F)); % SYNTHetic data flag\n\nhdr.event.imagtyp = sacReadLong(chrctr(381:381+F));\nhdr.event.imagsrc = sacReadLong(chrctr(385:385+F));\n\n% no logical SAC header variables in matlab SACdata structure!\n% previous version set these defaults\n% $$$ % SAC defaults\n% $$$ hdr.IEVTYPE = 'IUNKN';\n% $$$ %IEVTYPE= sacReadFloat(chrctr(369:369+F)); % EVent TYPE\n% $$$ hdr.LEVEN = 'TRUE'; % true, if data are EVENly spaced (required)\n% $$$ %LEVEN= sacReadFloat(chrctr(421:521+F)); % true, if data are EVENly spaced (required)\n% $$$ hdr.LPSPOL = 'FALSE'; % true, if station components have a PoSitive POLarity\n% $$$ %LPSPOL= sacReadFloat(chrctr(425:425+F)); % true, if station components have a PoSitive POLarity\n% $$$ hdr.LOVROK = 'FALSE'; % true, if it is OK to OVeRwrite this file in disk\n% $$$ %LOVROK= sacReadFloat(chrctr(429:429+F)); % true, if it is OK to OVeRwrite this file in disk\n% $$$ hdr.LCALDA = 'TRUE'; % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates\n% $$$ %LCALDA= sacReadFloat(chrctr(433:433+F)); % true, if DIST, AZ, BAZ and GCARC are to be calculated from station and event coordinates\n\n% Read alphanumeric data\nhdr.station.kstnm = sacReadAlphaNum(chrctr(441:441+K)); % STation NaMe\nhdr.event.kevnm = sacReadAlphaNum(chrctr(449:449+2*(K+1)-1)); % EVent NaMe\n%hdr.KHOLE = sacReadAlphaNum(chrctr(465:465+K)); % HOLE identification, if nuclear event\nhdr.times.ko = sacReadAlphaNum(chrctr(473:473+K)); % event Origin time identification\nhdr.times.ka = sacReadAlphaNum(chrctr(481:481+K)); % first Arrival time identification\n\nhdr.times.kt0 = sacReadAlphaNum(chrctr(489:489+K));\nhdr.times.kt1 = sacReadAlphaNum(chrctr(497:497+K));\nhdr.times.kt2 = sacReadAlphaNum(chrctr(505:505+K));\nhdr.times.kt3 = sacReadAlphaNum(chrctr(513:513+K));\nhdr.times.kt4 = sacReadAlphaNum(chrctr(521:521+K));\nhdr.times.kt5 = sacReadAlphaNum(chrctr(529:529+K));\nhdr.times.kt6 = sacReadAlphaNum(chrctr(537:537+K));\nhdr.times.kt7 = sacReadAlphaNum(chrctr(545:545+K));\nhdr.times.kt8 = sacReadAlphaNum(chrctr(553:553+K));\nhdr.times.kt9 = sacReadAlphaNum(chrctr(561:561+K));\n\n\nhdr.times.kf = sacReadAlphaNum(chrctr(569:569+K)); % Fini identification\nkuser0 = sacReadAlphaNum(chrctr(577:577+K)); % USER-defined variable storage area\nkuser1 = sacReadAlphaNum(chrctr(585:585+K)); % USER-defined variable storage area\nkuser2 = sacReadAlphaNum(chrctr(593:593+K)); % USER-defined variable storage area\nhdr.station.kcmpnm = sacReadAlphaNum(chrctr(601:601+K)); % CoMPonent NaMe\nhdr.station.knetwk = sacReadAlphaNum(chrctr(609:609+K)); % name of seismic NETWorK\n%hdr.KDATRD = sacReadAlphaNum(chrctr(617:617+K)); % DATa Recording Date onto the computer\n%hdr.KINST = sacReadAlphaNum(chrctr(625:625+K)); % generic name of recording INSTrument\n\nusercell=num2cell(userdata);\n[usercell{find(userdata==-12345)}]=deal([]);\n[hdr.user(1:10).data]=deal(usercell{:});\n[hdr.user(1:10).label]=deal(kuser0, kuser1,kuser2,[], [], [], [], [], [], []);\n\n\nfunction X = readSacData(fid,N,F)\n% function data = readSacData('filename',NPTS,floatByteSize)\nchrctr = fread(fid,N*F,'uchar');\nx=reshape(chrctr,F,N)';\n%x\nX = sacReadFloat(x); \n\n\nfunction lNumber = sacReadLong(cb)\n% reads long integers (4 bytes long)\n% cb is the character buffer\ncb = cb(:);\n% SUN sac format use: lNumber = (256.^(3:-1:0))*cb;\nlNumber = (256.^(0:3))*cb; % changed line\nif lNumber == -12345, lNumber = []; end\n\nfunction fNumber = sacReadFloat(cb)\n% reads floats (4 bytes long)\n% cb is the character buffer\nC = size(cb,1);\n% SUN sac format use: stringOfBitSequence = [dec2bin(cb(:,1),8) dec2bin(cb(:,2),8) dec2bin(cb(:,3),8) dec2bin(cb(:,4),8)];\nstringOfBitSequence = [dec2bin(cb(:,4),8) dec2bin(cb(:,3),8) ...\n dec2bin(cb(:,2),8) dec2bin(cb(:,1),8)]; %changed line\nbitSequence = stringOfBitSequence=='1';\nfSign = -2*bitSequence(:,1)+1;\nfExp = bitSequence(:,2:9)*(2.^(7:-1:0)') - 127;\nfMantissa = [ones(C,1) bitSequence(:,10:32)]*(2.^(0:-1:-23)');\nfNumber = fSign.*fMantissa.*(2.^fExp);\nisZeroCheck = sum(bitSequence')'==0;\nfNumber = fNumber.*(~isZeroCheck);\nif C==1 & fNumber == -12345, fNumber = []; end\n\n\nfunction alphaNum = sacReadAlphaNum(cb)\n% reads alphanumeric data (8 or 16 bytes long). If it cb is empty, it returns a ' ' \n% cb is the character buffer\nK = max(size(cb));\nalphaNumTemp = char(cb);\nif K == 8\n if alphaNumTemp == '-12345 ' \n alphaNum = [];\n else\n alphaNum = alphaNumTemp;\n end\nelse\n if K == 16\n if alphaNumTemp == '-12345 -12345 ' | alphaNumTemp == '-12345 ' \n alphaNum = [];\n else\n alphaNum = alphaNumTemp;\n end\n end\nend\n", "meta": {"author": "cultpenguin", "repo": "segymat", "sha": "6470f59fd8184f0fff0d89383265417b461cc1da", "save_path": "github-repos/MATLAB/cultpenguin-segymat", "path": "github-repos/MATLAB/cultpenguin-segymat/segymat-6470f59fd8184f0fff0d89383265417b461cc1da/sacpc2mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18759004810785965}} {"text": "% internal function\n\n% 'xform_nii.m' is an internal function called by \"load_nii.m\", so\n% you do not need run this program by yourself. It does simplified\n% NIfTI sform/qform affine transform, and supports some of the\n% affine transforms, including translation, reflection, and\n% orthogonal rotation (N*90 degree).\n%\n% For other affine transforms, e.g. any degree rotation, shearing\n% etc. you will have to use the included 'reslice_nii.m' program\n% to reslice the image volume. 'reslice_nii.m' is not called by\n% any other program, and you have to run 'reslice_nii.m' explicitly\n% for those NIfTI files that you want to reslice them.\n%\n% Since 'xform_nii.m' does not involve any interpolation or any\n% slice change, the original image volume is supposed to be\n% untouched, although it is translated, reflected, or even\n% orthogonally rotated, based on the affine matrix in the\n% NIfTI header.\n%\n% However, the affine matrix in the header of a lot NIfTI files\n% contain slightly non-orthogonal rotation. Therefore, optional\n% input parameter 'tolerance' is used to allow some distortion\n% in the loaded image for any non-orthogonal rotation or shearing\n% of NIfTI affine matrix. If you set 'tolerance' to 0, it means\n% that you do not allow any distortion. If you set 'tolerance' to\n% 1, it means that you do not care any distortion. The image will\n% fail to be loaded if it can not be tolerated. The tolerance will\n% be set to 0.1 (10%), if it is default or empty.\n%\n% Because 'reslice_nii.m' has to perform 3D interpolation, it can\n% be slow depending on image size and affine matrix in the header.\n%\n% After you perform the affine transform, the 'nii' structure\n% generated from 'xform_nii.m' or new NIfTI file created from\n% 'reslice_nii.m' will be in RAS orientation, i.e. X axis from\n% Left to Right, Y axis from Posterior to Anterior, and Z axis\n% from Inferior to Superior.\n%\n% NOTE: This function should be called immediately after load_nii.\n%\n% Usage: [ nii ] = xform_nii(nii, [tolerance], [preferredForm])\n%\n% nii\t- NIFTI structure (returned from load_nii)\n%\n% tolerance (optional) - distortion allowed for non-orthogonal rotation\n%\tor shearing in NIfTI affine matrix. It will be set to 0.1 (10%),\n%\tif it is default or empty.\n%\n% preferredForm (optional) - selects which transformation from voxels\n%\tto RAS coordinates; values are s,q,S,Q. Lower case s,q indicate\n%\t\"prefer sform or qform, but use others if preferred not present\".\n%\tUpper case indicate the program is forced to use the specificied\n%\ttranform or fail loading. 'preferredForm' will be 's', if it is\n%\tdefault or empty.\t- Jeff Gunter\n%\n% NIFTI data format can be found on: http://nifti.nimh.nih.gov\n%\n% - Jimmy Shen (jimmy@rotman-baycrest.on.ca)\n%\nfunction nii = xform_nii(nii, tolerance, preferredForm)\n\n % save a copy of the header as it was loaded. This is the\n % header before any sform, qform manipulation is done.\n %\n nii.original.hdr = nii.hdr;\n\n if ~exist('tolerance','var') | isempty(tolerance)\n tolerance = 0.1;\n elseif(tolerance<=0)\n tolerance = eps;\n end\n\n if ~exist('preferredForm','var') | isempty(preferredForm)\n preferredForm= 's';\t\t\t\t% Jeff\n end\n\n % if scl_slope field is nonzero, then each voxel value in the\n % dataset should be scaled as: y = scl_slope * x + scl_inter\n % I bring it here because hdr will be modified by change_hdr.\n %\n if nii.hdr.dime.scl_slope ~= 0 & ...\n\tismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768]) & ...\n\t(nii.hdr.dime.scl_slope ~= 1 | nii.hdr.dime.scl_inter ~= 0)\n\n nii.img = ...\n\tnii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;\n\n if nii.hdr.dime.datatype == 64\n\n nii.hdr.dime.datatype = 64;\n nii.hdr.dime.bitpix = 64;\n else\n nii.img = single(nii.img);\n\n nii.hdr.dime.datatype = 16;\n nii.hdr.dime.bitpix = 32;\n end\n\n nii.hdr.dime.glmax = max(double(nii.img(:)));\n nii.hdr.dime.glmin = min(double(nii.img(:)));\n\n % set scale to non-use, because it is applied in xform_nii\n %\n nii.hdr.dime.scl_slope = 0;\n\n end\n\n % However, the scaling is to be ignored if datatype is DT_RGB24.\n\n % If datatype is a complex type, then the scaling is to be applied\n % to both the real and imaginary parts.\n %\n if nii.hdr.dime.scl_slope ~= 0 & ...\n\tismember(nii.hdr.dime.datatype, [32,1792])\n\n nii.img = ...\n\tnii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;\n\n if nii.hdr.dime.datatype == 32\n nii.img = single(nii.img);\n end\n\n nii.hdr.dime.glmax = max(double(nii.img(:)));\n nii.hdr.dime.glmin = min(double(nii.img(:)));\n\n % set scale to non-use, because it is applied in xform_nii\n %\n nii.hdr.dime.scl_slope = 0;\n\n end\n\n % There is no need for this program to transform Analyze data\n %\n if nii.filetype == 0 & exist([nii.fileprefix '.mat'],'file')\n load([nii.fileprefix '.mat']);\t% old SPM affine matrix\n R=M(1:3,1:3);\n T=M(1:3,4);\n T=R*ones(3,1)+T;\n M(1:3,4)=T;\n nii.hdr.hist.qform_code=0;\n nii.hdr.hist.sform_code=1;\n nii.hdr.hist.srow_x=M(1,:);\n nii.hdr.hist.srow_y=M(2,:);\n nii.hdr.hist.srow_z=M(3,:);\n elseif nii.filetype == 0\n nii.hdr.hist.rot_orient = [];\n nii.hdr.hist.flip_orient = [];\n return;\t\t\t\t% no sform/qform for Analyze format\n end\n\n hdr = nii.hdr;\n\n [hdr,orient]=change_hdr(hdr,tolerance,preferredForm);\n\n % flip and/or rotate image data\n %\n if ~isequal(orient, [1 2 3])\n\n old_dim = hdr.dime.dim([2:4]);\n\n % More than 1 time frame\n %\n if ndims(nii.img) > 3\n pattern = 1:prod(old_dim);\n else\n pattern = [];\n end\n\n if ~isempty(pattern)\n pattern = reshape(pattern, old_dim);\n end\n\n % calculate for rotation after flip\n %\n rot_orient = mod(orient + 2, 3) + 1;\n\n % do flip:\n %\n flip_orient = orient - rot_orient;\n\n for i = 1:3\n if flip_orient(i)\n if ~isempty(pattern)\n pattern = flipdim(pattern, i);\n else\n nii.img = flipdim(nii.img, i);\n end\n end\n end\n\n % get index of orient (rotate inversely)\n %\n [tmp rot_orient] = sort(rot_orient);\n\n new_dim = old_dim;\n new_dim = new_dim(rot_orient);\n hdr.dime.dim([2:4]) = new_dim;\n\n new_pixdim = hdr.dime.pixdim([2:4]);\n new_pixdim = new_pixdim(rot_orient);\n hdr.dime.pixdim([2:4]) = new_pixdim;\n\n % re-calculate originator\n %\n tmp = hdr.hist.originator([1:3]);\n tmp = tmp(rot_orient);\n flip_orient = flip_orient(rot_orient);\n\n for i = 1:3\n if flip_orient(i) & ~isequal(tmp(i), 0)\n tmp(i) = new_dim(i) - tmp(i) + 1;\n end\n end\n\n hdr.hist.originator([1:3]) = tmp;\n hdr.hist.rot_orient = rot_orient;\n hdr.hist.flip_orient = flip_orient;\n\n % do rotation:\n %\n if ~isempty(pattern)\n pattern = permute(pattern, rot_orient);\n pattern = pattern(:);\n\n if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...\n\t\thdr.dime.datatype == 128 | hdr.dime.datatype == 511\n\n tmp = reshape(nii.img(:,:,:,1), [prod(new_dim) hdr.dime.dim(5:8)]);\n tmp = tmp(pattern, :);\n nii.img(:,:,:,1) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);\n\n tmp = reshape(nii.img(:,:,:,2), [prod(new_dim) hdr.dime.dim(5:8)]);\n tmp = tmp(pattern, :);\n nii.img(:,:,:,2) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);\n\n if hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n tmp = reshape(nii.img(:,:,:,3), [prod(new_dim) hdr.dime.dim(5:8)]);\n tmp = tmp(pattern, :);\n nii.img(:,:,:,3) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);\n end\n\n else\n nii.img = reshape(nii.img, [prod(new_dim) hdr.dime.dim(5:8)]);\n nii.img = nii.img(pattern, :);\n nii.img = reshape(nii.img, [new_dim hdr.dime.dim(5:8)]);\n end\n else\n if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...\n\t\thdr.dime.datatype == 128 | hdr.dime.datatype == 511\n\n nii.img(:,:,:,1) = permute(nii.img(:,:,:,1), rot_orient);\n nii.img(:,:,:,2) = permute(nii.img(:,:,:,2), rot_orient);\n\n if hdr.dime.datatype == 128 | hdr.dime.datatype == 511\n nii.img(:,:,:,3) = permute(nii.img(:,:,:,3), rot_orient);\n end\n else\n nii.img = permute(nii.img, rot_orient);\n end\n end\n else\n hdr.hist.rot_orient = [];\n hdr.hist.flip_orient = [];\n end\n\n nii.hdr = hdr;\n\n return;\t\t\t\t\t% xform_nii\n\n\n%-----------------------------------------------------------------------\nfunction [hdr, orient] = change_hdr(hdr, tolerance, preferredForm)\n\n orient = [1 2 3];\n affine_transform = 1;\n\n % NIFTI can have both sform and qform transform. This program\n % will check sform_code prior to qform_code by default.\n %\n % If user specifys \"preferredForm\", user can then choose the\n % priority.\t\t\t\t\t- Jeff\n %\n useForm=[];\t\t\t\t\t% Jeff\n\n if isequal(preferredForm,'S')\n if isequal(hdr.hist.sform_code,0)\n error('User requires sform, sform not set in header');\n else\n useForm='s';\n end\n end\t\t\t\t\t\t% Jeff\n\n if isequal(preferredForm,'Q')\n if isequal(hdr.hist.qform_code,0)\n error('User requires qform, qform not set in header');\n else\n useForm='q';\n end\n end\t\t\t\t\t\t% Jeff\n\n if isequal(preferredForm,'s')\n if hdr.hist.sform_code > 0\n useForm='s';\n elseif hdr.hist.qform_code > 0\n useForm='q';\n end\n end\t\t\t\t\t\t% Jeff\n\n if isequal(preferredForm,'q')\n if hdr.hist.qform_code > 0\n useForm='q';\n elseif hdr.hist.sform_code > 0\n useForm='s';\n end\n end\t\t\t\t\t\t% Jeff\n\n if isequal(useForm,'s')\n R = [hdr.hist.srow_x(1:3)\n hdr.hist.srow_y(1:3)\n hdr.hist.srow_z(1:3)];\n\n T = [hdr.hist.srow_x(4)\n hdr.hist.srow_y(4)\n hdr.hist.srow_z(4)];\n\n if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];\n R_sort = sort(abs(R(:)));\n R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;\n hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];\n\n if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];\n msg = [msg 'found inside the affine matrix' char(10)];\n msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];\n msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];\n msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];\n msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];\n msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];\n msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];\n msg = [msg ' without applying any affine geometric transformation or' char(10)];\n msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];\n msg = [msg ' to do some image processing regardless of image orientation' char(10)];\n msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];\n msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];\n msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];\n msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];\n msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];\n error(msg);\n end\n end\n\n elseif isequal(useForm,'q')\n b = hdr.hist.quatern_b;\n c = hdr.hist.quatern_c;\n d = hdr.hist.quatern_d;\n\n if 1.0-(b*b+c*c+d*d) < 0\n if abs(1.0-(b*b+c*c+d*d)) < 1e-5\n a = 0;\n else\n error('Incorrect quaternion values in this NIFTI data.');\n end\n else\n a = sqrt(1.0-(b*b+c*c+d*d));\n end\n\n qfac = hdr.dime.pixdim(1);\n if qfac==0, qfac = 1; end\n i = hdr.dime.pixdim(2);\n j = hdr.dime.pixdim(3);\n k = qfac * hdr.dime.pixdim(4);\n\n R = [a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c\n 2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b\n 2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b];\n\n T = [hdr.hist.qoffset_x\n hdr.hist.qoffset_y\n hdr.hist.qoffset_z];\n\n % qforms are expected to generate rotation matrices R which are\n % det(R) = 1; we'll make sure that happens.\n %\n % now we make the same checks as were done above for sform data\n % BUT we do it on a transform that is in terms of voxels not mm;\n % after we figure out the angles and squash them to closest\n % rectilinear direction. After that, the voxel sizes are then\n % added.\n %\n % This part is modified by Jeff Gunter.\n %\n if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n\n % det(R) == 0 is not a common trigger for this ---\n % R(find(R)) is a list of non-zero elements in R; if that\n % is straight (not oblique) then it should be the same as\n % columnwise summation. Could just as well have checked the\n % lengths of R(find(R)) and sum(R)' (which should be 3)\n %\n hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];\n R_sort = sort(abs(R(:)));\n R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;\n R = R * diag([i j k]);\n hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];\n\n if det(R) == 0 | ~isequal(R(find(R)), sum(R)')\n msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];\n msg = [msg 'found inside the affine matrix' char(10)];\n msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];\n msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];\n msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];\n msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];\n msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];\n msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];\n msg = [msg ' without applying any affine geometric transformation or' char(10)];\n msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];\n msg = [msg ' to do some image processing regardless of image orientation' char(10)];\n msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];\n msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];\n msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];\n msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];\n msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];\n error(msg);\n end\n\n else\n R = R * diag([i j k]);\n end\t\t\t\t\t% 1st det(R)\n\n else\n affine_transform = 0;\t% no sform or qform transform\n end\n\n if affine_transform == 1\n voxel_size = abs(sum(R,1));\n inv_R = inv(R);\n originator = inv_R*(-T)+1;\n orient = get_orient(inv_R);\n\n % modify pixdim and originator\n %\n hdr.dime.pixdim(2:4) = voxel_size;\n hdr.hist.originator(1:3) = originator;\n\n % set sform or qform to non-use, because they have been\n % applied in xform_nii\n %\n hdr.hist.qform_code = 0;\n hdr.hist.sform_code = 0;\n end\n\n % apply space_unit to pixdim if not 1 (mm)\n %\n space_unit = get_units(hdr);\n\n if space_unit ~= 1\n hdr.dime.pixdim(2:4) = hdr.dime.pixdim(2:4) * space_unit;\n\n % set space_unit of xyzt_units to millimeter, because\n % voxel_size has been re-scaled\n %\n hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,1,0));\n hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,2,1));\n hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,3,0));\n end\n\n hdr.dime.pixdim = abs(hdr.dime.pixdim);\n\n return;\t\t\t\t\t% change_hdr\n\n\n%-----------------------------------------------------------------------\nfunction orient = get_orient(R)\n\n orient = [];\n\n for i = 1:3\n switch find(R(i,:)) * sign(sum(R(i,:)))\n case 1\n orient = [orient 1];\t\t% Left to Right\n case 2\n orient = [orient 2];\t\t% Posterior to Anterior\n case 3\n orient = [orient 3];\t\t% Inferior to Superior\n case -1\n orient = [orient 4];\t\t% Right to Left\n case -2\n orient = [orient 5];\t\t% Anterior to Posterior\n case -3\n orient = [orient 6];\t\t% Superior to Inferior\n end\n end\n\n return;\t\t\t\t\t% get_orient\n\n\n%-----------------------------------------------------------------------\nfunction [space_unit, time_unit] = get_units(hdr)\n\n switch bitand(hdr.dime.xyzt_units, 7)\t% mask with 0x07\n case 1\n space_unit = 1e+3;\t\t% meter, m\n case 3\n space_unit = 1e-3;\t\t% micrometer, um\n otherwise\n space_unit = 1;\t\t\t% millimeter, mm\n end\n\n switch bitand(hdr.dime.xyzt_units, 56)\t% mask with 0x38\n case 16\n time_unit = 1e-3;\t\t\t% millisecond, ms\n case 24\n time_unit = 1e-6;\t\t\t% microsecond, us\n otherwise\n time_unit = 1;\t\t\t% second, s\n end\n\n return;\t\t\t\t\t% get_units\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/external/NIfTI_20140122/xform_nii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18734498043232764}} {"text": "function [p,x_min,upper] = initializesolution(p,x_min,upper)\n\nif p.options.warmstart\n x = p.x0;\n z = evaluate_nonlinear(p,x);\n residual = constraint_residuals(p,z);\n relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=-p.options.bmibnb.pdtol);\n if relaxed_feasible \n % upper_ = p.f+p.c'*z+z'*p.Q*z;\n upper_ = computecost(p.f,p.c,p.Q,z,p);\n if upper_ <= upper\n upper = upper_;\n x_min = z;\n end\n end\nelse\n x0 = p.x0;\n p.x0 = zeros(length(p.c),1);\n % Avoid silly warnings\n if ~isempty(p.evalMap)\n for i = 1:length(p.evalMap)\n if (isequal(p.evalMap{i}.fcn,'log') | isequal(p.evalMap{i}.fcn,'log2') | isequal(p.evalMap{i}.fcn,'log10'))\n p.x0(p.evalMap{i}.variableIndex) = (p.lb(p.evalMap{i}.variableIndex) + p.ub(p.evalMap{i}.variableIndex))/2;\n end\n end\n end\n p = correctEXPConeClosureInitial(p);\n x = p.x0;\n z = evaluate_nonlinear(p,x);\n z = propagateAuxilliary(p,z);\n \n residual = constraint_residuals(p,z);\n relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=-p.options.bmibnb.pdtol);\n if relaxed_feasible\n for i = 1:length(p.evalMap)\n if ~isempty(p.evalMap{i}.properties.forbidden)\n if z(p.evalMap{i}.variableIndex) > p.evalMap{i}.properties.forbidden(1) && z(p.evalMap{i}.variableIndex) < p.evalMap{i}.properties.forbidden(2)\n relaxed_feasible = 0;\n end\n end\n end\n end\n if relaxed_feasible\n infs = isinf(z);\n if ~any(infs)\n % upper_ = p.f+p.c'*z+z'*p.Q*z;\n upper_ = computecost(p.f,p.c,p.Q,z,p);\n if upper_ <= upper\n upper = upper_;\n x_min = z;\n x0 = x_min;\n end\n else\n % Allow inf solutions if variables aren't used in objective\n if all(p.c(infs)==0) & nnz(p.Q(infs,:))==0\n ztemp = z;ztemp(infs)=0;\n %upper_ = p.f+p.c'*ztemp+ztemp'*p.Q*ztemp;\n upper_ = computecost(p.f,p.c,p.Q,ztemp,p);\n if upper_ <= upper\n upper = upper_;\n x_min = z;\n x0 = x_min;\n end\n end\n end\n end\n p.x0 = (p.lb + p.ub)/2;\n p.x0(isinf(p.ub))=p.lb(isinf(p.ub));\n p.x0(isinf(p.lb))=p.ub(isinf(p.lb));\n p.x0(isinf(p.lb) & isinf(p.ub))=0;\n if ~isempty(p.integer_variables)\n p.x0(p.integer_variables) = round(p.x0(p.integer_variables));\n end\n if ~isempty(p.binary_variables)\n p.x0(p.binary_variables) = round(p.x0(p.binary_variables));\n end\n p = correctEXPConeClosureInitial(p);\n x = p.x0;\n x(isinf(x))=eps;\n x(isnan(x))=eps;\n z = evaluate_nonlinear(p,x);\n z = propagateAuxilliary(p,z); \n residual = constraint_residuals(p,z);\n relaxed_feasible = all(residual(1:p.K.f)>=-p.options.bmibnb.eqtol) & all(residual(1+p.K.f:end)>=p.options.bmibnb.pdtol); \n if relaxed_feasible \n tempcost = computecost(p.f,p.c,p.Q,z,p);\n if tempcost < upper\n upper = tempcost;\n x_min = z;\n x0 = x_min;\n end\n end\n p.x0 = x0;\nend\n\n\nfunction z = propagateAuxilliary(p,z)\n\ntry\n % New feature. If we introduce new variables xx = f(x) to be used\n % in a nonlinear operator, we can derive its value when x is chosen\n \n if ~isempty(p.aux_variables)\n if p.K.f > 1\n A = p.F_struc(1:p.K.f,2:end);\n b = p.F_struc(1:p.K.f,1);\n for i = 1:length(p.aux_variables)\n j = find(A(:,p.aux_variables(i)));\n if length(j)==1\n if A(j,p.aux_variables(i))==1\n z(p.aux_variables(i)) = -b(j)-A(j,:)*z;\n end\n end\n end\n z = evaluate_nonlinear(p,z);\n end\n end\ncatch\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/initializesolution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18715415826631684}} {"text": "function mriCoord = cs_scs2mri(MRI, scsCoord)\n% CS_SCS2MRI: Transform SCS point coordinates (in mm) to MRI coordinate system (in mm) \n%\n% DEPRECATED: Replace with cs_convert()\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n\ndisp('BST> WARNING: Deprecated function cs_scs2mri(), use cs_convert() instead.');\n\nmriCoord = cs_convert(MRI, 'scs', 'mri', scsCoord' / 1000)' * 1000;\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/anatomy/cs_scs2mri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18709289516676972}} {"text": "function msg = mpc_init(s,c)\n apm(s,c,'clear all');\n\n % load model and data\n apm_load(s,c,'control.apm');\n csv_load(s,c,'control.csv');\n\n % configure MV / CV\n apm_info(s,c,'MV','Q1');\n apm_info(s,c,'MV','Q2');\n apm_info(s,c,'CV','TC1');\n apm_info(s,c,'CV','TC2');\n\n % dynamic control\n apm_option(s,c,'apm.imode',6);\n apm_option(s,c,'apm.solver',3);\n apm_option(s,c,'apm.hist_hor',600);\n\n % tune MV\n % delta MV movement penalty\n apm_option(s,c,'Q1.dcost',1.0e-4);\n apm_option(s,c,'Q2.dcost',1.0e-4);\n % penalize energy use\n apm_option(s,c,'Q1.cost',0.0);\n apm_option(s,c,'Q2.cost',0.0);\n % limit MV movement each cycle\n apm_option(s,c,'Q1.dmax',50);\n apm_option(s,c,'Q2.dmax',50);\n % MV limits\n apm_option(s,c,'Q1.upper',100);\n apm_option(s,c,'Q1.lower',0);\n apm_option(s,c,'Q2.upper',100);\n apm_option(s,c,'Q2.lower',0);\n\n % tune CV\n % how fast to reach setpoint\n apm_option(s,c,'TC1.tau',10);\n apm_option(s,c,'TC2.tau',10);\n % trajectory type\n apm_option(s,c,'TC1.tr_init',2);\n apm_option(s,c,'TC2.tr_init',2);\n\n % let optimizer use MV\n apm_option(s,c,'Q1.status',1);\n apm_option(s,c,'Q2.status',1);\n % include CV in objective function\n apm_option(s,c,'TC1.status',1);\n apm_option(s,c,'TC2.status',1);\n\n % feedback status (whether we have measurements)\n apm_option(s,c,'Q1.fstatus',0);\n apm_option(s,c,'Q2.fstatus',0);\n apm_option(s,c,'TC1.fstatus',1);\n apm_option(s,c,'TC2.fstatus',1);\n\n % web-viewer option, update every second\n apm_option(s,c,'apm.web_plot_freq',3);\n\n msg = 'initialization complete';\nend", "meta": {"author": "APMonitor", "repo": "arduino", "sha": "f36e65a70dd7122d1829883899e40e56bf6c4279", "save_path": "github-repos/MATLAB/APMonitor-arduino", "path": "github-repos/MATLAB/APMonitor-arduino/arduino-f36e65a70dd7122d1829883899e40e56bf6c4279/6_Model_Predictive_Control/2nd_order_nonlinear/MATLAB/mpc_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.18709289516676972}} {"text": "function model = setup_fmincon_params(model)\n\nmonomtable = model.monomtable;\nnonlinearindicies = model.nonlinearindicies;\nlinearindicies = model.linearindicies;\n\nmodel.evalinobjective = 0;\n\nif ~isempty(model.evalMap)\n [i,j,k] = find(model.monomtable(:,model.evalVariables));\n evalInvolved = union(model.evalVariables,i);\n model.evalinobjective = any(model.c(evalInvolved)) | any(model.Q(evalInvolved,1));\n if size(model.Anonlineq,1)>0\n if nnz(model.Anonlineq(:,evalInvolved))>0\n model.evalinconstraint = 1;\n end\n end\n if size(model.Anonlinineq,1)>0\n if nnz(model.Anonlinineq(:,evalInvolved))>0\n model.evalinconstraint = 1;\n end\n end\n if any(model.K.q)\n if nnz(model.F_struc(1+model.K.f + model.K.l:end,1+evalInvolved)) > 0\n model.evalinconstraint = 1;\n end\n end\n % Speed up callbacks by removing last marker argument (only used in\n % expandmodel etc) and figuring out what R^m -> R^n operators computes\n for i = 1:length(model.evalMap) \n model.evalMap{i}.prearg = {model.evalMap{i}.fcn,model.evalMap{i}.arg{1:end-1}};\n model.evalMap{i}.prearg{1+model.evalMap{i}.argumentIndex} = [];\n if ~isfield(model.evalMap{i},'computes')\n model.evalMap{i}.computes = model.evalVariables(i);\n end\n end\nend\n\n% Figure out if YALMIP easily can compute the gradient of the objective\n% This will done completely general later\nmodel.SimpleLinearObjective = 0; % Linear\nmodel.SimpleQuadraticObjective = 0; % Quadratic\nmodel.SimpleNonlinearObjective = 1; % Polynomial\nif isempty(model.evalMap)\n if nnz(model.c(nonlinearindicies)) == 0\n if (nnz(model.Q)==0)\n model.SimpleLinearObjective = 1;\n else\n if nnz(model.Q(nonlinearindicies,nonlinearindicies))==0\n model.SimpleQuadraticObjective = 1;\n end\n end\n end\nelseif ~model.evalinobjective\n if nnz(model.c(nonlinearindicies)) == 0\n if (nnz(model.Q)==0)\n model.SimpleLinearObjective = 1;\n else\n if nnz(model.Q(nonlinearindicies,nonlinearindicies))==0\n model.SimpleQuadraticObjective = 1;\n end\n end\n elseif nnz(model.Q)==0\n r = find(model.c);\n if all(model.variabletype(r)<=2)\n if isempty(intersect(r,model.evalVariables))\n % Simple quadratic function\n for i = r(:)'\n if model.variabletype(i)==2\n j = find(model.monomtable(i,:));\n model.Q(j,j) = model.c(i);\n model.c(i) = 0;\n elseif model.variabletype(i)==1\n j = find(model.monomtable(i,:));\n model.Q(j(1),j(2)) = model.c(i)/2;\n model.Q(j(2),j(1)) = model.c(i)/2;\n model.c(i) = 0;\n end\n end\n model.SimpleQuadraticObjective = 1;\n end\n end\n end\nelse\n model.SimpleNonlinearObjective = 0;\nend\n\nmodel.linearconstraints = isempty(model.Anonlinineq) & isempty(model.Anonlineq) & nnz(model.K.q)==0;\nmodel.nonlinearinequalities = ~isempty(model.Anonlinineq);\nmodel.nonlinearequalities = ~isempty(model.Anonlineq);\nif any(model.K.q)\n if nnz(model.F_struc(1+model.K.f + model.K.l:end,1+model.nonlinearindicies)) > 0\n model.nonlinearcones = 1;\n else\n model.nonlinearcones = 0;\n end\nelse\n model.nonlinearcones = 0;\nend\n\n% Structure for fast evaluation of monomial terms in differentiation\n if isempty(model.evalMap) & (model.nonlinearinequalities | model.nonlinearequalities | model.nonlinearcones) & ~isfield(model,'fastdiff') \n allA = [model.Anonlineq;model.Anonlinineq];\n dgAll = [];\n n = length(model.c);\n linearindicies = model.linearindicies;\n mtNonlinear = model.monomtable(model.nonlinearindicies,:);\n \n allDerivemt = [];\n news = [];\n c = [];\n mtNonlinear = mtNonlinear(:,linearindicies);\n mtNonlinear = mtNonlinear';\n \n [jj,ii,val] = find(mtNonlinear');\n for k = 1:length(ii)\n i = ii(k);\n j = jj(k);\n s=mtNonlinear(:,j);\n c = [c;s((i))];\n s((i)) = s((i))-1;\n allDerivemt = [allDerivemt s(:)];\n news = [news;j i];\n end\n \n allDerivemt = allDerivemt';\n \n model.fastdiff.news = news;\n model.fastdiff.allDerivemt = allDerivemt;\n model.fastdiff.c = c;\n model.fastdiff.univariateDifferentiates = 0;\n \n a1 = model.fastdiff.news(1:length(model.fastdiff.c),2); \n a2 = model.nonlinearindicies(model.fastdiff.news(1:length(model.fastdiff.c),1))'; \n zzz = [ones(length(a1),1)]; \n nn = max(max(length(model.linearindicies)),max(news(:,2))); \n mm = max(max(linearindicies),max(model.nonlinearindicies(news(:,1))));\n a1f = [a1(:);(1:length(model.linearindicies))']; \n a2f = [a2(:);model.linearindicies(:)]; \n zzzf = [zzz;ones(length(linearindicies),1)]; \n \n %model.fastdiff.newdxx = sparse(a1f,a2f,zzzf,nn,mm); \n %model.fastdiff.linear_in_newdxx = sub2ind([nn mm],a1(:),a2(:));\n model.fastdiff.newdxx = sparse(a1f,a2f,zzzf,nn,mm)'; \n model.fastdiff.linear_in_newdxx = sub2ind([mm nn],a2(:),a1(:));\n model.fastdiff.newdxx(model.fastdiff.linear_in_newdxx)=1;\n \n if all(sum(allDerivemt | allDerivemt,2)==1)\n model.fastdiff.univariateDifferentiates = 1;\n [i,j,k] = find(allDerivemt');\n if any(diff(j)<0)\n error;\n end\n model.fastdiff.univariateDiffMonom = i(:);\n model.fastdiff.univariateDiffPower = k(:);\n end\n else\n allA = [model.Anonlineq;model.Anonlinineq]; \n if any(model.K.q)\n allA = [allA;model.F_struc(1+model.K.f + model.K.f:end,2:end)];\n end\n requested = any(allA',2); \n [i,j,k] = find((model.deppattern(find(requested),:))); \n requested(j) = 1; \n model.fastdiff.requested = requested; \n end", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/extras/setup_fmincon_params.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18709288794277976}} {"text": "port = int16(2000);\nclient = py.carla.Client('localhost', port);\nclient.set_timeout(10.0);\nworld = client.get_world();\nblueprint_library = world.get_blueprint_library();\nactor_list = py.list(world.get_actors());\n\nid = 0;\n\nfor i=1:length(actor_list)\n k = actor_list{i}.type_id;\n \n if k(1:7) == \"vehicle\"\n id = i - 1;\n end\nend\n\nif (id == 0)\n fprintf('ERROR: Could not find any vehicle!\\n');\n fprintf('The program will now exit!\\n');\n return;\nend\n\ncarla_is_running = true;\nyolo_detection = true;\n\n% Sensor 1\nblueprint = world.get_blueprint_library().find('sensor.camera.rgb');\nblueprint.set_attribute('image_size_x', '1920')\nblueprint.set_attribute('image_size_y', '1080')\n% blueprint.set_attribute('sensor_tick', '.1');\ntransform = py.carla.Transform(py.carla.Location(pyargs('x',0.8, 'z',1.7)));\nsensor = world.spawn_actor(blueprint, transform, pyargs('attach_to',actor_list{id}));\n\npyModule = py.importlib.import_module('senFunc');\npy.senFunc.getData(sensor);\n\npause(.5);\n% data = uint8(py.array.array('d',py.numpy.nditer(ml)));\n\n% Load YOLO model\nif exist('yoloml','var') ~= 1\n disp('loading modified network')\n load('yoloml.mat')\nend\n\n% Display Initial Frame\nimage = py.getattr(pyModule, 'array');\n% image = py.numpy.ascontiguousarray(image);\nimMat = uint8(image);\n\n% Set Yolo parameters\nprobThresh = 0.175;\niouThresh = 0.5;\n\nmyImageSize = size(imMat);\n\nclassLabels = [\"aeroplane\",\t\"bicycle\",\t\"bird\"\t,\"boat\",\t\"bottle\"\t,\"bus\"\t,\"car\",...\n\"cat\",\t\"chair\"\t,\"cow\"\t,\"diningtable\"\t,\"dog\"\t,\"horse\",\t\"motorbike\",\t\"person\",\t\"pottedplant\",...\n\"sheep\",\t\"sofa\",\t\"train\",\t\"tvmonitor\"];\n\nimageHandle = imshow(imMat);\n\n% Detect After how many frames\ntotalFramesElapsed = 0;\npredictEvery = 2; \n\nwhile carla_is_running\n% pause(1);\n% clc;\n\n image = py.getattr(pyModule, 'array');\n imMat = uint8(image);\n \n % Detect Cars\n% [bboxes,scores] = detect(detector,imMat);\n% imMat = insertObjectAnnotation(imMat,'rectangle',bboxes,1);\n\n if yolo_detection\n redImage = single(imresize(imMat,[448 448]))/255;\n\n if ~rem(totalFramesElapsed, predictEvery)\n out = predict(yoloml,redImage,'ExecutionEnvironment','gpu');\n % fprintf('%d\\n', totalFramesElapsed);\n end\n class = out(1:980);\n boxProbs = out(981:1078);\n boxDims = out(1079:1470);\n\n outArray = zeros(7,7,30);\n\n for j = 0:6\n for i = 0:6\n outArray(i+1,j+1,1:20) = class(i*20*7+j*20+1:i*20*7+j*20+20);\n outArray(i+1,j+1,21:22) = boxProbs(i*2*7+j*2+1:i*2*7+j*2+2);\n outArray(i+1,j+1,23:30) = boxDims(i*8*7+j*8+1:i*8*7+j*8+8);\n end\n end\n\n [cellProb, cellIndex] = max(outArray(:,:,21:22),[],3);\n contain = max(outArray(:,:,21:22),[],3)>probThresh;\n\n [classMax, classMaxIndex] = max(outArray(:,:,1:20),[],3);\n\n boxes = [];\n\n counter = 0;\n for i = 1:7\n for j = 1:7\n if contain(i,j) == 1\n counter = counter+1; \n\n % Bounding box center relative to cell\n x = outArray(i,j,22+1+(cellIndex(i,j)-1)*4);\n y = outArray(i,j,22+2+(cellIndex(i,j)-1)*4);\n\n % Yolo outputs the square root of the width and height of the\n % bounding boxes (subtle detail in paper that took me forver to realize). \n % Relative to image size.\n w = (outArray(i,j,22+3+(cellIndex(i,j)-1)*4))^2;\n h = (outArray(i,j,22+4+(cellIndex(i,j)-1)*4))^2;\n\n %absolute values scaled to image size\n wS = w*448; \n hS = h*448;\n xS = (j-1)*448/7+x*448/7-wS/2;\n yS = (i-1)*448/7+y*448/7-hS/2;\n\n % this array will be used for drawing bounding boxes in Matlab\n boxes(counter).coords = [xS yS wS hS]; \n\n %save cell indices in the structure\n boxes(counter).cellIndex = [i,j];\n\n %save classIndex to structure\n boxes(counter).classIndex = classMaxIndex(i,j); \n\n % save cell proability to structure\n boxes(counter).cellProb = cellProb(i,j);\n\n % put in a switch for non max which we will use later\n boxes(counter).nonMax = 1;\n end \n end\n end\n\n for i = 1:length(boxes)\n for j = i+1:length(boxes)\n %calculate intersection over union (can also use bboxOverlapRatio\n %with proper toolbox\n intersect = rectint(boxes(i).coords,boxes(j).coords);\n union = boxes(i).coords(3)*boxes(i).coords(4)+boxes(j).coords(3)*boxes(j).coords(4)-intersect;\n iou(i,j) = intersect/union;\n if boxes(i).classIndex == boxes(j).classIndex && iou(i,j) > iouThresh \n [value(i), dropIndex(i)] = min([boxes(i).cellProb boxes(j).cellProb]);\n if dropIndex(i) == 1\n boxes(i).nonMax=0;\n elseif dropIndex(i) == 2\n boxes(j).nonMax=0; \n end\n end \n end\n end \n\n %imagesc(imMat);\n\n for i = 1:length(boxes)\n if boxes(i).nonMax == 1\n textStr = convertStringsToChars(classLabels(boxes(i).classIndex));\n\n if sum(textStr == [ \"bicycle\", \"car\", \"motorbike\",\t\"person\"])\n position = [(boxes(i).cellIndex(2)-1)*myImageSize(2)/7 (boxes(i).cellIndex(1)-1)*myImageSize(1)/7];\n %text(position(1),position(2),textStr,'Color',[0 1 0],'fontWeight','bold','fontSize',12);\n transformedCoor = boxes(i).coords .* [myImageSize(2) myImageSize(1) myImageSize(2) myImageSize(1)] / 448;\n\n imMat = insertText(imMat, transformedCoor([1, 2]), textStr, 'AnchorPoint','LeftBottom', 'FontSize', 36);\n imMat = insertShape(imMat, 'Rectangle', transformedCoor, 'LineWidth',5);\n\n % rectangle('Position',transformedCoor, 'EdgeColor','green','LineWidth',2);\n end\n end\n end\n end\n \n % Write directly to Cdata. Consideribly faster than imshow\n set(imageHandle,'Cdata',imMat);\n drawnow;\n\n totalFramesElapsed = totalFramesElapsed + 1;\n \n pause(0.001);\n \n % Directly write to Cdata, Noticibly faster than just imshow\n % rectangle('Position',[1 1 30 30], 'EdgeColor','green','LineWidth',2);\n %imagesc(imMat);\n %pause(.05);\n %py.cv2.imshow('Carla', image);\n % pause(0.05);\n% data = uint8(py.array.array('d',py.numpy.nditer(image)));\n% \n% data = reshape(data, 4, []);\n% \n% imMat(:,:,1) = reshape(data(3,:), 1920, 1080)';\n% imMat(:,:,2) = reshape(data(2,:), 1920, 1080)';\n% imMat(:,:,3) = reshape(data(1,:), 1920, 1080)';\n% \n% imshow(imMat);\n \n% for n=0:1080*1920-1\n% i = fix(n/1920) + 1;\n% j = rem(n,1920) + 1;\n% \n% imMat(i, j, 3) = data(4*n + 1);\n% imMat(i, j, 2) = data(4*n + 2);\n% imMat(i, j, 1) = data(4*n + 3);\n% end\n\n% % currentLocation = actor_list{id}.get_location();\n% % fprintf('Location: [m]\\n')\n% % fprintf('x: %.2f \\t y: %.2f \\t z: %.2f \\n\\n',currentLocation.x, currentLocation.y, currentLocation.z);\n% % \n% % fprintf('Velocity: [m/s]\\n')\n% % currentVelocity = actor_list{id}.get_velocity();\n% % fprintf('x: %.2f \\t y: %.2f \\t z: %.2f \\n\\n',currentVelocity.x, currentVelocity.y, currentVelocity.z);\n% % \n% % fprintf('Acceleration: [m/s^2]\\n')\n% % currentAcceleration = actor_list{id}.get_acceleration();\n% % fprintf('x: %.2f \\t y: %.2f \\t z: %.2f \\n\\n',currentAcceleration.x, currentAcceleration.y, currentAcceleration.z);\n% % \n% % omega = char (hex2dec ( '03C9' ));\n% % fprintf('Angular Velocity: [%s]\\n', omega);\n% % currentAngVelocity = actor_list{id}.get_angular_velocity();\n% % fprintf('x: %.2f \\t y: %.2f \\t z: %.2f \\n\\n',currentAngVelocity.x, currentAngVelocity.y, currentAngVelocity.z);\n% \nend", "meta": {"author": "darkscyla", "repo": "MATLAB-Carla-Interface", "sha": "a089f34784b75c66490ce6055dfefaded6117409", "save_path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface", "path": "github-repos/MATLAB/darkscyla-MATLAB-Carla-Interface/MATLAB-Carla-Interface-a089f34784b75c66490ce6055dfefaded6117409/\ue83aobsolete_/Carla Image Processing/CarlaDataAcquisition-Raw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18701233755214625}} {"text": "function out = spm_deformations(job)\n% Various deformation field utilities\n% FORMAT out = spm_deformations(job)\n% job - a job created via spm_cfg_deformations.m\n% out - a struct with fields\n% .def - file name of created deformation field\n% .warped - file names of warped images\n%\n% See spm_cfg_deformations.m for more information.\n%__________________________________________________________________________\n% Copyright (C) 2005-2015 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_deformations.m 6577 2015-10-15 15:22:11Z volkmar $\n\n\n[Def,mat] = get_comp(job.comp);\nout = struct('def',{{}},'warped',{{}},'surf',{{}},'jac',{{}});\nfor i=1:numel(job.out)\n fn = fieldnames(job.out{i});\n fn = fn{1};\n switch fn\n case 'savedef'\n out.def = [out.def; save_def(Def,mat,job.out{i}.(fn))];\n case 'pull'\n out.warped = [out.warped; pull_def(Def,mat,job.out{i}.(fn))];\n case 'push'\n out.warped = [out.warped; push_def(Def,mat,job.out{i}.(fn))];\n case 'surf'\n out.surf = [out.surf; surf_def(Def,mat,job.out{i}.(fn))];\n case 'savejac'\n out.jac = [out.jac; jac_def(Def,mat,job.out{i}.(fn))];\n otherwise\n error('Unknown option');\n end\nend\n\n\n%==========================================================================\n% function [Def,mat] = get_comp(job)\n%==========================================================================\nfunction [Def,mat] = get_comp(job)\n% Return the composition of a number of deformation fields.\n\nif isempty(job)\n error('Empty list of jobs in composition');\nend\n[Def,mat] = get_job(job{1});\nfor i=2:numel(job)\n Def1 = Def;\n mat1 = mat;\n [Def,mat] = get_job(job{i});\n M = inv(mat1);\n tmp = zeros(size(Def),'single');\n tmp(:,:,:,1) = M(1,1)*Def(:,:,:,1)+M(1,2)*Def(:,:,:,2)+M(1,3)*Def(:,:,:,3)+M(1,4);\n tmp(:,:,:,2) = M(2,1)*Def(:,:,:,1)+M(2,2)*Def(:,:,:,2)+M(2,3)*Def(:,:,:,3)+M(2,4);\n tmp(:,:,:,3) = M(3,1)*Def(:,:,:,1)+M(3,2)*Def(:,:,:,2)+M(3,3)*Def(:,:,:,3)+M(3,4);\n Def(:,:,:,1) = single(spm_diffeo('bsplins',Def1(:,:,:,1),tmp,[1,1,1,0,0,0]));\n Def(:,:,:,2) = single(spm_diffeo('bsplins',Def1(:,:,:,2),tmp,[1,1,1,0,0,0]));\n Def(:,:,:,3) = single(spm_diffeo('bsplins',Def1(:,:,:,3),tmp,[1,1,1,0,0,0]));\n clear tmp\nend\n\n\n%==========================================================================\n% function [Def,mat] = get_job(job)\n%==========================================================================\nfunction [Def,mat] = get_job(job)\n% Determine what is required, and pass the relevant bit of the\n% job out to the appropriate function.\n\nfn = fieldnames(job);\nfn = fn{1};\nswitch fn\n case {'comp'}\n [Def,mat] = get_comp(job.(fn));\n case {'def'}\n [Def,mat] = get_def(job.(fn));\n case {'dartel'}\n [Def,mat] = get_dartel(job.(fn));\n case {'sn2def'}\n [Def,mat] = get_sn2def(job.(fn));\n case {'inv'}\n [Def,mat] = get_inv(job.(fn));\n case {'id'}\n [Def,mat] = get_id(job.(fn));\n case {'idbbvox'}\n [Def,mat] = get_idbbvox(job.(fn));\n otherwise\n error('Unrecognised job type');\nend\n\n\n%==========================================================================\n% function [Def,mat] = get_sn2def(job)\n%==========================================================================\nfunction [Def,mat] = get_sn2def(job)\n% Convert a SPM _sn.mat file into a deformation field, and return it.\n\nvox = job.vox;\nbb = job.bb;\nsn = load(job.matname{1});\n\nif any(isfinite(bb(:))) || any(isfinite(vox))\n [bb0, vox0] = spm_get_bbox(sn.VG(1));\n if any(~isfinite(vox)), vox = vox0; end\n if any(~isfinite(bb)), bb = bb0; end\n bb = sort(bb);\n vox = abs(vox);\n\n % Adjust bounding box slightly - so it rounds to closest voxel.\n bb(:,1) = round(bb(:,1)/vox(1))*vox(1);\n bb(:,2) = round(bb(:,2)/vox(2))*vox(2);\n bb(:,3) = round(bb(:,3)/vox(3))*vox(3);\n\n M = sn.VG(1).mat;\n vxg = sqrt(sum(M(1:3,1:3).^2));\n ogn = M\\[0 0 0 1]';\n ogn = ogn(1:3)';\n\n % Convert range into range of voxels within template image\n x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);\n y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);\n z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);\n\n og = -vxg.*ogn;\n of = -vox.*(round(-bb(1,:)./vox)+1);\n M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];\n M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];\n mat = sn.VG(1).mat*(M1\\M2);\n % dim = [length(x) length(y) length(z)];\nelse\n dim = sn.VG(1).dim;\n x = 1:dim(1);\n y = 1:dim(2);\n z = 1:dim(3);\n mat = sn.VG(1).mat;\nend\n\n[X,Y] = ndgrid(x,y);\n\nst = size(sn.Tr);\n\nif (prod(st) == 0)\n affine_only = true;\n basX = 0;\n basY = 0;\n basZ = 0;\nelse\n affine_only = false;\n basX = spm_dctmtx(sn.VG(1).dim(1),st(1),x-1);\n basY = spm_dctmtx(sn.VG(1).dim(2),st(2),y-1);\n basZ = spm_dctmtx(sn.VG(1).dim(3),st(3),z-1);\nend\n\nDef = zeros([numel(x),numel(y),numel(z),3],'single');\n\nfor j=1:length(z)\n if (~affine_only)\n tx = reshape( reshape(sn.Tr(:,:,:,1),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n ty = reshape( reshape(sn.Tr(:,:,:,2),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n tz = reshape( reshape(sn.Tr(:,:,:,3),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );\n\n X1 = X + basX*tx*basY';\n Y1 = Y + basX*ty*basY';\n Z1 = z(j) + basX*tz*basY';\n end\n\n Mult = sn.VF.mat*sn.Affine;\n if (~affine_only)\n X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);\n Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);\n Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);\n else\n X2= Mult(1,1)*X + Mult(1,2)*Y + (Mult(1,3)*z(j) + Mult(1,4));\n Y2= Mult(2,1)*X + Mult(2,2)*Y + (Mult(2,3)*z(j) + Mult(2,4));\n Z2= Mult(3,1)*X + Mult(3,2)*Y + (Mult(3,3)*z(j) + Mult(3,4));\n end\n\n Def(:,:,j,1) = single(X2);\n Def(:,:,j,2) = single(Y2);\n Def(:,:,j,3) = single(Z2);\nend\n\n\n%==========================================================================\n% function [Def,mat] = get_def(job)\n%==========================================================================\nfunction [Def,mat] = get_def(job)\n% Load a deformation field saved as an image\nNii = nifti(job{1});\nDef = single(Nii.dat(:,:,:,1,:));\nd = size(Def);\nif d(4)~=1 || d(5)~=3, error('Deformation field is wrong!'); end\nDef = reshape(Def,[d(1:3) d(5)]);\nmat = Nii.mat;\n\n%==========================================================================\n% function [Def,mat] = get_dartel(job)\n%==========================================================================\nfunction [Def,mat] = get_dartel(job)\n\nNii = nifti(job.flowfield{1});\n\nif ~isempty(job.template{1})\n %Nt = nifti(job.template{1});\n [pth,nam] = fileparts(job.template{1});\n if exist(fullfile(pth,[nam '_2mni.mat']),'file')\n load(fullfile(pth,[nam '_2mni.mat']),'mni');\n else\n % Affine registration of Dartel Template with MNI space.\n %------------------------------------------------------------------\n fprintf('** Affine registering \"%s\" with MNI space **\\n', nam);\n tpm = fullfile(spm('Dir'),'tpm','TPM.nii');\n Mmni = spm_get_space(tpm);\n Nt = nifti(job.template{1});\n mni.affine = Mmni/spm_klaff(Nt,tpm);\n mni.code = 'MNI152';\n save(fullfile(pth,[nam '_2mni.mat']),'mni', spm_get_defaults('mat.format'));\n end\n Mat = mni.affine;\n %do_aff = true;\nelse\n Mat = Nii.mat;\n %do_aff = false;\nend\n\n% Integrate a Dartel flow field\ny0 = spm_dartel_integrate(Nii.dat,job.times,job.K);\nif all(job.times == [0 1]),\n mat = Nii.mat0;\n Def = affine(y0,single(Mat));\nelse\n mat = Mat;\n Def = affine(y0,single(Nii.mat0));\nend\n\n\n%==========================================================================\n% function [Def,mat] = get_id(job)\n%==========================================================================\nfunction [Def,mat] = get_id(job)\n% Get an identity transform based on an image volume\n[mat, dim] = spm_get_matdim(job.space{1});\nDef = identity(dim, mat);\n\n\n%==========================================================================\n% function [Def,mat] = get_idbbvox(job)\n%==========================================================================\nfunction [Def,mat] = get_idbbvox(job)\n% Get an identity transform based on bounding box and voxel size.\n% This will produce a transversal image.\n[mat, dim] = spm_get_matdim('', job.vox, job.bb);\nDef = identity(dim, mat);\n\n\n%==========================================================================\n% function [Def,mat] = get_inv(job)\n%==========================================================================\nfunction [Def,mat] = get_inv(job)\n% Invert a deformation field (derived from a composition of deformations)\n\nNT = nifti(job.space{:});\n[Def0,mat0] = get_comp(job.comp);\nM0 = mat0;\nM1 = inv(NT.mat);\nM0(4,:) = [0 0 0 1];\nM1(4,:) = [0 0 0 1];\nDef = spm_diffeo('invdef',Def0,NT.dat.dim(1:3),M1,M0);\nmat = NT.mat;\nDef = spm_extrapolate_def(Def,mat);\n\n%==========================================================================\n% function fname = save_def(Def,mat,job)\n%==========================================================================\nfunction fname = save_def(Def,mat,job)\n% Save a deformation field as an image\n\nofname = job.ofname;\nif isempty(ofname), fname = {}; return; end;\n\n[pth,nam] = fileparts(ofname);\nif isfield(job.savedir,'savepwd')\n wd = pwd;\nelseif isfield(job.savedir,'saveusr')\n wd = job.savedir.saveusr{1};\nelse\n wd = pwd;\nend\n\nfname = {fullfile(wd,['y_' nam '.nii'])};\ndim = [size(Def,1) size(Def,2) size(Def,3) 1 3];\ndtype = 'FLOAT32-LE';\noff = 0;\nscale = 1;\ninter = 0;\ndat = file_array(fname{1},dim,dtype,off,scale,inter);\n\nN = nifti;\nN.dat = dat;\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.intent.code = 'VECTOR';\nN.intent.name = 'Mapping';\nN.descrip = 'Deformation field';\ncreate(N);\nN.dat(:,:,:,1,1) = Def(:,:,:,1);\nN.dat(:,:,:,1,2) = Def(:,:,:,2);\nN.dat(:,:,:,1,3) = Def(:,:,:,3);\n\n\n%==========================================================================\n% function fname = jac_def(Def,mat,job)\n%==========================================================================\nfunction fname = jac_def(Def,mat,job)\n% Save Jacobian determinants of deformation field \n\nofname = job.ofname;\nif isempty(ofname), fname = {}; return; end;\n\n[pth,nam] = fileparts(ofname);\nif isfield(job.savedir,'savepwd')\n wd = pwd;\nelseif isfield(job.savedir,'saveusr')\n wd = job.savedir.saveusr{1};\nelse\n wd = pwd;\nend\n\nDets = spm_diffeo('def2det',Def)/det(mat(1:3,1:3));\nDets(:,:,[1 end]) = NaN;\nDets(:,[1 end],:) = NaN;\nDets([1 end],:,:) = NaN;\n\nfname = {fullfile(wd,['j_' nam '.nii'])};\ndim = [size(Def,1) size(Def,2) size(Def,3) 1 1];\ndtype = 'FLOAT32-LE';\noff = 0;\nscale = 1;\ninter = 0;\ndat = file_array(fname{1},dim,dtype,off,scale,inter);\n\nN = nifti;\nN.dat = dat;\nN.mat = mat;\nN.mat0 = mat;\nN.mat_intent = 'Aligned';\nN.mat0_intent = 'Aligned';\nN.intent.code = 0;\nN.intent.name = 'Mapping';\nN.descrip = 'Jacobian Determinants';\ncreate(N);\nN.dat(:,:,:,1,1) = Dets;\n\n\n%==========================================================================\n% function out = pull_def(Def,mat,job)\n%==========================================================================\nfunction out = pull_def(Def,mat,job)\n\nPI = job.fnames;\nintrp = job.interp;\nintrp = [intrp*[1 1 1], 0 0 0];\nout = cell(numel(PI),1);\n\nif numel(PI)==0, return; end\n\nif job.mask\n oM = zeros(4,4);\n odm = zeros(1,3);\n dim = size(Def);\n msk = true(dim);\n for m=1:numel(PI)\n [pth,nam,ext,num] = spm_fileparts(PI{m});\n NI = nifti(fullfile(pth,[nam ext]));\n dm = NI.dat.dim(1:3);\n if isempty(num)\n j_range = 1:size(NI.dat,4);\n else\n num = sscanf(num,',%d');\n j_range = num(1);\n end\n for j=j_range\n\n M0 = NI.mat;\n if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat')\n M1 = NI.extras.mat;\n if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0\n M0 = M1(:,:,j);\n end\n end\n M = inv(M0);\n if ~all(M(:)==oM(:)) || ~all(dm==odm)\n tmp = affine(Def,M);\n msk = tmp(:,:,:,1)>=1 & tmp(:,:,:,1)<=size(NI.dat,1) ...\n & tmp(:,:,:,2)>=1 & tmp(:,:,:,2)<=size(NI.dat,2) ...\n & tmp(:,:,:,3)>=1 & tmp(:,:,:,3)<=size(NI.dat,3);\n end\n oM = M;\n odm = dm;\n end\n end\nend\n\noM = zeros(4,4);\nspm_progress_bar('Init',numel(PI),'Resampling','volumes completed');\nfor m=1:numel(PI)\n\n % Generate headers etc for output images\n %----------------------------------------------------------------------\n [pth,nam,ext,num] = spm_fileparts(PI{m});\n NI = nifti(fullfile(pth,[nam ext]));\n\n j_range = 1:size(NI.dat,4);\n k_range = 1:size(NI.dat,5);\n l_range = 1:size(NI.dat,6);\n if ~isempty(num)\n num = sscanf(num,',%d');\n if numel(num)>=1, j_range = num(1); end\n if numel(num)>=2, k_range = num(2); end\n if numel(num)>=3, l_range = num(3); end\n end\n\n NO = NI;\n if isfield(job.savedir,'savepwd')\n wd = pwd;\n elseif isfield(job.savedir,'saveusr')\n wd = job.savedir.saveusr{1};\n elseif isfield(job.savedir,'savesrc')\n wd = pth;\n else\n wd = pwd;\n end\n\n if sum(job.fwhm.^2)==0\n newprefix = spm_get_defaults('normalise.write.prefix');\n NO.descrip = sprintf('Warped');\n else\n newprefix = [spm_get_defaults('smooth.prefix') spm_get_defaults('normalise.write.prefix')];\n NO.descrip = sprintf('Smoothed (%gx%gx%g subopt) warped',job.fwhm);\n end\n if isfield(job,'prefix') && ~isempty(job.prefix)\n NO.dat.fname = fullfile(wd,[job.prefix nam ext]);\n else\n NO.dat.fname = fullfile(wd,[newprefix nam ext]);\n end\n dim = size(Def);\n dim = dim(1:3);\n NO.dat.dim = [dim NI.dat.dim(4:end)];\n NO.dat.offset = 0; % For situations where input .nii images have an extension.\n NO.mat = mat;\n NO.mat0 = mat;\n NO.mat_intent = 'Aligned';\n NO.mat0_intent = 'Aligned';\n if isempty(num)\n out{m} = NO.dat.fname;\n else\n out{m} = [NO.dat.fname, ',', num2str(num(1))]; \n end\n NO.extras = [];\n create(NO);\n\n % Smoothing settings\n vx = sqrt(sum(mat(1:3,1:3).^2));\n krn = max(job.fwhm./vx,0.25);\n\n % Loop over volumes within the file\n %----------------------------------------------------------------------\n %fprintf('%s',nam);\n for j=j_range\n\n M0 = NI.mat;\n if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat')\n M1 = NI.extras.mat;\n if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0\n M0 = M1(:,:,j);\n end\n end\n M = inv(M0);\n if ~all(M(:)==oM(:))\n % Generate new deformation (if needed)\n Y = affine(Def,M);\n end\n oM = M;\n % Write the warped data for this time point\n %------------------------------------------------------------------\n for k=k_range\n for l=l_range\n C = spm_diffeo('bsplinc',single(NI.dat(:,:,:,j,k,l)),intrp);\n dat = spm_diffeo('bsplins',C,Y,intrp);\n if job.mask\n dat(~msk) = NaN;\n end\n if sum(job.fwhm.^2)~=0\n spm_smooth(dat,dat,krn); % Side effects\n end\n NO.dat(:,:,:,j,k,l) = dat;\n %fprintf('\\t%d,%d,%d', j,k,l);\n end\n end\n end\n %fprintf('\\n');\n spm_progress_bar('Set',m);\nend\nspm_progress_bar('Clear');\n\n\n%==========================================================================\n% function out = push_def(Def,mat,job)\n%==========================================================================\nfunction out = push_def(Def,mat,job)\n% Generate deformation, which is the inverse of the usual one (it is for \"pushing\"\n% rather than the usual \"pulling\"). This deformation is affine transformed to\n% allow for different voxel sizes and bounding boxes, and also to incorporate\n% the affine mapping between MNI space and the population average shape.\n%--------------------------------------------------------------------------\n\n% Deal with desired bounding box and voxel sizes.\n%--------------------------------------------------------------------------\nif isfield(job.fov,'file')\n N1 = nifti(job.fov.file);\n mat0 = N1.mat;\n dim = N1.dat.dim(1:3);\nelse\n bb = job.fov.bbvox.bb;\n vox = job.fov.bbvox.vox;\n [mat0, dim] = spm_get_matdim('', vox, bb);\nend\n\nM = inv(mat0);\ny0 = affine(Def,M);\n\nif isfield(job,'weight') && ~isempty(job.weight) && ~isempty(job.weight{1})\n wfile = job.weight{1};\n Nw = nifti(wfile);\n Mw = Nw.mat;\n wt = Nw.dat(:,:,:,1,1,1);\nelse\n wt = [];\nend\n\nodm = zeros(1,3);\noM = zeros(4,4);\nPI = job.fnames;\nout = cell(numel(PI),1);\nfor m=1:numel(PI)\n\n % Generate headers etc for output images\n %----------------------------------------------------------------------\n [pth,nam,ext,num] = spm_fileparts(PI{m});\n NI = nifti(fullfile(pth,[nam ext]));\n j_range = 1:size(NI.dat,4);\n k_range = 1:size(NI.dat,5);\n l_range = 1:size(NI.dat,6);\n if ~isempty(num)\n num = sscanf(num,',%d');\n if numel(num)>=1, j_range = num(1); end\n if numel(num)>=2, k_range = num(2); end\n if numel(num)>=3, l_range = num(3); end\n end\n \n if isfield(job.savedir,'savepwd')\n wd = pwd;\n elseif isfield(job.savedir,'saveusr')\n wd = job.savedir.saveusr{1};\n elseif isfield(job.savedir,'savesrc')\n wd = pth;\n else\n wd = pwd;\n end\n\n NO = NI;\n if job.preserve\n NO.dat.scl_slope = 1.0;\n NO.dat.scl_inter = 0.0;\n NO.dat.dtype = 'float32-le';\n if sum(job.fwhm.^2)==0\n newprefix = [spm_get_defaults('deformations.modulate.prefix') spm_get_defaults('normalise.write.prefix')];\n NO.descrip = sprintf('Warped & Jac scaled');\n else\n newprefix = [spm_get_defaults('smooth.prefix') spm_get_defaults('deformations.modulate.prefix') spm_get_defaults('normalise.write.prefix')];\n NO.descrip = sprintf('Smoothed (%gx%gx%g) warped Jac scaled',job.fwhm);\n end\n else\n if sum(job.fwhm.^2)==0\n newprefix = spm_get_defaults('normalise.write.prefix');\n NO.descrip = sprintf('Warped');\n else\n newprefix = [spm_get_defaults('smooth.prefix') spm_get_defaults('normalise.write.prefix')];\n NO.descrip = sprintf('Smoothed (%gx%gx%g opt) warped',job.fwhm);\n end\n end\n if isfield(job,'prefix') && ~isempty(job.prefix)\n NO.dat.fname = fullfile(wd,[job.prefix nam ext]);\n else\n NO.dat.fname = fullfile(wd,[newprefix nam ext]);\n end\n NO.dat.dim = [dim NI.dat.dim(4:end)];\n NO.dat.offset = 0; % For situations where input .nii images have an extension.\n NO.mat = mat0;\n NO.mat0 = mat0;\n NO.mat_intent = 'Aligned';\n NO.mat0_intent = 'Aligned';\n\n if isempty(num)\n out{m} = NO.dat.fname;\n else\n out{m} = [NO.dat.fname, ',', num2str(num(1))];\n end\n\n NO.extras = [];\n create(NO);\n\n % Smoothing settings\n vx = sqrt(sum(mat0(1:3,1:3).^2));\n krn = max(job.fwhm./vx,0.25);\n\n % Loop over volumes within the file\n %----------------------------------------------------------------------\n fprintf('%s',nam); drawnow;\n for j=j_range\n\n % Need to resample the mapping by an affine transform\n % so that it maps from voxels in the native space image\n % to voxels in the spatially normalised image.\n %------------------------------------------------------------------\n M0 = NI.mat;\n if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat')\n M1 = NI.extras.mat;\n if size(M1,3) >= j && sum(sum(M1(:,:,j).^2)) ~=0\n M0 = M1(:,:,j);\n end\n end\n\n M = mat\\M0;\n dm = [size(NI.dat),1,1,1,1];\n if ~all(dm(1:3)==odm) || ~all(M(:)==oM(:))\n % Generate new deformation (if needed)\n y = zeros([dm(1:3),3],'single');\n for d=1:3\n yd = y0(:,:,:,d);\n for x3=1:size(y,3)\n y(:,:,x3,d) = single(spm_slice_vol(yd,M*spm_matrix([0 0 x3]),dm(1:2),[1 NaN]));\n end\n end\n end\n\n odm = dm(1:3);\n oM = M;\n % Write the warped data for this time point.\n %------------------------------------------------------------------\n for k=k_range\n for l=l_range\n f = single(NI.dat(:,:,:,j,k,l));\n if isempty(wt)\n if ~job.preserve\n % Unmodulated - note the slightly novel procedure\n [f,c] = spm_diffeo('push',f,y,dim);\n spm_smooth(f,f,krn); % Side effects\n spm_smooth(c,c,krn); % Side effects\n f = f./(c+0.001);\n else\n % Modulated, by pushing\n scal = abs(det(NI.mat(1:3,1:3))/det(NO.mat(1:3,1:3))); % Account for vox sizes\n f = spm_diffeo('push',f,y,dim)*scal;\n spm_smooth(f,f,krn); % Side effects\n end\n else\n if isequal(size(wt),size(f)) && sum((Mw(:)-M0(:)).^2)<1e-6\n wtw = single(wt);\n f = single(f.*wt);\n else\n wtw = zeros(size(f),'single');\n for z=1:size(wt,3)\n Mz = Mw\\M0*[1 0 0 0; 0 1 0 0; 0 0 1 z; 0 0 0 1];\n wtw(:,:,z) = single(spm_slice_vol(wt,Mz,[size(f,1),size(f,2)],1));\n end\n end\n if ~job.preserve\n % Unmodulated - note the slightly novel procedure\n f = spm_diffeo('push',f.*wtw,y,dim);\n c = spm_diffeo('push',wtw,y,dim);\n spm_smooth(f,f,krn); % Side effects\n spm_smooth(c,c,krn); % Side effects\n f = f./(c+0.001);\n else\n % Modulated, by pushing\n scal = abs(det(NI.mat(1:3,1:3))/det(NO.mat(1:3,1:3))); % Account for vox sizes\n f = spm_diffeo('push',f.*wtw,y,dim)*scal;\n spm_smooth(f,f,krn); % Side effects\n end\n clear wtw\n end\n NO.dat(:,:,:,j,k,l) = f;\n fprintf('\\t%d,%d,%d', j,k,l); drawnow;\n end\n end\n end\n fprintf('\\n'); drawnow;\nend\n\n\n%==========================================================================\n% function out = surf_def(Def,mat,job)\n%==========================================================================\nfunction out = surf_def(Def,mat,job)\nfilenames = job.surface;\nout = cell(numel(filenames),1);\nfor i=1:numel(filenames)\n fname = deblank(job.surface{i});\n [pth,nam] = fileparts(fname);\n fprintf('%s\\n', nam);\n d = size(Def);\n tmp = double(reshape(Def,[d(1:3) 1 d(4)]));\n Tmesh = spm_swarp(fname, tmp,mat);\n if isfield(job.savedir,'savepwd')\n wd = pwd;\n elseif isfield(job.savedir,'saveusr')\n wd = job.savedir.saveusr{1};\n elseif isfield(job.savedir,'savesrc')\n wd = pth;\n else\n wd = pwd;\n end\n filename = fullfile(wd,[nam,'_warped', '.gii']);\n save(gifti(Tmesh), filename);\n out{i} = filename;\nend\n\n\n%==========================================================================\n% function Def = affine(y,M)\n%==========================================================================\nfunction Def = affine(y,M)\nDef = zeros(size(y),'single');\nDef(:,:,:,1) = y(:,:,:,1)*M(1,1) + y(:,:,:,2)*M(1,2) + y(:,:,:,3)*M(1,3) + M(1,4);\nDef(:,:,:,2) = y(:,:,:,1)*M(2,1) + y(:,:,:,2)*M(2,2) + y(:,:,:,3)*M(2,3) + M(2,4);\nDef(:,:,:,3) = y(:,:,:,1)*M(3,1) + y(:,:,:,2)*M(3,2) + y(:,:,:,3)*M(3,3) + M(3,4);\n\n\n%==========================================================================\n% function Def = identity(d,M)\n%==========================================================================\nfunction Def = identity(d,M)\n[y1,y2] = ndgrid(single(1:d(1)),single(1:d(2)));\nDef = zeros([d 3],'single');\nfor y3=1:d(3)\n Def(:,:,y3,1) = y1*M(1,1) + y2*M(1,2) + (y3*M(1,3) + M(1,4));\n Def(:,:,y3,2) = y1*M(2,1) + y2*M(2,2) + (y3*M(2,3) + M(2,4));\n Def(:,:,y3,3) = y1*M(3,1) + y2*M(3,2) + (y3*M(3,3) + M(3,4));\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/spm12/spm_deformations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18692887382224538}} {"text": "% LFDispVidCirc - visualize a 4D light field animating a circular path through two dimensions\n% \n% Usage: \n% FigureHandle = LFDispVidCirc( LF )\n% FigureHandle = LFDispVidCirc( LF, [RenderOptions], [ScaleFactor] )\n% \n% \n% Inputs:\n% \n% LF : a colour or single-channel light field, and can a floating point or integer format. For\n% display, it is converted to 8 bits per channel. If LF contains more than three colour\n% channels, as is the case when a weight channel is present, only the first three are used.\n% \n% Optional Inputs: \n% \n% RenderOptions : struct controlling rendering\n% .PathRadius_percent : radius of the circular path taken by the viewpoint. Values that are\n% too high can result in collision with the edges of the lenslet image,\n% while values that are too small result in a less impressive\n% visualization. The default value is 60%.\n% .FrameDelay : delay between frames, in seconds. Default 1/30.\n% .NumCycles : how many times the circular path should repeat. Default inf.\n% .FramesPerCycle : how many frames along a single cycle. Default 20.\n% \n% ScaleFactor : Adjusts the size of the display -- 1 means no change, 2 means twice as\n% big, etc. Integer values are recommended to avoid scaling artifacts.\n% \n% Outputs:\n% \n% FigureHandle\n%\n%\n% User guide: LFToolbox.pdf\n% See also: LFDisp, LFDispMousePan, LFDispLawnmower, LFDispProj, LFDispTiles\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction FigureHandle = LFDispVidCirc( LF, RenderOptions, ScaleFactor )\n\n%---Defaults---\nScaleFactor = LFDefaultVal('ScaleFactor', 1);\nRenderOptions = LFDefaultField( 'RenderOptions', 'PathRadius_percent', 60 );\nRenderOptions = LFDefaultField( 'RenderOptions', 'FrameDelay', 1/30 );\nRenderOptions = LFDefaultField( 'RenderOptions', 'NumCycles', inf );\nRenderOptions = LFDefaultField( 'RenderOptions', 'FramesPerCycle', 20 );\n\n%---Check for mono and clip off the weight channel if present---\nMono = (ndims(LF) == 4);\nif( ~Mono )\n LF = LF(:,:,:,:,1:3);\nend\n\n%---Rescale for 8-bit display---\nif( isfloat(LF) )\n LF = uint8(LF ./ max(LF(:)) .* 255);\nelse\n LF = uint8(LF.*(255 / double(intmax(class(LF)))));\nend\n\n%---Setup the motion path---\n[TSize,SSize, ~,~] = size(LF(:,:,:,:,1));\nTCent = (TSize-1)/2 + 1;\nSCent = (SSize-1)/2 + 1;\n\nt = 0;\nRotRad = TCent*RenderOptions.PathRadius_percent/100;\nNumFrames = RenderOptions.NumCycles * RenderOptions.FramesPerCycle;\n\n%---Setup the display---\nTIdx = round(TCent + RotRad);\nSIdx = round(SCent);\n[ImageHandle,FigureHandle] = LFDispSetup( squeeze(LF(TIdx,SIdx,:,:,:)), ScaleFactor );\n\nwhile(1)\n TVal = TCent + RotRad * cos( 2*pi*t/RenderOptions.FramesPerCycle );\n SVal = SCent + RotRad * sin( 2*pi*t/RenderOptions.FramesPerCycle );\n \n SIdx = round(SVal);\n TIdx = round(TVal);\n\t\n CurFrame = squeeze(LF( TIdx, SIdx, :,:,: ));\n set(ImageHandle,'cdata', CurFrame );\n \n pause(RenderOptions.FrameDelay)\n t = t + 1;\n\t\n\tif( t > NumFrames )\n\t\tbreak;\n\tend\nend\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/LFDispVidCirc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1868103121533196}} {"text": "function [stimset,stim_full] = StimulusKeyPreprocessing(frame_turn,i_fish,isplotting)\n% [stimset,stim_full] = StimulusKeyPreprocessing(frame_turn,i_fish,'isplotting');\n\nif exist('isplotting','var'),\n isPlotting = true; % plot parsing process for manual inspection!\nelse\n isPlotting = false;\nend\n% Manual inputs needed for this function:\n% - protocol sequence and naming, as in 'block_raw' and 'stimset' initialization\n% - substitution array 'M_range', to substitute original stimulus code to a\n% tighter range that is better defined for plotting (both for plotting values and stimulus bar)\n\n\n%% Load stimulus\n\nst = frame_turn(:,17)'; % from raw file\n\n% cap abnormally high values in raw values\ntemp = sort(st,'descend');\nthr = temp(round(length(st)/100)); % arb. thr % used /10 up till 1/27/16 for all fish except Fish12\nst(st>thr) = thr+1; % assign cap value to be thr+1\n\nxv = 0:thr+1; % x-vector for histogram bins\n\n% Manual inspection\n% figure;\n% hist(st,xv);\n\n% (continue by default) find bins with significantly high counts, i.e.\n% whole range/set of raw stimulus keys, store in 'M_range_raw'\n% use to manually define standardized 'M_range'\ncounts = hist(st,xv);\nthr_counts = round(length(st)/500);\nM_range_raw = xv(counts>thr_counts);\nif isPlotting,\n disp(['M_range_raw = ' num2str(M_range_raw)]); % use this to adjust the substitution array, M_range, manually after this inspection!%%%%%%%%%%%%%%%%%%%%%%\nend\n\n%% Raw Stimlus Key ----------------------------------------------------------------------------- MANUAL INPUT!\n\n% Manually input protocol sequence\n% stored in 'block', based on the raw stimulus code\n%% Manual: params for each fish\n\n% write out protocol sequence for each block; write stimulus sets within block in arrays within cell\nif i_fish == 8,\n nBlocks = 3;\n block_raw = cell(nBlocks,1); % number of blocks\n block_raw{1} = {[2,3,4,5],[12,13,12,14,12,15],99,};\n block_raw{2} = {[2,100,2,3,4,100,4,5],[2,100,2,3,4,100,4,5],[12,100,12,13,12,100,12,14,12,100,12,15],99};\n block_raw{3} = {[2,3,4,5],[12,13,12,14,12,15],99};\n \n stimset = [];\n stimset(1).name = 'PT';\n stimset(1).ij = [1,1; 3,1;];\n stimset(2).name = 'OMR';\n stimset(2).ij = [1,2; 3,2;];\n stimset(3).name = 'Spontaneous';\n stimset(3).ij = [1,3; 2,4;3,3];\n stimset(4).name = 'PT-shock';\n stimset(4).ij = [2,1; 2,2;];\n stimset(5).name = 'OMT-shock';\n stimset(5).ij = [2,3];\n \n % M_range_raw = [2,3,4,5,12,13,14,15,99,100]; % for Fish 8\n M_range = [3,1,3,2, 3,10,11,12, 0,16]; % standardized\n \nelseif i_fish >=9 && i_fish <=11,\n nBlocks = 3;\n block_raw = cell(nBlocks,1); % number of blocks\n block_raw{1} = {[2,3,4,5],[12,13,12,14,12,15],99,[23,22],[30,31,30,32],[42,43,44,45]};\n block_raw{2} = {[2,100,2,3,4,100,4,5],99,[12,100,12,13,12,100,12,14,12,100,12,15],99,[23,22],[30,31,30,32],[42,100,42,43,44,100,44,45]};\n block_raw{3} = {[2,3,4,5],[12,13,12,14,12,15],99,[23,22],[30,31,30,32],[42,43,44,45],[2,3,4,5],[12,13,12,14,12,15]};\n \n stimset = [];\n stimset(1).name = 'PT';\n stimset(1).ij = [1,1; 3,1; 3,7];\n stimset(2).name = 'OMR';\n stimset(2).ij = [1,2; 3,2; 3,8];\n stimset(3).name = 'Spontaneous';\n stimset(3).ij = [1,3; 2,4; 3,3];\n stimset(4).name = 'Dot/prey';\n stimset(4).ij = [1,4; 2,5; 3,4];\n stimset(5).name = 'Looming';\n stimset(5).ij = [1,5; 2,6; 3,5];\n stimset(6).name = 'Red|Blue';\n stimset(6).ij = [1,6; 3,6];\n stimset(7).name = 'PT-shock';\n stimset(7).ij = [2,1];\n stimset(8).name = 'OMR-shock';\n stimset(8).ij = [2,3];\n stimset(9).name = 'RB-shock';\n stimset(9).ij = [2,7];\n \n % M_range_raw = [2,3,4,5,12,13,14,15,22,23,30,31,32,42,43,44,45,99,100] % for Fish 10\n M_range = [3,1,3,2, 3,10,11,12,13, 0, 3,14,15,23,21,23,22, 0,16]; % standardized\n \nelseif i_fish >=12 && i_fish <=14,\n nBlocks = 2;\n block_raw = cell(nBlocks,1); % number of blocks\n block_raw{1} = {[2,3,4,5],[12,13,12,14,12,15,12,16],[0,12],99,[30,31,30,32]};\n block_raw{2} = {[2,3,4,5],[12,13,12,14,12,15,12,16],[0,12],99,[30,31,30,32]};\n \n stimset = [];\n stimset(1).name = 'PT';\n stimset(1).ij = [1,1; 2,1];\n stimset(2).name = 'OMR';\n stimset(2).ij = [1,2; 2,2];\n stimset(3).name = 'DF';\n stimset(3).ij = [1,3; 2,3];\n stimset(4).name = 'Spontaneous';\n stimset(4).ij = [1,4; 2,4];\n stimset(5).name = 'Looming';\n stimset(5).ij = [1,5; 2,5];\n\n % M_range_raw = [0,2,3,4,5,12,13,14,15,16,30,31,32,99] % for Fish 12\n M_range = [0,3,1,3,2, 3,10, 9,11,12, 3,14,15, 4]; % standardized\n \n% elseif i_fish == 12 || i_fish == 13 || i_fish == 14,\n% nBlocks = 1;\n% block_raw = cell(nBlocks,1); % number of blocks\n% \n% block_raw{1} = {[0],[3],[4]};\n% \n% stimset = [];\n% stimset(1).name = 'pre-para';\n% stimset(1).ij = [1,1];\n% stimset(2).name = 'add para';\n% stimset(2).ij = [1,2];\n% stimset(3).name = 'post-para';\n% stimset(3).ij = [1,3];\n% \n% % M_range_raw = [1,3,4] % for Fish 10\n% M_range = [0,3,4]; % standardized\nelseif ismember(i_fish,[15,17,18]),\n% M_range_raw = [2 3 4 5 12 13 14 15 16 17 18 99]\n nBlocks = 2;\n block_raw = cell(nBlocks,1); % number of blocks\n block_raw{1} = {[2,3,4,5],[12,13,12,14,12,15,12,16],[17,18],99,[30,31,30,32]};\n block_raw{2} = {[2,3,4,5],[12,13,12,14,12,15,12,16],[17,18],99,[30,31,30,32]};\n \n stimset = [];\n stimset(1).name = 'PT';\n stimset(1).ij = [1,1; 2,1];\n stimset(2).name = 'OMR';\n stimset(2).ij = [1,2; 2,2];\n stimset(3).name = 'DF';\n stimset(3).ij = [1,3; 2,3];\n stimset(4).name = 'Spontaneous';\n stimset(4).ij = [1,4; 2,4];\n stimset(5).name = 'Looming';\n stimset(5).ij = [1,5; 2,5];\n\n % M_range_raw = [2,3,4,5,12,13,14,15,16,17,18,30,31,32,99] % for Fish 12\n M_range = [3,1,3,2, 3,10, 9,11,12, 3, 0, 3,14,15, 4]; % standardized\n\n% elseif i_fish==16,\n% % M_range_raw = [2 3 4 5 12 13 14 15 16 17 18 99]\n% nBlocks = 1;\n% block_raw = cell(nBlocks,1); % number of blocks\n% block_raw{1} = {31,[2,3,4,5],[12,13,12,14,12,15,12,16],31};\n% \n% stimset = [];\n% stimset(1).name = 'NA';\n% stimset(1).ij = [1,1; 2,1];\n% stimset(2).name = 'PT';\n% stimset(2).ij = [1,1; 2,1];\n% stimset(3).name = 'OMR';\n% stimset(3).ij = [1,2; 2,2];\n% stimset(4).name = 'NA';\n% stimset(4).ij = [1,3; 2,3];\n% \n% \n% % M_range_raw = [2,3,4,5,12,13,14,15,16,31] % for Fish 12\n% M_range = [3,1,3,2, 3,10, 9,11,12,0]; % standardized\n \nelse % inspect manually to set these manual params\n % set M_range here after first inspection of M_range_raw:\n M_range = [3,1,3,2, 9,10,11,12, 0,13, 3,14,15, 4,16]; % standardized\n \n M_replace = zeros(1,max(M_range_raw)+1); % starting from zero\n for i = 0:max(M_range_raw),\n ix = find(i==M_range_raw);\n if ~isempty(ix),\n M_replace(i+1) = M_range(ix);\n end\n end\n \n stim_full = zeros(size(st));\n for i = 1:length(M_range_raw),\n stim_full(st==M_range_raw(i)) = M_range(i);\n end\n \n figure;\n plot(stim_full);\n \n stimset = [];\n return;\nend\n%% Raw stimulus key:\n% PT:Red/Dark\n% 2,4: Red|Red\n% 3: Dark|Red\n% 5: Red|Dark\n%\n% PT:Red/Blue\n% 42,44: Red|Red\n% 43: Blue|Red\n% 45: Red|Blue\n\n% OMR\n% 12: Red\n% 13: OMR F\n% 14: OMR R\n% 15: OMR L\n% 16: OMR?\n\n% Spont\n% 99: same as black\n%\n% Dot(prey)\n% 22: Dot\n% 23: No dot\n%\n% Looming\n% 30: Red\n% 31: Blob R\n% 32: Blob L\n\n%% Standardized stimulus key:\n% (Define normalized code, e.g. same stimulus under different raw stim keys can be unified)\n \n% 0 = all black; 1 = phototaxis R; 2 = phototaxis L; 3 = all white; 4 = all gray;\n% 5 = gray/black; 6 = white/gray; 7 = black/gray; 8 = gray/white.\n% 9 = backward grating\n% 10 = forward grating (very slow, more for calibration)\n% 11 = rightward grating\n% 12 = leftward grating\n% 13 = Dot\n% 14 = looming L %Blob R\n% 15 = looming R %Blob L\n\n% 16 = electric shock (spike)\n\n% 21,22,23 = 'red|blue R','blue|red L','red|red'\n\n% % 0 = all black; 1 = black/white; 2 = white/black; 3 = all white; 4 = all gray;\n% % 5 = gray/black; 6 = white/gray; 7 = black/gray; 8 = gray/white.\n% % 9 = backward grating... %%OMR baseline = not moving?? grey??\n% % 10 = forward grating (very slow, more for calibration)\n% % 11 = rightward grating\n% % 12 = leftward grating\n% % 13 = Dot\n% % 14 = Blob R\n% % 15 = Blob L\n% \n% % 16 = electric shock (spike)\n% \n% % 21,22,23 = 'red|blue','blue|red','red|red'\n\n\n%% correct transient frames\n% short method: st_rounded = interp1(M_range,M_range,st,'nearest');\n% but this doesn't work if a frame is different from both the one\n% before and the one after. Use loop below to force a manual 'round'\n% to the closer one of the 2 neighbors.\ntemp = diff([0,st]);\nswitches = find(temp);\ntrans = switches(diff(switches)==1);\n\nfor i = 1:length(trans),\n j = trans(i);\n if j>1,\n st(j) = st(j-1) + round((st(j)-st(j-1))/abs(st(j+1)-st(j-1))); % round to nearest of st(j-1) and st(j+1)\n end\nend\n\n% (loop until all transient ones are corrected)\ntemp = diff([0,st]);\nswitches = find(temp);\ntrans = switches(diff(switches)==1);\ncount = 0;\nwhile ~isempty(trans),\n for i = 1:length(trans),\n j = trans(i);\n st(j) = st(j-1) + round((st(j)-st(j-1))/abs(st(j+1)-st(j-1))); % round to nearest of st(j-1) and st(j+1)\n end\n temp = diff([0,st]);\n switches = find(temp);\n trans = switches(diff(switches)==1);\n count = count+1;\n if count>5,\n disp('count>5??');\n break;\n end\nend\n\n%% Standardize stimulus keys for both 'stim' and 'block', based on 'M_range_raw'->'M_range'\n% (tricky for cell arrays) custom method:\n% make a replacement matrix 'M_replace' to substitude raw stimulus key in 'block_raw'\n% to normalized key, stored in new cell array 'block'\nM_replace = zeros(1,max(M_range_raw)+1); % starting from zero\nfor i = 0:max(M_range_raw),\n ix = find(i==M_range_raw);\n if ~isempty(ix),\n M_replace(i+1) = M_range(ix);\n end\nend\n\nstim_full = zeros(size(st));\nblock = cell(nBlocks,1);\nfor i = 1:length(M_range_raw),\n stim_full(st==M_range_raw(i)) = M_range(i);\n for j = 1:nBlocks,\n block{j} = cellfun(@(x) M_replace(x+1),block_raw{j},'UniformOutput',0);\n end\nend\nstim_full_1 = horzcat(stim_full,-1);% set a virtual next frame to a invalid number for segmentation later\n\n%% Stimulus set segmentation, based on 'block' (manual input of protocol sequence)\n% reduce 'stim' to a sequence of keys without consecutive repeats\nix_singles = [1,find(diff(stim_full_1))+1]; % index array to map back to raw indices (frame-number)\nsingles = stim_full_1(ix_singles); % sequence of keys without consecutive repeats.\n% '_sg' below stands for 'singles'. Manipulations below in both raw and singles, in parallel.\n\njump = 1; % searching for 'jumps' in 'singles'\n% Based on the known protocol sequence for each set, look for first\n% mismatch in 'singles', i.e. position where the next set begins, stored\n% as 'block_change(_sg)' and 'set_start(_sg)'.\nblock_change = cell(nBlocks,1);\nblock_change_sg = cell(nBlocks,1);\nflag_isbreakagain = false;\nfor I = 1:nBlocks,\n nSets = length(block{I});\n block_change{I} = zeros(1,nSets);\n block_change_sg{I} = zeros(1,nSets);\n for J = 1:nSets,\n jump_last = jump;\n pattern = block{I}{J}; % protocol sequence for this set\n \n % this is sort of awkward. Instead of padding the 'already-found' sets with zeros,\n % one could also search the cropped array and adjusted the index.\n % Now 'comparison' is aligned with stim, works.\n textile = repmat(pattern,1,ceil(length(singles)/length(pattern))); % tile, for use below\n \n template = zeros(size(singles));\n ixs_fill = jump_last:length(singles);\n template(ixs_fill) = textile(1:length(ixs_fill)); % crop the 'textile' to fill the space after jump_last\n \n singles_temp = singles;\n if jump_last>1,\n singles_temp(1:jump_last-1) = 0;\n end\n comparison = (singles_temp-template);\n % find the position where the next set begins\n jump = find((comparison),1,'first');\n \n %% contingency plan: if start of the new set is different from\n % expected protocol ('block')\n count_stuck = 0;\n count_stuck2 = 0;\n while jump-jump_lastlength(pattern),\n count_stuck = 0;\n jump_last = jump_last+1;\n count_stuck2 = count_stuck2+1;\n disp(['count_stuck2=' num2str(count_stuck2)]);\n if count_stuck2>10, % arb. thres\n disp('count_stuck2>10');\n break;\n end\n end\n \n pattern_ = circshift(pattern,-count_stuck,2);\n textile = repmat(pattern_,1,ceil(length(singles)/length(pattern_)));\n \n template = zeros(size(singles));\n ixs_fill = jump_last:length(singles);\n template(ixs_fill) = textile(1:length(ixs_fill));\n \n singles_temp = singles;\n if jump_last>1,\n singles_temp(1:jump_last-1) = 0;\n end\n comparison = (singles_temp-template);\n \n jump = find((comparison),1,'first');\n \n end\n %% save\n if isempty(jump), % reached end of experiment!\n flag_isbreakagain = true;\n break;\n end\n block_change_sg{I}(J) = jump;\n block_change{I}(J) = ix_singles(jump);\n end\n if flag_isbreakagain,\n break;\n end\nend\n\n% eliminate empty sets\nfor I = 1:nBlocks,\n nSets = length(block_change{I});\n if nSets == 0,\n block_change{I} = [];\n block_change_sg{I} = [];\n block{I} = [];\n nBlocks = I-1;\n else\n for J = 1:nSets,\n if block_change{I}(J) == 0,\n block_change{I}(J:end) = [];\n block_change_sg{I}(J:end) = [];\n if length(block{I})>= J,\n block{I}(J:end) = [];\n end\n break;\n end\n end\n end\nend\n\n% block_change is basically start of next set. shift by one set to get 'set_start'.\nset_start = cell(nBlocks,1);\nset_start_sg = cell(nBlocks,1);\nset_stop = cell(nBlocks,1);\nset_stop_sg = cell(nBlocks,1);\nfor I = 1:nBlocks,\n nSets = length(block{I});\n set_start{I} = zeros(1,nSets);\n set_start_sg{I} = zeros(1,nSets);\n if I == 1,\n set_start{I}(1) = 1;\n set_start_sg{I}(1) = 1;\n else\n set_start{I}(1) = block_change{I-1}(end);\n set_start_sg{I}(1) = block_change_sg{I-1}(end);\n end\n set_start{I}(2:end) = block_change{I}(1:end-1);\n set_start_sg{I}(2:end) = block_change_sg{I}(1:end-1);\n set_stop{I} = block_change{I}-1;\n set_stop_sg{I} = block_change_sg{I}-1;\nend\n\n%% Visualize current segmentation of blocks\nif isPlotting,\n figure;\n hold on;\n plot(stim_full_1);\n for I = 1:nBlocks,\n for J = 1:length(block_change{I}),\n x = block_change{I}(J);\n plot([x,x],[-1,max(M_range)+1],'r--')\n ylim([-1,max(M_range)+1]);\n end\n end\nend\n%% Find shift-corrections for each stim-set, used for averaging later\n\n\n%% Find periods for each set-stype, and organize info by type into 'stimset'.\nfor i_ss = 1:length(stimset),\n % find empty sets (for this particular experiment) and delete ij's in 'stimset'\n for i_SetRep = 1:size(stimset(i_ss).ij,1),\n I = stimset(i_ss).ij(i_SetRep,1);\n J = stimset(i_ss).ij(i_SetRep,2);\n if I>length(block) || J>length(block{I}),\n stimset(i_ss).ij(i_SetRep:end,:) = [];\n break;\n end\n end\n nSetReps = size(stimset(i_ss).ij,1);\n if nSetReps == 0,\n stimset(i_ss) = [];\n break;\n end\n \n %% get period from first set of block\n I = stimset(i_ss).ij(1,1);\n J = stimset(i_ss).ij(1,2);\n pattern = block{I}{J}; % protocol sequence (singles) in normalized code\n stimset(i_ss).pattern = pattern;\n \n % find periodicity\n if length(pattern)==1, % exception, e.g. 'Spontaneous' set, single stimlus key held for full duration of set\n if J < length(block{I}),\n next_start = set_start{I}(J+1);\n elseif J == length(block{I}),\n if I < nBlocks,\n next_start = set_start{I+1}(1);\n else\n next_start = length(stim_full_1);\n end\n end\n stimset(i_ss).period = next_start - set_start{I}(J);\n else % find periodicity based on stimlus key repetition\n ix_start = set_start_sg{I}(J);\n segment = singles(ix_start:ix_start+length(pattern)-1);\n \n for i_segment = 1:length(segment),\n if length(find(segment==segment(i_segment)))==1, % use a stimulus that appears only once per period\n % find period\n start_s = set_start_sg{I}(J) + i_segment -1;\n stop_s = start_s + find(singles(1,start_s+1:end)==segment(i_segment),1,'first');\n stimset(i_ss).period = ix_singles(stop_s+1)-ix_singles(start_s+1); % shift by 1!! in case first stim is not intact\n break;\n end\n end\n end\n \n %%\n % stimset(i_ss).period % assigned above\n \n stimset(i_ss).rawstarts = zeros(1,nSetReps);\n stimset(i_ss).rawstops = zeros(1,nSetReps);\n stimset(i_ss).starts = zeros(1,nSetReps);\n stimset(i_ss).stops = zeros(1,nSetReps);\n stimset(i_ss).nReps = zeros(1,nSetReps);\n for i_SetRep = 1:nSetReps,\n I = stimset(i_ss).ij(i_SetRep,1);\n J = stimset(i_ss).ij(i_SetRep,2);\n stimset(i_ss).rawstarts(i_SetRep) = set_start{I}(J);\n stimset(i_ss).rawstops(i_SetRep) = block_change{I}(J)-1;\n \n if length(pattern)==1, % exception, e.g. 'Spontaneous' set, single stimlus key held for full duration of set\n stimset(i_ss).starts(i_SetRep) = stimset(i_ss).rawstarts(i_SetRep);\n % length of following occurences need to match period\n % (period primitively extracted from first occurence)\n% i_start = stimset(i_ss).rawstarts(i_SetRep);\n i_stop = stimset(i_ss).rawstops(i_SetRep);\n\n stimset(i_ss).nReps(i_SetRep) = 1;\n ix = stimset(i_ss).starts(i_SetRep) + stimset(i_ss).period - 1;\n if ix < i_stop,\n stimset(i_ss).stops(i_SetRep) = ix;\n else\n stimset(i_ss).stops(i_SetRep) = i_stop;\n end\n \n else\n % circshift to find intact periods\n pattern = stimset(i_ss).pattern;\n \n ix_start = set_start_sg{I}(J);\n ix_stop = set_stop_sg{I}(J);\n \n % find 'shift' (shift = 1 means starting from 2nd in 'singles')\n segment = singles(ix_start:ix_start+length(pattern)-1);\n shift = 0;\n while ~isequal(segment,pattern),\n shift = shift+1;\n segment = singles(ix_start+shift:ix_start+length(pattern)-1+shift);\n end\n stimset(i_ss).starts(i_SetRep) = ix_singles(ix_start+shift);\n % round to period within this set\n nReps = floor((ix_stop-ix_start-shift+1)/length(pattern));\n stimset(i_ss).nReps(i_SetRep) = nReps;\n \n ix = stimset(i_ss).starts(i_SetRep) + nReps*stimset(i_ss).period - 1;\n if ix>stimset(i_ss).rawstops(i_SetRep),\n nReps = nReps-1;\n end\n stimset(i_ss).stops(i_SetRep) = stimset(i_ss).starts(i_SetRep) + nReps*stimset(i_ss).period - 1;\n end\n end\nend\n\n% discard very first period because of potential artifacts at beginning of\n% entire experiment\nif stimset(1).nReps(1)>1,\n stimset(1).nReps(1) = stimset(1).nReps(1) - 1;\n stimset(1).starts(1) = stimset(1).starts(1) + stimset(1).period;\nend\n\n\nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/GUI functions/StimulusKeyPreprocessing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1867701385788868}} {"text": "function test_xformInplaneToVolume\n%Validate transforming data from INPLANE view to VOLUME (gray) view\n%\n% test_xformInplaneToVolume()\n% \n% Tests: initHiddenGray, loadMeanMap, loadCorAnal, ip2volParMap, \n% ip2volCorAnal, ip2volTSeries\n%\n% INPUTS\n% No inputs\n%\n% RETURNS\n% No returns\n%\n% Example: test_getCurDataROI()\n%\n% See also MRVTEST\n%\n% Copyright Stanford team, mrVista, 2011\n\n%% Initialize the key variables and data path\n% Data directory (where the mrSession file is located)\ndataDir = mrtInstallSampleData('functional','mrBOLD_01');\n\n% This is the validation file\nval = mrtGetValididationData('ipToVolumeData');\n\n\n% These are the items we stored in the validation file\n%\n% val.codim = size(co);\n% val.comed = nanmedian(co);\n% val.cosample = co(1000);\n% val.mapdim = size(map);\n% val.mapmed = nanmedian(map);\n% val.mapsample = map(1000);\n% val.tSdim = size(tSeries);\n% val.tSsample = tSeries(1000);\n%\n% save(vFile, '-struct', 'val')\n\n%% Retain original directory, change to data directory\ncurDir = pwd;\ncd(dataDir);\n\n% There can be several data types - name the one you want to probe\ndataType = 'Original';\n\n% Which scan number from that data type?\nscan = 1;\n\n%% Get data structure:\nip = initHiddenInplane(); % Foregoes interface - loads data silently\nvol = initHiddenGray(); \n\n%% Set dataTYPE:\nip = viewSet(ip, 'Current DataType', dataType); % Data type\nvol = viewSet(vol, 'Current DataType', dataType); % Data type\n\n%% Load coranal and mean map into INPLANE view\nip = loadCorAnal(ip);\nip = loadMeanMap(ip);\n\n%% Transform data to VOLUME view\nvol = ip2volParMap( ip, vol, scan, [], 'linear', 1);\nvol = ip2volCorAnal(ip, vol, scan, -1);\nvol = ip2volTSeries(ip, vol, scan);\n\nco = viewGet(vol, 'scan coherence', scan);\nmap = viewGet(vol, 'scan map', scan);\ntSeries = loadtSeries(vol, scan, 1); %We can hardcode slice since gray view only has 1 slice\n\n%% Go home\ncd(curDir);\n\n%% Validate..\n\n% check the dimensions of coherence map and mean map\nassertEqual(val.codim, size(co));\nassertEqual(val.mapdim, size(map));\nassertEqual(val.tSdim, size(tSeries));\n\n% check the median value of the coherence map and mean map\nassertElementsAlmostEqual(val.comed,nanmedian(co));\nassertElementsAlmostEqual(val.mapmed,nanmedian(map));\n\n\n% check the values of the mean map and coherence map for an arbitrary voxel\n% (to make sure the sequence is correct)\nassertElementsAlmostEqual(val.cosample, co(1000));\nassertElementsAlmostEqual(val.mapsample, map(1000));\n\n% check the values of the time series for the max and an arbitrary voxel\nassertElementsAlmostEqual(val.tSsample, tSeries(1000));\nassertElementsAlmostEqual(val.tSmax,nanmax(tSeries(:)));\n\n\n%% Cleanup\n% clean up vistadata repository because this test script wrote new data\n% test_CleanUpSVN\n\nmrvCleanWorkspace;\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrTest/bold/core/test_xformInplaneToVolume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669733575576}} {"text": "function vis_im = visualise_bboxes(id, objectNames, cmap, rgb_dir, detection_dir)\n\nfont_size = 25;\n\ncity = strtok(id, '_');\n\nimage_filename = fullfile(rgb_dir, city, [id '_leftImg8bit.png']);\ndetection_filename = fullfile(detection_dir, [id '_leftImg8bit.mat']);\n\nrgb_im = imread(image_filename);\ntemp = load(detection_filename);\ndetections = temp.dets.annotation;\nvis_im = rgb_im;\n\nif ~isfield(detections, 'object') || isempty(detections.object)\n return;\nend\n\nrectangle_position = zeros(length(detections), 4);\ncolour = zeros(length(detections), 3);\ntext_strings = cell(length(detections), 1);\n% we eventually want to display the bboxes differently depending on whether\n% they are a group annotation or not. unfortunately it seems insertShape as\n% it is now doesn't support changes to line style.\nis_grp = zeros(length(detections), 1);\n\nfor k = length(detections.object):-1:1\n name = detections.object(k).name;\n train_id = find(strcmp(objectNames, name)) - 1;\n assert(~isempty(train_id));\n xmin = str2double(detections.object(k).bndbox.xmin) + 1;\n ymin = str2double(detections.object(k).bndbox.ymin) + 1;\n xmax = str2double(detections.object(k).bndbox.xmax) + 1;\n ymax = str2double(detections.object(k).bndbox.ymax) + 1;\n width = xmax - xmin + 1;\n height = ymax - ymin + 1;\n rectangle_position(k, :) = [xmin, ymin, width, height];\n \n colour(k, :) = cmap(train_id + 1,:);\n text_strings{k} = name;\n is_grp(k) = logical(str2double(detections.object(k).is_grp));\n % this is a temporary workaround\n if is_grp(k)\n text_strings{k} = [text_strings{k}, 'group'];\n end\n\nend\n\ntext_position = rectangle_position(:,1:2);\nvis_im = insertShape(vis_im, 'Rectangle', rectangle_position,...\n 'LineWidth', 4, 'Color', colour*255);\n\n% scale font size according to width of bbox for clearer visual\nmax_font_shrink_ratio = 2;\npixel_to_font_size_ratio = 2.6; % for three-letter word\nstep_size = 0.25;\nwidth_threshes = [0, ...\n (pixel_to_font_size_ratio/max_font_shrink_ratio + step_size) : step_size : pixel_to_font_size_ratio,...\n Inf] * font_size;\nfor k = (numel(width_threshes) - 1):(-1):1\n dets_in_range = width_threshes(k) <= rectangle_position(:,3) & ...\n rectangle_position(:,3) < width_threshes(k+1);\n adjusted_font_size = floor(max(width_threshes(k)/pixel_to_font_size_ratio, ...\n font_size/max_font_shrink_ratio));\n if any(dets_in_range)\n vis_im = insertText(vis_im, text_position(dets_in_range, :), text_strings(dets_in_range),...\n 'Font', 'UbuntuMono-R', 'FontSize', adjusted_font_size,...\n 'BoxColor', colour(dets_in_range, :)*255, 'BoxOpacity', 0.5, 'TextColor', 'white', ...\n 'AnchorPoint', 'LeftBottom');\n end\nend\nend\n", "meta": {"author": "qizhuli", "repo": "Weakly-Supervised-Panoptic-Segmentation", "sha": "80081fc42eff16977e6d83a1fec413eab79a4c02", "save_path": "github-repos/MATLAB/qizhuli-Weakly-Supervised-Panoptic-Segmentation", "path": "github-repos/MATLAB/qizhuli-Weakly-Supervised-Panoptic-Segmentation/Weakly-Supervised-Panoptic-Segmentation-80081fc42eff16977e6d83a1fec413eab79a4c02/visualisation/visualise_bboxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669733575575997}} {"text": "function MDP = DEMO_MDP_questions\n% Demo of active inference for visual salience\n%__________________________________________________________________________\n%\n% This routine provide simulations of reading to demonstrate deep temporal\n% generative models. It builds upon the scene construction simulations to\n% equip the generative model with a second hierarchical level. In effect,\n% this creates an agent that can accumulate evidence at the second level\n% based upon epistemic foraging at the first. In brief, the agent has to\n% categorise a sentence or narrative into one of two categories (happy or\n% sad), where it entertains six possible sentences. Each sentence comprises\n% four words, which are themselves constituted by two pictures or graphemes\n% These are the same visual outcomes used in previous illustrations of\n% scene construction and saccadic searches.\n%\n% Here, the agent has policies at two levels. The second level policy (with\n% just one step into the future) allows it to either look at the next word\n% or stay on the current page and make a decision. Concurrently, a first\n% level policy entails one of four saccadic eye movements to each quadrant\n% of the current page, where it will sample a particular grapheme.\n%\n% This provides a rough simulation of reading - that can be made more\n% realistic by terminating first level active inference, when there can be\n% no further increase in expected free energy (i.e., all uncertainty about\n% the current word has been resolved). The subsequent inferred hidden\n% states then become the outcome for the level above.\n%\n% To illustrate the schemes biological plausibility, one can change the\n% agent's prior beliefs and repeat the reading sequence under violations of\n% either local (whether the graphemes are flipped vertically) or globally\n% (whether the sentence is surprising) expectations. This produces a\n% mismatch negativity (MMN) under local violations) and a MMN with a\n% P300 with global violations.\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: DEMO_MDP_questions.m 7766 2020-01-05 21:37:39Z karl $\n \n% set up and preliminaries: first level\n%==========================================================================\n%\n%--------------------------------------------------------------------------\n \nrng('default')\n \n% first level (lexical)\n%==========================================================================\n% question 1: {'noun (7)'}\n% question 2: {'noun (7)','adverb (9)'}\n% question 3: {'adjective (8)','noun (7)','adverb (9)'}\n%--------------------------------------------------------------------------\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\nsentence{1} = {'Is there a ','&1_1','?'};\nsentence{2} = {'Is any ','&2_1','&2_3','?'};\nsentence{3} = {'Is a ','&3_2','&3_1','&3_3','?'};\nsentence{4} = {'Yes','!'};\nsentence{5} = {'No','!'};\nsentence{6} = {'Not sure','!'};\nsentence{7} = {'Ready','?'};\n\nsyn{1} = {'Ready','OK','please begin'};\nsyn{2} = {'Not sure','I dont know','Cannot say'};\nsyn{3} = {'No','Sorry, no','There is not'};\nsyn{4} = {'Yes','Yes there is','Well done'};\n\n% assemble hidden states and transition probabilities\n%--------------------------------------------------------------------------\nname = {};\nfor i = 1:numel(sentence)\n for j = 1:numel(sentence{i})\n phrase = sentence{i}(j);\n if ~any(ismember(name,phrase))\n name(end + 1) = phrase;\n end\n end\nend\n\nlabel.factor{1} = 'noun'; label.name{1} = {'square ','triangle '};\nlabel.factor{2} = 'adj.'; label.name{2} = {'green ','red '};\nlabel.factor{3} = 'adverb'; label.name{3} = {'above','below'};\nlabel.factor{4} = 'syntax'; label.name{4} = name;\n\n% prior beliefs about initial states D \n%--------------------------------------------------------------------------\nfor i = 1:numel(label.factor)\n n = numel(label.name{i});\n D{i} = ones(n,1)/n;\nend\n\n% restricted initial states to the beginning of a sentence\n%--------------------------------------------------------------------------\nstate = label.name{4};\nD{4} = spm_zeros(D{4});\nfor i = 1:numel(sentence)\n j = ismember(state,sentence{i}(1));\n D{4}(j) = 1;\nend\n\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\nNf = numel(D);\nfor f = 1:Nf\n Ns(f) = numel(D{f});\nend\n\noutcome = {};\nfor i = 1:numel(label.name)\n outcome = [outcome,label.name{i}];\nend\nfor i = 1:numel(syn)\n outcome = [outcome,syn{i}];\nend\noutcome = unique(outcome);\nj = [];\nfor i = 1:numel(outcome)\n if outcome{i}(1) ~= '&'\n j = [j,i];\n end\nend\noutcome = outcome(j);\n\n% single outcome modality with multiple phrases\n%--------------------------------------------------------------------------\nlabel.modality{1} = 'phrase'; label.outcome{1} = outcome;\n\nfor f1 = 1:Ns(1)\n for f2 = 1:Ns(2)\n for f3 = 1:Ns(3)\n for f4 = 1:Ns(4)\n \n % indices of the state\n %----------------------------------------------------------\n j = {f1,f2,f3,f4};\n \n % assemble phrases under this state\n %----------------------------------------------------------\n name = label.name{4}{f4};\n if name(1) == '&'\n p = eval(name(end));\n q = eval(['f' name(end)]);\n out = label.name{p}(q);\n else\n out = name;\n for i = 1:numel(syn)\n if any(ismember(syn{i},name))\n out = syn{i};\n end\n end\n end\n \n % placing likelihood matrix\n %----------------------------------------------------------\n i = ismember(outcome,out);\n A{1}(i,j{:}) = 1/sum(i);\n\n end\n end\n end\nend\n\n% transitions: B{f} for each factor\n%--------------------------------------------------------------------------\nfor f = 1:Nf\n B{f} = eye(Ns(f));\nend\n \n% specifies syntax\n%--------------------------------------------------------------------------\nB{4} = spm_zeros(B{4});\nfor s = 1:numel(sentence)\n for t = 2:numel(sentence{s})\n i = find(ismember(state,sentence{s}(t - 1)));\n j = find(ismember(state,sentence{s}(t)));\n B{4}(j,i) = 1;\n end\n B{4}(j,j) = 1;\nend\n\n \n% MDP Structure\n%--------------------------------------------------------------------------\nmdp.T = 5; % number of updates\nmdp.A = A; % observation model\nmdp.B = B; % transition probabilities\nmdp.D = D; % prior over initial states\n \nmdp.label = label;\nmdp.chi = 1/32;\n \nclear A B D\n \nMDP = spm_MDP_check(mdp);\n\n% % check belief updates (and behaviour)\n% %------------------------------------------------------------------------\n% MDP.s = [1 2 1 8]';\n% MDP = spm_MDP_VB_X(MDP);\n%\n% spm_figure('GetWin','Figure 1'); clf\n% spm_MDP_VB_trial(MDP,[3 4],1);\n% \n% % illustrate phase-precession and responses\n% %------------------------------------------------------------------------\n% spm_figure('GetWin','Figure 2'); clf\n% spm_MDP_VB_LFP(MDP,[],4);\n% \n% cell2mat(MDP.label.outcome{1}(MDP.o))\n\n\n% set up and preliminaries: first level\n%==========================================================================\n% \n%--------------------------------------------------------------------------\n \n%% second level (narrative)\n%==========================================================================\n% question 1: {'noun (7)'}\n% question 2: {'noun (7)','adverb (9)'}\n% question 3: {'adjective (8)','noun (7)','adverb (9)'}\n%--------------------------------------------------------------------------\nlabel.factor{1} = 'narrative'; label.name{1} = {'ready','question','answer'};\nlabel.factor{2} = 'question'; label.name{2} = {'is?','where?','what?'};\nlabel.factor{3} = 'upper colour'; label.name{3} = {'green','red'};\nlabel.factor{4} = 'lower colour'; label.name{4} = {'green','red'};\nlabel.factor{5} = 'upper shape'; label.name{5} = {'square','triangle'};\nlabel.factor{6} = 'lower shape'; label.name{6} = {'square','triangle'};\nlabel.factor{7} = 'noun'; label.name{7} = {'square','triangle'};\nlabel.factor{8} = 'adjective'; label.name{8} = {'green','red'};\nlabel.factor{9} = 'adverb'; label.name{9} = {'above','below'};\n\n% prior beliefs about initial states D \n%--------------------------------------------------------------------------\nfor i = 1:numel(label.factor)\n n = numel(label.name{i});\n D{i} = ones(n,1)/n;\nend\n\n% known initial states\n%--------------------------------------------------------------------------\nD{1}(1) = 128;\n\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\nlabel.modality{1} = 'noun'; label.outcome{1} = MDP.label.name{1};\nlabel.modality{2} = 'adj.'; label.outcome{2} = MDP.label.name{2};\nlabel.modality{3} = 'adverb'; label.outcome{3} = MDP.label.name{3};\nlabel.modality{4} = 'syntax'; label.outcome{4} = MDP.label.name{4}(find(MDP.D{4}));\n\nNf = numel(D);\nfor f = 1:Nf\n Ns(f) = numel(D{f});\nend\nfor f1 = 1:Ns(1)\n for f2 = 1:Ns(2)\n for f3 = 1:Ns(3)\n for f4 = 1:Ns(4)\n for f5 = 1:Ns(5)\n for f6 = 1:Ns(6)\n for f7 = 1:Ns(7)\n for f8 = 1:Ns(8)\n for f9 = 1:Ns(9)\n \n % indices\n %--------------------------------------\n j = {f1,f2,f3,f4,f5,f6,f7,f8,f9};\n \n % answer: depending on question and beliefs\n %--------------------------------------\n Y = 0;\n if f1 == 3\n if f2 == 1\n Y = (f7 == f5) | (f7 == f6);\n elseif f2 == 2\n if f9 == 1\n Y = (f7 == f5);\n elseif f9 == 2\n Y = (f7 == f6);\n end\n elseif f2 == 3\n if f9 == 1\n Y = (f7 == f5) & (f8 == f3);\n elseif f9 == 2\n Y = (f7 == f6) & (f8 == f4);\n end\n end\n end\n \n % A{1} noun:\n %======================================\n A{1}(f7,j{:}) = 1;\n \n % A{2} adjective:\n %======================================\n A{2}(f8,j{:}) = 1;\n \n % A{3} adverb:\n %======================================\n A{3}(f9,j{:}) = 1;\n \n % A{4} syntax: {'1','2','3','Y','N','?'}\n %======================================\n if f1 == 1\n A{4}(7,j{:}) = 1;\n elseif f1 == 2\n A{4}(f2,j{:}) = 1;\n elseif f1 == 3\n if Y\n A{4}(4,j{:}) = .98;\n else\n A{4}(5,j{:}) = .98;\n end\n A{4}(6,j{:}) = .02;\n end\n \n end\n end\n end\n end\n end\n end\n end\n end\nend\n\n% likelihood mappings\n%--------------------------------------------------------------------------\nNg = numel(A);\nfor g = 1:Ng\n No(g) = size(A{g},1);\n if any(spm_vec(sum(A{g})) ~= 1), disp('check A'), return, end\nend\n \n% controlled transitions: B{f} for each factor\n%--------------------------------------------------------------------------\nfor f = 1:Nf\n B{f} = eye(Ns(f));\n label.action{f} = {'stay'};\nend\n \n% transitions B(1): {'ready','question','answer'}\n%--------------------------------------------------------------------------\nB{1}(:,:,1) = spm_speye(Ns(1),Ns(1),-1); B{1}(1,Ns(1),1) = 1;\n\n% control states B(2): question {'1','2' or '3'} & control states B(7):B{9} \n%--------------------------------------------------------------------------\n% D{2} ; % question; {'1','2','3'};\n% D{7} ; % noun: {'square','triangle'}\n% D{8} ; % adjective: {'green','red'}\n% D{9} ; % adverb: {'above','below'}\n%--------------------------------------------------------------------------\nfor f = [2 7 8 9]\n for k = 1:Ns(f)\n B{f}(:,:,k + 1) = 0;\n B{f}(k,:,k + 1) = 1;\n end\n label.action{f} = ['stay', label.name{f}];\nend\n\n% allowable policies (time x polcy x factor)\n%--------------------------------------------------------------------------\n% question 1: {'noun (7)'}\n% question 2: {'noun (7)','adverb (9)'}\n% question 3: {'adjective (8)','noun (7)','adverb (9)'}\n%--------------------------------------------------------------------------\nV = ones(2,14,Nf);\nV(1,:,2) = 1 + [1 1 2 2 2 2 3 3 3 3 3 3 3 3];\nV(1,:,7) = 1 + [1 2 1 1 2 2 1 1 1 1 2 2 2 2];\nV(1,:,8) = 1 + [1 1 1 1 1 1 1 1 2 2 1 1 2 2];\nV(1,:,9) = 1 + [1 1 1 2 1 2 1 2 1 2 1 2 1 2];\nV(2,:,:) = 1;\n\n\n% priors: (utility) C: A{4} syntax: {'1','2','3','Y','N','S'}\n%--------------------------------------------------------------------------\nfor g = 1:Ng\n C{g} = zeros(No(g),1);\nend\n\n% the agent expects affirmative answers\n%--------------------------------------------------------------------------\nC{4}(4,:) = 1/4;\nC{4}(5,:) = -1/4;\n\n% actual state of the world\n%--------------------------------------------------------------------------\ns = ones(Nf,1);\ns(4) = 2;\n\n% MDP Structure\n%--------------------------------------------------------------------------\nmdp.MDP = MDP;\nmdp.label = label; % names of factors and outcomes\nmdp.tau = 4; % time constant of belief updating\nmdp.erp = 4; % initialization\nmdp.chi = 0; % initialization\n\nmdp.V = V; % allowable policies\nmdp.A = A; % observation model\nmdp.B = B; % transition probabilities\nmdp.C = C; % preferred outcomes\nmdp.D = D; % prior over initial states (context)\nmdp.s = s; % initial state\nmdp.o = []; % outcomes\n\nmdp.link = spm_MDP_link(mdp);\nMDP = spm_MDP_check(mdp);\n% spm_MDP_factor_graph(mdp);\n \n \n%% illustrate questioning\n%==========================================================================\nclear MDP\nOPTIONS.D = 1;\n[MDP(1,1:6)] = deal(mdp);\n\nMDP = spm_MDP_VB_X(MDP,OPTIONS);\n\n% show belief updates (and behaviour)\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 1'); clf\nspm_MDP_VB_trial(MDP(1),[1 2 4],[1 3 4]);\n\n% illustrate phase-precession and responses\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\nspm_MDP_VB_LFP(MDP,[],3);\n\nspm_figure('GetWin','Figure 2A'); clf\nspm_MDP_VB_LFP(MDP,[],3,1);\n\nspm_figure('GetWin','Figure 3'); clf\nspm_MDP_VB_ERP(MDP(4:6),[3,2]);\n\nspm_figure('GetWin','Figure 4'); clf\nfor i = 1:size(MDP,2)\n subplot(4,3,i)\n spm_questions_plot(MDP(1,i))\nend\n\n% illustrate violations\n%==========================================================================\nj = 5; % which answer\nNDP = MDP(j); % get states and outcomes\nif NDP.o(4,3) == 4 % switch the answer\n NDP.o(4,3) = 5;\nelse\n NDP.o(4,3) = 4;\nend\nNDP = rmfield(NDP,'link'); % remove link (outomes are given)\nNDP = spm_MDP_VB_X(NDP);\n\n% find greatest effect on belief updating (about the scene)\n%--------------------------------------------------------------------------\nfor f = 3:6\n v(f) = norm(spm_vec(MDP(j).X{f}) - spm_vec(NDP.X{f}),'inf');\nend\n[v,f] = max(v);\n\n% responses to appropriate and inappropriate answers\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 6 expected' ); clf, spm_MDP_VB_LFP(MDP(5),[],f);\nspm_figure('GetWin','Figure 7 violation'); clf, spm_MDP_VB_LFP(NDP ,[],f);\n\n\n% illustrate 'communication'\n%==========================================================================\n\n% increase efficiency (i.e., suppress neurophysiological correlates)\n%--------------------------------------------------------------------------\nmdp.tau = 3; % time constant of belief updating\nmdp.erp = 1; % initialization\nmdp.chi = 1/64; % initialization\n\n% create two agents\n%--------------------------------------------------------------------------\nclear MDP\n[MDP(1:2,1:6)] = deal(mdp);\n\n% give a second subject veridical beliefs about the scene\n%--------------------------------------------------------------------------\nfor i = [3 4 5 6]\n MDP(2,1).D{i} = sparse(s(i),1,1,Ns(i),1);\nend\n\n% confident player answers then asks\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 8'); clf\nfor i = 1:length(MDP)\n \n if i < 5\n % first model asks and the second answers\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[2 1 2];\n MDP(2,i).n = ones(Ng,1)*[2 1 2];\n else\n % switch roles\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 1];\n MDP(2,i).n = ones(Ng,1)*[1 2 1];\n end\nend\n\nTDP = spm_MDP_VB_X(MDP,OPTIONS);\nfor i = 1:size(TDP,2)\n subplot(4,3,i), spm_questions_plot(TDP(:,i))\nend\n\n% confident player asks then answers\n%--------------------------------------------------------------------------\nfor i = 1:length(MDP)\n \n if i < 5\n % first model asks and the second answers\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 1];\n MDP(2,i).n = ones(Ng,1)*[1 2 1];\n else\n % switch roles\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[2 1 2];\n MDP(2,i).n = ones(Ng,1)*[2 1 2];\n end\nend\n\nTDP = spm_MDP_VB_X(MDP,OPTIONS);\nfor i = 1:size(TDP,2)\n subplot(4,3,i + 6)\n spm_questions_plot(TDP(:,i))\nend\n\n\n% confident player tells then asks\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 9'); clf\nfor i = 1:length(MDP)\n \n if i < 7\n % first model asks and the second answers\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 2];\n MDP(2,i).n = ones(Ng,1)*[1 2 2];\n else\n % switch roles\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 1];\n MDP(2,i).n = ones(Ng,1)*[1 2 1];\n end\nend\n\nTDP = spm_MDP_VB_X(MDP,OPTIONS);\nfor i = 1:size(TDP,2)\n subplot(4,3,i)\n spm_questions_plot(TDP(:,i))\nend\n\n% building fantasies\n%==========================================================================\nspm_figure('GetWin','Figure 10'); clf\n\n% make both players uncertain about the scene at hand\n%--------------------------------------------------------------------------\nMDP(2,1).D = MDP(1,1).D;\n\nfor i = 1:length(MDP)\n \n if i < 3\n % first model asks and the second answers\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 1];\n MDP(2,i).n = ones(Ng,1)*[1 2 1];\n else\n % switch roles\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[2 1 2];\n MDP(2,i).n = ones(Ng,1)*[2 1 2];\n end\nend\n\nTDP = spm_MDP_VB_X(MDP,OPTIONS);\nfor i = 1:size(TDP,2)\n subplot(4,3,i)\n spm_questions_plot(TDP(:,i))\nend\n\n% now repeat when precluding uncertain responses\n%--------------------------------------------------------------------------\nfor i = 1:length(MDP)\n \n MDP(1,i).A{4} = MDP(1,i).A{4} > 1/2;\n MDP(2,i).A{4} = MDP(2,i).A{4} > 1/2;\n\n if i < 3\n % first model asks and the second answers\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[1 2 1];\n MDP(2,i).n = ones(Ng,1)*[1 2 1];\n else\n % switch roles\n %------------------------------------------------------------------\n MDP(1,i).n = ones(Ng,1)*[2 1 2];\n MDP(2,i).n = ones(Ng,1)*[2 1 2];\n end\nend\n\nTDP = spm_MDP_VB_X(MDP,OPTIONS);\nfor i = 1:size(TDP,2)\n subplot(4,3,6 + i)\n spm_questions_plot(TDP(:,i))\nend\n\n\nreturn\n\n\nfunction spm_questions_plot(MDP)\n%% illustrate beliefs\n%--------------------------------------------------------------------------\n\n% probabilistic mapping from hidden states to outcomes: A\n%--------------------------------------------------------------------------\n% label.modality{1} = 'noun'; label.outcome{1} = {'square','triangle'};\n% label.modality{2} = 'adj.'; label.outcome{2} = {'green','red'};\n% label.modality{3} = 'adverb'; label.outcome{3} = {'above','below'};\n% label.modality{4} = 'syntax'; label.outcome{4} = {'1','2','3','Y','N','Sil.'};\n\n% plot question, answer and posterior beliefs\n%==========================================================================\ncla;\n\nfor m = 1:numel(MDP)\n \n % Assemble question-and-answer\n %----------------------------------------------------------------------\n question = MDP(m).o(4,2);\n answer = MDP(m).o(4,3);\n \n try\n qstr = cell2mat(MDP(m).MDP.label.outcome{1}(MDP(m).mdp(2).o));\n astr = cell2mat(MDP(m).MDP.label.outcome{1}(MDP(m).mdp(3).o));\n catch\n noun = {'square','triangle'};\n adj = {'green','red'};\n adverb = {'above','below'};\n if question == 1\n qstr = ['is there a ' noun{MDP(m).o(1,2)} ' ?'];\n elseif question == 2\n qstr = ['Is any ' noun{MDP(m).o(1,2)} ' ' adverb{MDP(m).o(3,2)} ' ?'];\n elseif question == 3\n qstr = ['Is a ' adj{MDP(m).o(2,2)} ' ' noun{MDP(m).o(1,2)} ' ' adverb{MDP(m).o(3,2)} ' ?'];\n else\n qstr = '!';\n end\n if answer == 4\n astr = 'Yes !';\n elseif answer == 5\n astr = 'No !';\n else\n astr = 'I''m not sure';\n end\n end\n\n \n % is the answer right (for a single player)?\n %----------------------------------------------------------------------\n ind = num2cell(MDP(m).s(:,3));\n if answer == find(MDP(m).A{4}(:,ind{:}),1) || m > 1\n cor = spm_softmax(2*[0;1;0]);\n else\n cor = spm_softmax(2*[1;0;0]);\n end\n \n \n % plot posterior beliefs\n %----------------------------------------------------------------------\n % label.factor{3} = 'upper colour'; label.name{3} = {'green','red'};\n % label.factor{4} = 'lower colour'; label.name{4} = {'green','red'};\n % label.factor{5} = 'upper shape'; label.name{5} = {'square','triangle'};\n % label.factor{6} = 'lower shape'; label.name{6} = {'square','triangle'};\n \n % upper and lower object\n %----------------------------------------------------------------------\n T = 2;\n col{1} = [MDP(m).X{3}(2,T) MDP(m).X{3}(1,T) 0];\n col{1} = col{1}*MDP(m).X{5}(1,T) + (1 - MDP(m).X{5}(1,T));\n col{2} = [MDP(m).X{3}(2,T) MDP(m).X{3}(1,T) 0];\n col{2} = col{2}*MDP(m).X{5}(2,T) + (1 - MDP(m).X{5}(2,T));\n col{3} = [MDP(m).X{4}(2,T) MDP(m).X{4}(1,T) 0];\n col{3} = col{3}*MDP(m).X{6}(1,T) + (1 - MDP(m).X{6}(1,T));\n col{4} = [MDP(m).X{4}(2,T) MDP(m).X{4}(1,T) 0];\n col{4} = col{4}*MDP(m).X{6}(2,T) + (1 - MDP(m).X{6}(2,T));\n \n plot(m,0,'^','MarkerSize',24,'LineWidth',4,'Color',col{4}), hold on\n plot(m,0,'s','MarkerSize',24,'LineWidth',4,'Color',col{3})\n plot(m,1,'^','MarkerSize',24,'LineWidth',4,'Color',col{2})\n plot(m,1,'s','MarkerSize',24,'LineWidth',4,'Color',col{1})\n \nend\n\ntry, nq = MDP(1).n(4,2); catch, nq = 1; end\ntry, na = MDP(1).n(4,3); catch, na = 1; end\nif ~nq, nq = 1; end\nif ~na, na = 1; end\ntext(nq, 2,qstr,'HorizontalAlignment','Center')\ntext(na,-1,astr,'HorizontalAlignment','Center','FontWeight','bold','Color',cor)\naxis([0 (m + 1) -1.5 2.5]), axis off, axis square\n\n\n% return if multiple agents\n%--------------------------------------------------------------------------\nif numel(MDP) > 1, return, end\n\n% upper and lower object\n%--------------------------------------------------------------------------\nrgb = {[0 1 0],[1 0 0]};\nshape = {'s','^'};\nplot(1 + 1/2,1,shape{MDP.s(5)},'MarkerSize',8,'LineWidth',1,'Color',rgb{MDP.s(3)})\nplot(1 + 1/2,0,shape{MDP.s(6)},'MarkerSize',8,'LineWidth',1,'Color',rgb{MDP.s(4)})\n\n\n\n\n\n ", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DEM/DEMO_MDP_questions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3486451353339457, "lm_q1q2_score": 0.18655946406550664}} {"text": "function sampleScatterMatrix(rxnNames, model, sample, nPoints, fontSize, dispRFlag, rxnNames2)\n% Draws a scatterplot matrix with pairwise scatterplots\n% for multiple reactions\n%\n% USAGE:\n%\n% sampleScatterMatrix(rxnNames, model, sample, nPoints, fontSize, dispRFlag, rxnNames2)\n%\n% INPUTS:\n% rxnNames: Cell array of reaction names to be plotted\n% model: Model structure\n% sample: Samples to be analyzed (`nRxns x nSamples`)\n%\n% OPTIONAL INPUTS:\n% nPoints: How many sample points to plot (Default `nSamples`)\n% fontSize: Font size for labels (Default calculated based on\n% number of reactions)\n% dispRFlag: Display correlation coefficients (Default false)\n% rxnNames2: Optional second set of reaction names\n%\n% EXAMPLE:\n%\n% %Plots the scatterplots only between the three reactions listed -\n% %histograms for each reaction will be on the diagonal\n% sampleScatterMatrix({'PFK', 'PYK', 'PGL'}, model, sample);\n% %Plots the scatterplots between each of the first set of reactions and\n% %each of the second set of reactions. No histograms will be shown.\n% sampleScatterMatrix({'PFK', 'PYK', 'PGL'}, model, sample, 100, 10, true, {'ENO','TPI'});\n%\n% .. Author: - Markus Herrgard 9/14/06\n\n[isInModel, rxnInd] = ismember(rxnNames, model.rxns);\nrxnNames = rxnNames(isInModel);\nrxnInd = rxnInd(isInModel);\nnRxns = length(rxnNames);\n\n%no optional inputs specified\nif nargin < 4 \n nPoints = size(sample, 2);\n dispRFlag = false;\n nRxns2 = nRxns;\n rxnNames2 = rxnNames;\n nPanels = nRxns * nRxns2;\n fontSize = 10 + ceil(50 / sqrt(nPanels));\n twoSetsFlag = false;\n%some optional inputs specified \nelse \n if isempty(nPoints)\n nPoints = size(sample, 2);\n end\n if isempty(dispRFlag)\n dispRFlag = false;\n end\n if nargin == 7\n [isInModel2, rxnInd2] = ismember(rxnNames2, model.rxns);\n\n rxnNames2 = rxnNames2(isInModel2);\n rxnInd2 = rxnInd2(isInModel2);\n\n nRxns2 = length(rxnNames2);\n twoSetsFlag = true;\n nRxns = nRxns + 1;\n nRxns2 = nRxns2 + 1;\n else\n nRxns2 = nRxns;\n rxnNames2 = rxnNames;\n twoSetsFlag = false;\n end\n if isempty(fontSize)\n nPanels = nRxns * nRxns2;\n fontSize = 10 + ceil(50 / sqrt(nPanels));\n end\nend\nheight = 0.8 / nRxns;\nwidth = 0.8 / nRxns2;\n\nclf\nshowprogress(0, 'Drawing scatterplots ...');\nfor i = 1:nRxns\n\n for j = 1:nRxns2\n showprogress(((i - 1) * nRxns+j) / (nRxns * nRxns2));\n left = 0.1 + (j - 1) * width;\n bottom = 0.9 - i * height;\n if twoSetsFlag\n if i == 1 && j == 1\n else\n %subplot(nRxns,nRxns2,(i-1)*nRxns2+j);\n subplot('position', [left bottom width height]);\n if j >1 && i >1\n sampleScatterPlot(sample, rxnInd2(j - 1), rxnInd(i - 1), nPoints, fontSize, dispRFlag);\n elseif i == 1\n sampleHistInternal(sample, rxnInd2(j - 1), fontSize);\n elseif j == 1\n sampleHistInternal(sample, rxnInd(i - 1), fontSize);\n end\n if i == 1\n xlabel(rxnNames2{j - 1}, 'FontSize', fontSize);\n set(gca, 'XAxisLocation', 'top');\n end\n if j == 1\n ylabel(rxnNames{i - 1}, 'FontSize', fontSize);\n end\n end\n else\n if j == i\n %subplot(nRxns,nRxns2,(i-1)*nRxns2+j);\n subplot('position', [left bottom width height]);\n sampleHistInternal(sample, rxnInd(i), fontSize);\n\n elseif j > i\n %subplot(nRxns,nRxns2,(i-1)*nRxns2+j);\n subplot('position', [left bottom width height]);\n sampleScatterPlot(sample, rxnInd(j), rxnInd(i), nPoints, fontSize, dispRFlag);\n end\n if i == 1\n xlabel(rxnNames2{j}, 'FontSize', fontSize);\n set(gca, 'XAxisLocation', 'top');\n end\n if j == nRxns2\n set(gca, 'YAxisLocation', 'right');\n ylabel(rxnNames{i}, 'FontSize', fontSize);\n end\n end\n end\n\nend\n\n\nfunction sampleScatterPlot(sample, id1, id2, nPoints, fontSize, dispRFlag)\n\nselPts = randperm(size(sample, 2));\nselPts = selPts(1:nPoints);\n\nplot(sample(id1, selPts),sample(id2, selPts), 'r.');\nset(gca, 'YTickLabel', []);\nset(gca, 'XTickLabel', []);\nmaxx = max(sample(id1, :));\nmaxy = max(sample(id2, :));\nminx = min(sample(id1, :));\nminy = min(sample(id2, :));\naxis([minx maxx miny maxy]);\n% Display correlation coefficients\nif dispRFlag\n r = corrcoef(sample(id1, :)', sample(id2, :)');\n h = text(minx + 0.66 * (maxx-minx), miny + 0.2 * (maxy - miny), num2str(round(100 * r(1, 2)) / 100));\n set(h, 'FontSize', fontSize - 5);\nend\n\nfunction sampleHistInternal(sample , id, fontSize)\n\n[n, bins] = hist(sample(id , :), 30);\nif exist('smooth')\n plot(bins, smooth(bins, n') / sum(n'));\nelse\n plot(bins, n' / sum(n'));\nend\nmaxx = max(bins);\nminx = min(bins);\nset(gca, 'XTick', linspace(minx, maxx, 4));\nset(gca, 'XTickLabel', round(10 * linspace(minx, maxx, 4)) / 10);\nset(gca, 'YTickLabel', []);\nset(gca, 'FontSize', fontSize - 5);\naxis tight\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/sampling/sampleScatterMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18655885981546746}} {"text": "function mne_write_cov(fid,cov)\n%\n%\n% mne_write_cov(fid,cov)\n%\n% Write a covariance matrix to an open file\n%\n% fid - an open file id\n% cov - the covariance matrix to write\n%\n\n%\n% Author : Matti Hamalainen, MGH Martinos Center\n% License : BSD 3-clause\n%\n% Revision 1.4 2007/12/10 01:02:55 msh\n% Fixed writing of a diagonal covariance matrix\n%\n% Revision 1.3 2006/05/05 03:50:40 msh\n% Added routines to compute L2-norm inverse solutions.\n% Added mne_write_inverse_sol_stc to write them in stc files\n% Several bug fixes in other files\n%\n% Revision 1.2 2006/05/03 18:53:06 msh\n% Approaching Matlab 6.5 backward compatibility\n%\n% Revision 1.1 2006/04/29 12:44:10 msh\n% Added covariance matrix writing routines.\n%\n%\n\nme='MNE:mne_write_cov';\n\nglobal FIFF;\nif isempty(FIFF)\n FIFF = fiff_define_constants();\nend\n\nfiff_start_block(fid,FIFF.FIFFB_MNE_COV);\n%\n% Dimensions etc.\n%\nfiff_write_int(fid,FIFF.FIFF_MNE_COV_KIND,cov.kind);\nfiff_write_int(fid,FIFF.FIFF_MNE_COV_DIM,cov.dim);\nif cov.nfree > 0\n fiff_write_int(fid,FIFF.FIFF_MNE_COV_NFREE,cov.nfree);\nend\n%\n% Channel names\n%\nif ~isempty(cov.names)\n fiff_write_name_list(fid,FIFF.FIFF_MNE_ROW_NAMES,cov.names);\nend\n%\n% Data\n%\nif cov.diag\n fiff_write_double(fid,FIFF.FIFF_MNE_COV_DIAG,cov.data);\nelse\n if issparse(cov.data)\n fiff_write_float_sparse_rcs(fid,FIFF.FIFF_MNE_COV,cov.data);\n else\n q = 1;\n vals = zeros(cov.dim*(cov.dim+1)/2,1);\n for j = 1:cov.dim\n for k = 1:j\n vals(q) = cov.data(j,k);\n q = q + 1;\n end\n end\n fiff_write_double(fid,FIFF.FIFF_MNE_COV,vals);\n end\nend\n%\n% Eigenvalues and vectors if present\n%\nif ~isempty(cov.eig) && ~isempty(cov.eigvec)\n fiff_write_float_matrix(fid,FIFF.FIFF_MNE_COV_EIGENVECTORS,cov.eigvec);\n fiff_write_double(fid,FIFF.FIFF_MNE_COV_EIGENVALUES,cov.eig);\nend\n%\n% Projection operator\n%\nfiff_write_proj(fid,cov.projs);\n%\n% Bad channels\n%\nif ~isempty(cov.bads)\n fiff_start_block(fid,FIFF.FIFFB_MNE_BAD_CHANNELS);\n fiff_write_name_list(fid,FIFF.FIFF_MNE_CH_NAME_LIST,cov.bads);\n fiff_end_block(fid,FIFF.FIFFB_MNE_BAD_CHANNELS);\nend\n%\n% Done!\n%\nfiff_end_block(fid,FIFF.FIFFB_MNE_COV);\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/mne/mne_write_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.1865588598154674}} {"text": "function test_bug1397\n\n% MEM 2gb\n% WALLTIME 00:10:00\n% DEPENDENCY ft_preprocessing ft_appenddata\n\n% the following code was obtained from http://www.fieldtriptoolbox.org/tutorial/coherence\n% on Wed Mar 28 15:36:40 CEST 2012\n\n% find the interesting epochs of data\ncfg = [];\n% MODIFICATION, use trialfun handle and other path to the data\ncfg.trialfun = @trialfun_left;\ncfg.dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/SubjectCMC.ds');\ncfg = ft_definetrial(cfg);\n\n% MODIFICATION, use only 10 trials\ncfg.trl = cfg.trl(1:10,:);\n\n% MODIFICATION, the following should not affect the problem\n%\n% % detect EOG artifacts in the MEG data\n% cfg.continuous = 'yes';\n% cfg.artfctdef.eog.padding = 0;\n% cfg.artfctdef.eog.bpfilter = 'no';\n% cfg.artfctdef.eog.detrend = 'yes';\n% cfg.artfctdef.eog.hilbert = 'no';\n% cfg.artfctdef.eog.rectify = 'yes';\n% cfg.artfctdef.eog.cutoff = 2.5;\n% cfg.artfctdef.eog.interactive = 'no';\n% cfg = ft_artifact_eog(cfg);\n%\n% % detect jump artifacts in the MEG data\n% cfg.artfctdef.jump.interactive = 'no';\n% cfg.padding = 5;\n% cfg = ft_artifact_jump(cfg);\n%\n% % detect muscle artifacts in the MEG data\n% cfg.artfctdef.muscle.cutoff = 8;\n% cfg.artfctdef.muscle.interactive = 'no';\n% cfg = ft_artifact_muscle(cfg);\n%\n% % reject the epochs that contain artifacts\n% cfg.artfctdef.reject = 'complete';\n% cfg = ft_rejectartifact(cfg);\n\n% preprocess the MEG data\ncfg.demean = 'yes';\ncfg.dftfilter = 'yes';\ncfg.channel = {'MEG'};\ncfg.continuous = 'yes';\nmeg = ft_preprocessing(cfg);\n\ncfg = [];\ncfg.dataset = meg.cfg.dataset;\ncfg.trl = meg.cfg.trl;\ncfg.continuous = 'yes';\ncfg.demean = 'yes';\ncfg.dftfilter = 'yes';\ncfg.channel = {'EMGlft' 'EMGrgt'};\ncfg.hpfilter = 'yes';\ncfg.hpfreq = 10;\ncfg.rectify = 'yes';\nemg = ft_preprocessing(cfg);\n\n% see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1397\n% the reported problem in fieldtrip-20120302 was\n% \n% ??? Error using ==> ft_appenddata at 266\n% there is a difference in the time axes of the input data\n\ndata = ft_appenddata([], meg, emg);\nassert(numel(data.label)==153);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION to avoid external dependencies of this test\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction trl = trialfun_left(cfg)\n\n% read in the triggers and create a trial-matrix\n% consisting of 1-second data segments, in which\n% left ECR-muscle is active.\n\nevent = ft_read_event(cfg.dataset);\ntrig = [event(find(strcmp('backpanel trigger', {event.type}))).value];\nindx = [event(find(strcmp('backpanel trigger', {event.type}))).sample];\n\n%left-condition\nsel = [find(trig==1028):find(trig==1029)];\n\ntrig = trig(sel);\nindx = indx(sel);\n\ntrl = [];\nfor j = 1:length(trig)-1\n trg1 = trig(j);\n trg2 = trig(j+1);\n if trg1<=100 && trg2==2080\n trlok = [[indx(j)+1:1200:indx(j+1)-1200]' [indx(j)+1200:1200:indx(j+1)]'];\n trlok(:,3) = [0:-1200:-1200*(size(trlok,1)-1)]';\n trl = [trl; trlok];\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_bug1397.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1865588563139916}} {"text": "function createVolAnatSKERI(imgPathName,outputVAnatName,outputUnfoldName, clipVals)\n% createVolAnat([imgPathName],[outputVAnatName],[outputUnfoldName], ...\n% [clipVals=get from UI])\n%\n% imgPathName is the path to one of the I-files or to an analyze-format file. \n% A file browser comes up if none is given. \n%\n% If the optional clipVals (in the format of [minVal maxVal]) is provided,\n% will clip the vAnatomy before converting to uint8 (0-255, a big\n% annoyance resulting from older software constraints) for the .dat file.\n% Otherwise, pops up some example slices and a histogram, and lets you\n% select the cutoff.\n%\n% 2000.01.20 RFD (bob@white.stanford.edu): wrote it.\n% 2001.02.21 RFD: renamed from createVanatomy and added improved\n% the clipping UI by checking for obvious cases, like\n% when no clipping is necessary.\n% 2002.05.22 RFD: fixed a bug that would apply an incorrect upper clip\n% when the lower clip was not zero. THis probably didn't affect\n% anyone with the old (crappy) anatomy data, since the lower clip\n% was always best left at zero anyway.\n% I also now get the mmPerPix from the image header.\n% 2002.07.30 RFD: now allow Analyze format files as input. Reorients standard\n% axial Analyze data to match the mrGray sagittal convention.\n% 2002.08.05 RFD: fixed crash when imgPathName is passed that was introduced on 7/30.\n% 2003.06.25 DHB (brainard@psych.upenn.edu): Allow passing of output names.\n% 2004.01.24 Junjie: change GE_readHeader to readIfileHeader\n% Get the input filename\nif ~exist('imgPathName','var') | isempty(imgPathName)\n [fname, fullPath] = uigetfile({'*.img;*.nii;*.nii.gz','MRI images';'*.img','analyze';'*.nii','NIFTI';'*.nii.gz','NIFTI gz';'*.*','all files'}, 'Select analyze/NIFTI I-files...');\n if(isnumeric(fname))\n error('user canceled.');\n end\n imgPathName = fullfile(fullPath, fname);\nend\nif ~exist('outputVAnatName','var')\n outputVAnatName = [];\nend\nif ~exist('outputUnfoldName','var') | isempty(outputUnfoldName)\n outputUnfoldName = 'UnfoldParams';\nend\n[fullPath,fname,ext] = fileparts(imgPathName);\nif(strcmp(ext,'.hdr') | strcmp(ext,'.img'))\n [img,mmPerPix] = loadAnalyze(fullfile(fullPath,[fname '.hdr']));\n % To make analyze data the same orientation as vAnatomy, we reorient the data.\n % Note that we assume Analyze orientation code '0'- transverse, unflipped. \n % If that is the case, then the following will make the data look correct in mrGray.\n % It will even get left/right correct (left will be left and right right).\n img = permute(img,[3,2,1]);\n mmPerPix = [mmPerPix(3),mmPerPix(2),mmPerPix(1)];\n % flip each slice ud (ie. flip along matlab's first dimension, which is our x-axis)\n for jj=1:size(img,3)\n img(:,:,jj) = flipud(squeeze(img(:,:,jj)));\n end\n % flip each slice lr(ie. flip along matlab's second dimension, which is our y-axis)\n for jj=1:size(img,3)\n img(:,:,jj) = fliplr(squeeze(img(:,:,jj)));\n end\nelseif any(strcmpi(ext,{'.nii','.gz'}))\n% \tnii = load_nii(fullfile(fullPath,[fname,'.nii']));\t\t% old_RGB flag only matters if datatype=128 & bitpix=24\n% \tif isfield(nii.hdr.hist,'rot_orient')\t\t% already RAS?\n% \t\timg = nii.img;\n% \t\tmmPerPix = nii.hdr.dime.pixdim(2:4);\n% \telse\n% \t\terror('unknown orientation')\n% % \t\tk = [? ? ?];\n% % \t\timg = permute(nii.img,k);\n% % \t\tmmPerPix = nii.hdr.dime.pixdim(k+1);\n% \tend\n% \t% now orient to IPR for writeVolAnat to yield PIR vAnatomy\n% \timg = permute(img,[3 2 1]);\n% \tmmPerPix =mmPerPix([3 2 1]);\n% \timg = flipdim(img,1);\n% \timg = flipdim(img,2);\n\n\tnii = niftiRead(imgPathName);\n\tmmPerPix = nii.pixdim;\n\timg = double(nii.data);\n\t\n\t% get nifti rotation matrix\n\tqb = nii.quatern_b;\n\tqc = nii.quatern_c;\n\tqd = nii.quatern_d;\n\tqa = sqrt(1-qb^2-qc^2-qd^2);\n\tR = [ qa^2+qb^2-qc^2-qd^2, 2*(qb*qc+qa*qd), 2*(qb*qd-qa*qc);...\n\t\t\t2*(qb*qc-qa*qd), qa^2-qb^2+qc^2-qd^2, 2*(qc*qd+qa*qb);...\n\t\t\t2*(qb*qd+qa*qc), 2*(qc*qd-qa*qb), qa^2-qb^2-qc^2+qd^2];\n\tR = R';\t% something about the handedness??? only if positive determinant of R???\n\t\t\t\t% rows of R now [R;A;S]\n\tR(:,3) = nii.qfac * R(:,3);\n\tdisp(R)\n\t\n\t% now orient to IPR for writeVolAnat to yield PIR vAnatomy\n\tIPR = [0 0 0];\n\t[junk,IPR(3)] = max(abs(R(1,:)));\t% L-R dimension\n\t[junk,IPR(2)] = max(abs(R(2,:)));\t% P-A dimension\n\t[junk,IPR(1)] = max(abs(R(3,:)));\t% I-S dimension\n\tif numel(unique(IPR))~=3\n\t\terror('bad rotation matrix')\n\tend\n\tif any(abs([R(1,IPR(3)),R(2,IPR(2)),R(3,IPR(1))]) < 0.8)\n\t\tdisp('nifti quaternion inconsistent with 90deg rotations')\n\tend\n\timg = permute(img,IPR);\n\tif R(3,IPR(1)) >= 0\n\t\timg = flipdim(img,1);\n\tend\n\tif R(2,IPR(2)) >= 0\n\t\timg = flipdim(img,2);\n\tend\n\tif R(1,IPR(3)) < 0\n\t\timg = flipdim(img,3);\n\tend\n\t\n\n% elseif(strcmp(ext,'.gz') | strcmp(ext,'.nii'))\nelseif strcmp(ext,'.gz')\n ni = niftiRead(imgPathName);\n img = permute(double(ni.data),[3,2,1]);\n mmPerPix = [ni.pixdim(3),ni.pixdim(2),ni.pixdim(1)];\n for(jj=1:size(img,3))\n img(:,:,jj) = flipud(squeeze(img(:,:,jj)));\n end\n for(jj=1:size(img,3))\n img(:,:,jj) = fliplr(squeeze(img(:,:,jj)));\n end\nelse\n % get some info from the I-file header\n [su_hdr,ex_hdr,se_hdr,im_hdr,pix_hdr,im_offset] = readIfileHeader(imgPathName);\n mmPerPix = [im_hdr.pixsize_Y, im_hdr.pixsize_X, im_hdr.slthick];\n% nSlices = se_hdr.se_numimages;\n% Now, the DICOM format of i-files does not provide numimages info, so you\n% need to count all i-files in the folder.\n nSlices = length(getIfileNames(imgPathName));\n imDimXY = [im_hdr.dim_X, im_hdr.dim_Y];\n \n disp('Image header says:');\n disp([' ',num2str(nSlices),' slices']);\n disp([' ',num2str(imDimXY),' pixels inplane (x,y)']);\n disp([' ',num2str(mmPerPix),' mm per pixel']);\n % load ifiles\n disp('Loading I-files...');\n img = makeCubeIfiles(fullfile(fullPath,fname), imDimXY, [1:nSlices]);\nend\n% Get image information\nvolume_pix_size = 1./mmPerPix;\ndisp('Finding optimal clip values...');\nminVal = min(img(:));\nmaxVal = max(img(:));\n \n% Set the minumum to zero\nif(minVal~=0)\n disp(['Image minimum is not zero (',num2str(minVal),')- adjusting...']);\n img = img-minVal;\n\t maxVal = maxVal - minVal;\n\t minVal = 0;\nend\n \n% clip and scale, if necessary\nif (maxVal <= 255)\n disp('Image values are within 8-bit range- no clipping or scaling is necessary.');\n\t lowerClip = minVal;\n\t upperClip = maxVal;\nelseif exist('clipVals', 'var') && ~isempty(clipVals)\n % Clip and scale image values to be 0-255\n disp('Clipping intensities and scaling to 0-255...');\n img(img > clipVals(2)) = clipVals(2);\n img(img < clipVals(1)) = clipVals(1);\n img = round((img-clipVals(1))./(clipVals(2)-clipVals(1)) * 255);\n\t lowerClip = clipVals(1);\n\t upperClip = clipVals(2);\nelse\n figure(99);\n disp('Computing histogram...');\n [clippedImg, suggestedClipVals] = mrAnatHistogramClip(img, 0.5, 0.98);\n lowerClip = suggestedClipVals(1);\n upperClip = suggestedClipVals(2);\n [n,x] = hist(img(:),100);\n histHandle = subplot(2,2,1);\n\t \n% bar(x,n,1);\n% lcLine = line([lowerClip,lowerClip], [0,max(n)]);\n% ucLine = line([upperClip,upperClip], [0,max(n)]);\n\n% set yscale so you can see more than the largest histogram peak\n\tbar(x,n,1,'b');\n\tset(histHandle,'ylim',[-0.05 1.05]*2e5,'xlim',[-0.05 1.05]*max(x))\n\tcLineY = [-0.05,1.05]*max(n);\n\tlcLine = line([lowerClip,lowerClip], cLineY, 'color','r');\n\tucLine = line([upperClip,upperClip], cLineY, 'color','r');\n\t \n\t \n % display some slices\n slice{1} = squeeze(img(round(end/2),:,:));\n slice{2} = squeeze(img(:,round(end/2),:));\n slice{3} = squeeze(img(:,:,round(end/2)));\n for(i=[1:3])\n slice{i}(slice{i}upperClip) = upperClip;\n slice{i} = slice{i}-lowerClip;\n slice{i} = round(slice{i}./upperClip*255);\n subplot(2,2,2);\n image(slice{1});colormap(gray(256));axis image;axis off;\n subplot(2,2,3);\n image(slice{2});colormap(gray(256));axis image;axis off;\n subplot(2,2,4);\n image(slice{3});colormap(gray(256));axis image;axis off;\n end\n % Loop until user says it looks good\n ok = 0;\n while(~ok)\n% answer = inputdlg({'lower clip value (min=0): ',...\n% ['upper clip value (max=',num2str(maxVal),'):']}, ...\n% 'Set intensity clip values', 1, ...\n% {num2str(lowerClip),num2str(upperClip)}, 'on');\n% if ~isempty(answer)\n% lowerClip = str2num(answer{1});\n% upperClip = str2num(answer{2});\n% end\n \n disp(['intensity clip values are: ' num2str(lowerClip) ', ' num2str(upperClip)]);\n infoStr = 'Click twice on the histogram to set clip values. Define the smallest range that keeps the two right peaks.';\n uiwait(helpdlg(infoStr, 'clip info'))\n axes(histHandle);\n [x,y] = ginput(2);\n lowerClip = min(x);\n upperClip = max(x);\n\t\t \n% delete(lcLine); delete(ucLine);\n% lcLine = line([lowerClip,lowerClip], [0,max(n)]);\n% ucLine = line([upperClip,upperClip], [0,max(n)]);\n\t\t\tset(lcLine,'xdata',[lowerClip,lowerClip])\n\t\t\tset(ucLine,'xdata',[upperClip,upperClip])\n\t\t \n % Display some slices\n slice{1} = squeeze(img(round(end/2),:,:));\n slice{2} = squeeze(img(:,round(end/2),:));\n slice{3} = squeeze(img(:,:,round(end/2)));\n for(i=[1:3])\n slice{i} = rescale2(slice{i}, [lowerClip, upperClip]);\n% slice{i}(slice{i}upperClip) = upperClip;\n% slice{i} = slice{i}-lowerClip;\n% slice{i} = round(slice{i}./upperClip*255);\n subplot(2,2,2);\n image(slice{1});colormap(gray(256));axis image;axis off;\n subplot(2,2,3);\n image(slice{2});colormap(gray(256));axis image;axis off;\n subplot(2,2,4);\n image(slice{3});colormap(gray(256));axis image;axis off;\n end\n \n bn = questdlg('Is this OK?','Confirm clip values','Yes','No','Cancel','Yes');\n if(strcmp(bn,'Cancel'))\n error('Cancelled.');\n else\n ok = strcmp(bn,'Yes');\n end\n end\n \n % Clip and scale image values to be 0-255\n %\n % I haven't been fully satisfied by just automatically clipping off the top\n % few % of intensities (this is what mrInitRet currently does to the inplanes).\n % So, lately I've been looking at the histogram and picking intensityClip\n % by hand, then viewing the images to see how well it worked.\n disp('Clipping intensities and scaling to 0-255...');\n img(img>upperClip) = upperClip;\n img(img 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 [imref, im, mask] = histology_preprocessing(imref, im, opts)\n% HISTOLOGY_PREPROCESSING Prepare slices for intra-histology registration.\n%\n% HISTOLOGY_PREPROCESSING converts a list of histology images to grayscale,\n% inverts and thresholds them (so that the background is black instead of\n% white), extends the histograms to cover the dynamic range, and then\n% matches the histograms to a reference slice. This prepares the slices for\n% successful intra-histology registration.\n%\n% The function has two syntaxes. The reference can be provided as an image\n% or histogram.\n%\n% -------------------------------------------------------------------------\n% Reference image syntax:\n% [IMREF2, IM2, MASK] = HISTOLOGY_PREPROCESSING(IMREF, IM)\n%\n% IMREF is the slice whose histogram will be used as reference for the\n% others. IM is the stack of RGB colour or grayscale histology images to\n% preprocess. The images can be provided as:\n%\n% * A char with a single path and filename. E.g. 'file.mha'. With this\n% format, an output directory must be provided in OPTS.outdir, or\n% else a temporal one with a random name is created (see below).\n%\n% * A cell array of filenames. E.g. {'file1.mha', 'file2.mha'}. IM{I}\n% is the path and filename of the I-th slice. See note about\n% OPTS.outdir in previous item.\n%\n% * A plain array IM(R, C, I, CH), R=row, C=column, I=slice,\n% CH=channel.\n%\n% * A vector of scimat structs. IM(I) is a scimat struct with the I-th\n% slice. See \"help scimat\" for details.\n%\n% IMREF2, IM2 are the preprocessed images in the same format as the\n% inputs.\n%\n% MASK is a binary mask for IM2. This mask can be used to speed up\n% registration (when a mask is provided to elastix, only pixels within\n% the mask are used for the registration metric). The mask includes the\n% tissue and a bit of background around it.\n%\n% ... = HISTOLOGY_PREPROCESSING(..., OPTS)\n%\n% OPTS is a struct with options for the algorithm.\n%\n% 'outdir': If IM is a list of filenames, this is the path where the\n% preprocessed images are saved to.\n%\n% 'Grayscale': (def false) true/false whether image will be converted\n% to grayscale.\n%\n% -------------------------------------------------------------------------\n% Reference histogram syntax:\n% [HREF2, IM2, MASK] = HISTOLOGY_PREPROCESSING(HREF, IM)\n%\n% HREF is a (CH, L)-matrix with the reference histogram, where CH is the\n% number of channels, and L is the number of intensity levels. For\n% example, for an RGB image, CH=3, and for a uint8 class, L=256.\n%\n% IM is the image to preprocess, as in the syntax above.\n%\n% HREF2 is the histogram with the same preprocessing as the image.\n%\n% IM2, MASK are as in the syntax above.\n%\n% ... = HISTOLOGY_PREPROCESSING(..., OPTS)\n%\n% OPTS is as in the syntax above.\n%\n%\n% See also: regmatchedfilt, transfdiffreg.\n\n% Author: Ramon Casero \n% Copyright \u00a9 2014-2016 University of Oxford\n% Version: 0.5.1\n% \n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n% check arguments\nnarginchk(2, 3);\nnargoutchk(0, 3);\n\n% defaults\nif (nargin < 3 || isempty(opts))\n opts = struct;\nend\nif (~isfield(opts, 'Grayscale') || isempty(opts.Grayscale))\n opts.Grayscale = false;\nend\n\n% check the type and number of the input images\nif (ischar(im)) % single filename\n\n imType = 'filename';\n im = {im};\n N = 1;\n \nelseif (iscell(im)) % list of filenames\n\n imType = 'filename';\n N = length(im);\n \nelseif (isstruct(im)) % list of scimat structs\n \n imType = 'scimat';\n N = length(im);\n \nelse % plain array\n \n imType = 'array';\n N = size(im, 3);\n \nend\n\n% convert IMREF to a plain array if it's not already, or keep as histogram\n% if it's a histogram\nif (ischar(imref)) % filename\n\n imrefMat = scimat_load(imref);\n imrefMat = imrefMat.data;\n imrefType = 'filename';\n\nelseif (isstruct(imref)) % scimat struct\n \n imrefMat = imref.data;\n imrefType = 'scimat';\n \nelseif (isa(imref, 'double') && size(imref, 1)==3) % histogram as (3,256) matrix\n \n imrefType = 'histogram';\n \nelse % array\n \n % move channels to 5th index, so that it's the same format as IM.data\n imrefMat = reshape(imref, size(imref, 1), size(imref, 2), 1, 1, size(imref, 3));\n imrefType = 'array';\n \nend\n\nswitch (imrefType)\n case 'histogram'\n \n % is the histogram has more than one channel, we don't try to\n % convert to grayscale\n \n % preprocessing of histogram equivalent to preprocessing the\n % reference image (invert, threshold, etc.)\n imref = histogram_preprocessing(imref);\n \n otherwise\n \n % grayscale conversion of IMREF, if requested by user\n if (opts.Grayscale)\n \n imrefMat = rgb2gray(squeeze(imrefMat));\n \n end\n\n % preprocessing of the reference image (invert, threshold, etc.)\n imrefMat = individual_image_preprocessing(imrefMat);\n \nend\n\n% if images are provided as filenames, either the user must provide an\n% output directory, or we generate a temp one with a random name\nif (strcmp(imType, 'filename') ...\n && (~isfield(opts, 'outdir') || isempty(opts.outdir)))\n opts.outdir = tempname;\nend\n\n% allocate memory for masks\nswitch (imType)\n \n case 'filename' % filename\n \n mask = cell(1, N);\n \n case 'scimat' % scimat struct\n \n mask = im;\n \n case 'array' % plain array\n \n mask = zeros(size(im, 1), size(im, 2), size(im, 3), 'uint8');\n \nend\n\n% loop all images\nfor I = 1:N\n\n % convert IM to a scimat struct if it's not already\n switch (imType)\n \n case 'filename' % filename\n \n im0 = scimat_load(im{I});\n \n case 'scimat' % scimat struct\n \n im0 = im(I);\n \n case 'array' % plain array\n \n im0 = scimat_im2scimat(reshape(im(:, :, I, :, :), ...\n [size(im, 1) size(im, 2) 1 1 size(im, 4)]));\n \n end\n \n switch (imrefType)\n case 'histogram'\n \n % preprocessing of IM\n mask0 = im0;\n [im0.data, mask0.data] = individual_image_preprocessing(im0.data);\n\n im0.data = match_histograms_hist(imref, im0.data);\n \n % grayscale conversion of IM, if requested by user\n if (opts.Grayscale)\n \n im0.data = rgb2gray(squeeze(im0.data));\n \n end\n \n otherwise\n \n % grayscale conversion of IM, if requested by user\n if (opts.Grayscale)\n \n im0.data = rgb2gray(squeeze(im0.data));\n \n end\n \n % preprocessing of IM\n mask0 = im0;\n [im0.data, mask0.data] = individual_image_preprocessing(im0.data);\n \n % match IM histogram to IMREF\n im0.data = match_histograms_im(imrefMat, im0.data);\n \n end\n \n % convert processed images to output format\n switch (imType)\n \n case 'filename' % filename\n \n [~, name, ext] = fileparts(im{I});\n im{I} = [opts.outdir filesep name ext];\n scimat_save(im{I}, im0);\n mask{I} = [opts.outdir filesep 'mask-' name ext];\n scimat_save(mask{I}, mask0);\n \n case 'scimat' % scimat struct\n \n im(I) = im0;\n mask(I) = mask0;\n \n case 'array' % plain array\n \n im(:, :, I, :) = reshape(im0.data, ...\n [size(im, 1) size(im, 2) 1 size(im, 5)]);\n mask(:, :, I, :) = mask0.data;\n \n end\n \n \nend\n\n% convert processed images to output format\nswitch (imrefType)\n \n case 'filename' % filename\n\n error('Not implemented yet')\n \n case 'scimat' % scimat struct\n \n imref.data = imrefMat;\n \n case 'array' % plain array\n \n imref = reshape(imrefMat, ...\n [size(imrefMat, 1) size(imrefMat, 2) 1 size(imrefMat, 5)]);\n \nend\n\nend\n\n%% nested functions\n\n% individual_image_preprocessing:\n%\n% Preprocessing of an individual image. Invert, threshold background,\n% extend histogram to whole dynamic range. Compute a rough binary mask of\n% the object.\nfunction [im, mask] = individual_image_preprocessing(im)\n\n% loop image channels\nfor I = 1:size(im, 5)\n \n % select one channel\n ch = im(:, :, :, :, I);\n \n % the image should have two types of blackground pixels: white-ish and\n % pure black. The white-ish ones are from the original image, and the\n % black ones come from the B-spline fill-in. When we invert the image,\n % we don't want to invert the black ones, so we select non-black pixels\n idx = ch ~= 0;\n \n % invert image and make lowest intensity = 0\n ch(idx) = max(ch(idx)) - ch(idx);\n \n % remove background by zeroing anything <= mode (the background forms\n % the largest peak). We are quite conservative here in terms of keeping\n % all the tissue we can, to avoid losing detail, even if that means\n % that we are going to have a bit of background noise\n ch(ch <= mode(double(ch(idx)))) = 0;\n \n % extend histogram to cover whole dynamic range\n minh = double(min(ch(ch > 0)));\n maxh = double(max(ch(ch > 0)));\n ch = uint8(255 * (double(ch) - minh) / (maxh - minh));\n \n % replace image channel with the processed one\n im(:, :, :, :, I) = ch;\n \nend\n\n% compute a mask of the foreground\nif (size(im, 5) == 1)\n \n mask = uint8(im > 2);\n \nelse\n \n mask = uint8(rgb2gray(squeeze(im)) > 2);\n \nend\n\n% remove some background noise in the mask\nse = strel('disk', 1);\nmask = imerode(mask, se);\n\n% dilate mask to cover some background\nse = strel('disk', 10);\nmask = imdilate(mask, se);\n\nend\n\n% histogram_preprocessing:\n%\n% Transform histogram to replicate what individual_image_preprocessing()\n% does to an image\nfunction hgram = histogram_preprocessing(hgram)\n\n% invert histogram, except for the pixels == 0, that continue being 0\nhgram(:, 2:end) = hgram(:, end:-1:2);\n\n% find the modes of the histogram\n[~, imode] = max(hgram, [], 2);\n\n% number of intensity levels\nL = size(hgram, 2);\n\n% loop histogram channels\nfor CH = 1:size(hgram, 1)\n \n % crop the histogram <= mode\n hgram(CH, 1) = sum(hgram(CH, 1:imode(CH)));\n hgram(CH, 2:imode(CH)) = 0;\n \n % extend dynamic range of histogram\n xbin = linspace(1, L-1, L-imode(CH));\n hgram(CH, 2:end) = round(interp1(xbin, hgram(CH, (imode(CH)+1):end), 1:L-1));\n \nend\n\nend\n\n% match_histograms_im:\n%\n% Match the histogram of each channel in IM to IMREF, ignoring background\n% voxels. IMREF is a reference image.\n%\n% IMREF: reference image, array (R, C, CH)\nfunction im = match_histograms_im(imref, im)\n\n% match histograms to reference slice\nfor I = 1:size(im, 5)\n \n % select channels\n chref = imref(:, :, :, :, I);\n ch = im(:, :, :, :, I);\n \n % match histograms ignoring the background\n idxref = chref > 0;\n idx = ch > 0;\n ch(idx) = imhistmatch(ch(idx), chref(idxref));\n \n % replace image channel with processed ones\n %imref(:, :, I) = chref;\n im(:, :, :, :, I) = ch;\n \nend\n\nend\n\n% match_histograms_hist:\n%\n% Match the histogram of each channel in IM to IMREF, ignoring background\n% voxels. IMREF is a histogram with one or more channels.\n%\n% IMREF: histogram, array (CH, intensity)\nfunction im = match_histograms_hist(hgram, im)\n\n% match image histograms to reference histogram\nfor I = 1:size(im, 5)\n \n % select image channel\n ch = im(:, :, :, :, I);\n \n % match histograms ignoring the background\n idx = ch > 0;\n ch(idx) = histeq(ch(idx), hgram(I, 2:end));\n \n % replace image channel with processed ones\n %imref(:, :, I) = chref;\n im(:, :, :, :, I) = ch;\n \nend\n\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/CardiacToolbox/histology_preprocessing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18615861039910947}} {"text": "function flattenFromROI(view, ROI)\n% Initiates the mrFlatMesh GUI, filling in some fields\n%\n% flattenFromROI(view, ROI)\n%\n% Wrapper for mrFlatMesh GUI. Opens the GUI, filling in some\n% default starting values. Uses the center of mass of the specified\n% ROI as the start point.\n%\n% GLOBALS: uses mrSESSION fields to initialize the mrFlatMesh GUI.\n%\n% Example:\n% flattenFromROI(VOLUME{1}); % Uses selected (current) ROI\n%\n% HISTORY:\n% 2002.03.04 RFD (bob@white.stanford.edu): wrote it\n% 7/16/02 djh, replaced mrSESSION.vAnatomyPath with global vANATOMYPATH\n% 2002.07.19 RFD: cleaned up default filenames a bit\n% 2006.02.05 MMS: made it work with ROIs with only one coordinate\n\nmrGlobals\n\nswitch view.viewType\n case 'Gray'\n leftGrayPath = view.leftPath;\n rightGrayPath = view.rightPath;\n otherwise\n error([mfilename,': unsupported view type \"',view.viewType,'\".']);\nend\n\nif(~exist('ROI','var'))\n if(view.selectedROI>0)\n ROI = view.ROIs(view.selectedROI);\n else\n myErrorDlg('No ROI selected');\n return;\n end\nend\n\nmmPerPixXYZ = readVolAnatHeader(vANATOMYPATH);\n\nstartXYZ = round(mean(ROI.coords',1)');\nstartXYZ = [startXYZ(2);startXYZ(1);startXYZ(3)];\n\n% Now how do we find which hemisphere this coord belongs to?\nhemi = viewGet(view, 'roihemi', ROI.coords);\nif isempty('hemi'), hemi = 'left'; end;\n\nif strcmpi('hemi', 'left')\n grayPath = fullfile(leftGrayPath,'');\nelse\n grayPath = fullfile(rightGrayPath,'');\nend\n\n\n[grayPathDir,grayPathFileName] = fileparts(grayPath);\nif(exist(grayPath)~=2)\n if(exist(grayPathDir,'dir'))\n % at least get them close\n grayPath = grayPathDir;\n else\n grayPath = '';\n grayPathDir = '';\n end\nend\n\n% If the Gray coords are saved in the project as 'coords.mat', then use\n% this to get the gray graph\ncoordsFile = fullfile(HOMEDIR, 'Gray', 'coords.mat');\nif exist(coordsFile, 'file'),\n grayPath = coordsFile; \nend\n\n% Try to guess the mesh file path\n[p f e] = fileparts(leftGrayPath);\n\n% if the gray path is a nifti class file, then we use this and not a mesh\nif strcmpi(e, '.gz')\n if strcmpi('hemi', 'left')\n meshPath = fullfile(leftGrayPath,'');\n else\n meshPath = fullfile(rightGrayPath,'');\n end\nelse\n % otherwise we look for a mesh\n subDirs = {'','3dMeshes','3DMeshes','3Dmeshes'};\n extensions = {'.MrM','.mrm','.Mrm','.MRm','.MRM', 'nii.gz'};\n meshPath = grayPathDir;\n for ii=1:length(subDirs)\n for jj=1:length(extensions)\n if(exist(fullfile(grayPathDir,subDirs{ii},[grayPathFileName,extensions{jj}]))==2)\n meshPath = fullfile(grayPathDir,subDirs{ii},[grayPathFileName,extensions{jj}]);\n break;\n end\n end\n end\nend\nts = now;\nsaveFileName = ['unfold_',datestr(ts,'mm'),datestr(ts, 'dd'),datestr(ts,'yy')];\nif(exist(fullfile(grayPathDir,'Unfolds'), 'dir'))\n savePath = fullfile(grayPathDir, 'Unfolds', saveFileName);\nelse\n savePath = fullfile(grayPathDir, saveFileName);\nend\n\nunfoldRadiusMM = 60;\n\ndisp('calling mrFlatMesh...');\n\nmrFlatMesh({'grayPath', grayPath, ...\n 'meshPath', meshPath, ...\n 'savePath', savePath, ...\n 'scaleXYZ', mmPerPixXYZ , ...\n 'startXYZ', startXYZ, ...\n 'unfoldRadiusMM', unfoldRadiusMM, ...\n 'hemi', hemi});\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Segmentation/flattenFromROI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.18614772917743616}} {"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 [fv, normals] = MimCreateSurfaceFromSegmentation(segmentation, smoothing_size, small_structures, label, coordinate_system, template_image, limit_to_one_component_per_index, minimum_component_volume_mm3, reporting)\n % MimCreateSurfaceFromSegmentation. Creates a surface mesh from a segmentation volume.\n %\n % Inputs\n % ------\n %\n % filepath, filename - path and filename for STL file\n %\n % segmentation - a binary 3D PTKImage containing 1s for the voxels to\n % visualise\n %\n % smoothing_size - the amount of smoothing to perform. Higher\n % smoothing makes the image look better but removes small\n % structures such as airways and vessels\n %\n % small_structures - set to true for improved visualisation of\n % narrow structures such as airways and vessels\n %\n % label - Only voxels of this colour are considered\n %\n % coordinate_system a MimCoordinateSystem enumeration\n % specifying the coordinate system to use\n %\n % template_image A PTKImage providing voxel size and image size\n % parameters, which may be required depending on the coordinate\n % system\n %\n % limit_to_one_component_per_index - set this flag to true if each colour\n % index in the image represents only a single, large object.\n % This will prevent the appearance of orphaned 'island' components caused by the\n % image smoothing and surface rendering approximations.\n % \n % minimum_component_volume_mm3 - if two or more separate components in the\n % image could share the same colour index, but you want to prevent the\n % appearance of orphaned 'island' components caused by the\n % image smoothing and surface rendering approximations, then set this to\n % an appropriate minimum volume value. Any components smaller than this\n % value will not be rendered.\n %\n % reporting - an object implementing CoreReportingInterface\n % for reporting progress and warnings\n %\n %\n %\n % Licence\n % -------\n % Part of the TD MIM Toolkit. https://github.com/tomdoel\n % Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com\n % Distributed under the MIT licence. Please see website for details.\n %\n \n \n if ~isa(segmentation, 'PTKImage')\n error('Requires a PTKImage as input');\n end\n \n % Isolate this colour component\n sub_seg = segmentation.BlankCopy;\n raw_image = segmentation.GetMappedRawImage;\n sub_seg.ChangeRawImage(raw_image == label);\n \n sub_seg.CropToFit;\n \n \n % Perform a closing operation and filter the image to create a smoother appearance\n if small_structures\n morph_size = 1;\n threshold = 0.2;\n else\n morph_size = 3;\n threshold = 0.5;\n end\n\n required_padding_mm = 2*threshold + morph_size;\n required_padding = ceil(required_padding_mm/min(segmentation.VoxelSize)) + 1;\n sub_seg.AddBorder(required_padding);\n \n if morph_size > 0\n sub_seg.BinaryMorph(@imclose, morph_size);\n end\n \n if smoothing_size > 0\n sub_seg = MimGaussianFilter(sub_seg, smoothing_size);\n end\n \n if limit_to_one_component_per_index\n \n % The smoothing may split the segmentation, so we consider only the main component,\n % and remove any other components by setting their value to zero\n surviving_components = sub_seg.RawImage >= threshold;\n surviving_components = MimImageUtilities.GetLargestConnectedComponent(surviving_components);\n else\n\n cc = bwconncomp(sub_seg.RawImage >= threshold);\n num_pixels = cellfun(@numel, cc.PixelIdxList);\n voxel_threshold = minimum_component_volume_mm3/prod(segmentation.VoxelSize);\n larger_elements = num_pixels > voxel_threshold;\n surviving_components = false(sub_seg.ImageSize);\n for index = 1 : numel(larger_elements)\n if larger_elements(index)\n surviving_components(cc.PixelIdxList{index}) = true;\n end\n end\n end\n \n sub_seg_raw = sub_seg.RawImage >= threshold;\n sub_seg_raw(~surviving_components) = 0;\n sub_seg.ChangeRawImage(sub_seg_raw);\n \n [xc, yc, zc] = sub_seg.GetPTKCoordinates;\n [xc, yc, zc] = MimImageCoordinateUtilities.ConvertFromPTKCoordinatesCoordwise(xc, yc, zc, coordinate_system, template_image);\n \n fv = isosurface(xc, yc, zc, sub_seg.RawImage, threshold);\n \n if nargout > 1\n normals = isonormals(xc, yc, zc, sub_seg.RawImage, fv.vertices);\n end\nend", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/mim/Library/Visualisation/MimCreateSurfaceFromSegmentation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18600684358106406}} {"text": "function S=PartLabelCompSize(S,varargin)\n\n%% PartLabel Assigns particle labels to particles \n%% based on features in the carbon edge spectrum. Note that DiffMaps.m must\n%% be run on S prior to execution of this function.\n%% OUTPUT NOTES:\n%% S.CompSize is a matrix of areas for each component with particles in the\n%% rows and components in the columns. the components are ordered as\n%% follows: ['OCArea','InArea','Sp2Area','KArea','CO3Area','Total Area']\n\n%% 081201 Ryan C. Moffet\n\nif isempty(S.DiffMap)\n return\nend\nfigsav=0;\nparticle=S.particle;\nif ~isempty(varargin)\n rootdir=varargin{1};\n sample=varargin{2};\n figsav=1;\nend\nColorVec=[0,170,0;0,255,255;255,0,0;255,170,0;255,255,255]; %% rgb colors of the different components\n\nMatSiz=size(S.DiffMap(:,:,1));\nRgbMat=zeros([MatSiz,3]);\nRedMat=zeros(MatSiz);\nGreMat=zeros(MatSiz);\nBluMat=zeros(MatSiz);\n\ncnt=1;\n\nfor i=[5,1,3,2,4]; %% cooh, In, sp2, K, co3 \n GrayImage=mat2gray(S.DiffMap(:,:,i)); %% Turn into a greyscale with vals [0 1]\n GrayImage=imadjust(GrayImage,[0 1],[0 1],0.1); %% increase contrast\n% GrayImage=medfilt2(GrayImage); %% something weird was happening\n % %to the pixels on the corner\n Thresh=graythresh(GrayImage); %% Otsu thresholding\n Mask=im2bw(GrayImage,Thresh); %% Give binary image\n BinCompMap{cnt}=bwlabel(Mask,8);\n cnt=cnt+1;\nend\n\n% [j,k]=find(BinCompMap{3}>0); %% find index of >0 components\n% [l,m]=find(S.LabelMat>0);\n% S.BinCompMap=BinCompMap;\n% if ~isempty(j) || ~isempty(k)\n% [orgspec]=ComponentSpec(S,'COOH');\n% [inorgspec]=ComponentSpec(S,'Inorg');\n% [ecspec]=ComponentSpec(S,'sp2');\n% ecspec(:,2)=ecspec(:,2)-mean(ecspec(1:8,2));\n% svdM = stackSVD(S,ecspec,orgspec,inorgspec);\n% svdM(svdM<0)=0;\n% figure,imagesc(svdM(:,:,1)),colormap gray, colorbar\n% BinCompMap{3}=threshimage(svdM(:,:,1));\n% end\n% \n%% This first loop creates masks for the individual components over the\n%% entire field of view. Each component is then defined as a colored\n%% component for visualization.\ncnt=1;\nfor i=[5,1,3,2,4]%i=[5,1,2,3] %% loop over chemical components\n% GrayImage=mat2gray(S.DiffMap(:,:,i)); %% Turn into a greyscale with vals [0 1]\n% GrayImage=imadjust(GrayImage,[0 1],[0 1],0.1); %% increase contrast\n% % GrayImage=medfilt2(GrayImage); %% something weird was happening\n% % %to the pixels on the corner\n% Thresh=graythresh(GrayImage); %% Otsu thresholding\n% Mask=im2bw(GrayImage,Thresh); %% Give binary image\n% BinCompMap{cnt}=bwlabel(Mask,8);\n% end\n [j,k]=find(BinCompMap{cnt}>0); %% find index of >0 components\n [l,m]=find(S.LabelMat>0);\n if ~isempty(j) || ~isempty(k) %% this conditional defines a color for the component areas (if it exists)\n linidx=sub2ind(size(BinCompMap{cnt}),j,k); %% change to linear in dex\n labidx=sub2ind(size(BinCompMap{cnt}),l,m);\n rejidx=setdiff(linidx,labidx);\n BinCompMap{cnt}(rejidx)=0;\n linidx=sub2ind(size(BinCompMap{cnt}),find(BinCompMap{cnt}>0));\n RedMat(linidx)=ColorVec(cnt,1); %% define the color for the ith component\n GreMat(linidx)=ColorVec(cnt,2);\n BluMat(linidx)=ColorVec(cnt,3);\n trmat=zeros(size(RedMat));\n tgmat=zeros(size(RedMat));\n tbmat=zeros(size(RedMat));\n trmat(linidx)=ColorVec(cnt,1);\n tgmat(linidx)=ColorVec(cnt,2);\n tbmat(linidx)=ColorVec(cnt,3);\n ccmap{cnt}(:,:,1)=trmat;\n ccmap{cnt}(:,:,2)=tgmat;\n ccmap{cnt}(:,:,3)=tbmat;\n clear trmat tgmat tbmat\n else\n ccmap{cnt}=zeros(MatSiz(1),MatSiz(2),3);\n end\n cnt=cnt+1; %% this counter keeps track of the indivdual components.\n clear j k l m linidx GrayImage Thresh Mask rejidx;\nend\n\n%% This second loop assigns labels over individual particles defined\n%% previously in Diffmaps.m\nNumPart=max(max(S.LabelMat));\n% LabelStr={'OC','In','K','EC'};\nLabelStr={'OC','In','EC','K','CO3'};\n\nCompSize=zeros(NumPart,length(LabelStr)+1);\nPartLabel={};\nfor i=1:NumPart %% Loop over particles defined in Diffmaps.m\n PartLabel{i}='';\n for j=1:5 %% Loop over chemical components\n [a1,b1]=find(S.LabelMat==i); %% get particle i\n [a2,b2]=find(BinCompMap{j}>0); %% get component j\n if ~isempty([a1,b1]) && ~isempty([a2,b2])\n linidx1=sub2ind(size(S.LabelMat),a1,b1); %% Linear index for particle\n linidx2=sub2ind(size(BinCompMap{j}),a2,b2); %% Linear index for component\n IdxCom=intersect(linidx1,linidx2); %% find common indices\n if length(IdxCom)>3%0.05*length(linidx1) %% if component makes up greater than 2% of the pixels of the particle...\n PartLabel{i}=strcat(PartLabel{i},LabelStr{j}); %% give label of component.\n CompSize(i,j)=length(IdxCom); %% number of pixels in the component.\n end\n end\n end\n if isempty(PartLabel{i})\n PartLabel{i}='NoID'; %% Particles identified by Otsu's mehod here but not in Particle map script\n end\n CompSize(i,j+1)=length(linidx1); %% number of pixels in the particle\n clear linidx1 linidx2 IdxCom a1 b1 a2 b2;\nend\nif isempty(PartLabel)\n S.PartLabel='NoID';\nelse\n S.PartLabel=PartLabel;\nend\nS=ParticleSize(S);\n\nMatSiz=size(S.LabelMat);\nXSiz=S.Xvalue/MatSiz(1);\nYSiz=S.Yvalue/MatSiz(2);\nCompSize=CompSize.*(XSiz*YSiz); %% Area of components in um^2\nS.CompSize=CompSize;\n \nRgbMat(:,:,1)=RedMat;\nRgbMat(:,:,2)=GreMat;\nRgbMat(:,:,3)=BluMat;\nS.RGBCompMap=RgbMat;\nfor i=1:length(BinCompMap)\n temp{i}=BinCompMap{i};\n temp{i}(temp{i}>1)=1;\nend\nxdat=[0:XSiz:S.Xvalue];\nydat=[0:YSiz:S.Yvalue];\n\n% Show DiffMaps\nfigure('Name',particle,'NumberTitle','off','Position',[1,1,634,872])\nsubplot(3,2,1)\n% imagesc(temp{1})\nimage(xdat,ydat,uint8(ccmap{1}))\ntitle('Carbox')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\nsubplot(3,2,2)\n% imagesc(temp{2})\nimage(xdat,ydat,uint8(ccmap{2}))\ntitle('Inorg.')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\nsubplot(3,2,3)\n% imagesc(temp{3})\nimage(xdat,ydat,uint8(ccmap{3}))\ntitle('%sp2>35')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\nsubplot(3,2,4)\n% imagesc(temp{4})\nimage(xdat,ydat,uint8(ccmap{4}))\ntitle('Potassium')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\n% LabelMat=raw2mask(S);\nsubplot(3,2,5)\nimage(xdat,ydat,uint8(ccmap{5}))\ntitle('CO_{3}')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\n% title('Particle Map')\n% axis image\n\nsubplot(3,2,6)\nimage(xdat,ydat,uint8(RgbMat))\ntitle('Mixed')\naxis image\nxlabel('X (\\mum)');\nylabel('Y (\\mum)'); \n\nif figsav==1\nfilename=sprintf('%s%s%s%s',rootdir,sample,particle,'_f2_thresh');\nsaveas(gcf,filename,'tiff');\nend\nS.BinCompMap=temp;\nS=MultPartAvSpec(S);\nif figsav==1\nfilename=sprintf('%s%s%s%s',rootdir,sample,particle,'_f3_spec');\nsaveas(gcf,filename,'tiff');\nclose all\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29085-stxm-spectromicroscopy-particle-analysis-routines/AnalyticalChemistryScripts/PartLabelCompSize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.18572647436977052}} {"text": "function adc=makeAdc(num,varargin)\n%makeAdc Create a ADC readout event.\n% adc=makeAdc(n, 'Dwell', dwell) Create ADC with n samples\n% with given dwell time.\n%\n% adc=makeAdc(n, 'Duration', dur) Create ADC with n\n% samples and specified total duration.\n%\n% adc=makeAdc(..., 'Delay', d) Create ADC with initial delay.\n%\n% adc=makeAdc(n, sys, ...) Create ADC considering system properties\n% given in sys. For example, adcDeadTime can be taken into account by \n% making sure that both the before the ADC is as least as long as \n% adcDeadTime and another period of adcDeadTime is added after sampling \n% is finished. \n%\n% See also Sequence.addBlock\n\npersistent parser\nif isempty(parser)\n parser = inputParser;\n parser.FunctionName = 'makeAdc';\n \n addRequired(parser,'numSamples',@(x)(isnumeric(x) && (fix(x)-x)==0));\n addOptional(parser,'system',mr.opts(),@isstruct);\n addParamValue(parser,'dwell',0,@isnumeric);\n addParamValue(parser,'duration',0,@isnumeric);\n addParamValue(parser,'delay',0,@isnumeric);\n addParamValue(parser,'freqOffset',0,@isnumeric);\n addParamValue(parser,'phaseOffset',0,@isnumeric);\nend\n\nparse(parser,num,varargin{:});\n\nopt = parser.Results;\nadc.type = 'adc';\nadc.numSamples = num;\nadc.dwell = opt.dwell;\nadc.delay = opt.delay;\nadc.freqOffset = opt.freqOffset;\nadc.phaseOffset = opt.phaseOffset;\nadc.deadTime = opt.system.adcDeadTime;\n\nif (opt.dwell==0 && opt.duration==0) || (opt.dwell>0 && opt.duration>0)\n error('Either dwell or duration must be defined');\nend\n\nif opt.duration > 0\n adc.dwell = opt.duration/opt.numSamples;\nend\nif opt.dwell > 0\n adc.duration = opt.dwell*opt.numSamples;\nend\nif adc.deadTime > adc.delay\n adc.delay = adc.deadTime; % adcDeadTime is added before the actual sampling (and also second time after the sampling period)\nend\n\nend", "meta": {"author": "pulseq", "repo": "pulseq", "sha": "b4c8fee2a1ffa491d53bd6f507cba2029bf32835", "save_path": "github-repos/MATLAB/pulseq-pulseq", "path": "github-repos/MATLAB/pulseq-pulseq/pulseq-b4c8fee2a1ffa491d53bd6f507cba2029bf32835/matlab/+mr/makeAdc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18572181565205598}} {"text": "function z = uminus( x )\n\n% Disciplined convex programming information for UMINUS (-):\n% Unary minus may be used in DCPs without restrictions---with the\n% understanding, of course, that it produces a result with the \n% opposite cuvature to its argument; i.e., the negative of a convex\n% expression is concave, and vice versa.\n%\n% Disciplined geometric programming information for UMINUS(-):\n% Negation of non-constant values may not be used in disciplined\n% geometric programs.\n\npersistent remap\nif isempty( remap ),\n remap = cvx_remap( 'invalid', 'log-concave' ) & ~cvx_remap( 'log-affine' );\nend\ntt = remap( cvx_classify( x ) );\nif nnz( tt ),\n xt = cvx_subsref( x, tt );\n error( 'Disciplined convex programming error:\\n Illegal operation: - {%s}', cvx_class( xt ) );\nend\n\nz = cvx( x.size_, -x.basis_ );\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/builtins/@cvx/uminus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18551997042051485}} {"text": "classdef SetKinematicStateAction < AbstractEventAction\n %SetTimePositionVelocityMassStateAction Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n stateLog LaunchVehicleStateLog\n orbitModel(1,1) AbstractElementSet = KeplerianElementSet.getDefaultElements();\n \n %Inherit Time\n inheritTime(1,1) logical = false;\n inheritTimeFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;\n inheritTimeFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);\n \n %Inherit State\n inheritPosVel(1,1) logical = false;\n inheritPosVelFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;\n inheritPosVelFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);\n \n %Inherit Stage States\n stageStates(1,:) SetKinematicStateStageState \n engineStates(1,:) SetKinematicStateEngineState\n tankStates(1,:) SetKinematicStateTankState\n epsSinkStates(1,:) SetKinematicStateEPSinkState\n epsSrcStates(1,:) SetKinematicStateEPSrcState\n epsStorageStates(1,:) SetKinematicStateEPStorageState\n \n %Inherit all other state elements\n inheritStateElems(1,1) logical = true;\n inheritStateElemsFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;\n inheritStateElemsFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);\n \n optVar SetKinematicStateActionVariable\n end\n \n %deprecated\n properties\n inheritStageStates(1,1) logical = true;\n inheritStageStatesFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;\n inheritStageStatesFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);\n end\n \n properties(Dependent)\n time(1,1) double\n centralBody(1,1) KSPTOT_BodyInfo\n end\n \n methods\n function obj = SetKinematicStateAction(stateLog, orbitModel)\n if(nargin > 0)\n obj.stateLog = stateLog;\n obj.orbitModel = orbitModel;\n end\n \n obj.id = rand();\n end\n \n function time = get.time(obj)\n time = obj.orbitModel.time;\n end\n \n function set.time(obj, newTime)\n obj.orbitModel.time = newTime;\n end\n \n function time = get.centralBody(obj)\n time = obj.orbitModel.frame.getOriginBody();\n end\n \n function set.centralBody(obj, newCentralBody)\n obj.orbitModel.frame.setOriginBody(newCentralBody);\n end\n \n function newStateLogEntry = executeAction(obj, stateLogEntry)\n newStateLogEntry = stateLogEntry.deepCopy();\n\n % Time\n if(obj.inheritTime)\n if(obj.inheritTimeFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n not(isempty(obj.inheritTimeFromEvent)) && ...\n not(isempty(obj.inheritTimeFromEvent.getEventNum())) && ...\n obj.inheritTimeFromEvent.getEventNum() > 0)\n \n timeEvtStateLog = obj.stateLog.getLastStateLogForEvent(obj.inheritTimeFromEvent);\n if(not(isempty(timeEvtStateLog)))\n newStateLogEntry.time = timeEvtStateLog(end).time;\n obj.orbitModel.time = newStateLogEntry.time;\n end\n end\n else\n newStateLogEntry.time = obj.orbitModel.time;\n end\n \n % Orbit\n if(obj.inheritPosVel)\n if(obj.inheritPosVelFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n not(isempty(obj.inheritPosVelFromEvent)) && ...\n not(isempty(obj.inheritPosVelFromEvent.getEventNum())) && ...\n obj.inheritPosVelFromEvent.getEventNum() > 0)\n \n posVelEvtStateLog = obj.stateLog.getLastStateLogForEvent(obj.inheritPosVelFromEvent);\n if(not(isempty(posVelEvtStateLog)))\n newStateLogEntry.position = posVelEvtStateLog(end).position;\n newStateLogEntry.velocity = posVelEvtStateLog(end).velocity;\n newStateLogEntry.centralBody = posVelEvtStateLog(end).centralBody;\n end\n end\n else\n cartElemSet = obj.orbitModel.convertToCartesianElementSet();\n \n newStateLogEntry.setCartesianElementSet(cartElemSet);\n end\n \n\n for(i=1:length(obj.stageStates)) %#ok<*UNRCH>\n obj.stageStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n for(i=1:length(obj.engineStates))\n obj.engineStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n for(i=1:length(obj.tankStates))\n obj.tankStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n for(i=1:length(obj.epsSinkStates))\n obj.epsSinkStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n for(i=1:length(obj.epsSrcStates))\n obj.epsSrcStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n for(i=1:length(obj.epsStorageStates))\n obj.epsStorageStates(i).updateStateLogEntry(newStateLogEntry, obj.stateLog)\n end\n\n\n %Comment out this block once done\n% if(obj.inheritStageStates)\n% if(obj.inheritStageStatesFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n% not(isempty(obj.inheritStageStatesFromEvent)) && ...\n% not(isempty(obj.inheritStageStatesFromEvent.getEventNum())) && ...\n% obj.inheritStageStatesFromEvent.getEventNum() > 0)\n% \n% \n% stageStateEvtState = obj.stateLog.getLastStateLogForEvent(obj.inheritStageStatesFromEvent);\n% stageStateEvtState = stageStateEvtState(end);\n% if(not(isempty(stageStateEvtState)))\n% lvState = stageStateEvtState.lvState.deepCopy();\n% newStateLogEntry.lvState = lvState;\n% \n% for(i=1:length(stageStateEvtState.stageStates)) %#ok\n% newStateLogEntry.stageStates(i) = stageStateEvtState.stageStates(i).deepCopy(true, lvState);\n% end\n% end\n% end\n% \n% else\n% %do nothing, there is no behavior for this yet\n% warning('SetKinematicStateAction.inheritStageStates must be set to true, no behavior yet defined when this is set to false.');\n% end\n \n %Misc states\n if(obj.inheritStateElems)\n if(obj.inheritStateElemsFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n not(isempty(obj.inheritStateElemsFromEvent)) && ...\n not(isempty(obj.inheritStateElemsFromEvent.getEventNum())) && ...\n obj.inheritStateElemsFromEvent.getEventNum() > 0)\n \n stateElemsEvtState = obj.stateLog.getLastStateLogForEvent(obj.inheritStateElemsFromEvent);\n stateElemsEvtState = stateElemsEvtState(end);\n \n if(not(isempty(stateElemsEvtState)))\n newStateLogEntry.aero = stateElemsEvtState.aero.deepCopy();\n newStateLogEntry.thirdBodyGravity = stateElemsEvtState.thirdBodyGravity.copy();\n newStateLogEntry.stopwatchStates = stateElemsEvtState.stopwatchStates.copy();\n newStateLogEntry.extremaStates = stateElemsEvtState.extremaStates.copy();\n newStateLogEntry.steeringModel = stateElemsEvtState.steeringModel; %NEED TO WARN USE TO REINITIALIZE THROTTLE AND STEERING MODELS!\n newStateLogEntry.throttleModel = stateElemsEvtState.throttleModel;\n end\n end\n else\n %do nothing, there is no behavior for this yet\n warning('SetKinematicStateAction.inheritStateElems must be set to true, no behavior yet defined when this is set to false.');\n end\n end\n \n function initAction(obj, initialStateLogEntry)\n %nothing\n end\n \n function name = getName(obj)\n name = 'Set Kinematic State';\n end\n \n function tf = usesStage(obj, stage)\n tf = false;\n end\n \n function tf = usesEngine(obj, engine)\n tf = false;\n end\n \n function tf = usesTank(obj, tank)\n tf = false;\n end\n \n function tf = usesEngineToTankConn(obj, engineToTank)\n tf = false;\n end\n \n function tf = usesStopwatch(obj, stopwatch)\n tf = false;\n end\n \n function tf = usesExtremum(obj, extremum)\n tf = false;\n end\n \n function tf = usesTankToTankConn(obj, tankToTank)\n tf = false;\n end\n \n function tf = usesEvent(obj, event)\n tf = false;\n \n tankEvtsTf = logical([]);\n for(i=1:length(obj.tankStates))\n tankState = obj.tankStates(i);\n if(tankState.inheritTankStateFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n not(isempty(tankState.inheritTankStateFromEvent)) && tankState.inheritTankStateFromEvent == event)\n tankEvtsTf(end+1) = tankState.inheritTankStateFromEvent == event; %#ok\n end\n end\n\n epsSrcEvtsTf = logical([]);\n for(i=1:length(obj.epsStorageStates))\n storageState = obj.epsStorageStates(i);\n \n if(storageState.inheritStorageStateFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...\n not(isempty(storageState.inheritStorageStateFromEvent)) && storageState.inheritStorageStateFromEvent == event)\n epsSrcEvtsTf(end+1) = storageState.inheritStorageStateFromEvent == event; %#ok\n end\n end\n \n if((obj.inheritTime && obj.inheritTimeFrom == InheritStateEnum.InheritFromSpecifiedEvent && not(isempty(obj.inheritTimeFromEvent)) && obj.inheritTimeFromEvent == event) || ...\n (obj.inheritPosVel && obj.inheritPosVelFrom == InheritStateEnum.InheritFromSpecifiedEvent && not(isempty(obj.inheritPosVelFromEvent)) && obj.inheritPosVelFromEvent == event) || ...\n (obj.inheritStateElems && obj.inheritStateElemsFrom == InheritStateEnum.InheritFromSpecifiedEvent && not(isempty(obj.inheritStateElemsFromEvent)) && obj.inheritStateElemsFromEvent == event) || ...\n any(tankEvtsTf) || any(epsSrcEvtsTf))\n tf = true;\n end\n end\n \n function [tf, vars] = hasActiveOptimVar(obj)\n tf = false;\n vars = AbstractOptimizationVariable.empty(0,1);\n \n if(not(isempty(obj.optVar)))\n tf = any(obj.optVar.getUseTfForVariable());\n vars(end+1) = obj.optVar;\n end\n end\n \n function generateLvComponentElements(obj)\n lvdData = obj.event.lvdData;\n \n if(isempty(obj.stageStates))\n stages = lvdData.launchVehicle.stages;\n for(j=1:length(stages)) \n stageState = SetKinematicStateStageState(stages(j));\n stageState.inheritStageState = obj.inheritStageStates;\n stageState.inheritStageStateFrom = obj.inheritStageStatesFrom;\n stageState.inheritStageStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.stageStates(j) = stageState;\n end\n end\n addlistener(lvdData.launchVehicle, 'StageAdded', @(src, evt) stageAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'StageDeleted', @(src, evt) stageDeletedClbk(obj, src, evt));\n \n \n if(isempty(obj.engineStates))\n [~, engines] = lvdData.launchVehicle.getEnginesListBoxStr();\n for(j=1:length(engines))\n engineState = SetKinematicStateEngineState(engines(j));\n engineState.inheritEngineState = obj.inheritStageStates;\n engineState.inheritEngineStateFrom = obj.inheritStageStatesFrom;\n engineState.inheritEngineStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.engineStates(j) = engineState;\n end\n end\n addlistener(lvdData.launchVehicle, 'EngineAdded', @(src, evt) engineAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'EngineDeleted', @(src, evt) engineDeletedClbk(obj, src, evt));\n\n if(isempty(obj.tankStates))\n [~, storages] = lvdData.launchVehicle.getTanksListBoxStr();\n for(j=1:length(storages))\n tankState = SetKinematicStateTankState(storages(j));\n tankState.inheritTankState = obj.inheritStageStates;\n tankState.inheritTankStateFrom = obj.inheritStageStatesFrom;\n tankState.inheritTankStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.tankStates(j) = tankState;\n end\n end\n addlistener(lvdData.launchVehicle, 'TankAdded', @(src, evt) tankAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'TankDeleted', @(src, evt) tankDeletedClbk(obj, src, evt));\n\n if(isempty(obj.epsSinkStates))\n [~, sinks] = lvdData.launchVehicle.getPowerSinksListBoxStr();\n for(j=1:length(sinks))\n sinkState = SetKinematicStateEPSinkState(sinks(j));\n sinkState.inheritSinkState = obj.inheritStageStates;\n sinkState.inheritSinkStateFrom = obj.inheritStageStatesFrom;\n sinkState.inheritSinkStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.epsSinkStates(j) = sinkState;\n end\n end\n addlistener(lvdData.launchVehicle, 'EpsSinkAdded', @(src, evt) epsSinkAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'EpsSinkDeleted', @(src, evt) epsSinkDeletedClbk(obj, src, evt));\n\n if(isempty(obj.epsSrcStates))\n [~, srcs] = lvdData.launchVehicle.getPowerSrcsListBoxStr();\n for(j=1:length(srcs))\n srcState = SetKinematicStateEPSrcState(srcs(j));\n srcState.inheritSrcState = obj.inheritStageStates;\n srcState.inheritSrcStateFrom = obj.inheritStageStatesFrom;\n srcState.inheritSrcStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.epsSrcStates(j) = srcState; \n end\n end\n addlistener(lvdData.launchVehicle, 'EpsSrcAdded', @(src, evt) epsSrcAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'EpsSrcDeleted', @(src, evt) epsSrcDeletedClbk(obj, src, evt));\n \n if(isempty(obj.epsStorageStates))\n [~, storages] = lvdData.launchVehicle.getPowerStoragesListBoxStr();\n for(j=1:length(storages))\n storageState = SetKinematicStateEPStorageState(storages(j));\n storageState.inheritStorageState = obj.inheritStageStates;\n storageState.inheritStorageStateFrom = obj.inheritStageStatesFrom;\n storageState.inheritStorageStateFromEvent = obj.inheritStageStatesFromEvent;\n\n obj.epsStorageStates(j) = storageState;\n end\n end\n addlistener(lvdData.launchVehicle, 'EpsStorageAdded', @(src, evt) epsStorageAddedClbk(obj, src, evt));\n addlistener(lvdData.launchVehicle, 'EpsStorageDeleted', @(src, evt) epsStorageDeletedClbk(obj, src, evt));\n \n end\n end\n\n methods(Access=private)\n function stageAddedClbk(obj, src, evt)\n stage = evt.stage;\n \n stageState = SetKinematicStateStageState(stage);\n obj.stageStates(end+1) = stageState;\n end\n \n function stageDeletedClbk(obj, src, evt)\n stage = evt.stage;\n\n obj.stageStates([obj.stageStates.stage] == stage) = [];\n end\n\n function engineAddedClbk(obj, src, evt)\n engine = evt.engine;\n \n engineState = SetKinematicStateEngineState(engine);\n obj.engineStates(end+1) = engineState; \n end\n \n function engineDeletedClbk(obj, src, evt)\n engine = evt.engine;\n \n obj.engineStates([obj.engineStates.engine] == engine) = [];\n end\n \n function tankAddedClbk(obj, src, evt)\n tank = evt.tank;\n \n tankState = SetKinematicStateTankState(tank);\n obj.tankStates(end+1) = tankState; \n \n SetKinematicStateActionVariable(tankState); %doesn't need to get stored somewhere, it'll get stored on the tankState\n end\n \n function tankDeletedClbk(obj, src, evt)\n tank = evt.tank;\n \n obj.tankStates([obj.tankStates.tank] == tank) = [];\n end\n \n function epsSinkAddedClbk(obj, src, evt)\n sink = evt.sink;\n \n sinkState = SetKinematicStateEPSinkState(sink);\n obj.epsSinkStates(end+1) = sinkState; \n end\n \n function epsSinkDeletedClbk(obj, src, evt)\n sink = evt.sink;\n \n obj.epsSinkStates([obj.epsSinkStates.sink] == sink) = [];\n end\n \n function epsSrcAddedClbk(obj, src, evt)\n src = evt.src;\n \n srcState = SetKinematicStateEPSrcState(src);\n obj.epsSrcStates(end+1) = srcState; \n end\n \n function epsSrcDeletedClbk(obj, ~, evt)\n src = evt.src;\n \n obj.epsSrcStates([obj.epsSrcStates.src] == src) = [];\n end\n \n function epsStorageAddedClbk(obj, src, evt)\n storage = evt.storage;\n \n storageState = SetKinematicStateEPStorageState(storage);\n obj.epsStorageStates(end+1) = storageState; \n end\n \n function epsStorageDeletedClbk(obj, src, evt)\n storage = evt.storage;\n \n obj.epsStorageStates([obj.epsStorageStates.storage] == storage) = [];\n end\n end\n \n methods(Static)\n function addActionTf = openEditActionUI(action, lv)\n action.generateLvComponentElements();\n \n output = AppDesignerGUIOutput({false});\n lvd_EditActionSetKinematicStateGUI_App(action, lv.lvdData, output);\n \n addActionTf = output.output{1};\n end\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/Events/actions/@SetKinematicStateAction/SetKinematicStateAction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1855199630625036}} {"text": "function onl_write_background(varargin)\n% Periodically process data using a predictive model, and write results to some external device.\n% onl_write_background(ResultWriter,StreamNames,Model,OutputFormat,UpdateFrequency,StartDelay,PredictorName,PredictAt,Verbose,EmptyResultValue)\n% \n% This is a convenience function which simplifies the definition of components which load and then\n% periodically query a predictive model, in real time, and forward the results to some external\n% device. The function is internally implemented using a timer that periodically triggers the\n% computation of updated estimates, and their transfer to the data sink.\n%\n% In:\n% ResultWriter : Callback function that receives one or more BCI estimates and writes them to some\n% external device. The format passed to the ResultWriter is according to OutputFormat.\n%\n% StreamNames : optional names of stream data structures in the MATLAB base workspace to consider as\n% possible data sources (previously created with onl_newstream); any stream that \n% contains channels that are needed by the predictor will be linked to it (assuming \n% that the choice of stream to use is not ambiguous). \n%\n% The identification of needed channels is primarily done on the basis of the channel\n% labels -- if a stream has channels with labels that are required by a filter pipeline,\n% it will be used as a source for this pipeline. The framework attempts to gracefully\n% handle cases where a stream only provides a subset of the channels that were in the \n% training set and the model only effectively operates on this subset via flt_selchans.\n%\n% Model : A model data structure (as obtained from bci_train) according to which predictions shall be \n% made; typically this is a model struct, but for convenience it can be a file name, \n% variable name in the base workspace, or a cell array of {file name, variable name} to \n% refer to a variable inside a .mat file. The model is not modified by this function. \n% (default: 'lastmodel')\n%\n% OutputFormat : Output data format, see onl_predict (default: 'distribution')\n%\n% UpdateFrequency : Frequency at which the device should be queried, in Hz (default: 10)\n%\n% StartDelay : Delay before real-time processing begins; grace period until user resources are \n% created (default: 1)\n%\n% PredictorName : Name of a predictor data structure that shall be created in the MATLAB base \n% workspace to hold the predictor's state. If a variable of this name already exists\n% it will be overridden. (default: 'lastpredictor')\n%\n% PredictAt : Predict at markers. If nonempty, this is a cell array of online target markers \n% relative to which predictions shall be made. If empty, predictions are always made \n% on the most recently added sample. (default: {})\n%\n% Verbose : Verbose output. If false, the console output of the online pipeline will be suppressed.\n% (default: false)\n%\n% EmptyResultValue : Empty-result value. This value is returned for predictions that yielded no \n% result (e.g., due to an error or because not enough data was available).\n% (default: NaN)\n%\n% Examples:\n% % after a predictive model has been learned using bci_train, and a data stream supplying raw\n% % data has been established, load the model into the online system and periodically send its \n% % outputs to a target destination\n% onl_write_background(@send_outputs_to_destination,'mystream')\n%\n% % as before, but also specify a custom output format and a higher update frequency\n% onl_write_background(@send_outputs_to_destination,'mystream','lastmodel','expectation',25)\n%\n% % as before, but pass all arguments by their short names\n% onl_write_background('ResultWriter',@send_outputs_to_destination,'MatlabStream','mystream','Model','lastmodel','OutputFormat','expectation','UpdateFrequency',25)\n%\n% See also:\n% onl_predict\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2011-01-18\n\n% read options\narg_define(varargin, ...\n arg_norep({'result_writer','ResultWriter'},[],[],'Result writing callback. Callback function that receives one or more BCI estimates and writes them to some external device. The format passed to the ResultWriter is according to OutputFormat.'), ...\n arg({'in_stream','StreamName','MatlabStream'}, 'laststream',[],'Input stream name. This is the name of the stream data structure in the MATLAB base workspace that shall be read from. Can also be a cell array of stream names, if multiple, or empty if non-ambiguous.','typecheck',false,'shapecheck',false), ...\n arg({'pred_model','Model'}, 'lastmodel', [], 'Predictive model. A model data structure (as obtained from bci_train) according to which predictions shall be made; typically this is a model struct, but for convenience it can be a file name, variable name in the base workspace, or a cell array of {file name, variable name} to refer to a variable inside a .mat file. The model is not modified by this function.','type','expression'), ...\n arg({'out_form','OutputFormat'},'distribution',{'expectation','distribution','mode','raw'},'Format of the produced output values. Can be the expected value (posterior mean) of the target variable, or the distribution over possible target values (probabilities for each outcome, or parametric distribution), or the mode (most likely value) of the target variable.'), ...\n arg({'update_freq','UpdateFrequency'},10,[0 Inf],'Update frequency. This is the rate at which the outputs should be calculated.'), ...\n arg({'start_delay','StartDelay'}, 1, [0 Inf],'Start-up delay. Delay before real-time processing begins; grace period to initialize everything.'), ...\n arg({'pred_name','PredictorName'}, 'lastpredictor',[],'Name of new predictor. Name of a predictor data structure that shall be created in the MATLAB base workspace to hold the predictor''s state. If a variable of this name already exists it will be overridden.'), ...\n arg({'predict_at','PredictAt'}, {},[],'Predict at markers. If nonempty, this is a cell array of online target markers relative to which predictions shall be made. If empty, predictions are always made on the most recently added sample.','type','expression'), ...\n arg({'verbose','Verbose'}, false,[],'Verbose output. If false, the console output of the online pipeline will be suppressed.'), ...\n arg({'empty_result_value','EmptyResultValue'},NaN,[],'Empty-result value. This value is returned for predictions that yielded no result (e.g., due to an error or because not enough data was available).','type','expression'));\n\n% input validation\nif ischar(result_writer) && ~isempty(result_writer) %#ok\n if result_writer(1) ~= '@' && ~exist(result_writer,'file')\n error('The given ResultWriter argument (%s) is not a valid function name',result_writer); end\n result_writer = str2func(result_writer); \nend\nif ~isa(result_writer,'function_handle')\n error('The given ResultWriter argument must be a function handle (or function name), but was: %s',hlp_tostring(result_writer,10000)); end\nif ~iscell(in_stream) %#ok\n in_stream = {in_stream}; end\nfor c=1:length(in_stream)\n stream_name = in_stream{c};\n if ~isvarname(stream_name)\n error('The given StreamName argument must be a valid variable name, but was: %s',hlp_tostring(stream_name,10000)); end\n try\n stream = evalin('base',stream_name);\n catch e\n error('Failed to look up stream named %s in MATLAB base workspace with error: %s',stream_name,e.message);\n end\n if ~isstruct(stream)\n error('The given data structure named %s in the MATLAB base workspace was expected to be a stream data structure, but was not a struct (wrong name?): %s',stream_name,hlp_tostring(stream,10000)); end\n if ~isfield(stream,'streamid')\n if isfield(stream,{'data','srate'})\n error('The given stream data structure named %s appears to be an EEGLAB data set struct but is not a stream (use onl_newstream to create a valid stream)',stream_name);\n else\n error('The given data structure named %s is not a valid stream (use onl_newstream to create a valid stream)',stream_name);\n end\n end\n streamids{c} = stream.streamid; %#ok\nend\n\n% create new predictor\npredid = onl_newpredictor(pred_name,pred_model,in_stream,predict_at);\n\n% create & start timer (which periodically writes to the stream)\nstart(timer('ExecutionMode','fixedRate', 'Name',[pred_name '_timer'], 'Period',1/update_freq, ...\n 'StartDelay',start_delay, 'TimerFcn',@(timer_handle,varargin) write_data(pred_name,in_stream,out_form,result_writer,predid,streamids,timer_handle,verbose,empty_result_value)));\n\n% background data writer\nfunction write_data(predictor,stream_names,fmt,result_writer,pred_id,stream_ids,timer_handle,verbose,empty_result_value)\ntry\n % check if the stream and the predictor are still there\n for c=1:length(stream_names)\n s = evalin('base',stream_names{c});\n if s.streamid ~= stream_ids{c}\n error('Note: the stream named %s was recreated.',stream_names{c}); end\n end\n p = evalin('base',predictor);\n if p.predictorid ~= pred_id\n error('Note: the predictor named %s was recreated.',predictor); end\n % make a prediction\n y = onl_predict(predictor,fmt,~verbose,empty_result_value);\n % and write it out\n try\n result_writer(y);\n catch e\n disp('Error in result-writing function:');\n hlp_handleerror(e);\n end\ncatch e\n if ~strcmp(e.identifier,'MATLAB:UndefinedFunction')\n hlp_handleerror(e); end \n % stream or predictor have changed (e.g., replaced/deleted) --> stop timer\n stop(timer_handle);\n delete(timer_handle);\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/online_analysis/onl_write_background.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1855199630625036}} {"text": "function f = pskernelObjective(lntheta, models, prior)\n\n% PSKERNELOBJECTIVE Likelihood approximation for point set IVM.\n\n% KERN\n\n% KERN\n\n% PSIVM\n\nif nargin < 3\n prior = 1;\nend\nf = 0;\nnumTasks = length(models.task);\nfor taskNo = 1:numTasks\n models.task(taskNo).lntheta = models.lntheta;\n f = f + kernelObjective(lntheta, models.task(taskNo), prior);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/kern/pskernelObjective.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.18543260439660952}} {"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 hash = wsddnVOChash_init(strs)\n% From the PASCAL VOC 2011 devkit\n\nhsize=4999;\nhash.key=cell(hsize,1);\nhash.val=cell(hsize,1);\n\nfor i=1:numel(strs)\n s=strs{i};\n h=mod(str2double(s([4 6:end])),hsize)+1;\n j=numel(hash.key{h})+1;\n hash.key{h}{j}=strs{i};\n hash.val{h}(j)=i;\nend\n\n", "meta": {"author": "hbilen", "repo": "WSDDN", "sha": "bfdaa3f9ffed45e52a11a1342fd7476e08dfac39", "save_path": "github-repos/MATLAB/hbilen-WSDDN", "path": "github-repos/MATLAB/hbilen-WSDDN/WSDDN-bfdaa3f9ffed45e52a11a1342fd7476e08dfac39/pascal/wsddnVOChash_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.18520355668025226}} {"text": "function [net, info] = bcnn_train_simplenn(net, imdb, getBatch_train, getBatch_val, varargin)\n\n% BNN_TRAIN_SW training a symmetric BCNN \n% BCNN_TRAIN() is an example learner implementing stochastic gradient\n% descent with momentum to train a symmetric BCNN for image classification.\n% The net should built in simplenn structure\n\n% INPUT\n% net: a network with a bcnn layer\n% imdb: imdb structure of a dataset\n% getBatch_train: function to read a batch of training images\n% getBatch_val: function to read a batch of validation images\n\n% OUTPUT\n% net: bcnn network after fine-tuning\n% info: log of training and validation\n\n% A symmetric BCNN consists of multiple layers of convolutions, pooling, and\n% nonlinear activation. A bilinearpool layer is built on top followed by square-root\n% and L2 normalization and a sofmaxloss layer.\n\n% Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji.\n% All rights reserved.\n%\n% This file is part of the BCNN and is made available under\n% the terms of the BSD license (see the COPYING file).\n\n% This function is modified from CNN_TRAIN of MatConvNet\n\n% basic setting\nopts.train = [] ;\nopts.val = [] ;\nopts.numEpochs = 300 ;\nopts.batchSize = 256 ;\nopts.numSubBatches = 1 ;\nopts.gpus = [] ; % which GPU devices to use (none, one, or more)\nopts.learningRate = 0.001 ;\nopts.continue = false ;\nopts.expDir = fullfile('data','exp') ;\nopts.conserveMemory = false ;\nopts.backPropDepth = +inf ;\nopts.sync = false ;\nopts.prefetch = false ;\nopts.cudnn = true ;\nopts.weightDecay = 0.0005 ;\nopts.momentum = 0.9 ;\nopts.errorFunction = 'multiclass' ;\nopts.errorLabels = {} ;\nopts.plotDiagnostics = false ;\nopts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;\n\nopts = vl_argparse(opts, varargin) ;\n\nif ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\nif isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\nif isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\nif isnan(opts.train), opts.train = [] ; end\n\n% -------------------------------------------------------------------------\n% Network initialization\n% -------------------------------------------------------------------------\n% set hyperparameters\nevaluateMode = isempty(opts.train) ;\n\nif ~evaluateMode\n for i=1:numel(net.layers)\n if isfield(net.layers{i}, 'weights')\n J = numel(net.layers{i}.weights) ;\n for j=1:J\n net.layers{i}.momentum{j} = zeros(size(net.layers{i}.weights{j}), 'single') ;\n end\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, J, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = ones(1, J, 'single') ;\n end\n end\n % Legacy code: will be removed\n if isfield(net.layers{i}, 'filters')\n net.layers{i}.momentum{1} = zeros(size(net.layers{i}.filters), 'single') ;\n net.layers{i}.momentum{2} = zeros(size(net.layers{i}.biases), 'single') ;\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, 2, 'single') ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = single([1 0]) ;\n end\n end\n end\nend\n\n% -------------------------------------------------------------------------\n% Move network to GPU or CPU\n% -------------------------------------------------------------------------\n\n\n% setup GPUs\nnumGpus = numel(opts.gpus) ;\nif numGpus > 1\n if isempty(gcp('nocreate')),\n parpool('local',numGpus) ;\n spmd, gpuDevice(opts.gpus(labindex)), end\n end\nelseif numGpus == 1\n gpuDevice(opts.gpus)\nend\nif exist(opts.memoryMapFile), delete(opts.memoryMapFile) ; end\n\n% setup error calculation function\nif isstr(opts.errorFunction)\n switch opts.errorFunction\n case 'none'\n opts.errorFunction = @error_none ;\n case 'multiclass'\n opts.errorFunction = @error_multiclass ;\n if isempty(opts.errorLabels), opts.errorLabels = {'top1e', 'top5e'} ; end\n case 'binary'\n opts.errorFunction = @error_binary ;\n if isempty(opts.errorLabels), opts.errorLabels = {'bine'} ; end\n otherwise\n error('Uknown error function ''%s''', opts.errorFunction) ;\n end\nend\n\n\n\n\nmodelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\nmodelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n\nstart = opts.continue * findLastCheckpoint(opts.expDir) ;\nif start >= 1\n fprintf('resuming by loading epoch %d\\n', start) ;\n load(modelPath(start), 'net', 'info') ;\nend\n\nfor epoch=start+1:opts.numEpochs\n\n % train one epoch and validate\n learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n train = opts.train(randperm(numel(opts.train))) ; % shuffle\n val = opts.val ;\n if numGpus <= 1\n [net,stats.train] = process_epoch(opts, getBatch_train, epoch, train, learningRate, imdb, net) ;\n [~,stats.val] = process_epoch(opts, getBatch_val, epoch, val, 0, imdb, net) ;\n else\n spmd(numGpus)\n [net_, stats_train_] = process_epoch(opts, getBatch_train, epoch, train, learningRate, imdb, net) ;\n [~, stats_val_] = process_epoch(opts, getBatch_val, epoch, val, 0, imdb, net_) ;\n end\n net = net_{1} ;\n stats.train = sum([stats_train_{:}],2) ;\n stats.val = sum([stats_val_{:}],2) ;\n end\n\n % save\n if evaluateMode, sets = {'val'} ; else sets = {'train'} ; end\n if ~evaluateMode && ~isempty(opts.val)\n sets{2} = 'val';\n end\n for f = sets\n f = char(f) ;\n n = numel(eval(f)) ;\n info.(f).speed(epoch) = n / stats.(f)(1) * max(1, numGpus) ;\n info.(f).objective(epoch) = stats.(f)(2) / n ;\n info.(f).error(:,epoch) = stats.(f)(3:end) / n ;\n end\n if ~evaluateMode, save(modelPath(epoch), 'net', 'info') ; end\n\n figure(1) ; clf ;\n hasError = isa(opts.errorFunction, 'function_handle') ;\n subplot(1,1+hasError,1) ;\n if ~evaluateMode\n semilogy(1:epoch, info.train.objective, '.-', 'linewidth', 2) ;\n hold on ;\n end\n if ~isempty(opts.val)\n semilogy(1:epoch, info.val.objective, '.--') ;\n xlabel('training epoch') ; ylabel('energy') ;\n end\n grid on ;\n h=legend(sets) ;\n set(h,'color','none');\n title('objective') ;\n if hasError\n subplot(1,2,2) ; leg = {} ;\n if ~evaluateMode\n plot(1:epoch, info.train.error', '.-', 'linewidth', 2) ;\n hold on ;\n leg = horzcat(leg, strcat('train ', opts.errorLabels)) ;\n end\n \n if ~isempty(opts.val)\n plot(1:epoch, info.val.error', '.--') ;\n leg = horzcat(leg, strcat('val ', opts.errorLabels)) ;\n end\n set(legend(leg{:}),'color','none') ;\n grid on ;\n xlabel('training epoch') ; ylabel('error') ;\n title('error') ;\n end\n drawnow ;\n print(1, modelFigPath, '-dpdf') ;\nend\n\n% -------------------------------------------------------------------------\nfunction err = error_multiclass(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\n\n% be resilient to badly formatted labels\nif numel(labels) == size(predictions, 4)\n labels = reshape(labels,1,1,1,[]) ;\nend\n\n% skip null labels\nmass = single(labels(:,:,1,:) > 0) ;\nif size(labels,3) == 2\n % if there is a second channel in labels, used it as weights\n mass = mass .* labels(:,:,2,:) ;\n labels(:,:,2,:) = [] ;\nend\n\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;\nerr(2,1) = sum(sum(sum(mass .* min(error(:,:,1:5,:),[],3)))) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_binaryclass(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\nerror = bsxfun(@times, predictions, labels) < 0 ;\nerr = sum(error(:)) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_none(opts, labels, res)\n% -------------------------------------------------------------------------\nerr = zeros(0,1) ;\n\n% -------------------------------------------------------------------------\nfunction [net_cpu,stats,prof] = process_epoch(opts, getBatch, epoch, subset, learningRate, imdb, net_cpu)\n% -------------------------------------------------------------------------\n\n% move CNN to GPU as needed\nnumGpus = numel(opts.gpus) ;\nif numGpus >= 1\n net = vl_simplenn_move(net_cpu, 'gpu') ;\nelse\n net = net_cpu ;\n net_cpu = [] ;\nend\n\n% validation mode if learning rate is zero\ntraining = learningRate > 0 ;if training\n mode = 'train' ;\n evalMode = 'normal' ;\nelse\n mode = 'val' ;\n evalMode = 'test' ;\nend\nif nargout > 2, mpiprofile on ; end\n\nnumGpus = numel(opts.gpus) ;\nif numGpus >= 1\n one = gpuArray(single(1)) ;\nelse\n one = single(1) ;\nend\nres = [] ;\nmmap = [] ;\nstats = [] ;\nstart = tic ;\n\nfor t=1:opts.batchSize:numel(subset)\n fprintf('%s: epoch %02d: batch %3d/%3d: ', mode, epoch, ...\n fix(t/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;\n batchSize = min(opts.batchSize, numel(subset) - t + 1) ;\n numDone = 0 ;\n error = [] ;\n for s=1:opts.numSubBatches\n % get this image batch and prefetch the next\n batchStart = t + (labindex-1) + (s-1) * numlabs ;\n batchEnd = min(t+opts.batchSize-1, numel(subset)) ;\n batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n [im, labels] = getBatch(imdb, batch) ;\n\n if opts.prefetch\n if s==opts.numSubBatches\n batchStart = t + (labindex-1) + opts.batchSize ;\n batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ;\n else\n batchStart = batchStart + numlabs ;\n end\n nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;\n getBatch(imdb, nextBatch) ;\n end\n\n if numGpus >= 1\n im = gpuArray(im{1}) ;\n end\n\n % evaluate CNN\n net.layers{end}.class = labels ;\n if training, dzdy = one; else, dzdy = [] ; end\n if s==1, res = []; end\n res = vl_bilinearnn(net, im, dzdy, res, ...\n 'accumulate', s ~= 1, ...\n 'mode', evalMode, ...\n 'conserveMemory', opts.conserveMemory, ...\n 'backPropDepth', opts.backPropDepth, ...\n 'sync', opts.sync, ...\n 'cudnn', opts.cudnn) ;\n \n\n % accumulate training errors\n error = sum([error, [...\n sum(double(gather(res(end).x))) ;\n reshape(opts.errorFunction(opts, labels, res),[],1) ; ]],2) ;\n numDone = numDone + numel(batch) ;\n end\n\n % gather and accumulate gradients across labs\n if training\n if numGpus <= 1\n [net,res] = accumulate_gradients(opts, learningRate, batchSize, net, res) ;\n else\n if isempty(mmap)\n mmap = map_gradients(opts.memoryMapFile, net, res, numGpus) ;\n end\n write_gradients(mmap, net, res) ;\n labBarrier() ;\n [net,res] = accumulate_gradients(opts, learningRate, batchSize, net, res, mmap) ;\n end\n end\n\n % print learning statistics\n\n time = toc(start) ;\n stats = sum([stats,[0 ; error]],2); % works even when stats=[]\n stats(1) = time ;\n n = (t + batchSize - 1) / max(1,numlabs) ;\n speed = n/time ;\n fprintf('%.1f Hz%s\\n', speed) ;\n\n fprintf(' obj:%.3g', stats(2)/n) ;\n for i=1:numel(opts.errorLabels)\n fprintf(' %s:%.3g', opts.errorLabels{i}, stats(i+2)/n) ;\n end\n fprintf(' [%d/%d]', numDone, batchSize);\n fprintf('\\n') ;\n\n % debug info\n if opts.plotDiagnostics && numGpus <= 1\n figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ;\n end\nend\n\nif nargout > 2\n prof = mpiprofile('info');\n mpiprofile off ;\nend\n\nif numGpus >= 1\n net_cpu = vl_simplenn_move(net, 'cpu') ;\nelse\n net_cpu = net ;\nend\n\n% -------------------------------------------------------------------------\nfunction [net,res] = accumulate_gradients(opts, lr, batchSize, net, res, mmap)\n% -------------------------------------------------------------------------\nif nargin >= 6\n numGpus = numel(mmap.Data) ;\nelse\n numGpus = 1 ;\nend\n\nfor l=numel(net.layers):-1:1\n for j=1:numel(res(l).dzdw)\n\n % accumualte from multiple labs (GPUs) if needed\n if numGpus > 1\n tag = sprintf('l%d_%d',l,j) ;\n tmp = zeros(size(mmap.Data(labindex).(tag)), 'single') ;\n for g = setdiff(1:numGpus, labindex)\n tmp = tmp + mmap.Data(g).(tag) ;\n end\n res(l).dzdw{j} = res(l).dzdw{j} + tmp ;\n end\n\n if j == 3 && strcmp(net.layers{l}.type, 'bnorm')\n % special case for learning bnorm moments\n thisLR = net.layers{l}.learningRate(j) ;\n net.layers{l}.weights{j} = ...\n (1-thisLR) * net.layers{l}.weights{j} + ...\n (thisLR/batchSize) * res(l).dzdw{j} ;\n else\n % standard gradient training\n thisDecay = opts.weightDecay * net.layers{l}.weightDecay(j) ;\n thisLR = lr * net.layers{l}.learningRate(j) ;\n net.layers{l}.momentum{j} = ...\n opts.momentum * net.layers{l}.momentum{j} ...\n - thisDecay * net.layers{l}.weights{j} ...\n - (1 / batchSize) * res(l).dzdw{j} ;\n net.layers{l}.weights{j} = net.layers{l}.weights{j} + ...\n thisLR * net.layers{l}.momentum{j} ;\n end\n end\nend\n\n% -------------------------------------------------------------------------\nfunction mmap = map_gradients(fname, net, res, numGpus)\n% -------------------------------------------------------------------------\nformat = {} ;\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n format(end+1,1:3) = {'single', size(res(i).dzdw{j}), sprintf('l%d_%d',i,j)} ;\n end\nend\nformat(end+1,1:3) = {'double', [3 1], 'errors'} ;\nif ~exist(fname) && (labindex == 1)\n f = fopen(fname,'wb') ;\n for g=1:numGpus\n for i=1:size(format,1)\n fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ;\n end\n end\n fclose(f) ;\nend\nlabBarrier() ;\nmmap = memmapfile(fname, 'Format', format, 'Repeat', numGpus, 'Writable', true) ;\n\n% -------------------------------------------------------------------------\nfunction write_gradients(mmap, net, res)\n% -------------------------------------------------------------------------\nfor i=1:numel(net.layers)\n for j=1:numel(res(i).dzdw)\n mmap.Data(labindex).(sprintf('l%d_%d',i,j)) = gather(res(i).dzdw{j}) ;\n end\nend\n\n% -------------------------------------------------------------------------\nfunction epoch = findLastCheckpoint(modelDir)\n% -------------------------------------------------------------------------\nlist = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;\ntokens = regexp({list.name}, 'net-epoch-([\\d]+).mat', 'tokens') ;\nepoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;\nepoch = max([epoch 0]) ;\n\n\n", "meta": {"author": "zwx8981", "repo": "DBCNN", "sha": "64f6e3e86f1a055b387fc170c93aa2dd994a5256", "save_path": "github-repos/MATLAB/zwx8981-DBCNN", "path": "github-repos/MATLAB/zwx8981-DBCNN/DBCNN-64f6e3e86f1a055b387fc170c93aa2dd994a5256/dbcnn/BCNN/bcnn_train_simplenn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.18520355510042683}} {"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) 10\n fprintf('\\tConvolution Integral Interval (sec) = %G\\n',obj.cicEndTime)\n end\n fprintf('\\t Number of Time Steps = %u \\n',obj.maxIt)\n end\n \n function obj = loadSimMechModel(obj,fName)\n % This method loads the simulink model and sets parameters\n % \n % Parameters\n % ------------\n % fname : string\n % the name of the SimMechanics ``.slx`` file\n %\n \n load_system(fName);\n [~,modelName,~] = fileparts(fName);\n set_param(modelName,'Solver',obj.solver,...\n 'StopTime',num2str(obj.endTime),...\n 'SimulationMode',obj.mode,...\n 'StartTime',num2str(obj.startTime),...\n 'FixedStep',num2str(obj.dt),...\n 'MaxStep',num2str(obj.dt),...\n 'AutoInsertRateTranBlk',obj.rateTransition,...\n 'ZeroCrossControl',obj.zeroCross,...\n 'SimCompilerOptimization','on',... \n 'ReturnWorkspaceOutputs','off',...\n 'SimMechanicsOpenEditorOnUpdate',obj.explorer);\n end\n\n function rhoDensitySetup(obj,rho,gravity)\n % Assigns density and gravity values\n %\n % Parameters\n % ------------\n % rho : float\n % density of the fluid medium (kg/m^3)\n % gravity : float\n % gravitational acceleration constant (m/s^2)\n %\n obj.rho = rho;\n obj.gravity = gravity;\n end\n\n function getGitCommit(obj)\n % Determines GitHub commit tag\n try\n ws_exe = which('wecSim');\n ws_dir = fileparts(ws_exe);\n git_ver_file = [ws_dir '/../.git/refs/heads/master'];\n obj.gitCommit = textread(git_ver_file,'%s');\n catch\n obj.gitCommit = 'No git commit tag available';\n end\n end\n end\nend", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/simulationClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18452087299137426}} {"text": "function mrAnatAverageAcpcAnalyze(fileNameList, outFileBaseName, alignLandmarks, newMmPerVox, weights, bb, clipVals, showFigs);\n%\n% mrAnatAverageAcpcAnalyze(fileNameList, outFileBaseName, [alignLandmarks=[]], ...\n% [newMmPerVox=[1 1 1]], [weights=ones(size(fileNameList))], ...\n% [bb], [clipVals], [showFigs=1])\n%\n% Reslices the first analyze file to ac-pc space at\n% 1x1x1mm resolution and then aligns all the rest of the analyze\n% files to that one and averages them all together.\n%\n% You can specify the ac-pc landmarks as a 3x3 matrix of the form:\n% [ acX, acY, acZ; pcX, pcY, pcZ; midSagX, midSagY, midSagZ ]\n% Where:\n% X is the (left -> right) location of a point,\n% Y is the (posterior -> anterior) location of a point, \n% Z is the (inferior -> superior) location of a point,\n% ac is the anterior commissure, pc is the posterior commissure, and midSag\n% is another poit in the mid-sagittal plane that is somewhat distant from\n% the ac-pc line. These 3 points define the rotation/translation into ac-pc\n% space. If the ac is properly set in the image header, then you can just\n% pass in the pc and midSag coords, specified as the offset from the ac.\n%\n% If these landmarks aren't provided, then the xform from the image header\n% is used. Note that if the image origin isn't close to the AC, then the\n% default bounding box ([-90,90; -126,90; -72,108]') won't be appropriate. \n%\n% weights specifies the weighting factor to be applied to each of the input\n% images (fileNameList). \n%\n% REQUIRES:\n% * Stanford anatomy tools (eg. /usr/local/matlab/toolbox/mri/Anatomy)\n% * spm2 tools (eg. /usr/local/matlab/toolbox/mri/spm2)\n%\n% HISTORY:\n% 2004.11.10 RFD (bob@white.stanford.edu) wrote it, based on averageAnalyze\nif ~exist('showFigs','var') | isempty(showFigs), showFigs = 1; end\n\nif (~exist('fileNameList','var') | isempty(fileNameList) | ...\n ~exist('outFileBaseName','var') | isempty(outFileBaseName))\n help(mfilename);\n return;\nend\nif (~exist('newMmPerVox','var') | isempty(newMmPerVox))\n newMmPerVox = [1 1 1];\nend\nif ~exist('saveIntermediate','var') | isempty(saveIntermediate)\n saveIntermediate = 0; \nend\n\nif (~exist('alignLandmarks','var')) alignLandmarks = []; end\n\nif ~exist('weights','var') | isempty(weights)\n weights = ones(size(fileNameList)); \nend\n\nif(~exist('bb','var') | isempty(bb))\n % Bounding box, in physical space (ie. mm from the origin, which should be\n % at or near the AC).\n bb = [-90,90; -126,90; -72,108]';\nend\n\nif (~exist('clipVals','var')) clipVals = []; end\n\n% from spm_bsplins: \n% d(1:3) - degree of B-spline (from 0 to 7) along different dimensions\n% d(4:6) - 1/0 to indicate wrapping along the dimensions\n% not sure what wrapping is, but '7' is the highest quality (but slowest).\nbSplineParams = [7 7 7 0 0 0];\n\n% We explicitly initialize the spm_defaults global here, and ensure that\n% the analyze_flip option is turned off. (Our analyze files are never\n% right-left reversed!)\nspm_defaults;\ndefaults.analyze.flip = 0;\n\nnumImages = length(fileNameList);\n\n% Load the first image (the reference)\n[refImg,mmPerVox,refImgHdr] = loadAnalyze(fileNameList{1});\n\nif(isempty(clipVals))\n clipVals = repmat([0.4 0.98],numImages,1);\nend\n \nrefImg = mrAnatHistogramClip(refImg, clipVals(1,1), clipVals(1,2));\n%[refImg, lc, uc] = mrAnatHistogramClipOptimal(refImg, 99);\n%fprintf('\\nClipped reference image at [%0.1f, %0.1f].\\n', lc, uc);\n\nif(isempty(alignLandmarks))\n % *** TO DO: allow user to select the landmarks!\n tal2ref = inv(refImgHdr.mat);\n \nelse\n if(size(alignLandmarks,1)==2)\n origin = inv(refImgHdr.mat)*[0 0 0 1]'-0.5;\n %origin(3) = size(refImg,3)-origin(3);\n %alignLandmarks(:,3) = -alignLandmarks(:,3);\n origin = origin(1:3)';\n imY = alignLandmarks(1,:); imY = imY./norm(imY);\n imZ = alignLandmarks(2,:); imZ = imZ./norm(imZ);\n else\n %% flip 3rd axis\n %alignLandmarks(:,3) = size(refImg,3)-alignLandmarks(:,3);\n % The first landmark should be the anterior commissure (AC)- our origin\n origin = alignLandmarks(1,:);\n % Define the current image axes by re-centering on the origin (the AC)\n imY = alignLandmarks(2,:)-origin; imY = imY./norm(imY);\n imZ = alignLandmarks(3,:)-origin; imZ = imZ./norm(imZ);\n end\n % x-axis (left-right) is the normal to [ac, pc, mid-sag] plane\n imX = cross(imZ,imY);\n % Make sure the vectors point right, superior, anterior\n if(imX(1)<0) imX = -imX; end\n if(imY(2)<0) imY = -imY; end\n if(imZ(3)<0) imZ = -imZ; end\n % Project the current image axes to the cannonical AC-PC axes. These\n % are defined as X=[1,0,0], Y=[0,1,0], Z=[0,0,1], with the origin\n % (0,0,0) at the AC. Note that the following are the projections\n x = [0 1 imY(3)]; x = x./norm(x);\n y = [1 0 imX(3)]; y = y./norm(y);\n %z = [0 imX(2) 1]; z = z./norm(z);\n z = [0 -imY(1) 1]; z = z./norm(z);\n % Define the 3 rotations using the projections. We have to set the sign\n % of the rotation, depending on which side of the plane we came from.\n rot(1) = sign(x(3))*acos(dot(x,[0 1 0])); % rot about x-axis (pitch)\n rot(2) = sign(y(3))*acos(dot(y,[1 0 0])); % rot about y-axis (roll)\n rot(3) = sign(z(2))*acos(dot(z,[0 0 1])); % rot about z-axis (yaw)\n \n scale = mmPerVox;\n \n % Affine build assume that we need to translate before rotating. But,\n % our rotations have been computed about the origin, so we'll pass a\n % zero translation and set it ourselves (below).\n ref2tal = affineBuild([0 0 0], rot, scale, [0 0 0]);\n tal2ref = inv(ref2tal);\n \n % Insert the translation.\n tal2ref(1:3,4) = [origin+newMmPerVox/2]';\nend\n\n% Resample it to 1x1x1\ndisp('Resampling reference image to ac-pc space, isotropic voxels...');\n[newRefImg,xform] = mrAnatResliceSpm(refImg, tal2ref, bb, newMmPerVox, bSplineParams, showFigs);\nnewOrigin = inv(xform)*[0 0 0 1]'; newOrigin = newOrigin(1:3)'-newMmPerVox/2;\n% Reclip in case the interpolation introduced out-of-range values\nnewRefImg(newRefImg<0) = 0; newRefImg(newRefImg>1) = 1;\nif(showFigs)\n o = round(newOrigin);\n figure; set(gcf,'Name',[fileNameList{1} ' (ref)']);\n subplot(1,3,1); imagesc(flipud(squeeze(newRefImg(:,:,o(3)))')); axis image; colormap gray;\n subplot(1,3,2); imagesc(flipud(squeeze(newRefImg(:,o(2),:))')); axis image; colormap gray;\n subplot(1,3,3); imagesc(flipud(squeeze(newRefImg(o(1),:,:))')); axis image; colormap gray;\n %imagesc(makeMontage(refImg,[20:4:size(newRefImg,3)-18]));axis image;colormap gray;\n %title([fileNameList{1} ' (reference image) aligned.']);\n pause(0.1);\nend\nVref.uint8 = uint8(round(newRefImg.*255));\nVref.mat = xform;\n\noutImg = newRefImg.*weights(1);\nnumSamples = zeros(size(outImg));\nnans = isnan(outImg);\nnumSamples(~nans) = weights(1);\noutImg(nans) = 0;\nfor(ii=2:numImages)\n if(saveIntermediate)\n % We do this first since the final result will be saved after this loop.\n fname = sprintf('%s_%d',outFileBaseName,ii-1);\n disp(['writing intermediate result ',fname,'...']);\n img = outImg;\n nz = numSamples>0;\n img(nz) = img(nz)./numSamples(nz);\n img = img-min(img(:));\n img = int16(img.*(32767/max(img(:))));\n saveAnalyze(img, fname, newMmPerVox, ['AVERAGE:' refImgHdr.descrip], newOrigin);\n end\n fprintf('Aligning %s to reference image...\\n',fileNameList{ii});\n [img,mmPerVox,hdr] = loadAnalyze(fileNameList{ii});\n img = mrAnatHistogramClip(img, clipVals(ii,1), clipVals(ii,2));\n %[img, lc, uc] = mrAnatHistogramClipOptimal(img, 99);\n %fprintf('Clipped image %d at [%0.1f, %0.1f].\\n', ii, lc, uc);\n Vin.uint8 = uint8(round(img.*255));\n Vin.mat = hdr.mat;\n %transRot = spm_coreg(Vin, Vref);\n %xform = spm_matrix(transRot(:)')*Vin.mat\\Vref.mat*inv(Vref.mat);\n transRot = spm_coreg(Vref, Vin);\n xform = inv(Vin.mat)*spm_matrix(transRot(:)'); \n fprintf('Resampling %s to reference image...\\n',fileNameList{ii});\n [img,xform] = mrAnatResliceSpm(img, xform, bb, newMmPerVox, bSplineParams, showFigs);\n % Reclip in case the interpolation introduced out-of-range values\n img(img<0) = 0; img(img>1) = 1;\n if(showFigs)\n o = round(newOrigin);\n \tfigure; set(gcf,'Name',[fileNameList{ii}]);\n subplot(1,3,1); imagesc(flipud(squeeze(img(:,:,o(3)))')); axis image; colormap gray;\n subplot(1,3,2); imagesc(flipud(squeeze(img(:,o(2),:))')); axis image; colormap gray;\n subplot(1,3,3); imagesc(flipud(squeeze(img(o(1),:,:))')); axis image; colormap gray;\n %figure; imagesc(makeMontage(img,[20:4:size(img,3)-18])); axis image; colormap gray;\n %title([fileNameList{ii} ' aligned.']);\n pause(0.1);\n end\n nans = isnan(img);\n numSamples(~nans) = numSamples(~nans)+weights(ii);\n img(nans) = 0;\n outImg = outImg+img.*weights(ii);\nend\n% Rescale based on the number of samples at each voxel\nnz = numSamples>0;\noutImg(nz) = outImg(nz)./numSamples(nz);\n\nif(showFigs)\n o = round(newOrigin);\n figure; set(gcf,'Name',['Average']);\n subplot(1,3,1); imagesc(flipud(squeeze(outImg(:,:,o(3)))')); axis image; colormap gray;\n subplot(1,3,2); imagesc(flipud(squeeze(outImg(:,o(2),:))')); axis image; colormap gray;\n subplot(1,3,3); imagesc(flipud(squeeze(outImg(o(1),:,:))')); axis image; colormap gray;\n figure; imagesc(makeMontage(outImg,[20:4:size(outImg,3)-18])); axis image; colormap gray;\n title(['Average aligned.']);\n pause(0.1);\nend\n\n% rescale to 15 bits (0-32767)\noutImg = outImg-min(outImg(:));\noutImg = int16(outImg.*(32767/max(outImg(:))));\n\ndisp(['writing ',outFileBaseName,'...']);\nhdr = saveAnalyze(outImg, outFileBaseName, newMmPerVox, ['AVERAGE:' refImgHdr.descrip], newOrigin);\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrAnatomy/VolumeUtilities/mrAnatAverageAcpcAnalyze.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.18447270384783312}} {"text": "function [net_conv, net_fc, opts] = mdnet_init(image, net)\n% MDNET_INIT\n% Initialize MDNet tracker.\n%\n% Hyeonseob Nam, 2015\n% \n\n%% set opts\n% use gpu\nopts.useGpu = true;\n\n% model def\nopts.net_file = net;\n\n% test policy\nopts.batchSize_test = 256; % <- reduce it in case of out of gpu memory\n\n% bounding box regression\nopts.bbreg = true;\nopts.bbreg_nSamples = 1000;\n\n% learning policy\nopts.batchSize = 128;\nopts.batch_pos = 32;\nopts.batch_neg = 96;\n\n% initial training policy\nopts.learningRate_init = 0.0001; % x10 for fc6\nopts.maxiter_init = 30;\n\nopts.nPos_init = 500;\nopts.nNeg_init = 5000;\nopts.posThr_init = 0.7;\nopts.negThr_init = 0.5;\n\n% update policy\nopts.learningRate_update = 0.0003; % x10 for fc6\nopts.maxiter_update = 10;\n\nopts.nPos_update = 50;\nopts.nNeg_update = 200;\nopts.posThr_update = 0.7;\nopts.negThr_update = 0.3;\n\nopts.update_interval = 10; % interval for long-term update\n\n% data gathering policy\nopts.nFrames_long = 100; % long-term period\nopts.nFrames_short = 20; % short-term period\n\n% cropping policy\nopts.input_size = 107;\nopts.crop_mode = 'wrap';\nopts.crop_padding = 16;\n\n% scaling policy\nopts.scale_factor = 1.05;\n\n% sampling policy\nopts.nSamples = 256;\nopts.trans_f = 0.6; % translation std: mean(width,height)*trans_f/2\nopts.scale_f = 1; % scaling std: scale_factor^(scale_f/2)\n\n% set image size\nopts.imgSize = size(image);\n\n%% load net\nnet = load(opts.net_file);\nif isfield(net,'net'), net = net.net; end\nnet_conv.layers = net.layers(1:10);\nnet_fc.layers = net.layers(11:end);\nclear net;\n\nfor i=1:numel(net_fc.layers)\n switch (net_fc.layers{i}.name)\n case {'fc4','fc5'}\n net_fc.layers{i}.filtersLearningRate = 1;\n net_fc.layers{i}.biasesLearningRate = 2;\n case {'fc6'}\n net_fc.layers{i}.filtersLearningRate = 10;\n net_fc.layers{i}.biasesLearningRate = 20;\n end\nend\n\nif opts.useGpu\n net_conv = vl_simplenn_move(net_conv, 'gpu') ;\n net_fc = vl_simplenn_move(net_fc, 'gpu') ;\nelse\n net_conv = vl_simplenn_move(net_conv, 'cpu') ;\n net_fc = vl_simplenn_move(net_fc, 'cpu') ;\nend\n\nend", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/trackers/MDNet/tracking/mdnet_init.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1843200689308583}} {"text": "% nbins = 8;\n% psize = 10;\n% npatches = 8;\n% optflowwinsig = 3;\n% optflowsig = 2;\n% optreliability = 1e-4;\n% patchsz = psize*npatches;\n\nparams = getParams;\nnpatches = params.npatches;\npsize = params.psize;\nnbins = params.nbins; \npatchsz = params.patchsz;\nscale = params.scale;\n\noptflowwinsig = params.optflowwinsig ;\noptflowsig = params.optflowsig ;\noptreliability = params.optreliability ;\n\nmaxflow = 5;\nfly_thres = 90;\nflow_thres = params.flow_thres;\n\nmakeVideo = false;\n\n% Antennal grooming for andy\nexpdir = '/home/mayank/Dropbox/ForMayankFromAlice/grooming_GMR_30B01_AE_01_CsChr_RigB_20150903T161828/';\nfly = 1;\nframes = 5961:5980; \n\n% expdir = '../mated10_20140714T131113';\n% % frames = 10900 +(1:200);\n% % fly = 1;\n% fly = 1;\n% % frames = 11043; % large middle leg movement\n% frames = 10925; % large middle leg movement\n\n% expdir = '/home/mayank/Work/FlySpaceTime/walkMovies/SS03500';\n% fly = 1;\n% frames = 10200 + (1:100);\n% frames = 735:780;\n% fly = 3;\n% frames = 1886:1888;\n% frames = 1477:1477;\n\n% fly = 2; % This one shows the failure of HS-brightness on rear leg.\n% frames = 5503;\n\n[~,expname] = fileparts(expdir);\nmoviefilestr = 'movie.ufmf';\nmoviefile = fullfile(expdir,moviefilestr);\ntrxfilestr = 'trx.mat';\ntrxfile = fullfile(expdir,trxfilestr);\n\n\n[readframe,nframes] = get_readframe_fcn(moviefile);\ntd = load(trxfile);\ntracks = td.trx;\ndx = []; dy = [];\ntheta = [];\nrdx = [];rdy = [];\nim1 = []; im2 = []; im3 = [];\nfor i = 1:numel(frames),\n curf = readframe(frames(i));\n nextf = readframe(frames(i)+1);\n \n trackndx = frames(i) - tracks(fly).firstframe + 1;\n locy = round(tracks(fly).y(trackndx));\n locx = round(tracks(fly).x(trackndx));\n curpatch = extractPatch(curf,...\n locy,locx,tracks(fly).theta(trackndx),patchsz);\n locy = round(tracks(fly).y(trackndx+1));\n locx = round(tracks(fly).x(trackndx+1));\n curpatch2 = extractPatch(nextf,...\n locy,locx,tracks(fly).theta(trackndx+1),patchsz);\n\n curpatch3 = extractPatch(nextf,...\n locy,locx,tracks(fly).theta(trackndx),patchsz);\n \n im1(:,:,i) = curpatch;\n im2(:,:,i) = curpatch2;\n im3(:,:,i) = curpatch3;\n dx(i) = round(tracks(fly).x(trackndx+1))-round(tracks(fly).x(trackndx));\n dy(i) = round(tracks(fly).y(trackndx+1))-round(tracks(fly).y(trackndx));\n rdx(i) = tracks(fly).x(trackndx+1)-tracks(fly).x(trackndx)-dx(i);\n rdy(i) = tracks(fly).y(trackndx+1)-tracks(fly).y(trackndx)-dy(i);\n dtheta(i) = tracks(fly).theta(trackndx+1)-tracks(fly).theta(trackndx);\n theta(i) = tracks(fly).theta(trackndx);\nend\n\n\n\n[nr,nc,~] = size(im1);\n%\n% figure out the histogram bins\ntmptheta = (0:179)*pi/180;\nres = nan(nbins,numel(tmptheta));\nm = single(ones(10,10));\no = single(zeros(10,10));\nfor i = 1:numel(tmptheta),\n% fprintf('i = %d, theta = %f\\n',i,tmptheta(i));\n o(:) = single(tmptheta(i));\n rescurr = gradientHist(m,o,1,nbins,1);\n res(:,i) = rescurr(1,1,:);\nend\n\nbincenters = nan(1,nbins);\nfor i = 1:nbins,\n bincenters(i) = tmptheta(argmax(res(i,:)));\nend\n\n% this seems to be what the centers correspond to\nbincenters = linspace(0,pi,nbins+1);\nbincenters = bincenters(1:nbins);\n\n% mayank divides by 2\nbincenters2 = bincenters*2;\ndt = mean(diff(bincenters2));\nbinedges2 = [bincenters2(1)-dt/2,(bincenters2(1:end-1)+bincenters2(2:end))/2,bincenters2(end)+dt/2];\n\n\n%% make a video\n\ntr = 191;\nhfig = 100;\nt0 = frames(1);\nt1 = frames(end);\ncolorpos = [1,0,0];\ncolorneg = [0,.3,1];\n\nmaxv2 = 0;\ncolors = hsv(nbins);\nsz = size(im1);\nbwimg = zeros(sz(1),sz(2));\nctr = [ceil( (sz(1)+1)/2),ceil( (sz(2)+1)/2)];\nbwimg(ctr(1),ctr(2))=1;\ndimg = bwdist(bwimg,'euclidean');\n[xx,yy]= meshgrid(1:sz(2),1:sz(1));\naimg = atan2(-(yy-ctr(1)),-(xx-ctr(2)));\n\nfor t = t0:20:t1,\n\n im1curr = im1(:,:,t-t0+1);\n im2curr = im2(:,:,t-t0+1);\n% [Vx,Vy,~] = optFlowLk(im1(:,:,i),im2(:,:,i),[],optflowwinsig,optflowsig,optreliability);\n% [Vx,Vy,] = optFlowHorn(im1curr,im2curr,optflowsig);\n uv = estimate_flow_interface(im1curr,im2curr,'hs-brightness',{'max_warping_iters',10});\n% uv = estimate_flow_interface(im1curr,im2curr,'ba-brightness');\n Vx = uv(:,:,1); Vy = uv(:,:,2);\n\n% Vx = Vx-dx(t-t0+1);\n% Vy = Vy-dy(t-t0+1);\n \n M = sqrt(Vx.^2 + Vy.^2);\n O = mod(atan2(Vy,Vx)/2,pi);\n O = min(O,pi-1e-6);\n H = gradientHist(single(M),single(O),psize,nbins,1);\n maxv2 = max(maxv2,max(H(:)));\nend\n\n%%\nif makeVideo\n vid = VideoWriter(sprintf('%s_Fly%d_From%d_To%d_HOF_%s.avi',expname,fly,t0,t1,datestr(now,'yyyymmdd')));\n open(vid);\nend\n\ndd_err = dimg/patchsz;\n% There is some flow towards the center in certain cases.\n% d_err is for that.\n\nfor t = t0:t1,\n\n im1curr = im1(:,:,t-t0+1);\n im2curr = im2(:,:,t-t0+1);\n\n imsz = size(im1curr);\n pairimg = zeros(2*imsz(1),3*imsz(2),3);\n ttimg = [];\n tt(:,:,1) = im2curr;\n tt(:,:,2) = im1curr;\n tt(:,:,3) = im2curr;\n pairimg(1:imsz(1),:,:) = repmat(tt,[1 3 1]);\n \n \n% [Vx,Vy,~] = optFlowLk(im1curr,im2curr,[],3);\n% [Vx,Vy,~] = optFlowLk(im1curr,im2curr,[],optflowwinsig,optflowsig,optreliability);\n% [Vx,Vy,] = optFlowHorn(im1curr,im2curr,optflowsig);\n uv = estimate_flow_interface(im1curr,im2curr,'hs-brightness',...\n {'max_warping_iters',2 });\n% uv = estimate_flow_interface(im1curr,im2curr,'ba-brightness',{'max_warping_iters',2 });\n% uv = estimate_flow_interface(im1curr,im2curr,'classic++');\n uvorig = uv;\n pairimg(imsz(1)+(1:imsz(1)),1:imsz(2),:) = flowToColor(uv,maxflow);\n \n cdx = dx(t-t0+1);\n cdy = dy(t-t0+1);\n curt = theta(t-t0+1);\n rotd = [cos(curt) sin(curt); -sin(curt) cos(curt)]*[cdx;cdy];\n cdx = -rotd(1); cdy = -rotd(2);\n\n ctheta = dtheta(t-t0+1);\n rotflowu = dimg.*(cos(aimg+ctheta)-cos(aimg));\n rotflowv = dimg.*(sin(aimg+ctheta)-sin(aimg));\n\n \n uv = uvorig;\n dd1 = sqrt( (uv(:,:,1)-cdx-rotflowu).^2 + (uv(:,:,2)-cdy-rotflowv).^2);\n for ndx = 1:2\n tt = uv(:,:,ndx);\n tt(dd1< (dd_err+flow_thres)) = 0;\n uv(:,:,ndx) = tt;\n end\n uvmotion = uv;\n pairimg(imsz(1)+(1:imsz(1)),imsz(2)+(1:imsz(2)),:) = flowToColor(uvmotion,maxflow);\n\n % Using bkg/fkg.\n% fly_bod = im1curr> std_plottf( times, freqs, data, 'key', 'val', ...)\n% Inputs:\n% times - [vector] latencies in ms of the data points.\n% freqs - [vector] frequencies in Hz of the data points.\n% data - [cell array] mean data for each subject group and/or data\n% condition. For example, to plot mean ERPs from a STUDY \n% for epochs of 800 frames in two conditions from three groups \n% of 12 subjects:\n%\n% >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1\n% [800x12] [800x12] [800x12] }; % 3 groups, cond 2\n% >> std_plottf(erp_ms,data);\n%\n% By default, parametric statistics are computed across subjects \n% in the three groups. (group,condition) ERP averages are plotted. \n% See below and >> help statcond \n% for more information about the statistical computations.\n%\n% Optional display parameters:\n% 'datatype' - ['ersp'|'itc'] data type {default: 'ersp'}\n% 'titles' - [cell array of string] titles for each of the subplots. \n% { default: none}\n%\n% Statistics options:\n% 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n% 'condstats' - ['on'|'off'] Compute (or not) statistics across groups.\n% {default: 'off'}\n\n% 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the \n% p-values themselves on a different figure. When possible, \n% significance regions are indicated below the data.\n% {default: NaN}\n% 'maskdata' - ['on'|'off'] when threshold is non-NaN and not both \n% condition and group statistics are computed, the user \n% has the option to mask the data for significance.\n% {default: 'off'}\n%\n% Other plotting options:\n% 'plotmode' - ['normal'|'condensed'] statistics plotting mode:\n% 'condensed' -> plot statistics under the curves \n% (when possible); 'normal' -> plot them in separate \n% axes {default: 'normal'}\n% 'freqscale' - ['log'|'linear'|'auto'] frequency plotting scale. This\n% will only change the ordinate not interpolate the data.\n% If you change this option blindly, your frequency scale\n% might be inaccurate {default: 'auto'}\n%\n% ITC/ERSP image plotting options:\n% 'tftopoopt' - [cell array] TFTOPO plotting options (ERSP and ITC)\n% 'caxis' - [min max] color axis (ERSP, ITC, scalp maps)\n%\n% Scalp map plotting options:\n% 'chanlocs' - [struct] channel location structure\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2006-\n%\n% See also: POP_ERSPPARAMS, POP_ERPPARAMS, POP_SPECPARAMS, STATCOND\n\n% Copyright (C) 2006 Arnaud Delorme\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [pgroup, pcond, pinter] = std_plottf(timevals, freqs, data, varargin)\n\npgroup = [];\npcond = [];\npinter = [];\nif nargin < 2\n help std_plottf;\n return;\nend\n\nopt = finputcheck( varargin, { 'titles' 'cell' [] cellfun(@num2str, cell(20,20), 'uniformoutput', false);\n 'caxis' 'real' [] [];\n 'ersplim' 'real' [] []; % same as above\n 'itclim' 'real' [] []; % same as above\n 'ylim' 'real' [] [];\n 'tftopoopt' 'cell' [] {};\n 'threshold' 'real' [] NaN;\n 'unitx' 'string' [] 'ms'; % just for titles\n 'unitcolor' 'string' {} 'dB';\n 'chanlocs' 'struct' [] struct('labels', {});\n 'freqscale' 'string' { 'log','linear','auto' } 'auto'; % note that paramsersp in std_erspplot contains the information as well\n 'effect' 'string' { 'main','marginal' } 'marginal';\n 'averagemode' 'string' { 'rms','ave' } 'rms';\n 'events' 'cell' [] {};\n 'groupstats' 'cell' [] {};\n 'condstats' 'cell' [] {};\n 'interstats' 'cell' [] {}; \n 'maskdata' 'string' { 'on','off' } 'off';\n 'plottopo' 'string' { 'on','off' } 'off';\n 'datatype' 'string' { 'ersp','itc' 'erpim' } 'ersp';\n 'plotmode' 'string' { 'normal','condensed' } 'normal' }, 'std_plottf');\nif ischar(opt), error(opt); end\nif all(all(cellfun('size', data, 3)==1)) opt.singlesubject = 'on'; end\n\n% remove empty entries\ndatapresent = ~cellfun(@isempty, data);\nfor c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; opt.titles(c,:) = []; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end\nfor g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; opt.titles(:,g) = []; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end\n\nif ~isempty(opt.groupstats) && ~isempty(opt.condstats) && strcmpi(opt.maskdata, 'on')\n disp('Cannot use ''maskdata'' option with both condition stat. and group stat. on');\n disp('Disabling statistics');\n opt.groupstats = {}; opt.condstats = {}; opt.maskdata = 'off'; \nend\nif ~isempty(opt.ersplim), opt.caxis = opt.ersplim; end\nif ~isempty(opt.itclim), opt.caxis = opt.itclim; end\nonecol = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' };\nmanycol = { 'b' 'r' 'g' 'k' 'c' 'y' };\n\nnc = size(data,1);\nng = size(data,2);\nif nc >= ng, opt.transpose = 'on';\nelse opt.transpose = 'off';\nend\n\n% test log frequencies\n% --------------------\nif length(freqs) > 2 && strcmpi(opt.freqscale, 'auto')\n midind = floor(length(freqs)/2);\n if abs(freqs(midind)/freqs(end) - 1/2) < 0.1, opt.freqscale = 'linear';\n else opt.freqscale = 'log';\n end\nend\n\n% condensed plot\n% --------------\nif strcmpi(opt.plotmode, 'condensed') \n meanplot = zeros(size(data{1},1), size(data{1},2));\n count = 0;\n for c = 1:nc\n for g = 1:ng\n if ~isempty(data{c,g})\n meanplot = meanplot + mean(data{c,g},3);\n count = count+1;\n end\n end\n end\n meanplot = meanplot/count;\n options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'on', ...\n 'cmode', 'separate', opt.tftopoopt{:} }; \n if strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end\n if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end\n tftopo( meanplot', timevals, freqs, 'title', opt.titles{1}, options{:}); \n currentHangle = gca;\n if ~isempty( opt.caxis )\n caxis( currentHangle, opt.caxis )\n end\n cbar_standard(opt.datatype, ng, opt.unitcolor); \n axes(currentHangle); \n return; \nend\n\n% plotting parameters\n% ------------------\nif ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end\nif nc > 1 && ~isempty(opt.condstats ), addr = 1; else addr = 0; end\n\n% compute significance mask\n% --------------------------\npinterplot = {};\nif strcmpi(opt.effect, 'marginal') || ng == 1 || nc == 1\n if ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) ) \n pcondplot = opt.condstats;\n pgroupplot = opt.groupstats;\n maxplot = 1;\n else\n for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end\n for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end\n maxplot = 3;\n end\nelseif strcmpi(opt.effect, 'main') && ~isempty(opt.interstats)\n if ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) ) \n pcondplot = { opt.interstats{2} };\n pgroupplot = { opt.interstats{1} };\n pinterplot = opt.interstats{3};\n maxplot = 1;\n else\n if ~isempty(opt.interstats{2}), pcondplot = { -log10(opt.interstats{2}) }; end\n if ~isempty(opt.interstats{1}), pgroupplot = { -log10(opt.interstats{1}) }; end\n if ~isempty(opt.interstats{3}), pinterplot = -log10(opt.interstats{3}); end\n maxplot = 3;\n end\nend\n\n% -------------------------------\n% masking for significance of not\n% -------------------------------\nstatmask = 0;\nif strcmpi(opt.maskdata, 'on') && ~isnan(opt.threshold) && ...\n (~isempty(opt.condstats) || ~isempty(opt.condstats))\n addc = 0; addr = 0; statmask = 1;\nend\n\n% -------------------------\n% plot time/frequency image\n% -------------------------\noptions = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'off', ...\n 'cmode', 'separate', opt.tftopoopt{:} };\nif strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end\nif strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end\n \n% adjust figure size\n% ------------------\nfig = figure('color', 'w');\npos = get(fig, 'position');\nset(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/2.5*(nc+addr), pos(4)/2*(ng+addc) ]);\npos = get(fig, 'position');\nif strcmpi(opt.transpose, 'off'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]);\nelse set(gcf, 'position', pos);\nend\n\n% options\n% -------\noptions = { 'limits' [NaN NaN NaN NaN opt.caxis] 'verbose' 'off' 'mode' opt.averagemode options{:} };\n\nfor c = 1:nc\n for g = 1:ng\n %hdl(c,g) = mysubplot(nc+addr, ng+addc, g + (c-1)*(ng+addc), opt.transpose);\n hdl(c,g) = mysubplot(nc+addr, ng+addc, c, g, opt.transpose);\n if ~isempty(data{c,g})\n if strcmpi(opt.plottopo, 'off')\n tmpplot = mean(data{c,g},3);\n else\n tmpplot = data{c,g};\n tmpplot = permute(tmpplot, [3 1 2 4]);\n end\n if ~isreal(tmpplot(1)), tmpplot = abs(tmpplot); end % comes second for processing single trials\n if statmask, \n if ~isempty(opt.condstats), tmpplot(find(pcondplot{g}(:) == 0)) = 0;\n else tmpplot(find(pgroupplot{c}(:) == 0)) = 0;\n end\n end\n if ~isempty(opt.events) && ~isempty(opt.events{c,g})\n tmpevents = mean(opt.events{c,g},2);\n else tmpevents = [];\n end\n if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1\n metaplottopo(tmpplot, 'chanlocs', opt.chanlocs, 'plotfunc', 'tftopo', 'squeeze', 'on', ...\n 'plotargs', { timevals, freqs, 'events', tmpevents, options{:} }, 'title', opt.titles{c,g});\n else\n tftopo( tmpplot, timevals, freqs, 'events', tmpevents, 'title', opt.titles{c,g}, options{:});\n end\n\n if c > 1\n ylabel(''); \n end\n end\n \n % statistics across groups\n % -------------------------\n if strcmpi(opt.effect, 'marginal') || (strcmpi(opt.effect, 'main') && c == 1)\n if g == ng && ng > 1 && ~isempty(opt.groupstats) && ~isinf(pgroupplot{c}(1)) && ~statmask\n if strcmpi(opt.effect, 'main') && nc>1, centerc = nc/2-0.5; else centerc = 0; end\n hdl(c,g+1) = mysubplot(nc+addr, ng+addc, c+centerc, ng + 1, opt.transpose);\n pgroupplot{c}(pgroupplot{c}<0) = 0;\n tmpOptions = { 'limits' [nan nan nan nan -maxplot maxplot] options{3:end} };\n if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1\n metaplottopo(permute(pgroupplot{c}, [3 1 2]), 'chanlocs', opt.chanlocs, 'plotfunc', 'tftopo', 'squeeze', 'on', ...\n 'plotargs', { timevals, freqs, tmpOptions{:} }, 'title', opt.titles{c,g+1});\n else\n tftopo( pgroupplot{c}, timevals, freqs, 'title', opt.titles{c,g+1}, tmpOptions{:});\n end\n end\n end\n end\nend\n\nfor g = 1:ng\n % statistics across conditions\n % -----------------------------\n if strcmpi(opt.effect, 'marginal') || (strcmpi(opt.effect, 'main') && g == 1)\n if ~isempty(opt.condstats) && ~isinf(pcondplot{g}(1)) && ~statmask && nc > 1\n if strcmpi(opt.effect, 'main') && ng>1, centerg = ng/2-0.5; else centerg = 0; end\n hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, nc+addr, g+centerg, opt.transpose);\n pcondplot{g}(pcondplot{g}<0) = 0;\n tmpOptions = { 'limits' [nan nan nan nan -maxplot maxplot] options{3:end} };\n if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1\n metaplottopo(permute(pcondplot{g}, [3 1 2]), 'chanlocs', opt.chanlocs, 'plotfunc', 'tftopo', 'squeeze', 'on', ...\n 'plotargs', { timevals, freqs, tmpOptions{:} }, 'title', opt.titles{nc+1,g});\n else\n tftopo( pcondplot{g}, timevals, freqs, 'title', opt.titles{nc+1,g}, options{:});\n end\n end\n end\nend\n\n% statistics across group and conditions\n% ---------------------------------------\nif ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1 && ~isempty(pinterplot)\n hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, nc+addr, ng+1, opt.transpose);\n pinterplot(pinterplot<0) = 0;\n tftopo( pinterplot, timevals, freqs, 'title', opt.titles{nc+1,ng+1}, options{:});\n caxis([-maxplot maxplot]);\n ylabel('');\nend \n\n% color bars\n% ----------\naxes(hdl(nc,ng)); \ncbar_standard(opt.datatype, ng, opt.unitcolor); \nif isnan(opt.threshold) && (nc ~= size(hdl,1) || ng ~= size(hdl,2))\n ind = find(ishandle(hdl(end:-1:1)));\n axes(hdl(end-ind(1)+1));\n cbar_signif(ng, maxplot);\nend\n\n% mysubplot2 (allow to transpose if necessary)\n% -------------------------------------------\nfunction hdl = mysubplot(nr,nc,r,c,subplottype)\n\n cmargin = 0.2/nc;\n rmargin = 0.2/nr;\n if strcmpi(subplottype, 'transpose') || strcmpi(subplottype, 'on'), hdl = subplot('position',[(r-1)/nr+rmargin (nc-c)/nc+cmargin 1/nr-2*rmargin 1/nc-2*cmargin]);\n elseif strcmpi(subplottype, 'normal') || strcmpi(subplottype, 'off'), hdl = subplot('position',[(c-1)/nc+cmargin (nr-r)/nr+rmargin 1/nc-2*cmargin 1/nr-2*rmargin]);\n elseif strcmpi(subplottype, 'noplot'), hdl = gca;\n else error('Unknown subplot type');\n end\n \n% % mysubplot (allow to transpose if necessary)\n% % -------------------------------------------\n% function hdl = mysubplot(nr,nc,ind,transp);\n% \n% r = ceil(ind/nc);\n% c = ind -(r-1)*nc;\n% if strcmpi(transp, 'on'), hdl = subplot(nc,nr,(c-1)*nr+r);\n% else hdl = subplot(nr,nc,(r-1)*nc+c);\n% end\n\n% colorbar for ERSP and scalp plot\n% --------------------------------\nfunction cbar_standard(datatype, ng, unitcolor);\n pos = get(gca, 'position');\n tmpc = caxis;\n fact = fastif(ng == 1, 40, 20);\n tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]); \n set(gca, 'unit', 'normalized');\n if strcmpi(datatype, 'itc')\n cbar(tmp, 0, tmpc, 10); ylim([0.5 1]);\n title('ITC','fontsize',10,'fontweight','normal','interpreter','none');\n elseif strcmpi(datatype, 'erpim')\n cbar(tmp, 0, tmpc, 5);\n else\n cbar(tmp, 0, tmpc, 5);\n title(unitcolor);\n end\n \n\n% colorbar for significance\n% -------------------------\nfunction cbar_signif(ng, maxplot);\n % Retrieving Defaults\n icadefs;\n \n pos = get(gca, 'position');\n tmpc = caxis;\n fact = fastif(ng == 1, 40, 20);\n tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]); \n map = colormap(DEFAULT_COLORMAP);\n n = size(map,1);\n cols = [ceil(n/2):n]';\n image([0 1],linspace(0,maxplot,length(cols)),[cols cols]);\n %cbar(tmp, 0, tmpc, 5);\n tick = linspace(0, maxplot, maxplot+1);\n set(gca, 'ytickmode', 'manual', 'YAxisLocation', 'right', 'xtick', [], ...\n 'ytick', tick, 'yticklabel', round(10.^-tick*1000)/1000);\n xlabel('');\n colormap(DEFAULT_COLORMAP);\n\n% rapid filtering for ERP\n% -----------------------\nfunction tmpdata2 = myfilt(tmpdata, lowpass, highpass, factor, filtertype)\n\n tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4));\n tmpdata2 = eegfiltfft(tmpdata2',lowpass, highpass, factor, filtertype)';\n tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_plottf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.1842074224975566}} {"text": "function events = in_events_xltek(sFile, EventFile)\n% IN_EVENTS_XLTEK: Open an XLTEK exported events file (.txt)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Olivier David, Francois Tadel, 2017\n\n% Open and read file\nfid = fopen(EventFile,'r');\n% Skip 6 header lines\ntmp = fgetl(fid);\ntmp = fgetl(fid);\ntmp = fgetl(fid);\ntmp = fgetl(fid);\ntmp = fgetl(fid);\ntmp = fgetl(fid);\n\n% Read start time\nstrLine = fgetl(fid);\n[tmp,tmp2] = strtok(strLine);\nstarttime = strtok(tmp2);\nstarttime = sum(sscanf(starttime, '%d:%d:%d') .* [3600;60;1]);\n\n% Loop to read all the events\nevtLabel = {};\nevtTime = [];\nwhile 1\n % Get line\n strLine = fgetl(fid);\n if (strLine == -1)\n break;\n end\n % Get label and timing\n [tmp1,tmp2] = strtok(strLine);\n [tmp1,tmp2] = strtok(tmp2);\n evtTime(end+1) = sum(sscanf(tmp1, '%d:%d:%d') .* [3600;60;1]) - starttime;\n evtLabel{end+1} = strtrim(tmp2);\nend\n% Close file\nfclose(fid);\n\n \n% ===== CONVERT TO BRAINSTORM FORMAT =====\n% List of events (keep original order)\n[uniqueEvt, I] = unique(evtLabel);\nuniqueEvt = evtLabel(sort(I));\n% Initialize returned structure\nevents = repmat(db_template('event'), [1, length(uniqueEvt)]);\n% Create events list\nfor iEvt = 1:length(uniqueEvt)\n % Find all the occurrences of event #iEvt\n iMrk = find(strcmpi(evtLabel, uniqueEvt{iEvt}));\n % Add event structure\n events(iEvt).label = uniqueEvt{iEvt};\n events(iEvt).times = unique(round(evtTime(iMrk) .* sFile.prop.sfreq)) ./ sFile.prop.sfreq;\n events(iEvt).epochs = ones(1, length(events(iEvt).times)); \n events(iEvt).reactTimes = [];\n events(iEvt).select = 1;\n events(iEvt).channels = [];\n events(iEvt).notes = [];\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_events_xltek.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.1840685762569042}} {"text": "% pop_timtopo() - call the timtopo() function for epoched EEG datasets. \n% Plots the epoch mean for each channel on a single axis,\n% plus scalp maps of the data at specified latencies.\n% Usage:\n% >> pop_timtopo( EEG, timerange, topotimes, title, 'key', 'val', ...);\n%\n% Inputs:\n% EEG - input dataset\n% timerange - [min max] epoch time range (in ms) to plot \n% topotimes - array of times to plot scalp maps {Default: NaN \n% = display scalp map at frame of max var()}\n%\n% Optional inputs:\n% title - optional plot title\n% 'key','val' - optional topoplot() arguments (see >> help topoplot)\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001\n%\n% See also: timtopo()\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% 01-25-02 reformated help & license -ad \n% 02-16-02 text interface editing -sm & ad \n% 03-15-02 add all topoplot options -ad\n% 03-18-02 added title -ad & sm\n\nfunction com = pop_timtopo( EEG, timerange, topotime, plottitle, varargin);\n\ncom = '';\nif nargin < 1\n\thelp pop_timtopo;\n\treturn;\nend;\t\n\nif nargin < 3\n\tpromptstr = { 'Plotting time range (ms):', ...\n\t\t\t ['Scalp map latencies (ms, NaN -> max-RMS)'], ...\n\t\t\t\t\t 'Plot title:' ...\n\t\t\t 'Scalp map options (see >> help topoplot):' };\n\tinistr = { [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)], ...\n\t\t\t 'NaN', ...\n\t ['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ], ...\n\t\t\t '' };\n\tresult = inputdlg2( promptstr, 'ERP data and scalp maps -- pop_timtopo()', 1, inistr, 'pop_timtopo');\n\tif size(result,1) == 0 return; end;\n\ttimerange = eval( [ '[' result{1} ']' ] );\n\ttopotime = eval( [ '[' result{2} ']' ] );\n\tplottitle = result{3};\n\toptions = [ ',' result{4} ];\n\tfigure;\nelse\n\toptions = [];\n\tfor i=1:length( varargin )\n\t\tif isstr( varargin{ i } )\n\t\t\toptions = [ options ', ''' varargin{i} '''' ];\n\t\telse\n\t\t\toptions = [ options ', [' num2str(varargin{i}) ']' ];\n\t\tend;\n\tend;\t\nend;\ntry, icadefs; set(gcf, 'color', BACKCOLOR, 'Name', ' timtopo()'); catch, end;\n\nif exist('plottitle') ~= 1\n plottitle = ['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ];\nend;\n \nif ~isempty(EEG.chanlocs)\n if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;\n\tSIGTMP = reshape(EEG.data, size(EEG.data,1), EEG.pnts, EEG.trials);\n\tposi = round( (timerange(1)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;\n\tposf = round( (timerange(2)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;\n\tif length( options ) < 2\n \ttimtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, [timerange(1) timerange(2) 0 0], topotime, '', 0, 0, 'chaninfo', EEG.chaninfo);\n com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'');', inputname(1), num2str(timerange), num2str(topotime), plottitle);\n\telse\n\t\tcom = sprintf('timtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, [timerange(1) timerange(2) 0 0], topotime, '''', 0, 0, ''chaninfo'', EEG.chaninfo %s);', options);\n\t\teval(com)\n\t com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'' %s);', inputname(1), num2str(timerange), num2str(topotime), plottitle, options);\n\tend;\t\t\nelse\n\tfprintf('Cannot make plot without channel locations\\n');\n\treturn;\nend;\nreturn;\n\n\t\t\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/pop_timtopo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.18389260723565776}} {"text": "function Reinforce(~, ~, game, player)\n\n%% REPLACE BUTTONS\nbutton1 = findobj('style', 'pushbutton', 'String', 'Reinforce');\nbutton2 = findobj('style', 'pushbutton', 'String', 'Attack');\ndelete([button1, button2])\n\nConfirmBtn = ...\nuicontrol('style', 'pushbutton', ... \n 'Parent', game.figH, ...\n 'Units', 'normalized', ...\n 'Position', [0.46 0.87, 0.08, 0.03], ...\n 'String', 'Confirm', ...\n 'Callback', {@ConfirmReinforcements, game, player}); %5\n\nN = numel(game.board);\n\n%% CALCULATE NUMBER OF EXTRA TROOPS\nlist = zeros(1, N);\nfor i = 1:N\n occupant = get(game.board(i).Patch, 'UserData');\n list(i) = (occupant(1) == player); \nend\nn = floor(sum(list)/3);\nif n < 3\n n = 3;\nend\n\n%% SET BUTTONDWNFCNS\nfor i = find(list) \n set(game.board(i).Patch, 'ButtonDownFcn', {@ClickToReinforce, game, player})\nend\n\n%% SHOW TEXT\nstr = sprintf('%s, you may add %d troops.', game.names{player}, n);\nset(game.txtH, 'String', str, 'UserData', n);\n\nuiwait(game.figH); %5\n\n%% CONFIRMED!\ndelete(ConfirmBtn)\nuiresume(game.figH) %2", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34438-risk/Final/Reinforce.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.18384634779510403}} {"text": "function [trl] = ft_trialfun_twoclass_classification(cfg)\n\n% FT_TRIALFUN_TWOCLASS_CLASSIFICATION can be used to train and test a real-time\n% classifier in offline and online mode. It selects pieces of data in the two classes\n% based on two trigger values. The first N occurences in each class are marked as\n% training items. All subsequent occurrences are marked as test items.\n%\n% This function can be used in conjunction with FT_REALTIME_CLASSIFICATION. The\n% configuration structure should contain\n% cfg.dataset = string with the filename\n% cfg.trialfun = 'ft_trialfun_twoclass_classification'\n% cfg.trialdef.numtrain = number of training items, e.g. 20\n% cfg.trialdef.eventvalue1 = trigger value for the 1st class\n% cfg.trialdef.eventvalue2 = trigger value for the 2nd class\n% cfg.trialdef.eventtype = string, e.g. 'trigger'\n% cfg.trialdef.prestim = latency in seconds, e.g. 0.3\n% cfg.trialdef.poststim = latency in seconds, e.g. 0.7\n%\n% See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL\n\n% Copyright (C) 2009, DCCN\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 to count the number of training items in each class\npersistent numtrain1\npersistent numtrain2\n\nif isempty(numtrain1)\n numtrain1 = 0;\nend\nif isempty(numtrain2)\n numtrain2 = 0;\nend\n\nif isfield(cfg, 'hdr')\n hdr = cfg.hdr;\nelse\n hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);\nend\n\nif isfield(cfg, 'event')\n event = cfg.event;\nelse\n event = ft_read_event(cfg.headerfile, 'headerformat', cfg.headerformat);\nend\n\nbaseline = round(cfg.trialdef.prestim*hdr.Fs);\nduration = round(cfg.trialdef.prestim*hdr.Fs + cfg.trialdef.poststim*hdr.Fs);\n\n% make a subset of the interesting events\nsel = strcmp(cfg.trialdef.eventtype, {event.type});\nevent = event(sel);\nnum = length(event);\ntrl = zeros(num,5);\n\nfor i=1:num\n % determine the location of this trial in the data stream\n begsample = event(i).sample - baseline;\n endsample = begsample + duration - 1;\n offset = baseline;\n % determine the class and wether this trial is eligeable for training\n if event(i).value==cfg.trialdef.eventvalue1\n class = 1;\n train = (numtrain1 < cfg.trialdef.numtrain); % boolean\n numtrain1 = numtrain1 + train; % increment the counter\n elseif event(i).value==cfg.trialdef.eventvalue2\n class = 2;\n train = (numtrain2 < cfg.trialdef.numtrain); % boolean\n numtrain2 = numtrain2 + train; % increment the counter\n else\n % the class is unknown and therefore irrelevant\n class = nan;\n train = false;\n end\n % remember this trial, the class and whether it should be used for training\n trl(i,:) = [begsample endsample offset class train];\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/trialfun/ft_trialfun_twoclass_classification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.1838463442262995}} {"text": "function makeDatFromCTF(filesearch,datfilename,typego,typebutton)\n\n% makeDatFromCTF\n% filesearch is a string that if used with dir, can identify all files\n% necssary to include. Make sure you're in the right directory. It should\n% lead to files with columns of continuous STIM channel output\n% typego lists the types of stim that one should expect button responses\n% to.\n% typebutton is the button response one should get. 0 if not buttonpress\n\nif (nargin < 3)\n typego = [6 7 8 9];\n typebutton = [2 0 0 0];\nend\n\nrespvals = [33554432 65536 262144 327680 393216 458752 524288 589824];\nresptype = [2 1 4 5 6 7 8 9];\nmaxtypeval = 589824; % above this should be button presses only.\nRESPLENGTH = 50;\n\nfs = 1200;\nbuttonwait = fs*1.5;\nnumHeaderLines = 19;\nfiles = dir(filesearch);\n\nallStim = [];\nfor i = 1:length(files)\n fprintf('Getting Data from %s ... \\n',files(i).name);\n [time,stim] = textread(files(i).name,'%f %f','delimiter','\\t','headerlines',2);\n allStim = [allStim;stim];\n clear time stim;\nend\n\nfid = fopen(datfilename,'W');\n\nfor i = 1:numHeaderLines\n fprintf(fid,'\\n');\nend\n\nfprintf(fid,'Trial\\tResp\\tType\\tCorrect\\tLatency\\tStim/Resp\\n');\nfprintf(fid,'-----\\t----\\t----\\t-------\\t-------\\t---------\\n');\nfprintf(fid,'1\\t0\\t1\\t1\\t1000\\tStim\\n');\n\ni = 1;\ntrialnum = 2;\nwhile i <= length(allStim)\n nextJump = 1;\n tmp = allStim(i:min(i+RESPLENGTH,length(allStim)));\n if (tmp(1) > 10 && ~isempty(find(respvals == max(tmp))) && max(tmp) <= maxtypeval)\n type = resptype(find(respvals == max(allStim(i:i+RESPLENGTH))));\n\n correct = 1;\n latency = 0;\n buttonPressed = 0;\n\n if (~isempty(find(typego == type))) % s2 occured, look for button press\n validButton = typebutton(find(typego == type));\n j = i + RESPLENGTH;\n correct = 0;\n\n while j < i + buttonwait % see if a button was pressed during the wait period\n tmp = allStim(j:min(j+RESPLENGTH,length(allStim)));\n if (~isempty(tmp) && tmp(1) > 10 && ~isempty(find(respvals == max(tmp))))\n latency = round((j - i) * 1000 / fs);\n buttonPressed = resptype(find(respvals == max(tmp)));\n j = i + buttonwait;\n\n end\n j = j + 1;\n end\n \n if (buttonPressed == validButton)\n correct = 1;\n end\n\n end\n\n if (~buttonPressed) % get Latency if not button pressed\n j = i + RESPLENGTH;\n cont = 1;\n while (cont && j < length(allStim))\n j = j + 1;\n tmp = allStim(j:min(j+RESPLENGTH,length(allStim)));\n if (isempty(tmp))\n cont = 0;\n elseif (tmp(1) > 10 && ~isempty(find(respvals == max(tmp))) && max(tmp) <= maxtypeval)\n cont = 0;\n end\n end\n latency = round((j - i) * 1000 / fs);\n nextJump = (j - i) - 1;\n else\n nextJump = round(latency * fs / 1000) + RESPLENGTH;\n end\n fprintf(fid,'%d\\t%d\\t%d\\t%d\\t%d\\tStim\\n',trialnum,buttonPressed,type,correct,latency);\n trialnum = trialnum+1;\n end\n i = i + nextJump;\nend\n\nfclose(fid);\n\nfprintf('***********************************************\\n');\nfprintf('%s created successfully: %d events found\\n\\n',datfilename,trialnum);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ctfimport1.03/ctf_stim2dat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.18362044681797507}} {"text": "function c = minus(c,I)\n \n % C = MINUS(C,I)\n % The function subtracts the waveform specified by trace index I from all\n % other traces. The resulting correlation object has the same number of\n % traces as the original though trace I is essentially zero amplitude.\n %\n % C = MINUS(C)\n % Short hand version of MINUS where I is assumed to be the last trace in\n % the list. That is, MINUS(C, C.ntraces ). This use is common\n % following the STACK routine.\n %\n % Before using MINUS, time windows need to be cropped to the same interval\n % relative to the triggers. This is most easily accomplished using the CROP\n % function prior to MINUS. If the traces have not been cropped, MINUS will\n % attempt to figure out which time window of data should be differenced.\n % This can result in unanticipated signals at the ends of each trace.\n % Caveat Emptor!\n %\n % MINUS will erase the CORR, LAG, STAT, LINK and CLUST fields from the\n % objects. After differencing, these fields are no longer valid.\n %\n % The traces are not normalized prior to subtracting. For most\n % applications the user will first want to normalize the trace amplitudes\n % using the NORM function. Typically, plots of the residual data will use\n % the 'raw' plotting option.\n %\n % In order to be differenced, the \"phase shift\" of the samples within the\n % trace must be the same. If it is not, MINUS will make a call to ALIGN to\n % resample all traces such that one sample falls directly on the trigger\n % time.\n %\n % Example - subtract the stacked waveform from each trace\n % c = xcorr(c)\n % c = adjusttrig(c)\n % c = crop(c,-3,5)\n % c = stack(c)\n % c = norm(c) % stacked waveform is the last trace\n % c_residual = minus(c)\n % plot(c_residual,'raw');\n \n % Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n % $Date$\n % $Revision$\n \n \n % READ & CHECK ARGUMENTS\n if ~exist('I','var')\n I = c.ntraces;\n end;\n assert(numel(I)==1, 'Only one trace can be subtracted from the others');\n \n if check(c,'SCALE')\n disp('Warning: Traces appear to have very different overall amplitudes');\n end\n \n \n \n \n % CREATE CORREATION OBJECT FOR INTERNAL MANIPULATIONS\n c1 = NewCorrelation;\n c1.traces = c.traces;\n c1.trig = c.trig;\n if exist('index','var') % Is this necessary?\n c1 = subset(c1,index);\n end\n \n \n % CHECK IF TRACES ARE DESCRITIZED ON THE SAME INVERVALS\n t = 86400 * (c1.trig - c1.traces.firstsampletime());\n Fs = c1.samplerate;\n sampleshift = mod(t,1/Fs);\n if (mean(sampleshift) ~= sampleshift) % if all sampleshifts are the same\n c1 = align(c1);\n end\n \n \n % CHECK IF TRACES ARE EQUALLY CROPPED\n pretrig = c1.traces.firstsampletime() - c1.trig; %ALL? just one?\n posttrig = c1.traces.lastsampletime() - c1.trig;\n if (mean(pretrig)~=pretrig(1)) || (mean(posttrig)~=posttrig(1))\n center = mean([pretrig ; posttrig])*86400;\n pretrig = center - (0.5 * c1.nsamples * get(c1,'Period'));\n posttrig = pretrig + (c1.nsamples + 1) * get(c1,'Period');\n % is it the right length?\n c1 = crop(c1,pretrig(1),posttrig(1)); %should all have same pre & post\n end\n \n toSubtract = c1.traces(I).data; %this trace will be subtracted from all\n for i = 1:length(c.trig)\n d = c1.traces(i).data - toSubtract;\n c.traces(i).data = d;\n c.trig(i) = c1.trig(i);\n end\n c.corrmatrix = [];\n c.lags = [];\n c.stat = [];\n c.link = [];\n c.clust = [];\nend\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/dev/@NewCorrelation/minus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1834446276539179}} {"text": "function V=mrLoadRet3StatsToAnalyze(outFileName,scanNum,mapName)\n% \n% V=mrLoadRet3StatsToAnalyze(outFileName,scanNum,mapName)\n% \n% AUTHOR: Wade\n% DATE: 06.10.03\n% PURPOSE: \n% Converts a statistical map in a mrLoadRet 3 Gray view into a 8 bit\n% analyze file. Data are scaled from 0 to 2^8-1\n% Uses the current scan if no scanNum is passed\n% mapName can be 'co', 'amp', 'ph' or any other similar statistical map in\n% the VOLUME structure.\n% If no mapName is passed, it defaults to writing out 'co'.\n% If embedDimensions are passed, the data are embedded into an even larger\n% volume. This is useful when \n% dealing with BV volume anatomies that have been embedded into 256x256x256\n%\n% RETURNS: \n% Number of bytes written in main data block.\n% \n% EXAMPLE:\n% 1) V=mrLoadRet3StatsToAnalyze('temp');\n% 2) V=mrLoadRet3StatsToAnalyze('temp_ph','ph');\n%\n% NOTES\n% Originall coded to transfer mrLoadRet gray stats into SSI's EMSE / mrViewer\n% $Author: wade $\n% $Date: 2003/09/09 21:18:59 $\nmrGlobals;\nif (isempty(selectedVOLUME))\n error('You must select (click within) a volume window before proceeding');\nend\n\nif ((~exist('scanNum','var')) | (isempty(scanNum)))\n scanNum=getCurScan(VOLUME{selectedVOLUME});\nend\n% Get a coherence threshold\ncoThresh=getCothresh(VOLUME{selectedVOLUME});\n\n\nif ((~exist('outFileName','var')) | (isempty(outFileName)))\n a=dataTYPES(VOLUME{selectedVOLUME}.curDataType).name;\n outFileName=[a,'_',int2str(scanNum),'_co_',int2str(coThresh*100)];\nend\n\nif ((~exist('mapName','var')) | (isempty(mapName)))\n mapName='co';\nend\nvolAnatSize=size(VOLUME{selectedVOLUME}.anat);\n% We need to permute this into the correct format. \nvolAnatSize=volAnatSize([2 1 3]);\nif ((~exist('embedDimensions','var')) | (isempty(embedDimensions)))\n embedDimensions=volAnatSize;\nend\nif ((~exist('VOLUME','var')) | (isempty(VOLUME{selectedVOLUME}.co)))\n error('mrLoadRet must be running and the GRAY corAnal must be loaded');\nend\nif (isempty(VOLUME{selectedVOLUME}.anat))\n error('The anatomy must be loaded');\nend\n\n% % Find the size of the full anatomy\ncoords=VOLUME{selectedVOLUME}.coords;\ncoords=coords';\n% \n% minVals=min(coords);\n% maxVals=max(coords);\n% bbSize=maxVals-minVals+1\n% \n% if(find(bbSize<=0))\n% error('The GRAY data are in an invalid VOI');\n% end\n\ndataVolume=uint8(ones(size(VOLUME{selectedVOLUME}.anat)));\n[ySiz xSiz zSiz]=size(VOLUME{selectedVOLUME}.anat);\n\n% Do the mother of all sub2inds to get a linear index into dataVolume\ncoords=sub2ind([ySiz xSiz zSiz],coords(:,1),coords(:,2),coords(:,3));\nif (~strcmp(mapName,'co'))\n error('Only co maps allowed for now');\nend\n\n\n\nco=(VOLUME{selectedVOLUME}.co(scanNum));\nco=co{1};\n\n% Now threshold according to the current cothresh\nco(co=1)=0.9999; % Just to make sure\nco(co<=0)=0;\n\n\n\n% Scale co from 0 to 2^8-1\nmax(co);\nmin(co);\n% co=log10(co*10);\nco(co<=0)=0;\nco=co*((2^8)-1);\n\n\n\nmax(co)\nmin(co)\n\n% Send it into the large data volume\ndataVolume(coords)=(co);\n\ndataVolume=permute(dataVolume,[3 2 1]);\ndataVolume=flipdim(dataVolume,3);\n%dataVolume=flipdim(dataVolume,2);\ndataVolume=flipdim(dataVolume,1);\n% Call SPM writevol routine to write out the data.\n\n\n s=spm_hwrite(outFileName,[ySiz xSiz zSiz],[1 1 1],1,spm_type('uint8'),0);\n V=spm_vol(outFileName);\n \n \n V.descrip=['Converted from tSeries file in session',mrSESSION.sessionCode,' : ',mrSESSION.subject,': on ',datestr(now)];\n \n s=spm_write_vol(V,double(dataVolume));\n\nreturn;\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/analyze/mrLoadRet3StatsToAnalyze.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1829763406436181}} {"text": "function patcht(FF,VV,TF,VT,I,Options)\n% This function PATCHT, will show a triangulated mesh like Matlab function\n% Patch but then with a texture.\n%\n% Alec: Essentially this calls \"surface\" for each triangle of the triangle mesh\n% with the appropriate texture coordinates\n%\n% patcht(FF,VV,TF,VT,I,Options);\n%\n% inputs,\n% FF : Face list #F x 3 with vertex indices\n% VV : Vertices #V x 3\n% TF : Texture list #F x 3 with texture vertex indices\n% VT : Texture Coordinates s 2 x #VT, range must be [0..1] or real pixel postions\n% I : The texture-image RGB [O x P x 3] or Grayscale [O x P] \n% Options : Structure with options for the textured patch such as\n% EdgeColor, EdgeAlpha see help \"Surface Properties :: Functions\"\n%\n% Options.PSize : Special option, defines the image texturesize for each \n% individual polygon, a low number gives a more block \n% like texture, defaults to 64;\n%\n% note: \n% On a normal PC displaying 10,000 faces will take about 6 sec.\n%\n% Example,\n%\n% % Load Data;\n% load testdata;\n% % Show the textured patch\n% figure, patcht(FF,VV,TF,VT,I);\n% % Allow Camera Control (with left, right and center mouse button)\n% mouse3d\n%\n% % file containing image\n% image_source = 'woody.png';\n% % load image with alpha mask\n% [im,map,alpha] = imread(image_source);\n% % mesh based on alpha values with approximately 100 boundary vertices\n% [V,F] = png2mesh(image_source,0,100);\n% % treat alpha as white in display\n% im = over(im,alpha,ones(size(im)),1);\n% % dummy display white image the same size as input image\n% imshow(ones([max(V(:,2))-min(V(:,2)) max(V(:,1))-min(V(:,1))]));\n% % display original mesh\n% % reverse y-direction so mesh display is upright (we're displaying the mesh\n% % ontop of the imshow() display to get pixel perfect images)\n% patcht(F,[V(:,1) size(im,1)-V(:,2)],F,V,permute(flipdim(im,1),[2 1 3]));\n% % create some trivial deformation\n% new_V = [V(:,1) 2*V(:,2)];\n% figure;\n% % dummy display white image the same size as input image\n% imshow(ones([max(new_V(:,2))-min(new_V(:,2)) max(new_V(:,1))-min(new_V(:,1))]));\n% % display deformed mesh\n% patcht(F,[new_V(:,1) max(new_V(:,2)+0.5)-new_V(:,2)],F,V,permute(flipdim(im,1),[2 1 3]));\n%\n% Function is written by D.Kroon University of Twente (July 2010)\n\n% FaceColor is a texture\nOptions.FaceColor='texturemap';\n% noe edges\nOptions.EdgeColor='none';\n\n% Size of texture image used for every triangle\nif(isfield(Options,'PSize'))\n sizep=round(Options.PSize(1));\n Options=rmfield(Options,'PSize');\nelse\n sizep=64;\nend\n\n% Check input sizes\nif(size(FF,2)~=size(TF,2))\n error('patcht:inputs','Face list must be equal in size to texture-index list');\nend\n\nif((ndims(I)~=2)&&(ndims(I)~=3))\n error('patcht:inputs','No valid Input texture image');\nend\n\n% Detect if grayscale or color image\nswitch(size(I,3))\n case 1\n iscolor=false;\n case 3\n iscolor=true;\n otherwise\n error('patcht:inputs','No valid Input texture image');\nend\n\n \nif(max(VT(:))<2)\n % Remap texture coordinates to image coordinates\n VT2(:,1)=(size(I,1)-1)*(VT(:,1))+1;\n VT2(:,2)=(size(I,2)-1)*(VT(:,2))+1;\nelse\n VT2=VT;\nend\n\n% Calculate the texture interpolation values\n[lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep);\n \n% Split texture-image in r,g,b to allow fast 1D index \nIr=I(:,:,1); if(iscolor), Ig=I(:,:,2); Ib=I(:,:,3); end\n\n% The Patch used for every triangle (rgb)\nJr=zeros([(sizep+1) (sizep+1) 1],class(I));\nif(iscolor)\n Jg=zeros([(sizep+1) (sizep+1) 1],class(I));\n Jb=zeros([(sizep+1) (sizep+1) 1],class(I));\nend\n\n% if no z coordinates are given then use 0s\nif size(VV,2) < 3\n VV = [VV zeros(size(VV,1),1)];\nend\n\nhold on;\n% Loop through all triangles of the mesh\nfor i=1:size(FF,1)\n % Get current triangle vertices and current texture-vertices\n V=VV(FF(i,:),:); \n Vt=VT2(TF(i,:),:); \n \n % Define the triangle as a surface\n x=[V(1,1) V(2,1); V(3,1) V(3,1)];\n y=[V(1,2) V(2,2); V(3,2) V(3,2)];\n z=[V(1,3) V(2,3); V(3,3) V(3,3)];\n \n % Define the texture coordinates of the surface\n tx=[Vt(1,1) Vt(2,1) Vt(3,1) Vt(3,1)];\n ty=[Vt(1,2) Vt(2,2) Vt(3,2) Vt(3,2)] ;\n xy=[tx(1) ty(1); tx(2) ty(2); tx(3) ty(3); tx(3) ty(3)];\n\n % Calculate texture interpolation coordinates\n pos(:,1)=xy(1,1)*lambda1+xy(2,1)*lambda2+xy(3,1)*lambda3;\n pos(:,2)=xy(1,2)*lambda1+xy(2,2)*lambda2+xy(3,2)*lambda3;\n pos=round(pos); pos=max(pos,1); pos(:,1)=min(pos(:,1),size(I,1)); pos(:,2)=min(pos(:,2),size(I,2));\n posind=(pos(:,1)-1)+(pos(:,2)-1)*size(I,1)+1;\n \n % Map texture to surface image\n Jr(jind)=Ir(posind);\n J(:,:,1)=Jr; \n if(iscolor)\n Jg(jind)=Ig(posind); \n Jb(jind)=Ib(posind);\n J(:,:,2)=Jg; \n J(:,:,3)=Jb;\n end\n \n % Show the surface\n surface(x,y,z,J,Options)\nend\nhold off; \n\nfunction [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep)\n% Define a triangle in the upperpart of an square, because only that\n% part is used by the surface function\nx1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=0;\n% Calculate the bary centric coordinates (instead of creating a 2D image\n% with the interpolation values, we map them directly to an 1D vector)\ndetT = (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3);\n[x,y]=ndgrid(0:sizep,0:sizep); x=x(:); y=y(:);\nlambda1=((y2-y3).*(x-x3)+(x3-x2).*(y-y3))/detT;\nlambda2=((y3-y1).*(x-x3)+(x1-x3).*(y-y3))/detT;\nlambda3=1-lambda1-lambda2;\n% Make from 2D (surface)image indices 1D image indices\n[jx jy]=ndgrid(sizep-(0:sizep)+1,sizep-(0:sizep)+1);\njind=(jx(:)-1)+(jy(:)-1)*(sizep+1)+1;\n\n\n\n \n \n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/patcht.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017820478897, "lm_q1q2_score": 0.1829763354034026}} {"text": "function ps_parms_default()\n%PS_PARMS_DEFAULT set parms to default value if not already set\n%\n% Andy Hooper, June 2006\n%\n% ======================================================================\n% 04/2008 AH: SB default processing corrected\n% 06/2009 AH: scla_deramp added \n% 08/2009 AH: unwrap_gold_alpha added\n% 09/2009 AH: merge_resample_size added \n% 09/2009 AH: select_method added\n% 09/2009 AH: density_rand added\n% 11/2009 AH: pixel_aspect_ratio removed\n% 01/2010 AH: add check for write permission before saving\n% 02/2010 AH: weed_alpha replaced by weed_time_win\n% 02/2010 AH: weed_max_noise added\n% 02/2010 AH: plot_pixel_size replaced by plot_scatterer_size (in m)\n% 02/2010 AH: plot_dem_posting added\n% 02/2010 AH: ref_centre_lonlat and ref_radius added\n% 02/2010 AH: unwrap_ifg_index replaced by drop_ifg_index\n% 02/2010 AH: weed_time_win and unwrap_time_win default changed to 730\n% 03/2010 AH: add logging\n% 09/2010 MA: oversampling factor\n% 09/2010 AH: plot_pixels_scatterer added\n% 11/2010 AH: (sb_)recalc_index replaced by (sb_)scla_drop_index\n% 06/2011 AH: add weed_neighbours \n% 12/2012 AH: add insar_processor\n% 06/2013 DB: add parameters to include tropopshere in scla estimation\n% 01/2014 DB: Add wavelength and heading to parameters list. This in case\n% not all stamps steps are ran.\n% 01/2014 DB: Add a multi-core option for step 1-5\n% 02/2014 AH: add unwrap_hold_good_values\n% 08/2014 DB: explicit search if there is not a processor.txt file \n% 05/2015 AH: add gamma_max_iterations \n% 09/2015 AH: change default weed_neighbours = 'n' \n% 09/2015 AH: change default max_topo_err = 20 \n% 10/2016 DB: Change other processor type to a warning not an error.\n% ======================================================================\n\n\nparmfile='parms.mat';\nparent_flag=0;\n\nif exist('./parms.mat','file')\n parms=load(parmfile);\nelseif exist('../parms.mat','file')\n parmfile='../parms.mat';\n parms=load(parmfile);\n parent_flag=1;\nelse\n parms=struct('Created',date);\n parms.small_baseline_flag='n'; \nend\n\nparmfields_before=fieldnames(parms);\nnum_fields=size(parmfields_before,1);\n\nif ~isfield(parms,'max_topo_err')\n parms.max_topo_err=20;\nend\n\nif ~isfield(parms,'quick_est_gamma_flag')\n parms.quick_est_gamma_flag='y';\nend\n\nif ~isfield(parms,'select_reest_gamma_flag')\n parms.select_reest_gamma_flag='y';\nend\n\nif ~isfield(parms,'filter_grid_size')\n parms.filter_grid_size=50;\nend\n\nif ~isfield(parms,'filter_weighting')\n parms.filter_weighting='P-square'; % filter weighting strategy\nend\n\nif ~isfield(parms,'gamma_change_convergence')\n parms.gamma_change_convergence=0.005; % change in change in gamma that signals convergence\nend\n\nif ~isfield(parms,'gamma_max_iterations')\n parms.gamma_max_iterations=3; % maximum number of iterations for gamma estimation \nend\n\nif ~isfield(parms,'slc_osf')\n parms.slc_osf=1; % [MA] SLC oversampling factor\nend\n\nif ~isfield(parms,'clap_win')\n parms.clap_win=32;\nend\n\nif ~isfield(parms,'clap_low_pass_wavelength')\n parms.clap_low_pass_wavelength=800;\nend\n\nif ~isfield(parms,'clap_alpha')\n parms.clap_alpha=1;\nend\n\nif ~isfield(parms,'clap_beta')\n parms.clap_beta=0.3;\nend\n\nif ~isfield(parms,'select_method')\n parms.select_method='DENSITY'; %'DENSITY' or 'PERCENT'\nend\n \nif ~isfield(parms,'density_rand')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.density_rand=2; % Random-phase pixels per km2 (before weeding)\n else\n parms.density_rand=20; % Random-phase pixels per km2 (before weeding) \n end\nend\n\nif ~isfield(parms,'percent_rand')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.percent_rand=1; % Percent random-phase pixels (before weeding) \n else\n parms.percent_rand=20;% Percent random-phase pixels (before weeding) \n end\nend\n\nif ~isfield(parms,'gamma_stdev_reject')\n parms.gamma_stdev_reject=0;\nend\n\nif isfield(parms,'weed_alpha')\n parms=rmfield(parms,'weed_alpha');\nend\n\nif ~isfield(parms,'weed_time_win')\n parms.weed_time_win=730; % weeding smoothing window alpha (days)\nend\n\nif ~isfield(parms,'weed_max_noise')\n parms.weed_max_noise=inf; % maximum arc noise in any ifg (rad)\nend\n\nif ~isfield(parms,'weed_standard_dev')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.weed_standard_dev=inf;\n else \n parms.weed_standard_dev=1.0;\n end\nend\n\nif ~isfield(parms,'weed_zero_elevation')\n parms.weed_zero_elevation='n';\nend\n\nif ~isfield(parms,'weed_neighbours')\n parms.weed_neighbours='n';\nend\n\nif ~isfield(parms,'unwrap_method')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.unwrap_method='3D_QUICK'; \n else\n parms.unwrap_method='3D';\n end\nend\n\nif ~isfield(parms,'unwrap_patch_phase')\n parms.unwrap_patch_phase='n';\nend\n\nif isfield(parms,'unwrap_ifg_index')\n try\n ps=load('ps2.mat');\n catch\n try\n ps=load('ps1.mat');\n catch\n end\n end\n if exist('ps','var') & ~strcmpi(parms.unwrap_ifg_index,'all')\n parms.drop_ifg_index=setdiff([1:ps.n_ifg],parms.unwrap_ifg_index); \n end\n parms=rmfield(parms,'unwrap_ifg_index');\n num_fields=0;\nend\n\nif ~isfield(parms,'drop_ifg_index')\n parms.drop_ifg_index=[]; \nend\n\nif ~isfield(parms,'unwrap_la_error_flag')\n parms.unwrap_la_error_flag='y';\nend\n\nif ~isfield(parms,'unwrap_spatial_cost_func_flag')\n parms.unwrap_spatial_cost_func_flag='n';\nend\n\nif ~isfield(parms,'unwrap_prefilter_flag')\n parms.unwrap_prefilter_flag='y';\nend\n\nif ~isfield(parms,'unwrap_grid_size')\n parms.unwrap_grid_size=200; % prefilter grid size\nend\n\nif ~isfield(parms,'unwrap_gold_n_win')\n parms.unwrap_gold_n_win=32; % prefilter goldstein filtering window size\nend\n\nif ~isfield(parms,'unwrap_alpha')\n parms.unwrap_alpha=8; % unwrapping smoothing window alpha\nend\n\nif ~isfield(parms,'unwrap_time_win')\n parms.unwrap_time_win=730; % unwrapping smoothing window alpha\nend\n\nif ~isfield(parms,'unwrap_gold_alpha')\n parms.unwrap_gold_alpha=0.8; % unwrapping goldstein filter alpha\nend\n\nif ~isfield(parms,'unwrap_hold_good_values')\n parms.unwrap_hold_good_values='n'; % fix unwrapped values judged to be good\nend\n\nif isfield(parms,'recalc_index')\n try\n ps=load('ps2.mat');\n catch\n try\n ps=load('ps1.mat');\n catch\n end\n end\n if exist('ps','var') & ~strcmpi(parms.recalc_index,'all')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.scla_drop_index=setdiff([1:ps.n_image],parms.recalc_index); \n else\n parms.scla_drop_index=setdiff([1:ps.n_ifg],parms.recalc_index); \n end\n end\n parms=rmfield(parms,'recalc_index');\n if isfield(parms,'sb_recalc_index')\n if exist('ps','var') & ~strcmpi(parms.sb_recalc_index,'all')\n parms.sb_scla_drop_index=setdiff([1:ps.n_ifg],parms.sb_recalc_index); \n end\n parms=rmfield(parms,'sb_recalc_index');\n end\n num_fields=0;\nend\n\nif ~isfield(parms,'scla_drop_index')\n parms.scla_drop_index=[]; \nend\n\nif ~isfield(parms,'scn_wavelength')\n parms.scn_wavelength=100; % spatially correlated noise wavelength\nend\n\nif ~isfield(parms,'scn_time_win')\n parms.scn_time_win=365; % 1 year time window\nend\n\nif ~isfield(parms,'scn_deramp_ifg')\n parms.scn_deramp_ifg=[]; % deramp these ifgs and add to estimate of scn\nend\n\nif ~isfield(parms,'scn_kriging_flag')\n parms.scn_kriging_flag='n'; % use kriging, 'y' or 'n'\nend\n\nif ~isfield(parms,'ref_lon')\n parms.ref_lon=[-inf,inf]; % low and high longitude for ref ps\nend\n\nif ~isfield(parms,'ref_lat')\n parms.ref_lat=[-inf,inf]; % low and high latitude for ref ps\nend\n\nif ~isfield(parms,'ref_centre_lonlat')\n parms.ref_centre_lonlat=[0,0]; % centre lon/lat for ref ps\nend\n\nif ~isfield(parms,'ref_radius')\n parms.ref_radius=inf; % radius from centre for ref ps\nend\n\nif ~isfield(parms,'ref_velocity')\n parms.ref_velocity=0; % velocity of reference point if known\nend\n\nif ~isfield(parms,'n_cores')\n parms.n_cores=1; % n_cores for the muti-core option (step 1-5)\nend\n\n\nif ~isfield(parms,'plot_dem_posting')\n parms.plot_dem_posting=90; \nend\n\nif isfield(parms,'plot_pixel_size')\n parms.plot_scatterer_size=parms.plot_pixel_size*25; \n num_fields=0;\n parms=rmfield(parms,'plot_pixel_size');\nend\n\nif ~isfield(parms,'plot_scatterer_size')\n parms.plot_scatterer_size=120; \nend\n\nif ~isfield(parms,'plot_pixels_scatterer')\n parms.plot_pixels_scatterer=3; \nend\n\nif ~isfield(parms,'plot_color_scheme')\n parms.plot_color_scheme='inflation'; \nend\n\nif isfield(parms,'pixel_aspect_ratio')\n parms=rmfield(parms,'pixel_aspect_ratio');\nend\n\nif ~isfield(parms,'shade_rel_angle')\n parms.shade_rel_angle=[90,45]; % look angle for dem shaded relief\nend\n\nif ~isfield(parms,'lonlat_offset')\n parms.lonlat_offset=[0,0]; % offset of PS in degrees from dem\nend\n\nif ~isfield(parms,'merge_resample_size')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.merge_resample_size=100; % grid size (in m) to resample to during merge of patches\n else\n parms.merge_resample_size=0; % (0=no resampling)\n end\nend\n\nif ~isfield(parms,'merge_standard_dev')\n parms.merge_standard_dev=inf;\nend\n\nif ~isfield(parms,'scla_method')\n parms.scla_method='L2'; % method for estmating SCLA, L1- or L2-norm\nend\n\nif ~isfield(parms,'scla_deramp')\n parms.scla_deramp='n'; % estimate an orbital ramp before SCLA\nend\n\nlambdaname=['lambda.1.in']; % wavelength\nif ~isfield(parms,'lambda')\n if ~exist(lambdaname,'file')\n lambdaname= ['../',lambdaname];\n end\n if ~exist(lambdaname,'file')\n lambdaname= ['../',lambdaname];\n end\n if ~exist(lambdaname,'file')\n parms.lambda=NaN; % Add wavelength\n else\n lambda=load(lambdaname);\n parms.lambda=lambda; % Add wavelength\n end\nend\n\nheadingname=['heading.1.in']; % satellite heading\nif ~isfield(parms,'heading')\n if ~exist(headingname,'file')\n headingname= ['../',headingname];\n end\n if ~exist(headingname,'file')\n headingname= ['../',headingname];\n end\n if ~exist(headingname,'file')\n parms.heading=NaN; % Add heading\n else\n heading=load(headingname);\n parms.heading=heading; % Add heading\n end\nend\n\nif ~isfield(parms,'scla_deramp')\n parms.scla_deramp='n'; % estimate an orbital ramp before SCLA\nend\n\nif ~isfield(parms,'sb_scla_drop_index')\n if strcmpi(parms.small_baseline_flag,'y')\n parms.sb_scla_drop_index=[];\n end\nend\n\nif ~isfield(parms,'insar_processor')\n processor_file = 'processor.txt';\n if exist(processor_file,'file')~=2\n if exist(['..' filesep processor_file],'file')==2\n processor_file = ['..' filesep processor_file];\n if exist(['..' filesep processor_file],'file')==2\n processor_file = ['..' filesep processor_file];\n end\n end\n end \n \n if exist(processor_file,'file')~=2\n parms.insar_processor='doris'; % \n else\n processor = fileread(processor_file);\n processor = strtrim(processor);\n parms.insar_processor=processor; % \n\n if ~strcmpi(processor,'gamma') & ~strcmpi(processor,'doris')\n fprintf('WARNING: This processor is not supported (doris and gamma)')\n end\n end\nend\n\nif ~isfield(parms,'subtr_tropo')\n parms.subtr_tropo='n'; % remove tropospheric estimate\nend\n\nif ~isfield(parms,'tropo_method')\n parms.tropo_method='a_l'; % method for tropopsheric estimate\nend\n\n\nparmfields=fieldnames(parms);\nif size(parmfields,1)~=num_fields\n try\n save(parmfile,'-struct','parms')\n for i=1:size(parmfields,1)\n if isempty(strmatch(parmfields{i},parmfields_before))\n parmname=parmfields{i};\n value=getfield(parms,parmname);\n if isempty(value)\n value='[]';\n end\n if isnumeric(value)\n logit([parmname,' = ',num2str(value)],0,parent_flag);\n else\n logit([parmname,' = ',value],0,parent_flag);\n end\n end\n end\n\n catch\n fprintf('Warning: missing parameters could not be updated (no write access)\\n')\n end\nend\n", "meta": {"author": "dbekaert", "repo": "StaMPS", "sha": "c159eb81b16c446e0e8fdef7dd435eb22e0240ed", "save_path": "github-repos/MATLAB/dbekaert-StaMPS", "path": "github-repos/MATLAB/dbekaert-StaMPS/StaMPS-c159eb81b16c446e0e8fdef7dd435eb22e0240ed/matlab/ps_parms_default.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.18293281641203182}} {"text": "function [removingList] = plotTracks(ax, tracks, currentFrame, params, removingList)\n%% Plot bounding boxes\n% Remove old lines\nif nargin > 4\n if size(removingList, 1) > 0\n for i = 1:size(removingList, 1)\n delete(removingList(i)); \n end\n end\nend\n% Important parameters for plotting the bounding boxes\nremovingList = [];\nboundingBoxColor = params.boundingBoxColor;\n% We need to draw the bounding boxes from 0 to negative because the image \n% coordinate origin is in the upper left corner. Therefore the bounding box\n% coordinates are mirrored.\nySign = -1;\n% Now plot the bounding boxes together with annotations\nfor iTrack = 1:size(tracks, 2)\n track = tracks(iTrack);\n initialFrame = track.initialFrame;\n finalFrame = track.finalFrame;\n if (initialFrame <= currentFrame) && (currentFrame < finalFrame)\n % Get internal track index for the chosen frame\n currentIndex = currentFrame - initialFrame + 1;\n % Try to get the bounding box\n try\n boundingBox = track.bbox(currentIndex, :);\n velocity = track.xVelocity(currentIndex);\n catch\n continue \n end\n % Plot the bounding box\n positionBoundingBox = [boundingBox(1) ...\n ySign*boundingBox(2)+ySign*boundingBox(4) ...\n boundingBox(3) ...\n boundingBox(4)];\n if params.stop == 1\n rect = rectangle(ax, 'Position', positionBoundingBox, ...\n 'FaceColor', boundingBoxColor, ...\n 'EdgeColor', [0 0 0], ...\n 'PickableParts', 'visible', ...\n 'ButtonDownFcn',{@params.onClick, track, currentFrame});\n else\n rect = rectangle(ax, 'Position', positionBoundingBox, ...\n 'FaceColor', boundingBoxColor, ...\n 'EdgeColor', [0 0 0], ...\n 'PickableParts', 'visible');\n end\n removingList = [removingList; rect];\n \n % Plot the triangle that represents the direction of the vehicle\n if velocity < 0\n centroidSign = 1;\n front = boundingBox(1) + (boundingBox(3)*0.2);\n triangleXPosition = [front front boundingBox(1)];\n else\n centroidSign = -1;\n front = boundingBox(1) + boundingBox(3) - (boundingBox(3)*0.2);\n triangleXPosition = [front front boundingBox(1)+boundingBox(3)];\n end\n triangleYPosition = [ySign*boundingBox(2) ...\n ySign*boundingBox(2)+ySign*boundingBox(4)...\n ySign*boundingBox(2)+ySign*(boundingBox(4)/2)];\n triangle = fill(ax, triangleXPosition, triangleYPosition, [0 0 0]);\n removingList = [removingList; triangle];\n \n % Plot the text annotation\n if params.plotTextAnnotation\n velocityKmh = abs(velocity) * 3.6;\n boundingBoxAnnotationText = sprintf('%s|%.2fkm/h|ID%d', ...\n track.class(1), ...\n velocityKmh, ...\n track.id);\n textAnnotation = text(ax, boundingBox(1), ySign*boundingBox(2)+0.6, ...\n boundingBoxAnnotationText, 'FontSize',8);\n textAnnotation.BackgroundColor = [1 1 0.3];\n textAnnotation.Margin = .5;\n removingList = [removingList; textAnnotation];\n end\n \n % Plot the track line\n if params.plotTrackingLine\n relevantBoundingBoxes = track.bbox(1:currentIndex, :);\n centroids = [relevantBoundingBoxes(:,1) + relevantBoundingBoxes(:,3)/2, ...\n relevantBoundingBoxes(:,2) + relevantBoundingBoxes(:,4)/2];\n plottedCentroids = line(ax, centroids(:, 1)+ centroidSign * (boundingBox(3)/2), ...\n ySign*centroids(:, 2));\n removingList = [removingList; plottedCentroids];\n end\n end\nend\nxlim(ax, [0 params.trackWidth]);\naxis off;\nend\n", "meta": {"author": "RobertKrajewski", "repo": "highD-dataset", "sha": "b8cc983d4120cdaadd3bec76e5e8b913ed42590a", "save_path": "github-repos/MATLAB/RobertKrajewski-highD-dataset", "path": "github-repos/MATLAB/RobertKrajewski-highD-dataset/highD-dataset-b8cc983d4120cdaadd3bec76e5e8b913ed42590a/Matlab/utils/plotTracks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1829024223733729}} {"text": "function [planC,allLabelNamesC,dcmExportOptS] = ...\n processAndImportAIOutput(planC,userOptS,origScanNumV,scanNumV,...\n outputScanNum,algorithm,hashID,sessionPath,cmdFlag,hWait)\n%[planC,,origScanNumV,allLabelNamesC,dcmExportOptS] = ...\n%processAndImportAIOutput(planC,userOptS,origScanNumV,scanNumV,...\n% outputScanNum,algorithm,hashID,sessionPath,cmdFlag,hWait)\n%--------------------------------------------------------------------------\n% AI 08/29/22\n\noutputS = userOptS.output;\n\n%Loop over model outputs\n\noutputC = fieldnames(outputS);\nfor nOut = 1:length(outputC)\n\n outType = outputC{nOut};\n\n switch(lower(outType))\n\n case 'labelmap'\n %Segmentations\n\n % Import segmentations\n if ishandle(hWait)\n waitbar(0.9,hWait,'Importing segmentation results to CERR');\n end\n [planC,allLabelNamesC,dcmExportOptS] = ...\n processAndImportSeg(planC,origScanNumV,scanNumV,...\n outputScanNum,sessionPath,userOptS);\n\n case 'dvf'\n %Deformation vector field\n\n outFmt = outputS.DVF.outputFormat;\n DVFpath = fullfile(sessionPath,'outputH5','DVF');\n DVFfile = dir([DVFpath,filesep,'*.h5']);\n outFile = fullfile(DVFpath,DVFfile.name);\n switch(lower(outFmt))\n case 'h5'\n DVF4M = h5read(outFile,'/dvf');\n otherwise\n error('Invalid model output format %s.',outFmt)\n end\n\n\n % Convert to CERR coordinate sytem\n\n if ~iscell(planC)\n cerrDir = planC;\n cerrDirS = dir(cerrDir);\n cerrFile = cerrDirS(3).name;\n planC = loadPlanC(fullfile(cerrDir,cerrFile),tempdir);\n else\n cerrFile = '';\n end\n indexS = planC{end};\n\n % Get associated scan num\n idS = userOptS.outputAssocScan.identifier;\n assocScan = getScanNumFromIdentifiers(idS,planC);\n\n tempOptS = userOptS;\n outTypesC = fieldnames(userOptS.output);\n matchIdx = strcmpi(outTypesC,'DVF');\n outTypesC = outTypesC(~matchIdx);\n tempOptS.output = rmfield(tempOptS.output,outTypesC);\n niiOutDir = tempOptS.output.DVF.outputDir;\n DVFfilename = strrep(DVFfile.name,'.h5','');\n dimsC = {'dx','dy','dz'};\n niiFileNameC = cell(1,length(dimsC));\n for nDim = 1:size(DVF4M,1)\n DVF3M = squeeze(DVF4M(nDim,:,:,:));\n DVF3M = permute(DVF3M,[2,3,1]);\n [DVF3M,planC] = joinH5planC(assocScan,DVF3M,[DVFfilename,'_'...\n dimsC{nDim}],tempOptS,planC);\n niiFileNameC{nDim} = fullfile(niiOutDir,[DVFfilename,'_'...\n dimsC{nDim},'.nii.gz']);\n fprintf('\\n Writing DVF to file %s\\n',niiFileNameC{nDim});\n DVF3M_nii = make_nii(DVF3M);\n save_nii(DVF3M_nii, niiFileNameC{nDim}, 0);\n end\n\n %Calc. deformation magnitude\n DVFmag3M = zeros(size(DVF3M));\n assocScanUID = planC{indexS.scan}(assocScan).scanUID; \n for nDim = 1:size(DVF4M,1)\n doseNum = length(planC{indexS.dose})-nDim+1;\n doseArray3M = double(getDoseArray(doseNum,planC));\n DVFmag3M = DVFmag3M + doseArray3M.^2;\n end\n DVFmag3M = sqrt(DVFmag3M);\n description = 'Deformation magnitude';\n planC = dose2CERR(DVFmag3M,[],description,'',description,...\n 'CT',[],'no',assocScanUID, planC);\n\n % Store to deformS\n indexS = planC{end};\n idS = userOptS.register.baseScan.identifier;\n baseScanNum = getScanNumFromIdentifiers(idS,planC,1);\n idS = userOptS.register.movingScan.identifier;\n movScanNum = getScanNumFromIdentifiers(idS,planC,1);\n\n planC{indexS.deform}(end+1).baseScanUID = ...\n planC{indexS.scan}(baseScanNum).scanUID;\n planC{indexS.deform}(end+1).movScanUID = ...\n planC{indexS.scan}(movScanNum).scanUID;\n\n planC{indexS.deform}(end+1).algorithm = algorithm;\n planC{indexS.deform}(end+1).registrationTool = 'CNN';\n planC{indexS.deform}(end+1).algorithmParamsS.singContainerHash = ...\n hashID;\n planC{indexS.deform}(end+1).DVFfileName = niiFileNameC;\n\n if ~isempty(cerrFile)\n save_planC(planC,[],'PASSED',cerrFile);\n planC = cerrFile;\n end\n\n case 'derivedimage'\n %Read output image\n outFmt = outputS.derivedImage.outputFormat;\n outputImgType = outputS.derivedImage.imageType;\n imgPath = fullfile(sessionPath,'outputH5');\n imgFile = dir([imgPath,filesep,'*.h5']);\n outFile = fullfile(imgFile,DVFfile.name);\n switch(lower(outFmt))\n case 'h5'\n img3M = h5read(outFile,'/scan'); %Dataset name for derived images?\n otherwise\n error('Invalid model output format %s.',outFmt)\n end\n\n indexS = planC{end};\n initTextureS = initializeCERR('texture');\n initTextureS(end+1).textureUID = createUID('texture');\n planC{indexS.texture} = ...\n dissimilarInsert(planC{indexS.texture},initTextureS);\n currentTexture = length(planC{indexS.texture});\n planC{indexS.texture}(currentTexture).textureUID = ...\n createUID('TEXTURE');\n\n %Get associated scan index\n identifierS = userOptS.outputAssocScan.identifier;\n idS = rmfield(identifierS,{'warped','filtered'});\n idC = fieldnames(idS);\n if ~isempty(idC)\n assocScanNum = getScanNumFromIdentifiers(identifierS,planC);\n else\n assocScanNum = 1; %Assoc with first scan by default\n end\n assocScanUID = planC{indexS.scan}(assocScanNum).scanUID;\n planC{indexS.texture}(currentTexture).assocScanUID = assocScanUID;\n\n %Get associated structure index\n sizeV = size(getScanArray(assocScanNum,planC));\n minc = 1;\n maxr = sizeV(1);\n uniqueSlicesV = 1:sizeV(3);\n if isfield(userOptS.input,'structure')\n strC = {planC{indexS.structures}.structureName};\n if isfield(userOptS.input.structure,'name')\n strName = userOptS.input.structure.name;\n else\n if isfield(userOptS.input.structure,'strNameToLabelMap')\n strName = userOptS.input.structure.strNameToLabelMap.structureName;\n end\n end\n strIdx = getMatchingIndex(strName,strC,'EXACT');\n if ~isempty(strIdx)\n assocStrUID = planC{indexS.structures}(strIdx).strUID;\n planC{indexS.texture}(currentTexture).assocStructUID = assocStrUID;\n mask3M = getStrMask(strIdx,planC);\n [~,maxr,minc,~,~,~] = compute_boundingbox(mask3M);\n uniqueSlicesV = find(sum(sum(mask3M))>0);\n end\n end\n\n % Assign parameters based on category of texture\n planC{indexS.texture}(currentTexture).parameters = ...\n userOptS;\n planC{indexS.texture}(currentTexture).description = algorithm;\n\n % Create Texture Scans\n [xValsV, yValsV] = ...\n getScanXYZVals(planC{indexS.scan}(assocScanNum));\n dx = median(diff(xValsV));\n dy = median(diff(yValsV));\n zV = zVals(uniqueSlicesV);\n regParamsS.horizontalGridInterval = dx;\n regParamsS.verticalGridInterval = dy;\n regParamsS.coord1OFFirstPoint = xVals(minc);\n regParamsS.coord2OFFirstPoint = yVals(maxr);\n regParamsS.zValues = zV;\n regParamsS.sliceThickness = ...\n [planC{indexS.scan}(assocScanNum).scanInfo(uniqueSlicesV).sliceThickness];\n assocTextureUID = planC{indexS.texture}(currentTexture).textureUID;\n\n %Save to planC\n planC = scan2CERR(img3M,outputImgType,'Passed',regParamsS,...\n assocTextureUID,planC);\n\n\n otherwise\n error('Invalid output type '' %s ''.',outType)\n\n\n end\n userOptS.output.(outType) = outputS;\n\nend\n\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Contouring/BABS/processAndImportAIOutput.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18290241542856903}} {"text": "function Script_CECLM_general()\n\naddpath(genpath('../'));\n\n% Replace this with the location of the 300W data location\nif(exist([getenv('USERPROFILE') '/Dropbox/AAM/test data/'], 'file'))\n root_test_data = [getenv('USERPROFILE') '/Dropbox/AAM/test data/']; \nelse\n root_test_data = 'F:\\Dropbox\\AAM\\test data/';\nend\n[images, detections, labels] = Collect_wild_imgs(root_test_data);\n\n%% loading the CE-CLM model and parameters \n[patches, pdm, clmParams, early_term_params] = Load_CECLM_general();\n% Use the multi-hypothesis model, as bounding box tells nothing about\n% orientation\nviews = [0,0,0; 0,-30,0; 0,30,0; 0,0,30; 0,0,-30;];\nviews = views * pi/180; \n\n%% Setup recording\n\nnum_points = numel(pdm.M)/3;\n\nshapes_all = zeros(size(labels,2),size(labels,3), size(labels,1));\nlabels_all = zeros(size(labels,2),size(labels,3), size(labels,1));\nlhoods = zeros(numel(images),1);\nall_lmark_lhoods = zeros(num_points, numel(images));\nall_views_used = zeros(numel(images),1);\n\n% Change if you want to visualize the outputs\nverbose = false;\noutput_img = false;\n\nif(output_img)\n output_root = './ceclm_gen_out/';\n if(~exist(output_root, 'dir'))\n mkdir(output_root);\n end\nend\nif(verbose)\n f = figure;\nend\n\n%% Fitting the model to the provided images\n\ntic\nfor i=1:numel(images)\n\n image = imread(images(i).img);\n image_orig = image;\n \n if(size(image,3) == 3)\n image = rgb2gray(image);\n end \n\n bbox = detections(i,:); \n \n [shape,~,~,lhood,lmark_lhood,view_used] =...\n Fitting_from_bb_multi_hyp(image, [], bbox, pdm, patches, clmParams, views, early_term_params);\n\n all_lmark_lhoods(:,i) = lmark_lhood;\n all_views_used(i) = view_used;\n\n shapes_all(:,:,i) = shape;\n labels_all(:,:,i) = labels(i,:,:);\n\n if(mod(i, 200)==0)\n fprintf('%d done\\n', i );\n end\n\n lhoods(i) = lhood;\n\n if(output_img)\n v_points = sum(squeeze(labels(i,:,:)),2) > 0;\n DrawFaceOnImg(image_orig, shape, sprintf('%s/%s%d.jpg', output_root, 'fit', i), bbox, v_points);\n end\n \n if(verbose)\n v_points = sum(squeeze(labels(i,:,:)),2) > 0;\n DrawFaceOnFig(image_orig, shape, bbox, v_points);\n end\nend\ntoc\n\nexperiment.errors_normed = compute_error(labels_all, shapes_all + 1.0);\nexperiment.lhoods = lhoods;\nexperiment.shapes = shapes_all;\nexperiment.labels = labels_all;\nexperiment.all_lmark_lhoods = all_lmark_lhoods;\nexperiment.all_views_used = all_views_used;\n\nfprintf('Done: mean normed error %.3f median normed error %.4f\\n', ...\n mean(experiment.errors_normed), median(experiment.errors_normed));\n\n%%\noutput_results = 'results/results_ceclm_general.mat';\nsave(output_results, 'experiment');\n \nend\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/experiments_300W/Script_CECLM_general.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3140505449918074, "lm_q1q2_score": 0.18255855697825102}} {"text": "function [output, layerOut] = FeatureTree_obj(visible, para, layer)\n% remove target and cost function nodes if any\nfor i=1:length(layer)\n if strcmpi(layer{i}.name, 'target') || strcmpi(layer{i}.name, 'cross_entropy') || strcmpi(layer{i}.name, 'mse') || strcmpi(layer{i}.name, 'logistic')\n layer{i}.name = 'ignore';\n end\n if i > max(para.out_layer_idx) % we don't compute layers that is after the last output layer\n layer{i}.name = 'ignore';\n end\nend\npara.NET.sentenceMinibatch = 1;\nvisible = visible.ShuffleData(para);\nrandomOrder = 0;\n\noutput = {}; layerOut = {};\nfor blk_i = 1:visible.nBlock\n minibatch = visible.PrepareMinibatch(para.precision, 1, para.NET.batchSize, blk_i,randomOrder);\n nMinibatch = size(minibatch,2);\n \n for utt_i = 1:nMinibatch\n PrintProgress(utt_i, nMinibatch, 100);\n batch_data = GetMinibatch(minibatch, utt_i, para.useGPU);\n \n % Use mode=3 to generate network output only\n if nargout>1\n [~, layerOut{end+1}, output{end+1}] = DNN_Cost10(layer, batch_data, para,3);\n else\n [~, ~, output{end+1}] = DNN_Cost10(layer, batch_data, para,3);\n end\n end\nend\nend", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/tools/FeatureTree_obj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.18248937302468726}} {"text": "function [ds_all, bs_all, targets] = bboxpred_data(name)\n% Collect training data for bounding box prediction.\n% [ds, bs, targets] = bboxpred_data(name)\n%\n% Return values\n% ds_all Predicted bounding boxes (clipped to the image)\n% One cell percomponent\n% bs_all All filter bounding boxes (unclipped)\n% One cell percomponent\n% targets Ground-truth bounding boxes (clipped)\n% One cell percomponent\n%\n% Argument\n% name Object class\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nconf = voc_config();\n\ntry\n load([conf.paths.model_dir name '_bboxdata']);\ncatch\n % load final model for class\n load([conf.paths.model_dir name '_final']);\n % get training data\n pos = pascal_data(model.class, model.year);\n\n numpos = length(pos);\n model.interval = conf.training.interval_fg;\n pixels = model.minsize * model.sbin / 2;\n minsize = prod(pixels);\n nrules = length(model.rules{model.start});\n parb = cell(1,numpos);\n part = cell(1,numpos);\n\n % compute latent filter locations and record target bounding boxes\n parfor i = 1:numpos\n pard{i} = cell(1,nrules);\n parb{i} = cell(1,nrules);\n part{i} = cell(1,nrules);\n fprintf('%s %s: bboxdata: %d/%d\\n', procid(), name, i, numpos);\n bbox = pos(i).boxes;\n % skip small examples\n if (bbox(3)-bbox(1)+1)*(bbox(4)-bbox(2)+1) < minsize\n continue;\n end\n % get example\n im = imreadx(pos(i));\n [im, bbox] = croppos(im, bbox);\n [pyra, model_dp] = gdetect_pos_prepare(im, model, bbox, 0.7);\n [ds, bs] = gdetect_pos(pyra, model_dp, 1, ...\n 1, 0.7, [], 0.5);\n if ~isempty(ds)\n % component index\n c = ds(1,end-1);\n bs = reduceboxes(model, bs);\n ds = clipboxes(im, ds);\n pard{i}{c} = [pard{i}{c}; ds(:,1:end-2)];\n parb{i}{c} = [parb{i}{c}; bs(:,1:end-2)];\n part{i}{c} = [part{i}{c}; bbox];\n end\n end\n ds_all = cell(1,nrules);\n bs_all = cell(1,nrules);\n targets = cell(1,nrules);\n for i = 1:numpos\n for c = 1:nrules\n ds_all{c} = [ds_all{c}; pard{i}{c}];\n bs_all{c} = [bs_all{c}; parb{i}{c}];\n targets{c} = [targets{c}; part{i}{c}];\n end\n end\n save([conf.paths.model_dir name '_bboxdata'], ...\n 'ds_all', 'bs_all', 'targets');\nend\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/bbox_pred/bboxpred_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.182487953207627}} {"text": "function ir = sofa_get_data_fir(sofa,idx)\n%SOFA_GET_DATA_FIR returns a FIR data matrix from a SOFA file or struct\n%\n% Usage: ir = sofa_get_data_fir(sofa,[idx])\n%\n% Input parameters:\n% sofa - impulse response data set (SOFA struct/file)\n% idx - index of the single impulse responses that should be returned.\n% idx could be a single value, then only one impulse response\n% will be returned, or it can be a vector then all impulse\n% responses for the corresponding index positions will be\n% returned (default: return all impulse responses)\n%\n% Output parameters:\n% ir - impulse response (M,2,N), where\n% M ... number of impulse responses\n% N ... samples\n%\n% SOFA_GET_DATA_FIR(sofa,idx) returns impulse response of the given\n% SOFA file or struct, specified by idx. If no idx is specified all data\n% contained in sofa is returned.\n% For the struct the SOFA file has to loaded before with SOFAload().\n% For a description of the SOFA file format see: https://sofaconventions.org\n%\n% See also: sofa_get_data_fire, sofa_get_header, get_ir, SOFAload\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 1;\nnargmax = 2;\nnarginchk(nargmin,nargmax)\nif nargin==nargmax-1\n idx = [];\nelse\n isargvector(idx);\nend\n\n\n%% ===== Computation ====================================================\nif length(idx)==0\n if sofa_is_file(sofa)\n sofa = SOFAload(sofa);\n end\n ir = sofa.Data.IR;\nelse\n header = sofa_get_header(sofa);\n if sofa_is_file(sofa)\n ir = zeros(length(idx),2,header.API.N);\n for ii=1:length(idx)\n tmp = SOFAload(sofa,[idx(ii) 1]);\n ir(ii,:,:) = tmp.Data.IR;\n end\n else\n ir = sofa.Data.IR(idx,:,:);\n end\nend\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_ir/sofa_get_data_fir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.18231697114817394}} {"text": "function [inside] = ft_inside_vol(pos, vol)\n\n% FT_INSIDE_VOL locates dipole locations inside/outside the source\n% compartment of a volume conductor model.\n%\n% [inside] = ft_inside_vol(pos, vol, ...)\n%\n% where the input should be\n% pos Nx3 matrix with dipole positions\n% vol structure with volume conductor model\n% and the output is\n% inside list of dipoles inside the brain compartment\n% (1=inside, 0=outisde)\n%\n% Additional optional input arguments should be given in key value pairs\n% and can include\n% \n\n% Copyright (C) 2003-2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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: ft_inside_vol.m 2885 2011-02-16 09:41:58Z roboos $\n\n% determine the type of volume conduction model\nswitch ft_voltype(vol)\n\n % single-sphere or multiple concentric spheres\n case {'singlesphere' 'concentric'}\n if ~isfield(vol, 'source')\n % locate the innermost compartment and remember it\n [dum, vol.source] = min(vol.r);\n end\n if isfield(vol, 'o')\n % shift dipole positions toward origin of sphere\n tmp = pos - repmat(vol.o, size(pos,1), 1);\n else\n tmp = pos;\n end\n distance = sqrt(sum(tmp.^2, 2))-vol.r(vol.source);\n % positive if outside, negative if inside\n inside = distance<0;\n\n % multi-sphere volume conductor model\n case 'multisphere'\n\n % nspheres = size(vol.r,1);\n % ndipoles = size(pos,1);\n % inside = zeros(ndipoles,1);\n % for sph=1:nspheres\n % for dip=1:ndipoles\n % if inside(dip)\n % % the dipole has already been detected in one of the other spheres\n % continue\n % end\n % inside(dip) = (norm(pos(dip,:) - vol.o(sph,:)) <= vol.r(sph));\n % end\n % end\n % outside = find(inside==0);\n % inside = find(inside==1);\n\n % this is a much faster implementation\n nspheres = size(vol.r,1);\n ndipoles = size(pos,1);\n inside = zeros(ndipoles,1);\n for sph=1:nspheres\n % temporary shift dipole positions toward origin\n if isfield(vol, 'o')\n tmp = pos - repmat(vol.o(sph,:), [ndipoles 1]);\n else\n tmp = pos;\n end\n flag = (sqrt(sum(tmp.^2,2)) <= vol.r(sph));\n inside = inside + flag;\n end\n inside = inside>0;\n\n % realistic BEM volume conductor model\n case {'bem', 'dipoli', 'bemcp', 'asa', 'avo', 'nolte', 'neuromag'}\n if ~isfield(vol, 'source')\n % locate the innermost compartment and remember it\n vol.source = find_innermost_boundary(vol.bnd);\n end\n % use the specified source compartment\n pnt = vol.bnd(vol.source).pnt;\n tri = vol.bnd(vol.source).tri;\n % determine the dipole positions that are inside the brain compartment\n inside = bounding_mesh(pos, pnt, tri);\n\n % unrecognized volume conductor model\n otherwise\n error('unrecognized volume conductor model');\nend\n\n% ensure that these are column vectors\ninside(find(isnan(inside(:)))) = 0;\ninside = logical(inside(:));\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fieldtrip_partial/inverse/private/ft_inside_vol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.18230959561525392}} {"text": "% Jiao Xianjun (putaoshu@msn.com; putaoshu@gmail.com)\n% multi_rtl_sdr_split_scanner.m\n% Frequency band scanning via multiple rtl-sdr dongles. Each dongle for each sub-band to speedup!\n% A script of project: https://github.com/JiaoXianjun/multi-rtl-sdr-calibration\n\n% Assume that you have installed rtl-sdr\n% (http://sdr.osmocom.org/trac/wiki/rtl-sdr) and have those native utilities run correctly already.\n\n% For example, you have multiple dongles, please run multiple rtl_tcp in multiple shell respectively as:\n% rtl_tcp -p 1234 -d 0\n% rtl_tcp -p 1235 -d 1\n% rtl_tcp -p 1236 -d 2\n% ...\n\n% Then run this script in MATLAB.\n\n% ATTENTION! In some computer, every time before you run this script, maybe you need to terminate multiple rtl_tcp and re-launch them again.\n% ATTENTION! Please reduce number of inspected points by reducing frequency range or increasing step size, if your computer hasn't enough memory installed. Because all signlas are stored firstly before processing.\n\n% Change following parameters as you need:\n\n% Number of dongles you have connected to your computer\nnum_dongle = 1; % more dongles, much faster.\n\n% Beginning of the band you are interested in\nstart_freq = 502e6; % for test\n% start_freq = 935e6; % Beginning of Primary GSM-900 Band downlink\n% start_freq = (1575.42-15)*1e6; % GPS L1\n% start_freq = (1207.14-30)*1e6; % COMPASS B2I\n% start_freq = (1561.098-30)*1e6; % COMPASS B1I\n% start_freq = 1.14e9; % Beginning of GNSS(GPS/GLONASS/COMPASS/Galileo) Band\n\n% End of the band you are interested in\nend_freq = 702e6; % for test\n% end_freq = 960e6; % End of Primary GSM-900 Band downlink\n% end_freq = (1575.42+30)*1e6; % GPS L1\n% end_freq = (1207.14+30)*1e6; % COMPASS B2I\n% end_freq = (1561.098+30)*1e6; % COMPASS B1I\n% end_freq = 1.63e9; % Beginning of GNSS(GPS/GLONASS/COMPASS/Galileo) Band\n\nfreq_step = 0.5e6; % less step, higher resolution, narrower FIR bandwidth, slower speed\n\nobserve_time = 0.2; % observation time at each frequency point. ensure it can capture your signal!\n\nRBW = freq_step; % Resolution Bandwidth each time we inspect\n\ngain = 20; % If this is larger than 0, the fixed gain will be set to dongles\n\n% use high sampling rate and FIR to improve estimation accuracy\nsample_rate = 2.048e6; % sampling rate of dongles\n\ncoef_order = (2^(ceil(log2(sample_rate/RBW))))-1;\ncoef_order = min(coef_order, 127);\ncoef_order = max(coef_order, 31);\ncoef = fir1(coef_order, RBW/sample_rate);\n% freqz(coef, 1, 1024);\n\nnum_samples = observe_time*sample_rate;\n\nclf;\nclose all;\n\n% construct freq set for each dongle\nfreq_orig = start_freq:freq_step:end_freq;\nnum_freq_per_sub_band = ceil(length(freq_orig)/num_dongle);\nnum_pad = num_freq_per_sub_band*num_dongle - length(freq_orig);\nfreq = [freq_orig freq_orig(end)+(1:num_pad).*freq_step];\nfreq = vec2mat(freq, num_freq_per_sub_band);\n\nreal_count = zeros(1, num_dongle);\ns_all = uint8( zeros(2*num_samples, num_freq_per_sub_band*num_dongle) );\ndecimate_ratio = floor(sample_rate/(2*RBW));\n\n% check if previous tce objects existed. if so clear them\nif ~isempty(who('tcp_obj'))\n for i=1:length(tcp_obj)\n fclose(tcp_obj{i});\n delete(tcp_obj{i});\n end\n clear tcp_obj;\nend\n\n% construct tcp objects\ntcp_obj = cell(1, num_dongle);\nfor i=1:num_dongle\n tcp_obj{i} = tcpip('127.0.0.1', 1233+i); % for dongle i\nend\n\n% set some parameters to tcp objects, and open them.\nfor i=1:num_dongle\n set(tcp_obj{i}, 'InputBufferSize', 8*2*num_samples);\n set(tcp_obj{i}, 'Timeout', 60);\nend\nfor i=1:num_dongle\n fopen(tcp_obj{i});\nend\n\n% set gain\nfor i=1:num_dongle\n set_gain_tcp(tcp_obj{i}, gain*10); %be careful, in rtl_sdr the 10x is done inside C program, but in rtl_tcp the 10x has to be done here.\nend\n\n% set sampling rate\nfor i=1:num_dongle\n set_rate_tcp(tcp_obj{i}, sample_rate);\nend\n\n% set different start freq to different dongle\nfor i=1:num_dongle\n set_freq_tcp(tcp_obj{i}, freq(i,1));\nend\n\n% read and discard to flush\nfor i=1:num_dongle\n fread(tcp_obj{i}, 8*2*num_samples, 'uint8');\nend\n\n% capture samples of all frequencies firstly!\ntic;\nfor freq_idx = 1:num_freq_per_sub_band\n while 1 % read data at current frequency until success\n for i=1:num_dongle\n set_freq_tcp(tcp_obj{i}, freq(i, freq_idx)); % set different frequency to different dongle\n end\n for i=1:num_dongle\n [s_all(:, freq_idx + (i-1)*num_freq_per_sub_band), real_count(i)] = fread(tcp_obj{i}, 2*num_samples, 'uint8'); % gather data from different dongles to s_all\n end\n\n if sum(real_count-(2*num_samples)) ~= 0\n disp(num2str([idx 2*num_samples, real_count]));\n else\n break;\n end\n end\nend\ne = toc;\nideal_time_cost = observe_time*num_freq_per_sub_band;\n\n% close TCP\nfor i=1:num_dongle\n fclose(tcp_obj{i});\nend\nfor i=1:num_dongle\n delete(tcp_obj{i});\nend\nclear tcp_obj;\n\ndisp('Scanning done!');\ndisp(['actual time cost ' num2str(e) ' ideal cost ' num2str(ideal_time_cost) ' efficiency(ideal/actual) ' num2str(ideal_time_cost/e)]);\ndisp(' ');\ndisp('Begin process ...');\n\n% generate power spectrum\ntic;\nr = raw2iq( double( s_all ) ); % remove DC. complex number constructed.\nr_flt = filter(coef, 1, r);% filter target band out\npower_spectrum = mean(abs(r_flt(1:decimate_ratio:end, :)).^2, 1);% get averaged power\ne1 = toc;\ndisp(['time cost ' num2str(e1) ' scan/process ' num2str(e/e1)]);\ndisp(['total time cost ' num2str(e1+e)]);\n\n% plot power spectrum (converted to dB)\nfreq_linear = freq';\nfreq_linear = freq_linear(:)';\nfigure;\nformat_string = {'b.-', 'r.-', 'k.-', 'm.-'};\nfor i=1:num_dongle\n plot(freq(i,:).*1e-6, 10.*log10(power_spectrum( (i-1)*num_freq_per_sub_band+1: i*num_freq_per_sub_band)), format_string{i}); hold on;\nend\n\nlegend_string = cell(1, num_dongle);\nfor i=1:num_dongle\n legend_string{i} = ['dongle ' num2str(i)];\nend\nlegend(legend_string);\n\nfilename = ['split_scan_' num2str(start_freq) '_' num2str(end_freq) '_gain' num2str(gain) '_' num2str(num_dongle) 'dongles.mat'];\nsave(filename, 'power_spectrum', 'start_freq', 'end_freq', 'freq_step', 'observe_time', 'RBW', 'gain', 'sample_rate', 'coef', 'freq');\n", "meta": {"author": "JiaoXianjun", "repo": "rtl-sdr-LTE", "sha": "037a25f164f17b1a1d82e2eb02285550f50af9b9", "save_path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE", "path": "github-repos/MATLAB/JiaoXianjun-rtl-sdr-LTE/rtl-sdr-LTE-037a25f164f17b1a1d82e2eb02285550f50af9b9/matlab/multi_rtl_sdr_split_scanner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.18229405101433052}} {"text": "function fg = dtiXformFibersToMrVista(handles, fgNum, scale)\n%\n% fg = dtiXformFibersToMrVista(handles, [fiberGroupNum], [scale])\n%\n% Uses the xformVAnatToAcpc (see dtiXformVanatCompute) to convert the specified\n% fiber group (ac-pc coords) to mrVista vAnatomy coords.\n%\n% HISTORY:\n% 2004.05.03 RFD (bob@white.stanford.edu) wrote it.\n\nif(~exist('fgNum','var') | isempty(fgNum))\n fgNum = handles.curFiberGroup;\nend\nif(~exist('scale','var') | isempty(scale))\n scale = [1 1 1];\nend\nif(length(scale(:))<3)\n scale = repmat(scale(1),1,3);\nend\n\nfg = handles.fiberGroups(fgNum);\nxform = diag([scale 1])*inv(handles.xformVAnatToAcpc);\nfg = dtiXformFiberCoords(fg, xform);\nif(~isempty(fg.seeds))\n fg.seeds = mrAnatXformCoords(xform, fg.seeds);\nend\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/xform/dtiXformFibersToMrVista.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18227753049014572}} {"text": "function N = spm_ecat2nifti(fname,opts)\n% Import ECAT 7 images from CTI PET scanners\n% FORMAT N = spm_ecat2nifti(fname)\n% fname - name of ECAT file\n% opts - options structure\n%\n% N - NIfTI object (written in current directory)\n%__________________________________________________________________________\n% Copyright (C) 2005-2015 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner & Roger Gunn\n% $Id: spm_ecat2nifti.m 6315 2015-01-23 17:09:06Z guillaume $\n\n\nif nargin==1\n opts = struct('ext',spm_file_ext);\nelse\n if opts.ext(1) ~= '.', opts.ext = ['.' opts.ext]; end\nend\n\nfp = fopen(fname,'r','ieee-be');\nif fp == -1,\n error(['Can''t open \"' fname '\".']);\nend\n\nmh = ECAT7_mheader(fp);\nif ~strcmp(mh.MAGIC_NUMBER,'MATRIX70v') &&...\n ~strcmp(mh.MAGIC_NUMBER,'MATRIX71v') &&...\n ~strcmp(mh.MAGIC_NUMBER,'MATRIX72v')\n fclose(fp);\n error(['\"' fname '\" does not appear to be ECAT 7 format.']);\nend\n\nif mh.FILE_TYPE ~= 7\n fclose(fp);\n error(['\"' fname '\" does not appear to be an image file.']);\nend\n\nlist = s7_matlist(fp);\nmatches = find((list(:,4) == 1) | (list(:,4) == 2));\nllist = list(matches,:);\n\nfor i=1:size(llist,1)\n sh(i) = ECAT7_sheader(fp,llist(i,2));\nend\nfclose(fp);\n\nfor i=1:size(llist,1)\n dim = [sh(i).X_DIMENSION sh(i).Y_DIMENSION sh(i).Z_DIMENSION];\n dtype = [4 1];\n off = 512*llist(i,2);\n scale = sh(i).SCALE_FACTOR*mh.ECAT_CALIBRATION_FACTOR;\n inter = 0;\n dati = file_array(fname,dim,dtype,off,scale,inter);\n\n dircos = diag([-1 -1 -1]);\n step = ([sh(i).X_PIXEL_SIZE sh(i).Y_PIXEL_SIZE sh(i).Z_PIXEL_SIZE]*10);\n start = -(dim(1:3)'/2).*step';\n mat = [[dircos*diag(step) dircos*start] ; [0 0 0 1]];\n\n matnum = sprintf('%.8x',list(i,1));\n nam = spm_file(fname,'basename');\n fnameo = fullfile(pwd,[nam '_' matnum opts.ext]);\n dato = file_array(fnameo,dim,[4 spm_platform('bigend')],0,scale,inter);\n\n N = nifti;\n N.dat = dato;\n N.mat = mat;\n N.mat0 = mat;\n N.mat_intent = 'aligned';\n N.mat0_intent = 'scanner';\n N.descrip = sh(i).ANNOTATION;\n N.timing = struct('toffset',sh(i).FRAME_START_TIME/1000,'tspace',sh(i).FRAME_DURATION/1000);\n create(N);\n for j=1:dim(3)\n N.dat(:,:,j) = dati(:,:,j);\n end\n N.extras = struct('mh',mh,'sh',sh(i));\nend\n\n\n%==========================================================================\n% function list = s7_matlist(fp)\n%==========================================================================\nfunction list = s7_matlist(fp)\n%S7_MATLIST List the available matrixes in an ECAT 7 file.\n% LIST = S7_MATLIST(FP) lists the available matrixes\n% in the file specified by FP.\n%\n% Columns in LIST:\n% 1 - Matrix identifier.\n% 2 - Matrix subheader record number\n% 3 - Last record number of matrix data block.\n% 4 - Matrix status:\n% 1 - exists - rw\n% 2 - exists - ro\n% 3 - matrix deleted\n%\n\n% I believe fp should be opened with:\n% fp = fopen(filename,'r','ieee-be');\n\nfseek(fp,512,'bof');\nblock = fread(fp,128,'int');\nif size(block,1) ~= 128\n list = [];\n return;\nend\nblock = reshape(block,4,32);\nlist = [];\nwhile block(2,1) ~= 2\n if block(1,1)+block(4,1) ~= 31\n list = []; return;\n end\n list = [list block(:,2:32)];\n\n fseek(fp,512*(block(2,1)-1),'bof');\n block = fread(fp,128,'int');\n if size(block,1) ~= 128, list = []; return; end\n block = reshape(block,4,32);\nend\nlist = [list block(:,2:(block(4,1)+1))];\nlist = list';\n\n%==========================================================================\n% function SHEADER=ECAT7_sheader(fid,record)\n%==========================================================================\nfunction SHEADER=ECAT7_sheader(fid,record)\n%\n% Sub header read routine for ECAT 7 image files\n%\n% Roger Gunn, 260298\noff = (record-1)*512;\nstatus = fseek(fid, off,'bof');\ndata_type = fread(fid,1,'uint16',0);\nnum_dimensions = fread(fid,1,'uint16',0);\nx_dimension = fread(fid,1,'uint16',0);\ny_dimension = fread(fid,1,'uint16',0);\nz_dimension = fread(fid,1,'uint16',0);\nx_offset = fread(fid,1,'float32',0);\ny_offset = fread(fid,1,'float32',0);\nz_offset = fread(fid,1,'float32',0);\nrecon_zoom = fread(fid,1,'float32',0);\nscale_factor = fread(fid,1,'float32',0);\nimage_min = fread(fid,1,'int16',0);\nimage_max = fread(fid,1,'int16',0);\nx_pixel_size = fread(fid,1,'float32',0);\ny_pixel_size = fread(fid,1,'float32',0);\nz_pixel_size = fread(fid,1,'float32',0);\nframe_duration = fread(fid,1,'uint32',0);\nframe_start_time = fread(fid,1,'uint32',0);\nfilter_code = fread(fid,1,'uint16',0);\nx_resolution = fread(fid,1,'float32',0);\ny_resolution = fread(fid,1,'float32',0);\nz_resolution = fread(fid,1,'float32',0);\nnum_r_elements = fread(fid,1,'float32',0);\nnum_angles = fread(fid,1,'float32',0);\nz_rotation_angle = fread(fid,1,'float32',0);\ndecay_corr_fctr = fread(fid,1,'float32',0);\ncorrections_applied = fread(fid,1,'uint32',0);\ngate_duration = fread(fid,1,'uint32',0);\nr_wave_offset = fread(fid,1,'uint32',0);\nnum_accepted_beats = fread(fid,1,'uint32',0);\nfilter_cutoff_frequency = fread(fid,1,'float32',0);\nfilter_resolution = fread(fid,1,'float32',0);\nfilter_ramp_slope = fread(fid,1,'float32',0);\nfilter_order = fread(fid,1,'uint16',0);\nfilter_scatter_fraction = fread(fid,1,'float32',0);\nfilter_scatter_slope = fread(fid,1,'float32',0);\nannotation = fread(fid,40,'char',0);\nmt_1_1 = fread(fid,1,'float32',0);\nmt_1_2 = fread(fid,1,'float32',0);\nmt_1_3 = fread(fid,1,'float32',0);\nmt_2_1 = fread(fid,1,'float32',0);\nmt_2_2 = fread(fid,1,'float32',0);\nmt_2_3 = fread(fid,1,'float32',0);\nmt_3_1 = fread(fid,1,'float32',0);\nmt_3_2 = fread(fid,1,'float32',0);\nmt_3_3 = fread(fid,1,'float32',0);\nrfilter_cutoff = fread(fid,1,'float32',0);\nrfilter_resolution = fread(fid,1,'float32',0);\nrfilter_code = fread(fid,1,'uint16',0);\nrfilter_order = fread(fid,1,'uint16',0);\nzfilter_cutoff = fread(fid,1,'float32',0);\nzfilter_resolution = fread(fid,1,'float32',0);\nzfilter_code = fread(fid,1,'uint16',0);\nzfilter_order = fread(fid,1,'uint16',0);\nmt_4_1 = fread(fid,1,'float32',0);\nmt_4_2 = fread(fid,1,'float32',0);\nmt_4_3 = fread(fid,1,'float32',0);\nscatter_type = fread(fid,1,'uint16',0);\nrecon_type = fread(fid,1,'uint16',0);\nrecon_views = fread(fid,1,'uint16',0);\nfill = fread(fid,1,'uint16',0);\nannotation = deblank(char(annotation.*(annotation>0))');\n\nSHEADER = struct('DATA_TYPE', data_type, ...\n 'NUM_DIMENSIONS', num_dimensions, ...\n 'X_DIMENSION', x_dimension, ...\n 'Y_DIMENSION', y_dimension, ...\n 'Z_DIMENSION', z_dimension, ...\n 'X_OFFSET', x_offset, ...\n 'Y_OFFSET', y_offset, ...\n 'Z_OFFSET', z_offset, ...\n 'RECON_ZOOM', recon_zoom, ...\n 'SCALE_FACTOR', scale_factor, ...\n 'IMAGE_MIN', image_min, ...\n 'IMAGE_MAX', image_max, ...\n 'X_PIXEL_SIZE', x_pixel_size, ...\n 'Y_PIXEL_SIZE', y_pixel_size, ...\n 'Z_PIXEL_SIZE', z_pixel_size, ...\n 'FRAME_DURATION', frame_duration, ...\n 'FRAME_START_TIME', frame_start_time, ...\n 'FILTER_CODE', filter_code, ...\n 'X_RESOLUTION', x_resolution, ...\n 'Y_RESOLUTION', y_resolution, ...\n 'Z_RESOLUTION', z_resolution, ...\n 'NUM_R_ELEMENTS', num_r_elements, ...\n 'NUM_ANGLES', num_angles, ...\n 'Z_ROTATION_ANGLE', z_rotation_angle, ...\n 'DECAY_CORR_FCTR', decay_corr_fctr, ...\n 'CORRECTIONS_APPLIED', corrections_applied, ...\n 'GATE_DURATION', gate_duration, ...\n 'R_WAVE_OFFSET', r_wave_offset, ...\n 'NUM_ACCEPTED_BEATS', num_accepted_beats, ...\n 'FILTER_CUTOFF_FREQUENCY', filter_cutoff_frequency, ...\n 'FILTER_RESOLUTION', filter_resolution, ...\n 'FILTER_RAMP_SLOPE', filter_ramp_slope, ...\n 'FILTER_ORDER', filter_order, ...\n 'FILTER_SCATTER_CORRECTION', filter_scatter_fraction, ...\n 'FILTER_SCATTER_SLOPE', filter_scatter_slope, ...\n 'ANNOTATION', annotation, ...\n 'MT_1_1', mt_1_1, ...\n 'MT_1_2', mt_1_2, ...\n 'MT_1_3', mt_1_3, ...\n 'MT_2_1', mt_2_1, ...\n 'MT_2_2', mt_2_2, ...\n 'MT_2_3', mt_2_3, ...\n 'MT_3_1', mt_3_1, ...\n 'MT_3_2', mt_3_2, ...\n 'MT_3_3', mt_3_3, ...\n 'RFILTER_CUTOFF', rfilter_cutoff, ...\n 'RFILTER_RESOLUTION', rfilter_resolution, ...\n 'RFILTER_CODE', rfilter_code, ...\n 'RFILTER_ORDER', rfilter_order, ...\n 'ZFILTER_CUTOFF', zfilter_cutoff, ...\n 'ZFILTER_RESOLUTION', zfilter_resolution, ...\n 'ZFILTER_CODE', zfilter_code, ...\n 'ZFILTER_ORDER', zfilter_order, ...\n 'MT_4_1', mt_4_1, ...\n 'MT_4_2', mt_4_2, ...\n 'MT_4_3', mt_4_3, ...\n 'SCATTER_TYPE', scatter_type, ...\n 'RECON_TYPE', recon_type, ...\n 'RECON_VIEWS', recon_views, ...\n 'FILL', fill);\n\n%==========================================================================\n% function [MHEADER]=ECAT7_mheader(fid)\n%==========================================================================\nfunction [MHEADER]=ECAT7_mheader(fid)\n%\n% Main header read routine for ECAT 7 image files\n%\n% Roger Gunn, 260298\n\nstatus = fseek(fid, 0,'bof');\nmagic_number = fread(fid,14,'char',0);\noriginal_file_name = fread(fid,32,'char',0);\nsw_version = fread(fid,1,'uint16',0);\nsystem_type = fread(fid,1,'uint16',0);\nfile_type = fread(fid,1,'uint16',0);\nserial_number = fread(fid,10,'char',0);\nscan_start_time = fread(fid,1,'uint32',0);\nisotope_name = fread(fid,8,'char',0);\nisotope_halflife = fread(fid,1,'float32',0);\nradiopharmaceutical = fread(fid,32,'char',0);\ngantry_tilt = fread(fid,1,'float32',0);\ngantry_rotation = fread(fid,1,'float32',0);\nbed_elevation = fread(fid,1,'float32',0);\nintrinsic_tilt = fread(fid,1,'float32',0);\nwobble_speed = fread(fid,1,'uint16',0);\ntransm_source_type = fread(fid,1,'uint16',0);\ndistance_scanned = fread(fid,1,'float32',0);\ntransaxial_fov = fread(fid,1,'float32',0);\nangular_compression = fread(fid,1,'uint16',0);\ncoin_samp_mode = fread(fid,1,'uint16',0);\naxial_samp_mode = fread(fid,1,'uint16',0);\necat_calibration_factor = fread(fid,1,'float32',0);\ncalibration_units = fread(fid,1,'uint16',0);\ncalibration_units_type = fread(fid,1,'uint16',0);\ncompression_code = fread(fid,1,'uint16',0);\nstudy_type = fread(fid,12,'char',0);\npatient_id = fread(fid,16,'char',0);\npatient_name = fread(fid,32,'char',0);\npatient_sex = fread(fid,1,'char',0);\npatient_dexterity = fread(fid,1,'char',0);\npatient_age = fread(fid,1,'float32',0);\npatient_height = fread(fid,1,'float32',0);\npatient_weight = fread(fid,1,'float32',0);\npatient_birth_date = fread(fid,1,'uint32',0);\nphysician_name = fread(fid,32,'char',0);\noperator_name = fread(fid,32,'char',0);\nstudy_description = fread(fid,32,'char',0);\nacquisition_type = fread(fid,1,'uint16',0);\npatient_orientation = fread(fid,1,'uint16',0);\nfacility_name = fread(fid,20,'char',0);\nnum_planes = fread(fid,1,'uint16',0);\nnum_frames = fread(fid,1,'uint16',0);\nnum_gates = fread(fid,1,'uint16',0);\nnum_bed_pos = fread(fid,1,'uint16',0);\ninit_bed_position = fread(fid,1,'float32',0);\nbed_position = zeros(15,1);\nfor bed=1:15\n tmp = fread(fid,1,'float32',0);\n if ~isempty(tmp), bed_position(bed) = tmp; end\nend\nplane_separation = fread(fid,1,'float32',0);\nlwr_sctr_thres = fread(fid,1,'uint16',0);\nlwr_true_thres = fread(fid,1,'uint16',0);\nupr_true_thres = fread(fid,1,'uint16',0);\nuser_process_code = fread(fid,10,'char',0);\nacquisition_mode = fread(fid,1,'uint16',0);\nbin_size = fread(fid,1,'float32',0);\nbranching_fraction = fread(fid,1,'float32',0);\ndose_start_time = fread(fid,1,'uint32',0);\ndosage = fread(fid,1,'float32',0);\nwell_counter_corr_factor = fread(fid,1,'float32',0);\ndata_units = fread(fid,32,'char',0);\nsepta_state = fread(fid,1,'uint16',0);\nfill = fread(fid,1,'uint16',0);\n \nmagic_number = deblank(char(magic_number.*(magic_number>32))');\noriginal_file_name = deblank(char(original_file_name.*(original_file_name>0))');\nserial_number = deblank(char(serial_number.*(serial_number>0))');\nisotope_name = deblank(char(isotope_name.*(isotope_name>0))');\nradiopharmaceutical = deblank(char(radiopharmaceutical.*(radiopharmaceutical>0))');\nstudy_type = deblank(char(study_type.*(study_type>0))');\npatient_id = deblank(char(patient_id.*(patient_id>0))');\npatient_name = deblank(char(patient_name.*(patient_name>0))');\npatient_sex = deblank(char(patient_sex.*(patient_sex>0))');\npatient_dexterity = deblank(char(patient_dexterity.*(patient_dexterity>0))');\nphysician_name = deblank(char(physician_name.*(physician_name>0))');\noperator_name = deblank(char(operator_name.*(operator_name>0))');\nstudy_description = deblank(char(study_description.*(study_description>0))');\nfacility_name = deblank(char(facility_name.*(facility_name>0))');\nuser_process_code = deblank(char(user_process_code.*(user_process_code>0))');\ndata_units = deblank(char(data_units.*(data_units>0))');\n\nMHEADER = struct('MAGIC_NUMBER', magic_number, ...\n 'ORIGINAL_FILE_NAME', original_file_name, ...\n 'SW_VERSION', sw_version, ...\n 'SYSTEM_TYPE', system_type, ...\n 'FILE_TYPE', file_type, ...\n 'SERIAL_NUMBER', serial_number, ...\n 'SCAN_START_TIME', scan_start_time, ...\n 'ISOTOPE_NAME', isotope_name, ...\n 'ISOTOPE_HALFLIFE', isotope_halflife, ...\n 'RADIOPHARMACEUTICAL', radiopharmaceutical, ... \n 'GANTRY_TILT', gantry_tilt, ...\n 'GANTRY_ROTATION', gantry_rotation, ... \n 'BED_ELEVATION', bed_elevation, ...\n 'INTRINSIC_TILT', intrinsic_tilt, ... \n 'WOBBLE_SPEED', wobble_speed, ...\n 'TRANSM_SOURCE_TYPE', transm_source_type, ...\n 'DISTANCE_SCANNED', distance_scanned, ...\n 'TRANSAXIAL_FOV', transaxial_fov, ...\n 'ANGULAR_COMPRESSION', angular_compression, ... \n 'COIN_SAMP_MODE', coin_samp_mode, ...\n 'AXIAL_SAMP_MODE', axial_samp_mode, ...\n 'ECAT_CALIBRATION_FACTOR', ecat_calibration_factor, ...\n 'CALIBRATION_UNITS', calibration_units, ...\n 'CALIBRATION_UNITS_TYPE', calibration_units_type, ...\n 'COMPRESSION_CODE', compression_code, ...\n 'STUDY_TYPE', study_type, ...\n 'PATIENT_ID', patient_id, ...\n 'PATIENT_NAME', patient_name, ...\n 'PATIENT_SEX', patient_sex, ...\n 'PATIENT_DEXTERITY', patient_dexterity, ...\n 'PATIENT_AGE', patient_age, ...\n 'PATIENT_HEIGHT', patient_height, ...\n 'PATIENT_WEIGHT', patient_weight, ...\n 'PATIENT_BIRTH_DATE', patient_birth_date, ...\n 'PHYSICIAN_NAME', physician_name, ...\n 'OPERATOR_NAME', operator_name, ...\n 'STUDY_DESCRIPTION', study_description, ...\n 'ACQUISITION_TYPE', acquisition_type, ...\n 'PATIENT_ORIENTATION', patient_orientation, ...\n 'FACILITY_NAME', facility_name, ...\n 'NUM_PLANES', num_planes, ...\n 'NUM_FRAMES', num_frames, ...\n 'NUM_GATES', num_gates, ...\n 'NUM_BED_POS', num_bed_pos, ...\n 'INIT_BED_POSITION', init_bed_position, ...\n 'BED_POSITION', bed_position, ...\n 'PLANE_SEPARATION', plane_separation, ...\n 'LWR_SCTR_THRES', lwr_sctr_thres, ...\n 'LWR_TRUE_THRES', lwr_true_thres, ...\n 'UPR_TRUE_THRES', upr_true_thres, ...\n 'USER_PROCESS_CODE', user_process_code, ...\n 'ACQUISITION_MODE', acquisition_mode, ...\n 'BIN_SIZE', bin_size, ...\n 'BRANCHING_FRACTION', branching_fraction, ...\n 'DOSE_START_TIME', dose_start_time, ...\n 'DOSAGE', dosage, ...\n 'WELL_COUNTER_CORR_FACTOR', well_counter_corr_factor, ...\n 'DATA_UNITS', data_units, ...\n 'SEPTA_STATE', septa_state, ...\n 'FILL', fill);\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_ecat2nifti.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.18210059915324742}} {"text": "function sourceLoc = dba_anatmodel(ind, sScout, CortexMat, srcType)\n% \n% Compute sources locations for deep structures\n% \n% Yohan Attal - HM-TC project 2013\n\ndisp = 0;\n\nswitch srcType\n case 'surf' \n sourceLoc = CortexMat.Vertices(ind,:);\n \n case 'vol'\n [ind_s, I_ind] = sort(ind);\n vertTmp = CortexMat.Vertices(sScout.Vertices,:); \n tessTmp.Vertices = vertTmp(I_ind,:);\n iFaces = sum(ismember(CortexMat.Faces, ind_s),2)==3;\n tessTmp.Faces = CortexMat.Faces(iFaces,:);\n for iv=1:numel(tessTmp.Faces)\n tessTmp.Faces(iv) = find(ind_s==tessTmp.Faces(iv));\n end\n sourceLoc = dba_vol_grids(tessTmp);\nend\nif disp && isequal(srcType,'vol')\n figure('color','w'); hold on; pp = patch(tessTmp);\n set(pp, 'FaceColor', [0 0 1] , 'FaceAlpha', .5, 'EdgeAlpha', 0)\n plot3(sourceLoc(:,1), sourceLoc(:,2),sourceLoc(:,3),'ro')\nend\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/external/dba/dba_anatmodel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18205592753851138}} {"text": "function TestEnhanceNet()\naddpath('local');\n\ndnn_files{1} = 'nnet/EnhanceRegression.noCMN.DeltaByEqn.MbSize40.U28539.771-LSTM-2048-771.L2_3E-4.LR_3E-3/nnet.itr37.LR1E-5.CV2453.828.mat';\ndnn_files{2} = 'nnet/EnhanceRegression.noCMN.DeltaByEqn.MbSize20.U28539.771-LSTM-2048-771.L2_3E-4.LR_1E-4/nnet.itr62.LR4.97E-8.CV2439.245.mat';\ndnn_files{3} = 'nnet/EnhanceGaussian.noCMN.init1.expDecay.Decay0.999.DeltaByEqn.MbSize40.U28539.771-LSTM-2048-771.L2_0.LR_3E-3/nnet.itr26.LR3.62E-5.CV756.273.mat';\nIsMaskNet = [0 0 0];\n\ntestset = 2;\nT60 = [0.01 0.3 0.6];\nnoise = {'buccaneer2', 'pink', 'm109', 'hfchannel', 'factory2', 'factory1', 'destroyerops', 'babble', 'volvo', 'leopard', 'buccaneer1', 'destroyerengine', 'f16', 'machinegun', 'white'};\n% noise = {'f16', 'machinegun', 'white'};\nSNR = [10 0 -10];\nDEBUG = 0;\nmeasures = {'PESQ', 'FWSEQ', 'CD', 'IS', 'LLR', 'WSS'};\nuseGPU = 0;\n\nfor t60_i = 2%:length(T60)\n for n_i = 12%:length(noise)\n for s_i = 3%:length(SNR)\n TestEnhanceNetByCategory(dnn_files, testset, T60(t60_i), noise{n_i}, SNR(s_i), IsMaskNet, measures, useGPU, DEBUG)\n end\n end\nend\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/enhancement/TestEnhanceNet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.181979708129701}} {"text": "% TEST_CNNSKETCH2IMAGERETRIEVAL Code to evaluate (not train) the methods presented in the paper:\n% F. Radenovic, G. Tolias, O. Chum, Deep Shape Matching, ECCV 2018\n%\n% Authors: F. Radenovic, G. Tolias, O. Chum. 2018. \n\nclear;\n\n%---------------------------------------------------------------------\n% Set data folder and testing parameters\n%---------------------------------------------------------------------\n\n% Set data folder, change if you have downloaded the data somewhere else\ndata_root = fullfile(get_root_cnnimageretrieval(), 'data');\n% Check, and, if necessary, download test data (Flickr15 sketch dataset), and fine-tuned networks\ndownload_test_sketch(data_root); \n\n% Set test options\ntest_dataset = 'flickr15k_sketch'; % dataset to evaluate on\ntest_imdim = 227; % choose test image dimensionality\nuse_mirror = 1; % use mirror representation, otherwise use only original image\nuse_ms = 1; % use multi-scale representation, otherwise use single-scale\nuse_gpu = [1]; % use GPUs (array of GPUIDs), if empty use CPU\n\n% Choose ECCV18 fine-tuned CNN network\nnetwork_file = fullfile(data_root, 'networks', 'retrieval-SfM-30k', 'retrievalSfM30k-edgemac-vgg.mat');\n\n% After running the training script train_cnnsketch2imageretrieval.m you can evaluate fine-tuned network\n% network_file = fullfile(data_root, 'networks', 'exp', 'vgg_edgefilter_mac_test', 'net-epoch-20');\n\n%---------------------------------------------------------------------\n% Set dependent variables\n%---------------------------------------------------------------------\n\n% Prepare function for desc extraction\nif ~use_ms\n descfun = @(x, y, z) cnn_vecms_sketch (x, y, z, 1, use_mirror);\nelse\n descfun = @(x, y, z) cnn_vecms_sketch (x, y, z, [1, 1/sqrt(2), sqrt(2), 1/2, 2], use_mirror);\nend\n\n%---------------------------------------------------------------------\n% Testing\n%---------------------------------------------------------------------\n[~, network_name, ~] = fileparts(network_file);\nfprintf('>> %s: Evaluating CNN image retrieval...\\n', network_name);\n\n% Load pre-trained edge detector\nfprintf('>> Loading Dollar edge detector toolbox and model...\\n');\nemodel = load_edgedetector(data_root);\n\n% Load pre-trained CNN network\nfprintf('>> Loading CNN model...\\n');\nload(network_file);\nnet = dagnn.DagNN.loadobj(net);\n\n% prepare GPUs if necessary\nnumGpus = numel(use_gpu);\nif numGpus, fprintf('>> Preparing GPU(s)...\\n'); end\nif numGpus > 1\n % check parallel pool integrity as it could have timed out\n pool = gcp('nocreate');\n if ~isempty(pool) && pool.NumWorkers ~= numGpus\n delete(pool);\n end\n pool = gcp('nocreate');\n if isempty(pool)\n parpool('local', numGpus);\n end\nend\nif numGpus >= 1\n if numGpus == 1\n gpuinfo = gpuDevice(use_gpu);\n net.move('gpu');\n fprintf('>>>> Running on GPU %s with Index %d\\n', gpuinfo.Name, gpuinfo.Index); \n else\n spmd\n gpuinfo = gpuDevice(use_gpu(labindex));\n fprintf('>>>> Running on GPU %s with Index %d\\n', gpuinfo.Name, gpuinfo.Index); \n end\n end\nend\n\n% extract and evaluate\nfprintf('>> %s: Processing test dataset...\\n', test_dataset); \ncfg = configdataset (test_dataset, fullfile(data_root, 'test/')); % config file for the dataset\n\nfprintf('>> %s: Extracting CNN descriptors for db images...\\n', test_dataset); \nvecs = cell(1, cfg.n);\nif numGpus <= 1\n progressbar(0);\n for i = 1:cfg.n\n vecs{i} = descfun(imresizemaxd(imread(cfg.im_fname(cfg, i)), test_imdim), net, emodel);\n progressbar(i/cfg.n);\n end\nelse\n time = tic;\n parfor i = 1:cfg.n\n if strcmp(net.device, 'cpu'), net.move('gpu'); end\n vecs{i} = descfun(imresizemaxd(imread(cfg.im_fname(cfg, i)), test_imdim), net, emodel);\n end\n fprintf('>>>> done in %s\\n', htime(toc(time)));\nend\nvecs = cell2mat(vecs);\n\nfprintf('>> %s: Extracting CNN descriptors for query images...\\n', test_dataset); \nqvecs = cell(1, cfg.nq);\nif numGpus <= 1\n progressbar(0);\n for i = 1:cfg.nq\n qvecs{i} = descfun(imresizemaxd(imread(cfg.qim_fname(cfg, i)), test_imdim), net, 0);\n progressbar(i/cfg.nq);\n end\nelse\n time = tic;\n parfor i = 1:cfg.nq\n if strcmp(net.device, 'cpu'), net.move('gpu'); end\n qvecs{i} = descfun(imresizemaxd(imread(cfg.qim_fname(cfg, i)), test_imdim), net, 0);\n end\n fprintf('>>>> done in %s\\n', htime(toc(time)));\nend\nqvecs = cell2mat(qvecs);\n\n\nfprintf('>> %s: Retrieval...\\n', test_dataset);\nsim = vecs'*qvecs;\n[sim, ranks] = sort(sim, 'descend');\nmap = compute_map (ranks, cfg.gnd); \nfprintf('>> %s: mAP = %.4f\\n', test_dataset, map);\n", "meta": {"author": "filipradenovic", "repo": "cnnimageretrieval", "sha": "93a7391a2f8b13ff189d0c6131b95e0363542659", "save_path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval", "path": "github-repos/MATLAB/filipradenovic-cnnimageretrieval/cnnimageretrieval-93a7391a2f8b13ff189d0c6131b95e0363542659/examples/test_cnnsketch2imageretrieval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.18197970300258084}} {"text": "function [p] = mesh_open(p)\n\n% mesh_open - calls functions to read a triangulation file\n% \n% Usage: [p] = mesh_open(p)\n% \n% p is a parameter structure (see eeg_toolbox_defaults for\n% more details). In this function, it should contain at least\n% the following string fields:\n%\n% p.mesh.path - the directory location of the file to load\n% p.mesh.file - the name of the file to load\n% p.mesh.type - the file format:\n%\n% 'emse'\n% 'brainstorm'\n% 'ascii' or 'freesurfer_ascii' for *.asc/.tri files\n% 'freesurfer_surf' for freesurfer binary surface\n% 'freesurfer_curv' for freesurfer binary curvature\n% 'freesurfer_overlay' for freesurfer binary overlay (.w) \n% \n% The last two file types are associated with the current cortex,\n% if it contains the same number of vertices (eg, load 'freesurfer_surf'\n% first, then 'freesurfer_curv' or 'freesurfer_overlay').\n% \n% The file formats supported here are described in more detail \n% at their respective websites:\n% \n% FreeSurfer: http://surfer.nmr.mgh.harvard.edu\n% EMSE: http://www.sourcesignal.com\n% BrainStorm: http://neuroimage.usc.edu/brainstorm\n% \n% The return structure creates or updates p.mesh.data, which \n% contains cell arrays:\n%\n% p.mesh.data.meshtype type of surface, strings\n% p.mesh.data.vertices Mx3 (x,y,z) vertices\n% p.mesh.data.faces Mx3 vertex indices\n% p.mesh.data.Cdata scalar overlay, M vert x N overlays\n%\n% For example, having loaded a scalp and an inner skull mesh, \n% p.mesh.data.meshtype could be:\n% \n% p.mesh.data.meshtype{1} = 'scalp'\n% p.mesh.data.meshtype{2} = 'inner skull'\n%\n% To plot the data returned, see mesh_plot or try\n% \n% Hpatch = patch('Vertices',p.mesh.data.vertices{1}',...\n% 'Faces',p.mesh.data.faces{1},...\n% 'Property','PropertyValue',...);\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $\n\n% Licence: GNU GPL, no express or implied warranties\n% History: 02/2002 Darren.Weber_at_radiology.ucsf.edu\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfprintf('\\nMESH_OPEN...\\n'); tic;\n\nif ~exist('p','var'),\n [p] = eeg_toolbox_defaults;\n fprintf('...creating default p structure.\\n');\nend\n\n[path,name,ext] = fileparts(strcat(p.mesh.path,filesep,p.mesh.file));\nfile = fullfile(path,[name ext]);\n\nif exist(file) ~= 2,\n msg = sprintf('\\n\\n...file does not exist:\\n\\t%s\\n',file);\n error(msg);\nend\n\ntype = lower(p.mesh.type);\n\nswitch type,\n \n case 'emse',\n \n fprintf('...loading EMSE mesh from:\\n\\t%s\\n',file);\n \n % Get EMSE .wfr data (in meters)\n options = {'vertex','face'};\n [vertices,faces,edges,meshtype] = mesh_emse2matlab(file,options);\n \n vertex_matrix = [vertices.x; vertices.y; vertices.z]';\n face_matrix = [faces.vertex1;faces.vertex2;faces.vertex3]';\n \n % Rotate 90 degrees around Z for EMSE data\n vertex_matrix = Rz(vertex_matrix,90,'degrees');\n \n % Is this a new or replacement mesh?\n [p.mesh.current,meshExists] = mesh_check(p,meshtype);\n \n p.mesh.data.meshtype{p.mesh.current} = meshtype;\n p.mesh.data.vertices{p.mesh.current} = vertex_matrix;\n p.mesh.data.faces{p.mesh.current} = face_matrix;\n p.mesh.data.lapmat{p.mesh.current} = [];\n p.mesh.data.lapint{p.mesh.current} = [];\n p.mesh.data.timeseries{p.mesh.current} = [];\n p.mesh.data.Cdata{p.mesh.current} = [];\n \n case 'brainstorm',\n \n fprintf('...loading BrainStorm data from:\\n\\t%s\\n',file);\n load(file);\n \n p.mesh.data = [];\n \n for i=1:size(Comment,2),\n if isempty(Comment{i}), continue; end\n fprintf('...converting tesselation: %s\\n',Comment{i});\n p.mesh.data.meshtype{i} = Comment{i};\n p.mesh.data.vertices{i} = Vertices{i}'; % transpose Vertices\n p.mesh.data.faces{i} = Faces{i};\n p.mesh.data.lapmat{i} = [];\n p.mesh.data.lapint{i} = [];\n p.mesh.data.timeseries{i} = [];\n p.mesh.data.Cdata{i} = [];\n p.mesh.current = i;\n end\n \n case {'ascii','freesurfer_ascii'},\n \n fprintf('...loading ASCII or FreeSurfer data from:\\n\\t%s\\n',file);\n \n % Get Freesurfer data\n if findstr(file,'.tri'),\n [vertex_matrix,face_matrix] = freesurfer_read_tri(file);\n else\n [vertex_matrix,face_matrix] = freesurfer_read_ascii(file);\n end\n \n fprintf('...converting surface coordinates (mm to meters)\\n');\n vertex_matrix = vertex_matrix ./ 1000;\n \n meshtype = freesurfer_meshtype(file); % see function below\n \n [p.mesh.current,meshExists] = mesh_check(p,meshtype);\n \n p.mesh.data.meshtype{p.mesh.current} = meshtype;\n p.mesh.data.vertices{p.mesh.current} = vertex_matrix;\n p.mesh.data.faces{p.mesh.current} = face_matrix;\n p.mesh.data.lapmat{p.mesh.current} = [];\n p.mesh.data.lapint{p.mesh.current} = [];\n p.mesh.data.timeseries{p.mesh.current} = [];\n p.mesh.data.Cdata{p.mesh.current} = [];\n \n case 'freesurfer_surf',\n \n fprintf('...loading FreeSurfer binary surface from:\\n\\t%s\\n',file);\n \n meshtype = freesurfer_meshtype(file); % see function below\n \n [p.mesh.current,meshExists] = mesh_check(p,meshtype);\n \n [vertex_matrix, face_matrix] = freesurfer_read_surf(file);\n \n fprintf('...converting surface coordinates (mm to meters)\\n');\n vertex_matrix = vertex_matrix ./ 1000;\n \n p.mesh.data.meshtype{p.mesh.current} = meshtype;\n p.mesh.data.vertices{p.mesh.current} = vertex_matrix;\n p.mesh.data.faces{p.mesh.current} = face_matrix;\n p.mesh.data.lapmat{p.mesh.current} = [];\n p.mesh.data.lapint{p.mesh.current} = [];\n p.mesh.data.timeseries{p.mesh.current} = [];\n p.mesh.data.Cdata{p.mesh.current} = [];\n \n case 'freesurfer_curv',\n \n fprintf('...loading FreeSurfer binary curvature from:\\n\\t%s\\n',file);\n \n [curv, Nfaces] = freesurfer_read_curv(file);\n \n allocated = 0;\n for meshN = 1:length(p.mesh.data.meshtype),\n \n type = p.mesh.data.meshtype{meshN};\n \n if size(p.mesh.data.vertices{meshN},1) == size(curv,1),\n fprintf('...allocating overlay to Cdata for ''%s'' surface.\\n',type);\n p.mesh.data.Cdata{meshN} = curv;\n p.mesh.current = meshN;\n allocated = 1;\n end\n \n end\n if allocated < 1,\n fprintf('...failed to allocate curvature to any surface, incompatible Nfaces!\\n');\n end\n \n case 'freesurfer_overlay',\n \n fprintf('...loading FreeSurfer binary overlay from:\\n\\t%s\\n',file);\n \n [w,vert] = freesurfer_read_wfile(file);\n \n Nvert = length(vert); clear vert;\n \n allocated = 0;\n for meshN = 1:length(p.mesh.data.meshtype),\n \n type = p.mesh.data.meshtype{meshN};\n \n if size(p.mesh.data.vertices{meshN},1) == Nvert,\n fprintf('...allocating overlay to Cdata for ''%s'' surface.\\n',type);\n p.mesh.data.Cdata{meshN} = w;\n p.mesh.current = meshN;\n allocated = 1;\n end\n \n end\n if allocated < 1,\n fprintf('...failed to allocate overlay to any surface, incompatible vertices!\\n');\n end\n \n otherwise,\n fprintf('...mesh format: %s\\n', p.mesh.type);\n fprintf('...sorry, cannot load this data format at present.\\n');\n return;\nend\n\nt=toc; fprintf('...done (%5.2f sec).\\n\\n',t);\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/mesh_open.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1816363261955486}} {"text": "function [Channel] = elec_3dspace2brainstorm(filename,N,bsfile)\n\n% elec_3dspace2brainstorm - Convert NeuroScan 3Dspace ascii to brainstorm file\n% \n% The ascii file format is that of NeuroScan 3Dspace export files. Each row\n% of the file comprises an electrode label, an electrode type code, and\n% the x,y,z coordinates (cm). Each field is separated by spaces. See\n% ELEC_LOAD for more information.\n% \n% Useage: Channel = elec_3dspace2brainstorm(filename,[N],[brainstormfile])\n% \n% where: file = 'path\\filename' with format described in ELEC_LOAD\n% \n% N is how many electrodes to load (rows of 3Dspace file, 129 default).\n% \n% Result: Channel is an array of structures. The fields are:\n% \n% Loc - a 3x2 matrix of electrode coordinates (x,y,z in rows).\n% BrainStorm (x,y,z meters) = 3Dspace (x,y,z cm) / 100.\n% Orient - a corresponding matrix of sensor orientations (MEG); \n% all zero for EEG.\n% Weight - a vector of relative or absolute weights (eg, amplification);\n% all ones for this routine.\n% Type - a character string, 'EEG' in this case.\n% Name - a charater string indicating the electrode name.\n% Comment - a charater string indicating the reference electrode. Empty\n% for active electrodes and 'EEG REF' for reference electrode.\n% \n% See brainstorm website at http://neuroimage.usc.edu/, including a\n% download pdf file describing the brainstorm database formats.\n% \n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:54 $\n\n% Licence: GNU GPL, no express or implied warranties\n% History: 20/05/2002, Darren.Weber_at_radiology.ucsf.edu\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~exist('N', 'var'), N = 129;\nelseif isempty(N), N = 129;\nend\n\nfile = char(filename);\n\n[elec,type,X,Y,Z] = elec_load(file,[],[],[],[],N);\n\ntic;\n\nfprintf('\\nELEC_3DSPACE2BRAINSTORM...\\n');\nfprintf('...Converting to brainstorm structure.\\n');\n\nelecindex = find(type == 69);\nEe = elec(elecindex);\nXe = X(elecindex) ./ 100; % 3Dspace is cm, BrainStorm is m\nYe = Y(elecindex) ./ 100;\nZe = Z(elecindex) ./ 100;\n\nreftype = ones(size(type)) * 120;\nrefindex = find(type == reftype);\nEref = elec(refindex);\nXref = X(refindex) ./ 100; % 3Dspace is cm, BrainStorm is m\nYref = Y(refindex) ./ 100;\nZref = Z(refindex) ./ 100;\n\nfor i=1:length(elecindex),\n Channel(i).Loc = [[Xe(i) Ye(i) Ze(i)]',[Xref Yref Zref]'];\n Channel(i).Orient = []; % used for MEG rather than EEG\n Channel(i).Weight = 1; % Like Amplification\n Channel(i).Type = 'EEG';\n Channel(i).Name = char(Ee(i));\n Channel(i).Comment = '';\nend\nChannel(i+1).Loc = [[Xref Yref Zref]',[Xref Yref Zref]'];\nChannel(i+1).Orient = [];\nChannel(i+1).Weight = 1;\nChannel(i+1).Type = 'EEG';\nChannel(i+1).Name = char(Eref);\nChannel(i+1).Comment = 'EEG REF';\n\nif ~exist('bsfile', 'var'),\n bsfile = 'channel';\nelseif isempty(bsfile),\n bsfile = 'channel';\nend\n\nif findstr('.mat',bsfile),\n bsfile = strrep(bsfile,'.mat','');\nend\n\nfprintf('...saving BrainStorm channel data to:\\n\\t%s.mat\\n',bsfile);\nsave(bsfile, 'Channel');\n\n\nt = toc; fprintf('...done (%6.2f sec).\\n\\n',t);\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/elec_3Dspace2brainstorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1816363225935586}} {"text": "function DCM = spm_dcm_erp_data(DCM,ERP)\n% prepares structures for forward model(EEG, MEG and LFP)\n% FORMAT DCM = spm_dcm_erp_data(DCM,ERP)\n% DCM - DCM structure\n% ERP - switch to average over trials (default)\n%\n% requires\n%\n% DCM.xY.Dfile - data file\n% DCM.options.trials - trial codes\n% DCM.options.Tdcm - Peri-stimulus time window\n% DCM.options.D - Down-sampling\n% DCM.options.han - Hanning\n% DCM.options.h - Order of (DCT) detrending\n%\n% sets\n% DCM.xY.modality - 'MEG','EEG' or 'LFP'\n% DCM.xY.Time - Time [ms] data\n% DCM.xY.pst - Time [ms] of down-sampled data\n% DCM.xY.dt - sampling in seconds (s)\n% DCM.xY.y - cell array of trial-specific response {[ns x nc]}\n% DCM.xY.It - Indices of (ns) time bins\n% DCM.xY.Ic - Indices of (nc) good channels\n% DCM.xY.name - names of (nc) channels\n% DCM.xY.scale - scalefactor applied to raw data\n% DCM.xY.coor2D - 2D coordinates for plotting\n% DCM.xY.X0 - (DCT) confounds\n% DCM.xY.R - Residual forming matrix (with hanning)\n% DCM.xY.Hz - Frequency bins (for Wavelet transform)\n% DCM.options.h\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: spm_dcm_erp_data.m 7749 2019-12-05 17:05:46Z guillaume $\n \n \n% Set defaults and Get D filename\n%--------------------------------------------------------------------------\ntry\n Dfile = DCM.xY.Dfile;\ncatch\n errordlg('Please specify data and trials');\n error('')\nend\n\n% options\n%========================================================================== \n\n% order of drift terms\n%--------------------------------------------------------------------------\nif nargin < 2, ERP = 1; end\ntry, han = DCM.options.han; catch, han = 0; end\ntry, h = DCM.options.h; catch, h = 1; end\ntry\n DT = DCM.options.D;\ncatch\n errordlg('Please specify down sampling');\n error('')\nend\ntry\n trial = DCM.options.trials;\ncatch\n errordlg('please specify trials');\n error('')\nend\n \n% load D\n%--------------------------------------------------------------------------\ntry\n D = spm_eeg_load(Dfile);\ncatch\n try\n [dum,f] = fileparts(Dfile);\n D = spm_eeg_load(f);\n DCM.xY.Dfile = fullfile(pwd,f);\n catch\n try\n [f,p] = uigetfile('*.mat','please select data file');\n name = fullfile(p,f);\n D = spm_eeg_load(name);\n DCM.xY.Dfile = fullfile(name);\n catch\n warndlg([Dfile ' could not be found'])\n return\n end\n end\nend\n \n% get time-frequency data if appropriate\n%--------------------------------------------------------------------------\nif isequal(D.transformtype, 'TF')\n DCM = spm_dcm_ind_data(DCM);\n return;\nend\n \n% indices of EEG channel (excluding bad channels) and peristimulus times\n%--------------------------------------------------------------------------\nif ~isfield(DCM.xY, 'modality')\n [mod, list] = modality(D, 0, 1);\n if isequal(mod, 'Multimodal')\n qstr = 'Only one modality can be modelled at a time';\n if numel(list) < 4\n \n % Pretty dialog box\n %--------------------------------------------------------------\n options = [];\n options.Default = list{1};\n options.Interpreter = 'none';\n DCM.xY.modality = questdlg(qstr, 'Select modality', list{:}, options);\n \n else\n \n % can accommodate more buttons\n %--------------------------------------------------------------\n ind = menu(qstr, list);\n DCM.xY.modality = list{ind};\n end\n else\n DCM.xY.modality = mod;\n end\nend\n \n% good channels\n%--------------------------------------------------------------------------\nIc = D.indchantype(DCM.xY.modality,'GOOD');\nif isempty(Ic)\n warndlg('No good channels in these data');\n return\nend\n \nNc = length(Ic); % number of channels\nDCM.xY.name = D.chanlabels(Ic); % channel names\nDCM.xY.Ic = Ic; % channel indices\nDCM.xY.Time = time(D, [], 'ms'); % PST (ms)\nDCM.xY.dt = 1/D.fsample; % time bins\nDCM.xY.coor2D = D.coor2D(Ic); % coordinates (topographic)\n \n% time window\n%--------------------------------------------------------------------------\ntry\n \n % time window and bins for modelling\n %----------------------------------------------------------------------\n T1 = DCM.options.Tdcm(1);\n T2 = DCM.options.Tdcm(2);\n [dum, T1] = min(abs(DCM.xY.Time - T1));\n [dum, T2] = min(abs(DCM.xY.Time - T2));\n \n % Time [ms] of down-sampled data\n %----------------------------------------------------------------------\n It = (T1:DT:T2)';\n Ns = length(It); % number of samples\n DCM.xY.pst = DCM.xY.Time(It); % Down-sampled PST\n DCM.xY.dt = DT/D.fsample; % sampling in seconds\n DCM.xY.It = It; % Indices of time bins\n \ncatch\n errordlg('Please specify time window');\n error('')\nend\n\n% confounds - DCT:\n%--------------------------------------------------------------------------\nif h == 0\n X0 = sparse(Ns,1);\nelse\n X0 = spm_dctmtx(Ns,h);\nend\nR = speye(Ns) - X0*X0';\n \n% hanning (omit second residualization for very long time-series)\n%--------------------------------------------------------------------------\nif han\n if Ns < 2048\n R = R*sparse(diag(spm_hanning(Ns)))*R;\n else\n R = sparse(diag(spm_hanning(Ns)))*R;\n end\nend\n \n \n% get trial averages - ERP\n%--------------------------------------------------------------------------\ncond = D.condlist;\nfor i = 1:length(trial)\n \n % trial indices\n %----------------------------------------------------------------------\n c = D.indtrial(cond(trial(i)), 'GOOD');\n Nt = length(c);\n DCM.xY.nt(i) = Nt;\n\n % ERP\n %----------------------------------------------------------------------\n if ERP\n Y = zeros(Ns,Nc);\n for j = 1:Nt\n Y = Y + R*D(Ic,It,c(j))';\n end\n DCM.xY.y{i} = Y/Nt;\n \n % all trials\n %----------------------------------------------------------------------\n else\n Y = zeros(Ns,Nc,Nt);\n for j = 1:Nt\n Y(:,:,j) = R*D(Ic,It,c(j))';\n end\n DCM.xY.y{i} = Y;\n end\n \nend\n \n \n% condition units of measurement\n%--------------------------------------------------------------------------\nDCM.xY.code = cond(trial);\nDCM.xY.scale = 1;\nDCM.xY.X0 = X0;\nDCM.xY.R = R;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/dcm_meeg/spm_dcm_erp_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.18163631764442806}} {"text": "% DEPRECATED...\n%\n% Author: Javier Lopez-Calderon\n% Center for Mind and Brain\n% University of California, Davis,\n% Davis, CA\n% 2009\n\nfunction EEG = checkzerolat(EEG)\nnepoch = EEG.trials;\nif isempty(EEG.epoch)\n fprintf('\\nWARNING: checkzerolat() only works for epoched datasets. This call was ignored.\\n')\n return\nend\nfor i=1:nepoch\n latcell = cell2mat(EEG.epoch(i).eventlatency);\n [v, indx] = min(abs(latcell));\n EEG.epoch(i).eventlatency = num2cell(latcell - latcell(indx));\nend\n\nauxtimes = EEG.times;\n[v, indx] = min(abs(auxtimes));\nEEG.times = auxtimes - auxtimes(indx);\nEEG.xmin = min(EEG.times)/1000;\nEEG.xmax = max(EEG.times)/1000;\nEEG.srate = round(EEG.srate);\nEEG = eeg_checkset( EEG );\n\nif EEG.times(1)~=auxtimes(1)\n msg = ['\\nWarning: zero time-locked stimulus latency values were not found.\\n'...\n 'Therefore, ERPLAB adjusted latency values at EEG.epoch.eventlatency, EEG.times, EEG.xmin,and EEG.xmax.\\n\\n'];\n fprintf(msg);\n fprintf('Time range is now [%.3f %.3f] sec.\\n', EEG.min, EEG.max )\nelse\n fprintf('Zero latencies OK.\\n')\nend", "meta": {"author": "ucdavis", "repo": "erplab", "sha": "e4f66f7a512c4dee2f7596982318e44bb1b72644", "save_path": "github-repos/MATLAB/ucdavis-erplab", "path": "github-repos/MATLAB/ucdavis-erplab/erplab-dd2f60aa41b01c866fcec342efafc48323523cc2/deprecated_functions/checkzerolat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18145182904258483}} {"text": "function main_image = PTKGetMainRegionExcludingBorder(threshold_image, minimum_region_volume_mm3, reporting)\n % PTKGetMainRegionExcludingBorder. Finds the largest connected region in a\n % binary 3D volume, excluding any regions which touch the borders in the\n % first and second dimensions.\n %\n % Syntax:\n % main_image = PTKGetMainRegionExcludingBorder(threshold_image, reporting)\n %\n % Inputs:\n % threshold_image - a binary 3D volume as a PTKImage.\n %\n % minimum_region_volume_mm3 (optional) - ignore any regions below this\n % threshold\n %\n % reporting (optional) - an object implementing CoreReportingInterface\n % for reporting progress and warnings\n %\n % Outputs:\n % main_image - a PTKImage binary volume of the found region\n %\n %\n % Licence\n % -------\n % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n % Author: Tom Doel, 2012. www.tomdoel.com\n % Distributed under the GNU GPL v3 licence. Please see website for details.\n %\n\n if ~isa(threshold_image, 'PTKImage')\n error('Requires a PTKImage as input');\n end\n \n if nargin < 2 || isempty(minimum_region_volume_mm3)\n minimum_region_volume_mm3 = 0;\n end\n \n if nargin < 3\n reporting = CoreReportingDefault;\n end\n\n reporting.ShowProgress('Finding lung region');\n \n \n \n bordered_image = true(threshold_image.ImageSize + [2 2 2]);\n bordered_image(2:end-1, 2:end-1, 2:end-1) = threshold_image.RawImage;\n bordered_image(2:end-1, 2:end-1, 1) = false;\n bordered_image(2:end-1, 2:end-1, end) = false;\n \n image_opening_params_mm = [0, 2, 4, 6];\n image_opening_index = 1;\n still_searching = true;\n \n while still_searching\n \n [results, CC] = OpenAndGetRegions(bordered_image, image_opening_params_mm(image_opening_index), threshold_image.VoxelSize, minimum_region_volume_mm3, reporting);\n \n if numel(results) > 0 || image_opening_index == numel(image_opening_params_mm)\n still_searching = false;\n else\n image_opening_index = image_opening_index + 1;\n end\n end\n \n if numel(results) == 0\n main_image = [];\n reporting.Error('PTKGetMainRegionExcludingBorder:NoRegionFound', 'No region could be found');\n end\n \n if numel(results) > 1\n % If more than one region was found (after excluding boundary-touching\n % regions), then check if they are disconnected left and right lungs\n bounding_boxes = regionprops(CC, 'BoundingBox');\n bb_1 = bounding_boxes(results(1)).BoundingBox;\n bb_1 = bb_1([2,1,3,5,4,6]); % Bounding box is [xyz] but Matlab indices are [yxz]\n bb_2 = bounding_boxes(results(2)).BoundingBox;\n bb_2 = bb_2([2,1,3,5,4,6]); % Bounding box is [xyz] but Matlab indices are [yxz]\n image_centre = round(size(bordered_image)/2);\n \n image_centre_j = image_centre(2);\n \n if threshold_image.IsCT\n centre_offset = 0;\n else\n % Allow some leeway for MRI images where the lung boundaries may not be so\n % clear\n centre_offset = 10;\n end\n \n use_both_regions = false;\n if (bb_1(2) >= image_centre_j - centre_offset) && (bb_2(5) < image_centre_j + centre_offset)\n reporting.LogVerbose('I appear to have found 2 disconnected lungs. I am connecting them.');\n use_both_regions = true;\n end\n \n if (bb_2(2) >= image_centre_j - centre_offset) && (bb_1(5) < image_centre_j + centre_offset)\n reporting.LogVerbose('I appear to have found 2 disconnected lungs. I am connecting them.');\n use_both_regions = true;\n end\n else\n use_both_regions = false;\n end\n\n bordered_image(:) = false;\n bordered_image(CC.PixelIdxList{results(1)}) = true;\n if use_both_regions\n bordered_image(CC.PixelIdxList{results(2)}) = true; \n end\n \n main_image = threshold_image.BlankCopy;\n main_image.ChangeRawImage(bordered_image(2:end-1, 2:end-1, 2:end-1));\nend\n\nfunction [results, CC] = OpenAndGetRegions(bordered_image_input, opening_mm, voxel_size, minimum_region_volume_mm3, reporting)\n \n bordered_image = bordered_image_input;\n if opening_mm > 0\n ball_element = CoreImageUtilities.CreateBallStructuralElement(voxel_size, opening_mm);\n bordered_image = imopen(bordered_image_input > 0, ball_element);\n end\n\n % Borders are marked as segmented - this ensures all components\n % touching the border are connected and allows us to eliminate them\n % when extracting the lung\n \n % Obtain connected component matrix\n CC = bwconncomp(bordered_image, 26);\n\n % Find largest region\n num_pixels = cellfun(@numel, CC.PixelIdxList);\n [sorted_largest_areas, sorted_largest_areas_indices] = sort(num_pixels, 'descend');\n \n % Remove regions that are below the volume threshold\n pixel_volume = prod(voxel_size);\n sorted_largest_areas_indices = sorted_largest_areas_indices(pixel_volume*sorted_largest_areas >= minimum_region_volume_mm3);\n \n \n result_index = 1;\n results = [];\n index_in_sorted_array = 1;\n while (result_index < 3 && index_in_sorted_array <= length(sorted_largest_areas_indices))\n current_region_being_checked = sorted_largest_areas_indices(index_in_sorted_array);\n bordered_image(:) = false;\n bordered_image(CC.PixelIdxList{current_region_being_checked}) = true;\n if (bordered_image(1) || bordered_image(end))\n % This region is connected to the edge\n% reporting.ShowMessage('PTKGetMainRegionExcludingBorder:LargestROIConnectedToExterior', 'The largest region connected with the edge of the volume. I''m assuming this region is outside the body so choosing the next largest region');\n else\n results(result_index) = current_region_being_checked;\n result_index = result_index + 1;\n end\n index_in_sorted_array = index_in_sorted_array + 1;\n end\nend", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Segmentation/PTKGetMainRegionExcludingBorder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.18145182548206984}} {"text": " function y = ir_imfilter_many(x, psf, varargin)\n%function y = ir_imfilter_many(x, psf, varargin)\n%|\n%| as of 2015-04-12, octave's imfilter can handle only 2D input\n%| whereas matlab can handle 3D inputs\n%| this is a kludge to deal with that.\n%|\n%| 2015-04-12, Jeff Fessler, University of Michigan\n\nif nargin < 2, ir_usage, end\n\nif ~ir_is_octave || ndims(x) == ndims(psf)\n\ty = imfilter(x, psf, varargin{:}); % matlab or usual sizes\nreturn\nend\n\n% hereafter for octave with unequal sizes\n\nif ndims(x) == 3 && ndims(psf) == 2\n\ttmp = imfilter(x(:,:,1), psf, varargin{:});\n\tnz = size(x,3);\n\ty = zeros([size(tmp) nz]);\n\ty(:,:,1) = tmp;\n\tfor iz = 2:nz\n\t\ty(:,:,iz) = imfilter(x(:,:,iz), psf, varargin{:});\n\tend\nreturn\nend\n\npr size(x)\npr size(psf)\nfail('imfilter in octave does not support such sizes, nor does my kludge')\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/ir_imfilter_many.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1814518219215549}} {"text": "function [D,Ds,hdr,p,coords,X,Y,Z] = tor_3d(varargin)\n% :Usage:\n% ::\n%\n% [D,Ds,hdr,p,coords,X,Y,Z] = tor_3d(varargin)\n%\n% made to use single_subj_T1.img from SPM99\n%\n% :Options:\n%\n% **'data':**\n% followed by image data, must also use 'hdr'; data is full image volume\n%\n% **'hdr':**\n% followed by hdr structure (use read_hdr)\n%\n% **'coords':**\n% 3 element row vector of x,y,z coordinates at which to cut away\n%\n% **'figure':**\n% create a new figure to plot on\n%\n% **'whichcuts':**\n% followed by incisions; choices are x y z w (whole)\n%\n% example:'whichcuts','xyz' (xyz is default)\n% order of output handles (p(i)) is 'wyzx'\n%\n% New: Special methods:\n% - 'coronal slice right'\n% - 'coronal slice left'\n% - 'coronal slice'\n%\n% **'filename':**\n% followed by filename of image data to load, in single quotes\n%\n% should be analyze img format, without the .img extension\n%\n% cluster imaging assumes neurological orientation, but should work anyway.\n%\n% **'revx':**\n% reverse x cut direction, so cut in from left instead of right\n%\n% **'topmm':**\n% topmm = varargin{i+1};\n%\n% **'intensity_threshold':**\n% percentile of data above which is considered in-object\n% higher = more sparse object\n%\n% :Outputs:\n%\n% **D:**\n% img data\n%\n% **Ds:**\n% smoothed data\n%\n% **hdr:**\n% header\n%\n% **p:**\n% image handles\n%\n% **coords:**\n% coordinates\n%\n% **X, Y, Z:**\n% are the millimeter, origin centered reference frame for the head isosurface\n%\n% :Examples:\n% ::\n%\n% [D,Ds,hdr,p,coords] = tor_3d('figure','data',D,'hdr',hdr,'whichcuts','yzx');\n% [D,Ds,hdr,p,coords] = tor_3d('figure');\n% [D,Ds,hdr,headhandle,coords] = tor_3d('whichcuts','z', 'coords', [-Inf\n% -Inf Inf], 'filename', 'T1_face_exemplar', 'intensity_threshold', 80); set(gcf, 'Color', 'w'); axis on\n%\n% % Special slice example:\n% [D,Ds,hdr,handle,coords] = tor_3d('whichcuts', 'coronal slice right', 'coords', [0 12 0], 'topmm', 100);\n% lightRestoreSingle\n% set(handle(1), 'FaceColor', [.5 .5 .5])\n%\n% ..\n% Made by Tor Wager, 10/3/2001 last modified 10/19/01\n% ..\n\n\n% ..\n% Set up arguments and default values\n% ..\n\n[D,Ds,hdr] = deal([]);\np = zeros(1,2);\ncoords = [0 0 0];\nwhichcuts = 'xyz';\nfilename = 'spm2_single_subj_T1_scalped'; 'single_subj_T1'; % default structural image to use\ntopmm = 60; % image only this high in mm to avoid image distortions above head.\nbottommm = nan; % bottom cutoff in mm\ndolight = 1;\nrevx = 0;\nintensity_threshold = [];\n\nfor i = 1:nargin\n if isstr(varargin{i})\n switch varargin{i}\n case 'data', D = varargin{i+1};\n case 'hdr', hdr = varargin{i+1};\n case 'coords', coords = varargin{i+1};\n case 'figure', h3dfig = figure; set(h3dfig,'Tag','myFig');\n colormap(gray(100)),set(gcf,'Color','k'),axis off,set(gcf,'Position',[184 115 672 543])\n case 'whichcuts',whichcuts = varargin{i+1};\n case 'filename',filename = varargin{i+1};\n case 'nolight', dolight = 0;\n case 'revx', revx = 1;\n case 'topmm', topmm = varargin{i+1};\n case 'bottommm', bottommm = varargin{i+1}; \n \n case 'intensity_threshold', intensity_threshold = varargin{i + 1};\n \n end\n end\nend\n\n%------------------------------------------------------------------------------\n% Load the image file, if necessary\n% Get origin and voxel size\n%------------------------------------------------------------------------------\nif isempty(D) \n \n if isa(D, 'fmri_data'), D = []; end % empty fmri_data object\n \n if ~exist(filename, 'file')\n fullpath = which([filename '.img']);\n else\n fullpath = filename;\n end\n \n if isempty(fullpath), error(['Cannot find file: ' filename '.img']);\n else disp(['Loading structural image: ' fullpath]);drawnow\n end\n [array,hdr] = readim2(filename);\n % rotate 270 degrees so that front of head is positive y\n % (works with canonical SPM images, at least, so this orientation is ok.)\n for i = 1:size(array,3)\n D(:,:,i) = rot90(rot90(rot90((array(:,:,i)))));\n end\n\n VV = spm_vol(fullpath);\n origin = VV.mat(1:3, 4);\n voxsize = (diag(VV.mat(1:3, 1:3)));\n\nelseif isa(D, 'fmri_data')\n\n mymat = D.volInfo.mat;\n origin = mymat(1:3, 4);\n voxsize = (diag(mymat(1:3, 1:3)));\n array = reconstruct_image(D);\n \n % rotate 270 degrees so that front of head is positive y\n % (works with canonical SPM images, at least, so this orientation is ok.)\n D = [];\n for i = 1:size(array,3)\n D(:,:,i) = rot90(rot90(rot90((array(:,:,i)))));\n end\n \nelse\n error('Use no ''data'' argument for default surface, or enter ''data'' followed by fmri_data object')\nend\n\nif isempty(Ds)\n Ds = smooth3(D);\nend\n\n\n%------------------------------------------------------------------------------\n% Define X Y Z coordinates of head data\n%------------------------------------------------------------------------------\n% Define X, Y, Z relative to the origin, so head will be centered on origin\n% Multiply by voxel size in header so that coordinates are in mm from the origin\n% Make sure origin is set properly in header for this to work accurately.\n\n% NOTE: spm5 no longer sets things in origin, apparently, so use spm_vol\n% to get origin\n\n[M N P] = size(D);\n%[X Y Z] = meshgrid(((1:N)-hdr.origin(1))*hdr.xsize, ((1:M)-hdr.origin(2))*hdr.ysize, ((1:P)-hdr.origin(3))*hdr.zsize);\n[X Y Z] = meshgrid(((1:N)*voxsize(1)+origin(1)), ((1:M)*voxsize(2)+origin(2)), ((1:P)*voxsize(3)+origin(3)));\n\n% define threshold\nif isempty(intensity_threshold)\n surface_threshold = mean(D(:)); % original way, pre-2009\nelse\n surface_threshold = prctile(D(:), intensity_threshold); %mean(mean(mean(D)));\nend\n\n%------------------------------------------------------------------------------\n% Make patches for cutaway\n%------------------------------------------------------------------------------\nindex = 1;\n\nif strcmp(whichcuts, 'coronal slice right')\n % Special methods\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[0 nan coords(2)-2 coords(2) bottommm topmm], surface_threshold);\n\nelseif strcmp(whichcuts, 'coronal slice left')\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan 0 coords(2)-10 coords(2) bottommm topmm], surface_threshold);\n\nelseif strcmp(whichcuts, 'coronal slice')\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan coords(2)-10 coords(2) bottommm topmm], surface_threshold);\n\nelse\n\n if any(whichcuts == 'w')\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan nan bottommm topmm], surface_threshold); % whole head\n index = index + 2;\n end\n\n % xyz inset cutaway - seems to work only if x does not come first\n if any(whichcuts == 'y')\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan coords(2) bottommm topmm], surface_threshold);\n index = index + 2;\n end\n if any(whichcuts == 'z')\n [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan nan bottommm coords(3)], surface_threshold);\n index = index + 2;\n end\n if any(whichcuts == 'x')\n if revx, [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[coords(1) nan nan nan bottommm topmm], surface_threshold);\n else [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan coords(1) nan nan bottommm topmm], surface_threshold);\n end\n index = index + 2;\n end\n\nend\n\n%------------------------------------------------------------------------------\n% Set lighting conditions\n%------------------------------------------------------------------------------\nif dolight && length(p) > 1\n myLight = standardMRIlighting('full',p(1:2));\nelseif dolight\n myLight = standardMRIlighting('full',p);\nend\n\nif length(p) > 2, standardMRIlighting('reflectance',p(3:4)); end\nif length(p) > 4, standardMRIlighting('reflectance',p(5:6)); end\n\n% set(myLight,'Tag','myLight') % done in stMRIlighting.\n\nrotate3d off\n\t%------------------------------------------------------------------------------\n % set callback to light follow the camera\n\t%------------------------------------------------------------------------------\n\tif exist('lightFollowView') == 2\n set(gcf, 'WindowButtonUpFcn', 'lightFollowView');\n else\n warning('Cannot find lightFollowView.m to set light position.')\n end\n\n\n%------------------------------------------------------------------------------\n% Sub-function for imaging patch\n%------------------------------------------------------------------------------\nfunction [p1,p2] = imagePatch(X,Y,Z,D,Ds,inValues, surface_threshold)\n\n \n\n if isempty(inValues)\n inValues = [nan nan nan nan nan nan];\n end\n\n if isempty(X) | isempty(Y) | isempty(Z)\n % no xyz coordinates\n FV2 = isosurface(Ds,surface_threshold);\n IS2 = isocaps(D,surface_threshold);\n\n % Draw figure patches\n try\n p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);\n p2 = patch(IS2,'FaceColor','interp','EdgeColor','none','FaceAlpha',1);\n catch\n p1 = patch(FV2,'FaceColor',[1,.75,.65],'EdgeColor','none','SpecularExponent',200,'SpecularStrength',.2);\n p2 = patch(IS2,'FaceColor','interp','EdgeColor','none');\n end\n \n else\n\n % Define subvolume for cutaway view\n [x y z A] = subvolume(X,Y,Z,D,inValues);\n [x y z As] = subvolume(X,Y,Z,Ds,inValues);\n FV2 = isosurface(x,y,z,As,surface_threshold);\n IS2 = isocaps(x,y,z,A,surface_threshold);\n\n % Draw figure patches\n try\n p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);\n p2 = patch(IS2,'FaceColor','interp','EdgeColor','none','FaceAlpha',1);\n catch\n p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);\n p2 = patch(IS2,'FaceColor','interp','EdgeColor','none');\n end\n % isonormals(A,p1)\n end\n\n drawnow\n return\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/tor_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.18145181836103996}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MoveJ:\n% Caution. The global variable robot should be loaded\n% with a valid robot arm.\n% Example: MoveJ(pos_b_rec, 'v1000', 'z100', gripper, wobj0);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Copyright (C) 2012, by Arturo Gil Aparicio\n%\n% This file is part of ARTE (A Robotics Toolbox for Education).\n% \n% ARTE is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% ARTE is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with ARTE. If not, see .\nfunction MoveJ(robtarget, speeddata, zonedata, gripper, Wobj)\n\nglobal configuration robot\n\nfprintf('\\nCall to MoveJ');\n\n%obtain current joint coordinates\nq_current = robot.q;\n\n%Ttool, transformation from the robot's end to the TCP\nTtool = transform_to_homogeneous(gripper(2:end));\n\n%compute target joint coordinates, from the inverse kinematics\n%select desired joint values by using conf data from robtarget\n%select configuration\nconf = get_conf_data(robtarget);\nTtotal = transform_to_homogeneous(robtarget);\n\n%T = Ttotal*inv(Ttool);\nT = Ttotal/Ttool;\n\n%Obtain solutions from inversekinematic function\nq_final=inversekinematic(robot, T, robot.q);\n\n%select one of the solutions of the inverse kinematic problem\n% solution according to configuration and language.\n% The conf vector defines the quadrants of the joints [theta1 theta4 theta6 thetax]\n% =[cf1 cf4 cf6 cfx]. Where the x angle is zero in this implementation.\nq_final=select_configuration(robot, q_final, conf);\n%(q_final*180/pi)'\n\nspeed = obtain_joint_speed(robot, speeddata);\n%when fine is specified, the radius is zero, otherwise, \n%the radius represents a sphere around the target where the\n%movement is changed to the next target\nradius = obtain_zone_data(zonedata);\n\n%find time to perform movement\n[actual_speed, tmax]=synchronize(q_current, q_final, speed, robot.accelmax);\n\n%in this case, if the total time for the movement is lower than the\n%configuration.delta_time time then 10 points are interpolated\nif tmax <= configuration.delta_time\n t = [0:tmax/10:tmax]';\nelse\n %local time for the planning, normal case\n t = [0:configuration.delta_time:tmax]';\nend\n\nif radius==0\n %compute a smooth trajectory in q and qd\n %in this case, the final speed is zero\n [q, qd, qdd] = compute_joint_trajectory_indep(robot, q_current, q_final, robot.qd, zeros(1,robot.DOF), t);\nelse\n %in this case, the final speed is selected as the speed selected by the\n %variable speeddata\n [q, qd, qdd] = compute_joint_trajectory_indep(robot, q_current, q_final, robot.qd, actual_speed, t);\nend\n%finds the first joint coordinates that are inside a radius r of the target\n%point\nindex = find_first_in_zone_data(robot, q, T, radius);\n\n%the robot performs the movement until the index found. The coordinates, joint speed and acceleratin\n%are stored and used in the planning of the next point\nrobot.q=q(:,index);\nrobot.qd=qd(:,index);\nrobot.qdd=qdd(:,index);\n\n%store all the trajectory for plotting\n%the joint trajectories, speeds and acceleration of susequent movements are\n%store here\n%robot.q_vector=[robot.q_vector q(:, 1:index)];\n%robot.qd_vector=[robot.qd_vector qd(:, 1:index)];\n%robot.qdd_vector=[robot.qdd_vector qdd(:, 1:index)];\n\nrobot.q_vector = q(:, 1:index);\nrobot.qd_vector = qd(:, 1:index);\nrobot.qdd_vector = qdd(:, 1:index);\n\n%a global time for the planning is computed.\n%in this way, the total trajectory of different movements can be plotted\nif length(robot.time)==0\n tend = 0;\nelse\n tend = robot.time(end);\nend\nt = t + tend;\n%store total time\nrobot.time=t(1:index)';\n\n%Test whether there are joints outside mechanical limits\ntest_joint_limits(robot);\n\n%Plot position, velocity and acceleration\n%plot_joint_data(robot);\n%Now, animate the robot in 3D\nanimate(robot, q);\n\n%Plot the trajectory\npp = zeros(3,size(q,2));\nfor i=1:size(q,2),\n T=directkinematic(robot, q(:,i));\n %pp=[pp T(1:3,4)];\n pp(1:3,i)=T(1:3,4);\nend\nplot3(pp(1,:),pp(2,:),pp(3,:), 'k', 'LineWidth', 2)\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/RAPID/functions/MoveJ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.18128856517677414}} {"text": "function [planar] = constructplanargrad(cfg, grad)\n\n% CONSTRUCTPLANARGRAD constructs a planar gradiometer array from an axial gradiometer\n% definition. This can be used to compute the planar field gradient for a known\n% (estimated) source configuration.\n% \n% Use as\n% [grad_planar] = constructplanargrad(cfg, grad_axial)\n%\n% Where cfg contains the following configuration details\n% cfg.baseline_axial = number (default is 5)\n% cfg.baseline_planar = number (default is 0.5)\n% cfg.planaraxial = 'no' or 'yes' (default)\n% \n% The option planaraxial='yes' specifies that the planar gradiometers\n% should consist of axial gradiometers, to make them comparable with\n% Ole Jensens planar gradient computation. If planaraxial='no', the\n% planar gradiometers will be more or less similar to the Neuromag\n% system.\n%\n% The input grad can be a CTF type axial gradiometer definition, but\n% just as well be a magnetometer definition. This function only assumes\n% that\n% grad.coilpos\n% grad.coilori\n% grad.label\n% exist and that the first Nlabel channels in pnt and ori should be\n% used to compute the position of the coils in the planar gradiometer\n% channels.\n\n% Copyright (C) 2004, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif ~isfield(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": "function [net_matching] = init_siamese_model()\n% this file implements the matching network\n% By Xin Li, 11-27-2017\n\nnet_matching = dagnn.DagNN();\n net_matching.addLayer('xcorr', XCorr(), ...\n {'w_feat', 'x_feat'}, ...\n {'m_score'}, ...\n {});\nnet_matching.move('gpu');\n\nend", "meta": {"author": "XinLi-zn", "repo": "TADT", "sha": "659e031a9c40624d53b7b1d4d25f16cd70795c3b", "save_path": "github-repos/MATLAB/XinLi-zn-TADT", "path": "github-repos/MATLAB/XinLi-zn-TADT/TADT-659e031a9c40624d53b7b1d4d25f16cd70795c3b/tracking/init_siamese_model.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18112858160085782}} {"text": "% REREF - convert common reference EEG data to some other common reference\n% or to average reference\n% Usage:\n% >> Dataout = reref(data); % convert all channels to average reference\n% >> [Dataout Chanlocs] = reref(data, refchan, 'key', 'val');\n% % convert data to new reference with options\n% Inputs:\n% data - 2-D or 3-D data matrix (chans,frames*epochs) \n% refchan - reference channel number(s). There are three possibilities:\n% 1) [] - compute average reference\n% 2) [X]: re-reference to channel X \n% 2) [X Y Z ...]: re-reference to the average of channel X Y Z ... \n% \n% Optional inputs:\n% 'exclude' - [integer array] channel indices to exclude from re-referencing\n% (e.g., event marker channels, etc.)\n% 'keepref' - ['on'|'off'] keep reference channel in output (only usable \n% when there are several references).\n% 'elocs' - Current data electrode location structure (e.g., EEG.chanlocs).\n% 'refloc' - Reference channel location single element structure or cell array\n% {'label' theta radius} containing the name and polar coordinates \n% of the current channel. Including this entry means that\n% this channel will be included (reconstructed) in the\n% output.\n%\n% Outputs:\n% Dataout - Input data converted to the new reference\n% Chanlocs - Updated channel locations structure\n%\n% Notes: 1) The average reference calculation implements two methods \n% (see www.egi.com/Technotes/AverageReference.pdf)\n% V'i = (Vi-Vref) - sum(Vi-Vref)/number_of_electrodes\n%\n% Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2009-\n% previous version: Arnaud Delorme & Scott Makeig, 1999-2002\n\n% Deprecated inputs:\n% These inputs are still accepted but not processed. The function returns\n% accurate results irrespective of the entry of these options.\n% 'refstate ' - ['common'|'averef'|[indices]] Current reference condition,\n% ('averef') = average reference; ('common' or 0) = common\n% reference. [indices] designate the current reference channel \n% or channels if present in the data {default: 'common'}\n% 'method' - ['standard'|'withref'] Do not ('standard') or do ('withref') \n% include reference channel data in output {def: 'standard'}. \n% Note: Option 'withref' not possible when multiple ref channel \n% indices are given as argument to 'refstate' (below).\n%\n% ICA inputs:\n% These inputs are still accepted but not the ICA conversion is now\n% performed from within POP_REREF\n% 'icaweights' - ICA weight matrix. Note: If this is ICA weights*sphere, \n% then the 'icasphere' input below should be [] or identity.\n% 'icasphere' - ICA sphere matrix (if any)\n% 'icachansind' - Indices of the channels used in ICA decomposition\n%\n% Outputs:\n% Wout - ICA weight matrix (former icaweights*icasphere)\n% converted to new data reference\n% Sout - ICA sphere matrix converted to an identity matrix\n% ICAinds - New indices of channels used in ICA decomposition\n% meandata - (1,dataframes) means removed from each data point\n%\n% 2) In conversion of the weight matrix to a new reference\n% where WS = Wts*Sph and ica_act = WS*data, then\n% data = inv(WS)*ica_act;\n% If R*data are the re-referenced data,\n% R*data= R*inv(WS)*ica_act; \n% And Wout = inv(R*inv(WS));\n% Now, Sout = eye(length(ICAinds));\n% The re-referenced ICA component maps are now the \n% columns of inv(Wout), and the icasphere matrix, Sout, \n% is an identity matrix. Note: INV -> PINV when \n% PCA dimension reduction is used during ICA decomposition.\n\n% Copyright (C) 1999 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK\n% 01-25-02 reformated help & license -ad \n\nfunction [data, Elocs, morechans, W, S, icachansind, meandata] = reref(data, ref, varargin)\n\nif nargin<1\n help reref\n return\nend\nif nargin < 2\n ref = [];\nend\n\n% check inputs\n% ------------\ng = finputcheck(varargin, { 'icaweight' 'real' [] [];\n 'icaweights' 'real' [] [];\n 'icasphere' 'real' [] [];\n 'icachansind' 'integer' [] [];\n 'interpchan' {''} [] [];\n 'method' 'string' { 'standard','withref' } 'standard';\n 'refstate' { 'string','integer' } { { 'common','averef' } [1 size(data,1)] } 'common'; % ot used but kept for backward compatib.\n 'exclude' 'integer' [1 size(data,1)] [];\n 'refloc' { 'cell','struct' } { [] [] } {};\n 'keepref' 'string' {'on','off' } 'off';\n 'elocs' {'integer','struct'} [] [] });\nif ischar(g), error(g); end\nif ~isempty(g.icaweight)\n g.icaweights = g.icaweight;\nend\nif ~isempty(g.icaweights)\n if isempty(g.icachansind), \n g.icachansind = [1:size(g.icaweights,2)]; \n disp('Warning: reref() output has changed slightly since EEGLAB 5.02');\n disp(' the 4th output argument is the indices of channels used for ICA instead');\n disp(' of the mean reference value (which is now output argument 5)');\n end\nend\nif ischar(ref), ref = { ref }; end\nif iscell(ref), ref = eeg_chaninds(g.elocs, ref); end\nif ~isempty(ref)\n if ref > size(data,1)\n error('reference channel index out of range');\n end\nend\n\n[dim1, dim2, dim3] = size(data);\ndata = reshape(data, dim1, dim2*dim3);\n\n% single reference not present in the data\n% add it as blank data channel at the end\n% ----------------------------------------\nif ~isempty(g.refloc) == 1\n if ~isempty(g.elocs)\n if iscell(g.refloc)\n data(end+1,:) = 0;\n g.elocs(end+1).labels = g.refloc{1};\n g.elocs(end ).theta = g.refloc{2};\n g.elocs(end ).radius = g.refloc{3};\n else\n data(end+length(g.refloc),:) = 0;\n for iLocs = 1:length(g.refloc)\n g.elocs(end+1).labels = g.refloc(iLocs).labels;\n fieldloc = fieldnames(g.elocs);\n for ind = 1:length(fieldloc)\n g.elocs(end) = setfield(g.elocs(end), fieldloc{ind}, getfield(g.refloc(iLocs), fieldloc{ind}));\n end\n end\n end\n end\n [dim1 dim2 dim3] = size(data);\nend\n\n% exclude some channels\n% ---------------------\nchansin = setdiff_bc([1:dim1], g.exclude);\nnchansin = length(chansin);\n\n% return mean data\n% ----------------\nif nargout > 4\n meandata = sum(data(chansin,2))/nchansin;\nend\n\n% generate rereferencing matrix\n% -----------------------------\nif 0 % alternate code - should work exactly the same\n if isempty(ref)\n ref=chansin; % average reference\n end % if \n chansout=chansin; \n data(chansout,:)=data(chansout,:)-ones(nchansin,1)*mean(data(ref,:),1); \nelse\n if ~isempty(ref) % not average reference \n refmatrix = eye(nchansin); % begin with identity matrix\n tmpref = ref;\n for index = length(g.exclude):-1:1\n tmpref(find(g.exclude(index) < tmpref)) = tmpref(find(g.exclude(index) < tmpref))-1;\n end\n for index = 1:length(tmpref)\n refmatrix(:,tmpref(index)) = refmatrix(:,tmpref(index))-1/length(tmpref);\n end\n else % compute average reference\n refmatrix = eye(nchansin)-ones(nchansin)*1/nchansin;\n end\n chansout = chansin;\n data(chansout,:) = refmatrix*data(chansin,:);\nend\n\n% change reference in elocs structure\n% -----------------------------------\nif ~isempty(g.elocs)\n if isempty(ref)\n for ind = chansin\n g.elocs(ind).ref = 'average';\n end\n else\n reftxt = { g.elocs(ref).labels };\n if length(reftxt) == 1, reftxt = reftxt{1}; \n else\n reftxt = cellfun(@(x)([x ' ']), reftxt, 'uniformoutput', false);\n reftxt = [ reftxt{:} ];\n end\n for ind = chansin\n g.elocs(ind).ref = reftxt;\n end\n end\nend\n\n% remove reference\n% ----------------\nmorechans = [];\nif strcmpi(g.keepref, 'off')\n data(ref,:) = [];\n if ~isempty(g.elocs)\n morechans = g.elocs(ref);\n g.elocs(ref) = [];\n end\nend\n\ndata = reshape(data, size(data,1), dim2, dim3);\n\n% treat optional ica parameters\n% -----------------------------\nW = []; S = []; icachansind = [];\nif ~isempty(g.icaweights) \n disp('Warning: This function does not process ICA array anymore, use the pop_reref function instead');\nend\nElocs = g.elocs;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/reref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.18109460635402175}} {"text": "% ------------------------------------------------------------------------\n% Get ROI reference-space locations and region annotations\n% ------------------------------------------------------------------------\n\n\n%% SET FILE LOCATIONS OF TRANSFORM AND ROIS\n\n\n% file location of transform and transformed image\ntransform_location = 'C:\\Drive\\Histology\\for tutorial - sample data\\SS096_done\\processed\\transformations\\SS096_1_1_transform_data';\ntransformed_slice_location = 'C:\\Drive\\Histology\\for tutorial - sample data\\SS096_done\\processed\\transformations\\SS096_1_1_transformed.tif';\n\n% file location of ROIs (image / array of the same size as the reference ie 800 x 1140)\nroi_location = 'C:\\Drive\\Histology\\for tutorial - sample data\\SS096_1_1_ROIs.tif';\n\n\n% directory of reference atlas files\nannotation_volume_location = 'C:\\Drive\\Histology\\for tutorial\\annotation_volume_10um_by_index.npy';\nstructure_tree_location = 'C:\\Drive\\Histology\\for tutorial\\structure_tree_safe_2017.csv';\n\n% plane used to view ROI ('coronal' -- most common, 'sagittal', 'transverse')\nplane = 'coronal';\n\n% Synthetic ROIs for testing\n% rois = zeros(800,1140,'uint8');\n% rois(250:300, 600:610) = 200; rois(480:500, 200:210) = 200;\n% imwrite(rois,roi_location)\n% \n% Using a set of x and y coordinates from the ImageJ function Analyze Particles to generate an ROI image\n% roi_array = zeros(800,1140,'uint8');\n% roi_array_values = csvread('C:\\ROI_files\\cfos_cells.csv', 1, 5);\n% y = roi_array_values(:, 1);\n% x = roi_array_values(:, 2);\n% \n% for i = 1:length(roi_array_values)-1\n% roi_array(x(i),y(i)) = 200; \n% end\n \n\n\n%% LOAD THE DATA\n\n% load the transformed slice image\ntransformed_slice_image = imread(transformed_slice_location);\n\n% load the transform from the transform file\ntransform_data = load(transform_location);\ntransform_data = transform_data.save_transform;\n\n% get the actual transformation from slice to atlas\nslice_to_atlas_transform = transform_data.transform;\n\n% get the position within the atlas data of the transformed slice\nslice_num = transform_data.allen_location{1};\nslice_angle = transform_data.allen_location{2};\n\n% load the rois\nrois = imread(roi_location);\n\n% if the rois come from a transformed roi image of non-contiguous roi\n% pixels (e.g. an ROI pixel for each neuron), then run this line to ensure\n% a one-to-one mapping between ROIs in the original and transformed images:\n% rois = uint8(imregionalmax(rois));\n\n% load the reference brain annotations\nif ~exist('av','var') || ~exist('st','var')\n disp('loading reference atlas...')\n av = readNPY(annotation_volume_location);\n st = loadStructureTree(structure_tree_location);\nend\n\n% select the plane for the viewer\nif strcmp(plane,'coronal')\n av_plot = av;\nelseif strcmp(plane,'sagittal')\n av_plot = permute(av,[3 2 1]);\nelseif strcmp(plane,'transverse')\n av_plot = permute(av,[2 3 1]);\nend\n\n%% GET REFERENCE-SPACE LOCATIONS AND REGION ANNOTATIONS FOR EACH ROI\n\n% I will do this for every *pixel* in the roi image with nonzero value, \n% but this code can be modified, e.g. to do it by clusters of pixels\n\n\n% show the transformed ROI, together with the transformed image\nfigure; imshow(imfuse(rois, transformed_slice_image));\ntitle('transformed slice image, fused with ROIs')\n\n% make sure the rois are in a properly size image\nassert(size(rois,1)==800&size(rois,2)==1140&size(rois,3)==1,'roi image is not the right size');\n\n\n\n% initialize array of locations (AP, DV, ML relative to bregma) in reference space\n% and the correponding region annotations\nroi_location = zeros(sum(rois(:)>0),3);\nroi_annotation = cell(sum(rois(:)>0),3);\n\n% get location and annotation for every roi pixel\n[pixels_row, pixels_column] = find(rois>0);\n\n% generate other necessary values\nbregma = allenCCFbregma(); % bregma position in reference data space\n\natlas_resolution = 0.010; % mm\nref_size = size(squeeze(av_plot(1,:,:)));\noffset_map = get_offset_map(slice_angle, ref_size);\n\n% loop through every pixel to get ROI locations and region annotations\nfor pixel = 1:length(pixels_row)\n \n % get the offset from the AP value at the centre of the slice, due to\n % off-from-coronal angling\n offset = offset_map(pixels_row(pixel),pixels_column(pixel));\n \n % use this and the slice number to get the AP, DV, and ML coordinates\n if strcmp(plane,'coronal')\n ap = -(slice_num-bregma(1)+offset)*atlas_resolution;\n dv = (pixels_row(pixel)-bregma(2))*atlas_resolution;\n ml = (pixels_column(pixel)-bregma(3))*atlas_resolution;\n elseif strcmp(plane,'sagittal')\n ml = -(slice_num-bregma(3)+offset)*atlas_resolution;\n dv = (pixels_row(pixel)-bregma(2))*atlas_resolution;\n ap = -(pixels_column(pixel)-bregma(1))*atlas_resolution;\n elseif strcmp(plane,'transverse')\n dv = -(slice_num-bregma(2)+offset)*atlas_resolution;\n ml = (pixels_row(pixel)-bregma(3))*atlas_resolution;\n ap = -(pixels_column(pixel)-bregma(1))*atlas_resolution;\n end\n \n\n\n roi_location(pixel,:) = [ap dv ml];\n \n % finally, find the annotation, name, and acronym of the current ROI pixel\n ann = av_plot(slice_num+offset,pixels_row(pixel),pixels_column(pixel));\n name = st.safe_name{ann};\n acr = st.acronym{ann};\n \n roi_annotation{pixel,1} = ann;\n roi_annotation{pixel,2} = name;\n roi_annotation{pixel,3} = acr;\n\nend\n \n roi_table = table(roi_annotation(:,2),roi_annotation(:,3), ...\n roi_location(:,1),roi_location(:,2),roi_location(:,3), roi_annotation(:,1), ...\n 'VariableNames', {'name', 'acronym', 'AP_location', 'DV_location', 'ML_location', 'avIndex'});\n\n disp(roi_table(1:10,:))\n \n% now, use roi_locations and roi_annotations for your further analyses\n\n\n\n\n", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/SHARP-Track/Analyze_ROIs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1810858171278222}} {"text": "classdef featureMatrices < handle\n\n% featureMatrices object for ECGwrapper\n% -------------------------------------\n% \n% Description:\n% \n% \n% Arguments: (specified as ECGwrapper('arg_name1', arg_val1, ... , 'arg_nameN', arg_valN) )\n% \n% a. ECG specification:\n% \n% a.1 Recording filename where ECG is stored in a valid format.\n% \n% + recording_name: ECG recording to be classified.\n% + recording_format : Valid ECG format. (MIT, ISHNE, AHA, HES, MAT)\n% \n% b. Operating modes\n% \n% \n% c. Modifiers\n% \n% \n% Output:\n% \n% Examples:\n% \n% \n% Limits and Known bugs:\n% Probably a lot :( ... but dont panic! send me feedback if you need\n% help.\n% \n% Author: Mariano Llamedo Soria (llamedom at frba.utn.edu.ar)\n% Version: 0.1 beta\n% Birthdate : 20/3/2012\n% Last update: 20/3/2012\n \n properties(GetAccess = private, Constant)\n sampling_rate = 360; %Hz\n fnPayload = {'featMat_clust' 'featMat_ldc' 'ECG' 'QRS_locations' 'RR_intervals'};\n fnFMfile = {'featMat_clust' 'featMat_ldc'};\n fnECGfile = {'ECG' 'QRS_locations' 'RR_intervals'};\n SmallValue = 0.0001;\n end\n \n properties ( Access = private )\n delayLP\n autovec\n q_filters\n LP\n LPsize\n scale_idx\n scales\n global_struct\n end\n \n properties (SetAccess = private, GetAccess = public) \n %read-only \n name\n class_labeling\n true_labels\n %auxiliary indexes\n file_count = 1;\n File_list = [];\n File_idx = [];\n QRS_idx = [];\n \n end\n\n properties\n %read-write\n recording_name\n recording_format\n progress_hdl\n tmp_path\n bCache\n cant_pids\n this_pid\n cant_iteration\n this_iteration\n end\n \n\n methods \n \n function obj = featureMatrices(class_labeling)\n\n %% Constants and definitions\n\n obj.name = 'feat_matrix_construction';\n obj.class_labeling = class_labeling;\n\n end\n \n function Start(obj)\n \n\n %% Calculate accesories signals\n \n %load low-pass preprocessing filter.\n load( ['LP Fs ' num2str(obj.sampling_rate) 'Hz - Fc 35Hz - 80db stop.mat' ]);\n obj.LPsize = length(LP.numerator);\n obj.delayLP = round((obj.LPsize-1)/2);\n obj.LP = LP;\n clear LP\n \n % Wavelet transform filter bank design\n obj.scales = 1:6;\n CantScales = length(obj.scales);\n MaxScales = max(obj.scales);\n obj.scale_idx= nan(MaxScales,1);\n\n filters_cache_filename = ['wt_filters_' num2str(MaxScales) ' scales_' num2str(obj.sampling_rate) ' Hz.mat' ];\n if( exist(filters_cache_filename, 'file') )\n aux = load( filters_cache_filename );\n obj.q_filters = aux.q_filters;\n clear aux\n else\n obj.q_filters = qs_filter_design(MaxScales, obj.sampling_rate);\n end\n \n for ii = 1:CantScales\n %indice para saber que escala corresponde a cada columna de MyWavelets\n obj.scale_idx(obj.scales(ii)) = ii;\n end\n\n % Update point\n obj.progress_hdl.checkpoint('PCA projection');\n\n% obj.autovec = PCA_proj_basis(obj.recording_name, obj.recording_format, obj.q_filters);\n \n obj.autovec = [-0.696609733483207 -0.403719836632163 -0.593081084444745;-0.487887339191286 -0.339521516938205 0.804171053814316;-0.526023595928265 0.849550135686930 0.0395441965529324;];\n \n % data structure to keep data through all iterations.\n obj.global_struct = [];\n \n end\n \n function payload = Process(obj, ECG, this_header, this_iter_ECG_relative_start_end_idx, this_iter_annotations)\n\n obj.progress_hdl.checkpoint('Label parsing');\n \n [QRS_locations, obj.true_labels ] = Annotation_process(this_iter_annotations, obj.recording_format, obj.class_labeling);\n \n % RR interval sequence\n RR_intervals = diff(QRS_locations, 1);\n RR_intervals = colvec([ RR_intervals(1); RR_intervals ]);\n\n dRR_intervals = diff(RR_intervals, 1);\n dRR_intervals = colvec([ dRR_intervals(2); dRR_intervals(2); dRR_intervals(2:end) ]);\n\n % interval resampling.\n RR_intervals = RR_intervals * obj.sampling_rate / this_header.freq;\n dRR_intervals = dRR_intervals * obj.sampling_rate / this_header.freq;\n \n %% Preprocessing\n \n % Update point\n obj.progress_hdl.checkpoint('Resampling');\n \n cant_QRS_locations = length(QRS_locations);\n this_iter_QRS_seq_idx = 1:cant_QRS_locations;\n\n %resample to obj.sampling_rate Hz\n ECG = resample(ECG, obj.sampling_rate, this_header.freq);\n QRS_locations = colvec(round(QRS_locations * obj.sampling_rate / this_header.freq));\n % this_iter_true_labels = true_labels(this_iter_QRS_seq_idx);\n this_iter_ECG_resampled_size = size(ECG,1);\n\n if( this_header.nsig > 2 ) \n %multilead approach.\n % project ECG and wtECG to obtain PCA components\n ECG = ECG * obj.autovec(:,1:2);\n % wtECG = cellfun(@(a)( a * obj.autovec(:,1:2) ), mat2cell(wtECG, this_iter_ECG_resampled_size, obj.ECG_header.nsig, ones(1,CantScales) ), 'UniformOutput', false);\n % wtECG = cell2mat(wtECG);\n end\n\n % Update point\n obj.progress_hdl.checkpoint('Filtering');\n\n %Low pass filtering @ 35Hz => ECG recovery\n ECG = filter(obj.LP, ECG);\n %delay compensation.\n ECG = [ zeros(obj.delayLP, size(ECG,2) ) ;ECG(obj.LPsize:end,:) ; zeros(obj.delayLP, size(ECG,2))];\n\n %Quito la linea de base.\n % ECG = BaselineWanderRemovalMedian( ECG, obj.sampling_rate);\n ECG = BaselineWanderRemovalSplines( ECG, QRS_locations, obj.sampling_rate);\n\n % Update point\n obj.progress_hdl.checkpoint('Wavelet transform calculation');\n\n wtECG = qs_wt(ECG, obj.scales, obj.sampling_rate, obj.q_filters);\n\n %% Features Calculation\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n this_iter_seq_idx = 1:length(QRS_locations);\n\n % log(RRactual)\n %%%%%%%%%%%%%%%\n featMat_ldc = log(colvec(RR_intervals(this_iter_QRS_seq_idx))/obj.sampling_rate);\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(RRpost)\n %%%%%%%%%%%%%%%\n\n featMat_ldc = [ featMat_ldc log(colvec(RR_intervals(min(cant_QRS_locations, this_iter_QRS_seq_idx+1)))/obj.sampling_rate)];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(RRmean1)\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( find( QRS_locations >= (QRS_locations(a) - 1*60*obj.sampling_rate) & ... \n QRS_locations <= QRS_locations(a) )), ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a)(mean(RR_intervals(a))/obj.sampling_rate), aux_idx);\n featMat_ldc = [ featMat_ldc colvec(log(aux_featval)) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(RRmean20)\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( find( QRS_locations >= (QRS_locations(a) - 20*60*obj.sampling_rate) & ... \n QRS_locations <= QRS_locations(a) )), ...\n this_iter_QRS_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a)(mean(RR_intervals(a))/obj.sampling_rate), aux_idx);\n featMat_ldc = [ featMat_ldc colvec(log(aux_featval)) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % AutoCorr1PlanoWTZeroCross\n %%%%%%%%%%%%%%%\n % AutoCorr1PlanoWTModMaxPos\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( max(1, QRS_locations(a) - round(0.08*obj.sampling_rate)): ...\n min(this_iter_ECG_resampled_size, QRS_locations(a) + round(0.08*obj.sampling_rate))) , ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a)(squeeze(wtECG(a,:,obj.scale_idx(4)))), aux_idx, 'UniformOutput', false);\n\n %calculate PCA matrix in this slices for feature\n %AutoCorr1PlanoWTModMaxPos\n autovec_slices = cellfun(@(a)(autovec_calculation(a)), aux_featval, 'UniformOutput', false );\n\n aux_idx = arrayfun(@(a)( max(1, QRS_locations(a) - round(0.13*obj.sampling_rate)): ...\n min(this_iter_ECG_resampled_size, QRS_locations(a) + round(0.2*obj.sampling_rate))) , ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a,b)(squeeze(wtECG(a,:,obj.scale_idx(4))) * b), aux_idx, autovec_slices, 'UniformOutput', false);\n [ aux_mp aux_zc ] = cellfun(@(a)(CalcModMaxPos(a(:,1))), aux_featval );\n\n featMat_ldc = [ featMat_ldc colvec(aux_zc) colvec(aux_mp) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % AutoCorr2PlanoWTZeroCross\n %%%%%%%%%%%%%%%\n % AutoCorr2PlanoWTModMaxPos\n %%%%%%%%%%%%%%%\n\n [ aux_mp aux_zc ] = cellfun(@(a)(CalcModMaxPos(a(:,2))), aux_featval );\n\n featMat_ldc = [ featMat_ldc colvec(aux_zc) colvec(aux_mp) ];\n\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n %clear some auxiliar variables.\n clear aux*\n\n %calculate clustering features.\n\n\n % log(RRactual)\n %%%%%%%%%%%%%%%\n featMat_clust = featMat_ldc(:,1);\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(RRant)\n %%%%%%%%%%%%%%%\n featMat_clust = [ featMat_clust log(colvec(RR_intervals(max(1, this_iter_QRS_seq_idx-1)))/obj.sampling_rate)];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(Prematuridad_loc)\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)(max(1,a-1):min(cant_QRS_locations,a+1)), this_iter_QRS_seq_idx, 'UniformOutput', false);\n %tengo que contemplar los casos extremos\n if( length(aux_idx{1}) < 3 )\n aux_idx{1} = [1 aux_idx{1}];\n end\n if( length(aux_idx{end}) < 3 )\n aux_idx{end} = [aux_idx{end} cant_QRS_locations];\n end\n\n aux_featval = cellfun(@(a)( RR_intervals(a(2))/sum(RR_intervals(a)) ), aux_idx);\n featMat_clust = [ featMat_clust colvec(log(aux_featval)) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(AbsRRlocalVar)\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)(max(1,a-1):min(cant_QRS_locations,a+1)), this_iter_QRS_seq_idx, 'UniformOutput', false);\n if( length(aux_idx{1}) < 3 )\n aux_idx{1} = [1 aux_idx{1}];\n end\n if( length(aux_idx{end}) < 3 )\n aux_idx{end} = [aux_idx{end} cant_QRS_locations];\n end\n\n aux_featval = cellfun(@(a)(obj.SmallValue+sum(abs(dRR_intervals(a)))/obj.sampling_rate), aux_idx);\n\n featMat_clust = [ featMat_clust colvec(log(aux_featval)) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(RRmean20)\n %%%%%%%%%%%%%%%\n\n featMat_clust = [ featMat_clust featMat_ldc(:,4) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % log(QRS_max_scale_proj12)\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( max(1, QRS_locations(a) - round(0.08*obj.sampling_rate)): ...\n min(this_iter_ECG_resampled_size, QRS_locations(a) + round(0.08*obj.sampling_rate))) , ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a)(wtECG(a,:,:)), aux_idx, 'UniformOutput', false);\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n aux_featval = cellfun(@(a)(squeeze(sum(abs(a(:,1,:))))'), aux_featval, 'UniformOutput', false );\n aux_featval = cellfun(@(a)(obj.scales * colvec(a) ./ sum(a)), aux_featval );\n\n % iAreaAbs = squeeze(sum(abs(wtAux)))';\n % MaxProjArea = obj.scales * iAreaAbs ./ sum(iAreaAbs);\n\n featMat_clust = [ featMat_clust colvec(log(aux_featval)) ];\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % AutoCorr1PlanoWTModMaxPos\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( max(1, QRS_locations(a) - round(0.13*obj.sampling_rate)): ...\n min(this_iter_ECG_resampled_size, QRS_locations(a) + round(0.2*obj.sampling_rate))) , ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n aux_featval = cellfun(@(a,b)(squeeze(wtECG(a,:,obj.scale_idx(4))) * b), aux_idx, autovec_slices, 'UniformOutput', false);\n aux_featval = cellfun(@(a)(CalcModMaxPos(a(:,1))), aux_featval);\n\n featMat_clust = [ featMat_clust colvec(aux_featval) ];\n\n\n % Update point\n obj.progress_hdl.checkpoint('Features calculation');\n\n % CrossCorr_QRST_ModMaxVal13\n %%%%%%%%%%%%%%%\n\n aux_idx = arrayfun(@(a)( max(1, QRS_locations(a) - round(0.13*obj.sampling_rate)): ...\n min( [ this_iter_ECG_resampled_size, ...\n QRS_locations(a) + round(0.4*obj.sampling_rate), ...\n QRS_locations(a) + RR_intervals(a) - round(0.13*obj.sampling_rate) ] ) ), ...\n this_iter_seq_idx, 'UniformOutput', false);\n\n\n if( this_header.nsig > 2 ) \n % wtECG already projected in obj.autovec.\n aux_featval = cellfun(@(a)( CalcModMaxVal( squeeze(wtECG(a,:,obj.scale_idx(3))) ) ), aux_idx);\n else\n aux_featval = cellfun(@(a)( CalcModMaxVal( squeeze(wtECG(a,:,obj.scale_idx(3))) * obj.autovec ) ), aux_idx);\n end\n\n featMat_clust = [ featMat_clust colvec(aux_featval) ];\n\n %save ECG for user interface and cluster analysis\n for ii = 1:length(obj.fnPayload)\n payload.(obj.fnPayload{ii}) = eval(obj.fnPayload{ii});\n end\n \n end\n \n function allPayloads = Concatenate(obj, allPayloads, payload )\n \n if( isempty(allPayloads) )\n for ii = 1:length(obj.fnFMfile)\n allPayloads.(obj.fnFMfile{ii}) = payload.(obj.fnFMfile{ii});\n end\n else\n for ii = 1:length(obj.fnFMfile)\n allPayloads.(obj.fnFMfile{ii}) = [allPayloads.(obj.fnFMfile{ii}); payload.(obj.fnFMfile{ii})];\n end\n end\n \n [~, rec_filename] = fileparts(obj.recording_name);\n\n for ii = 1:length(obj.fnECGfile)\n aux_payload.(obj.fnECGfile{ii}) = payload.(obj.fnECGfile{ii});\n end\n \n save([obj.tmp_path 'tmpfile_' rec_filename '_ECG_cantpids_' num2str(obj.cant_pids) '_' num2str(obj.this_pid) '_' num2str(obj.this_iteration) '_' num2str(obj.cant_iteration) '.mat'], '-struct', 'aux_payload' );\n\n aux_ECG_filename = [obj.tmp_path 'tmpfile_' rec_filename '_ECG_cantpids_' num2str(obj.cant_pids) '_thispid_' num2str(obj.this_pid) '_iteration_' num2str(obj.this_iteration) '_of_' num2str(obj.cant_iteration) '.mat'];\n %do this for cluster supercomputers reasons\n movefile( [obj.tmp_path 'tmpfile_' rec_filename '_ECG_cantpids_' num2str(obj.cant_pids) '_' num2str(obj.this_pid) '_' num2str(obj.this_iteration) '_' num2str(obj.cant_iteration) '.mat'], ...\n aux_ECG_filename, 'f' );\n \n cant_QRS = length(payload.QRS_locations);\n obj.QRS_idx = [obj.QRS_idx; uint16(colvec(1:cant_QRS))];\n obj.File_idx = [obj.File_idx; repmat(uint16(obj.file_count), cant_QRS, 1)];\n obj.File_list = [obj.File_list; cellstr(aux_ECG_filename)];\n obj.file_count = obj.file_count + 1;\n\n end\n \n \n \n end\n \nend\n \nfunction autovec = autovec_calculation(wtECGslice)\n\n mean_wtECGslice = mean(wtECGslice); \n wtECGslice_cov = cov( bsxfun( @minus, wtECGslice, mean_wtECGslice ));\n [autovec autoval] = eig(wtECGslice_cov); \n [~, autoval_idx] = sort(diag(autoval), 'descend');\n autovec = autovec(:,autoval_idx);\n \nend\n\nfunction [ ModMaxPos ZeroCross ] = CalcModMaxPos( wtSignal )\n\n ModMaxPos = nan;\n ZeroCross = nan;\n\n lwtSignal = size(wtSignal, 1);\n\n if( all( wtSignal == 0 ) )\n return\n end\n\n ac1 = conv(wtSignal(:,1), flipud(wtSignal(:,1)));\n\n ac1 = ac1(lwtSignal:end);\n ac1 = 1/ac1(1)*ac1;\n\n interp_idx = (1:0.1:lwtSignal)';\n\n ac1_interp = spline( 1:lwtSignal, ac1, interp_idx );\n iZeroCrossPos_ac1 = myzerocros(ac1);\n\n if( isempty(iZeroCrossPos_ac1))\n return\n else\n if( iZeroCrossPos_ac1(1) < lwtSignal )\n if( sign(ac1(iZeroCrossPos_ac1(1))) ~= sign(ac1(iZeroCrossPos_ac1(1)+1)) )\n ZeroCross = iZeroCrossPos_ac1(1) - ac1(iZeroCrossPos_ac1(1)) / ( ac1(iZeroCrossPos_ac1(1)+1) - ac1(iZeroCrossPos_ac1(1)) );\n else\n ZeroCross = (iZeroCrossPos_ac1(1)-1) - ac1(iZeroCrossPos_ac1(1)-1) / ( ac1(iZeroCrossPos_ac1(1)) - ac1(iZeroCrossPos_ac1(1)-1) );\n end\n else\n return\n end \n end\n\n ModMaxPos_ac1 = modmax( ac1_interp, 2, 0, 0 );\n\n if( ~isempty(ModMaxPos_ac1) )\n valid_ac1_max_idx = find(interp_idx(ModMaxPos_ac1) > ZeroCross);\n if( ~isempty(valid_ac1_max_idx) )\n ModMaxPos = interp_idx(ModMaxPos_ac1(valid_ac1_max_idx(1)));\n else\n return\n end\n else\n return\n end\n\nend\n\nfunction ModMaxVal = CalcModMaxVal( wtSignal )\n\n % std_wtSignal = std(wtSignal);\n % wtSignal = bsxfun( @times, wtSignal, 1./std_wtSignal);\n\n cc = conv(wtSignal(:,1), flipud(wtSignal(:,2)));\n\n [~, max_pos] = max(abs(cc));\n\n ModMaxVal = cc(max_pos);\n\nend", "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/a2hbc/scripts/@featureMatrices/featureMatrices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.1810858136704529}} {"text": "function SenFig = drawSenFig(SenFig, Sen, Raw, Obs, FigOpt)\n\n% DRAWSENFIG Redraw one sensor figure.\n% \tDRAWSENFIG(SENFIG, SEN, RAW, OBS, FIGOPT) updates all the handles in\n% \tthe handles structure SENFIG to reflect the observations OBS taken by\n% \tsensor SEN, together with the raw data RAW. SENFIG is one sensor figure\n% \tstructure created with CREATESENFIG.\n%\n% See also CREATESENFIG, DRAWMAPFIG.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\n% Sensor type:\n% ------------\nswitch Sen.type\n\n % camera pinhole\n % --------------\n case {'pinHole','pinHoleDepth'}\n\n % 1. Raw data visualisation\n switch Raw.type\n case 'simu'\n drawRawPnts(SenFig, Raw);\n drawRawLines(SenFig, Raw);\n case 'dump'\n set(SenFig.img,'cdata',Raw.data.img);\n drawRawPnts(SenFig, Raw);\n drawRawLines(SenFig, Raw);\n case 'img'\n set(SenFig.img,'cdata',Raw.data.img);\n otherwise\n end\n\n % 2. Process only visible landmarks:\n % a - first erase lmks that were drawn but are no longer visible\n vis = [Obs(:).vis];\n drawn = SenFig.drawn;\n erase = drawn & ~vis;\n if any(erase)\n set(SenFig.measure(erase), 'vis', 'off');\n set(SenFig.mean(erase), 'vis', 'off');\n set(SenFig.ellipse(erase,:), 'vis', 'off');\n set(SenFig.label(erase), 'vis', 'off');\n SenFig.drawn(erase) = false;\n end\n\n % b - now draw only visible landmarks\n for lmk = find(vis)\n\n SenFig.drawn(lmk) = true;\n % Landmark type:\n % --------------\n switch Obs(lmk).ltype\n \n case {'eucPnt'} % Euclidean point\n colors = FigOpt.sensor.colors.defPnt;\n drawObsPnt(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n case {'idpPnt','hmgPnt','ahmPnt','fhmPnt'} % IDP and HMG points\n colors = FigOpt.sensor.colors.othPnt;\n drawObsPnt(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n case {'plkLin','aplLin','idpLin','hmgLin', 'ahmLin'} % lines\n colors = FigOpt.sensor.colors.othLin; \n drawObsLin(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n % ADD HERE FOR NEW LANDMARK TYPE\n case {'newLandmark'}\n % do something\n\n\n otherwise\n % Print an error and exit\n error('??? Unable to display landmark ''%s'' with sensor ''%s''.',Obs(lmk).ltype,Sen.type);\n\n end % and of the \"switch\" on sensor type\n\n end\n\n \n % --------------\n case {'omniCam'}\n\n % 1. Raw data visualisation\n if strcmp(Raw.type,'simu')\n drawRawPnts(SenFig, Raw);\n else\n %drawRawImage(SenFig, Raw);\n imshow(Raw.img,'InitialMagnification', 'fit', 'Parent', SenFig.axes);\n end\n \n % 2. Process only visible landmarks:\n % a - first erase lmks that were drawn but are no longer visible\n vis = [Obs(:).vis];\n drawn = SenFig.drawn;\n erase = drawn & ~vis;\n if any(erase)\n set(SenFig.measure(erase), 'vis', 'off');\n set(SenFig.mean(erase), 'vis', 'off');\n set(SenFig.ellipse(erase,:), 'vis', 'off');\n set(SenFig.label(erase), 'vis', 'off');\n SenFig.drawn(erase) = false;\n end\n % b - now draw only visible landmarks\n for lmk = find(vis)\n\n SenFig.drawn(lmk) = true;\n\n % Landmark type:\n % --------------\n switch Obs(lmk).ltype\n \n case {'eucPnt'} % Euclidean point\n colors = FigOpt.sensor.colors.defPnt;\n drawObsPnt(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n case {'idpPnt','hmgPnt','ahmPnt','fhmPnt'} % IDP and HMG points\n colors = FigOpt.sensor.colors.othPnt;\n drawObsPnt(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n case {'plkLin','aplLin','idpLin','hmgLin', 'ahmLin'} % Plucker line\n colors = FigOpt.sensor.colors.othLin; \n drawObsLin(SenFig, Obs(lmk), colors, FigOpt.sensor.showEllip);\n\n % ADD HERE FOR NEW LANDMARK TYPE\n case {'newLandmark'}\n % do something\n\n\n otherwise\n % Print an error and exit\n error('??? Unable to display landmark ''%s'' with sensor ''%s''.',Obs(lmk).ltype,Sen.type);\n\n end % and of the \"switch\" on sensor type\n\n end\n \n \n % ADD HERE FOR INITIALIZATION OF NEW SENSORS's FIGURES\n % case {'newSensor'}\n % do something\n\n\n % unknown\n % -------\n otherwise\n error('??? Unknown sensor type ''%s''.',Sen.type);\nend\n\n\n% end\n\n% end\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/drawSenFig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18108580329834503}} {"text": "% Formatting_step3_align\n\nclear all;close all;clc\n\n%% set manually\nM_stimset = GetFishStimset();\nM_dir = GetFishDirectories();\nsave_masterdir = GetNestedDataDir();\n\n%% \nrange_fish = GetFishRange();\n\nfor i_fish = range_fish,\n disp(['i_fish = ', num2str(i_fish)]);\n\n %% load data\n save_dir = fullfile(save_masterdir,['subject_' num2str(i_fish)]);\n load(fullfile(save_dir,'CoreInfo.mat'));\n load(fullfile(save_dir,'OptionalInfo.mat'));\n load(fullfile(save_dir,'AdditionalInfo.mat'));\n\n %% index processing\n if M_stimset(i_fish)==1, % fish 1-7\n % 'periods'\n M_period = {480,160,160,320,480,140,150,8,9,10,11,12,13,14,15,200}; %,{120,150,360}};% 8-15 are place holders\n periods = M_period{i_fish};\n \n % 'timelists'\n period = periods; \n nrep = floor(size(frame_keys,1)/period)-1;\n shift = period; \n timelists_raw = 1+shift:period*nrep+shift;\n \n % 'timelists_name'\n if i_fish<6,\n timelists_names = {'16 permut: B/W/phototaxis*2'};\n else % i_fish = 6 or 7\n timelists_names = {'phototaxis'};\n end\n \n % stimuluskey_raw\n stimuluskey_raw = round(frame_keys(:,17)');\n \n else % fish recorded with multiple protocols \n % 'stimset': struct that contains all info parsed from recorded params\n [stimset,stimuluskey_raw] = StimulusKeyPreprocessing(frame_keys,i_fish); % StimulusKeyPreprocessing(frame_keys,i_fish,'isplotting') to show plot\n \n % 'periods','timelists_names'\n periods = [stimset.period];\n timelists_names = {stimset.name};\n\n % very first 100 frames of experiment should be discarded (prone to artifacts)\n if stimset(1).starts(1)<100,\n if stimset(1).nReps(1)>1,\n stimset(1).starts(1) = stimset(1).starts(1)+stimset(1).period;\n stimset(1).nReps(1) = stimset(1).nReps(1)-1;\n elseif stimset(1).nReps(1)==1, % (n/a for current fish, improbable for future fish)\n stimset(1).ij(1,:) = [];\n stimset(1).rawstarts(1) = [];\n stimset(1).rawstops(1) = [];\n stimset(1).starts(1) = [];\n stimset(1).stops(1) = [];\n stimset(1).nReps(1) = [];\n end\n end\n \n % 'timelists' = list of time-frames numbers for a certain stimulus\n nTypes = length(stimset);\n timelists_raw = cell(1,nTypes); % time-lists, i.e. frame indices \n for i_type = 1:nTypes,\n nSets = length(stimset(i_type).starts);\n IX = [];\n for i_set = 1:nSets,\n IX = horzcat(IX,stimset(i_type).starts(i_set):stimset(i_type).stops(i_set));\n end\n timelists_raw{i_type} = IX;\n end \n end \n \n %% Behavioral data: fictive motor recordings\n rows = [7,8,9,13,14];\n Behavior_raw = frame_keys(:,rows)'; \n Behavior_raw(2,:) = -Behavior_raw(2,:);\n \n %% save to nested directory\n save_dir_nested = fullfile(save_masterdir,['subject_' num2str(i_fish)]);\n \n filename = fullfile(save_dir_nested,'CoreInfo.mat');\n varList = {'timelists_raw','timelists_names','periods','stimuluskey_raw'}; % {'CellXYZ','anat_stack','fpsec'};\n save(filename,varList{:},'-append');\n \n filename = fullfile(save_dir_nested,'OptionalInfo.mat');\n varList = {'Behavior_raw'}; % {'numcell_full','CellXYZ_norm'};\n save(filename,varList{:},'-append'); \n \n if exist('stimset','var'),\n filename = fullfile(save_dir_nested,'AdditionalInfo.mat');\n save(filename,'stimset','-append'); % {'frame_keys','IX_inval_anat'};\n end \nend\n\n% % renameing\n% Behavior_raw = F;\n% stimuluskey_raw = stim_full_raw;\n% timelists = tlists_raw;\n% timelists_names = stimrangenames;\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/GUI preload processing/Formatting_step3_align.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.18103579581253573}} {"text": "function write_wobj(OBJ,fullfilename)\n% Write objects to a Wavefront OBJ file\n%\n% write_wobj(OBJ,filename);\n%\n% OBJ struct containing:\n%\n% OBJ.vertices : Vertices coordinates\n% OBJ.vertices_texture: Texture coordinates \n% OBJ.vertices_normal : Normal vectors\n% OBJ.vertices_point : Vertice data used for points and lines \n% OBJ.material : Parameters from external .MTL file, will contain parameters like\n% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,\n% example of an entry from the material object:\n% OBJ.material(i).type = newmtl\n% OBJ.material(i).data = 'vase_tex'\n% OBJ.objects : Cell object with all objects in the OBJ file, \n% example of a mesh object:\n% OBJ.objects(i).type='f' \n% OBJ.objects(i).data.vertices: [n x 3 double]\n% OBJ.objects(i).data.texture: [n x 3 double]\n% OBJ.objects(i).data.normal: [n x 3 double]\n%\n% example reading/writing,\n%\n% OBJ=read_wobj('examples\\example10.obj');\n% write_wobj(OBJ,'test.obj');\n%\n% example isosurface to obj-file,\n%\n% % Load MRI scan\n% load('mri','D'); D=smooth3(squeeze(D));\n% % Make iso-surface (Mesh) of skin\n% FV=isosurface(D,1);\n% % Calculate Iso-Normals of the surface\n% N=isonormals(D,FV.vertices);\n% L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps;\n% N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L;\n% % Display the iso-surface\n% figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight\n% % Invert Face rotation\n% FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)];\n%\n% % Make a material structure\n% material(1).type='newmtl';\n% material(1).data='skin';\n% material(2).type='Ka';\n% material(2).data=[0.8 0.4 0.4];\n% material(3).type='Kd';\n% material(3).data=[0.8 0.4 0.4];\n% material(4).type='Ks';\n% material(4).data=[1 1 1];\n% material(5).type='illum';\n% material(5).data=2;\n% material(6).type='Ns';\n% material(6).data=27;\n%\n% % Make OBJ structure\n% clear OBJ\n% OBJ.vertices = FV.vertices;\n% OBJ.vertices_normal = N;\n% OBJ.material = material;\n% OBJ.objects(1).type='g';\n% OBJ.objects(1).data='skin';\n% OBJ.objects(2).type='usemtl';\n% OBJ.objects(2).data='skin';\n% OBJ.objects(3).type='f';\n% OBJ.objects(3).data.vertices=FV.faces;\n% OBJ.objects(3).data.normal=FV.faces;\n% write_wobj(OBJ,'skinMRI.obj');\n%\n% Function is written by D.Kroon University of Twente (June 2010)\n\nif(exist('fullfilename','var')==0)\n [filename, filefolder] = uiputfile('*.obj', 'Write obj-file');\n fullfilename = [filefolder filename];\nend\n[filefolder,filename] = fileparts( fullfilename);\n\ncomments=cell(1,4);\ncomments{1}=' Produced by Matlab Write Wobj exporter ';\ncomments{2}='';\n\nfid = fopen(fullfilename,'w');\nwrite_comment(fid,comments);\n\nif(isfield(OBJ,'material')&&~isempty(OBJ.material))\n filename_mtl=fullfile(filefolder,[filename '.mtl']);\n fprintf(fid,'mtllib %s\\n',filename_mtl);\n write_MTL_file(filename_mtl,OBJ.material)\n \nend\n\nif(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices))\n write_vertices(fid,OBJ.vertices,'v');\nend\n\nif(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point))\n write_vertices(fid,OBJ.vertices_point,'vp');\nend\n\nif(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal))\n write_vertices(fid,OBJ.vertices_normal,'vn');\nend\n\nif(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture))\n write_vertices(fid,OBJ.vertices_texture,'vt');\nend\n\nfor i=1:length(OBJ.objects)\n type=OBJ.objects(i).type;\n data=OBJ.objects(i).data;\n switch(type)\n case 'usemtl'\n fprintf(fid,'usemtl %s\\n',data);\n case 'f'\n check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture));\n check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal));\n if(check1&&check2)\n for j=1:size(data.vertices,1)\n fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1));\n fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2));\n fprintf(fid,' %d/%d/%d\\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3));\n end\n elseif(check1)\n for j=1:size(data.vertices,1)\n fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1));\n fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2));\n fprintf(fid,' %d/%d\\n', data.vertices(j,3),data.texture(j,3));\n end\n elseif(check2)\n for j=1:size(data.vertices,1)\n fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1));\n fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2));\n fprintf(fid,' %d//%d\\n', data.vertices(j,3),data.normal(j,3));\n end\n else\n for j=1:size(data.vertices,1)\n fprintf(fid,'f %d %d %d\\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3));\n end\n end\n otherwise\n fprintf(fid,'%s ',type);\n if(iscell(data))\n for j=1:length(data)\n if(ischar(data{j}))\n fprintf(fid,'%s ',data{j});\n else\n fprintf(fid,'%0.5g ',data{j});\n end\n end \n elseif(ischar(data))\n fprintf(fid,'%s ',data);\n else\n for j=1:length(data)\n fprintf(fid,'%0.5g ',data(j));\n end \n end\n fprintf(fid,'\\n');\n end\nend\nfclose(fid);\n\nfunction write_MTL_file(filename,material)\nfid = fopen(filename,'w');\ncomments=cell(1,2);\ncomments{1}=' Produced by Matlab Write Wobj exporter ';\ncomments{2}='';\nwrite_comment(fid,comments);\n\nfor i=1:length(material)\n type=material(i).type;\n data=material(i).data;\n switch(type)\n case('newmtl')\n fprintf(fid,'%s ',type);\n fprintf(fid,'%s\\n',data);\n case{'Ka','Kd','Ks'}\n fprintf(fid,'%s ',type);\n fprintf(fid,'%5.5f %5.5f %5.5f\\n',data);\n case('illum')\n fprintf(fid,'%s ',type);\n fprintf(fid,'%d\\n',data);\n case {'Ns','Tr','d'}\n fprintf(fid,'%s ',type);\n fprintf(fid,'%5.5f\\n',data);\n otherwise\n fprintf(fid,'%s ',type);\n if(iscell(data))\n for j=1:length(data)\n if(ischar(data{j}))\n fprintf(fid,'%s ',data{j});\n else\n fprintf(fid,'%0.5g ',data{j});\n end\n end \n elseif(ischar(data))\n fprintf(fid,'%s ',data);\n else\n for j=1:length(data)\n fprintf(fid,'%0.5g ',data(j));\n end \n end\n fprintf(fid,'\\n');\n end\nend\n\ncomments=cell(1,2);\ncomments{1}='';\ncomments{2}=' EOF';\nwrite_comment(fid,comments);\nfclose(fid);\n\nfunction write_comment(fid,comments)\nfor i=1:length(comments), fprintf(fid,'# %s\\n',comments{i}); end\n\nfunction write_vertices(fid,V,type)\nswitch size(V,2)\n case 1\n for i=1:size(V,1)\n fprintf(fid,'%s %5.5f\\n', type, V(i,1));\n end\n case 2\n for i=1:size(V,1)\n fprintf(fid,'%s %5.5f %5.5f\\n', type, V(i,1), V(i,2));\n end\n case 3\n for i=1:size(V,1)\n fprintf(fid,'%s %5.5f %5.5f %5.5f\\n', type, V(i,1), V(i,2), V(i,3));\n end\n otherwise\nend\nswitch(type)\n case 'v'\n fprintf(fid,'# %d vertices \\n', size(V,1));\n case 'vt'\n fprintf(fid,'# %d texture verticies \\n', size(V,1));\n case 'vn'\n fprintf(fid,'# %d normals \\n', size(V,1));\n otherwise\n fprintf(fid,'# %d\\n', size(V,1));\n \nend\n\n\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/wavefront/write_wobj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.18103579092158026}} {"text": "function CstDefineFrequencydomainSolver(mws,startFreq,endFreq,samples)\n\n\n\nChangeSolverType = invoke(mws,'ChangeSolverType','HF Frequency Domain');\n\n\n\n%'@ define frequency domain solver parameters\nMesh = invoke(mws,'Mesh');\ninvoke(Mesh,'SetCreator','High Frequency');\nFDSolver = invoke(mws,'FDSolver');\ninvoke(FDSolver,'Reset');\ninvoke(FDSolver,'SetMethod','Tetrahedral','General purpose');\ninvoke(FDSolver,'OrderTet','Second');\ninvoke(FDSolver,'OrderSrf','First');\ninvoke(FDSolver,'Stimulation','All','All');\ninvoke(FDSolver,'ResetExcitationList');\ninvoke(FDSolver,'AutoNormImpedance','True');\ninvoke(FDSolver,'NormingImpedance','50');\ninvoke(FDSolver,'ModesOnly','False');\ninvoke(FDSolver,'ConsiderPortLossesTet','True');\ninvoke(FDSolver,'SetShieldAllPorts','False');\ninvoke(FDSolver,'AccuracyHex','1e-6');\ninvoke(FDSolver,'AccuracyTet','1e-4');\ninvoke(FDSolver,'AccuracySrf','1e-3');\ninvoke(FDSolver,'LimitIterations','False');\ninvoke(FDSolver,'MaxIterations','0');\ninvoke(FDSolver,'SetCalculateExcitationsInParallel','True','True','');\ninvoke(FDSolver,'StoreAllResults','False');\ninvoke(FDSolver,'StoreResultsInCache','False');\ninvoke(FDSolver,'UseHelmholtzEquation','True');\ninvoke(FDSolver,'LowFrequencyStabilization','True');\ninvoke(FDSolver,'Type','Auto');\ninvoke(FDSolver,'MeshAdaptionHex','False');\ninvoke(FDSolver,'MeshAdaptionTet','True');\ninvoke(FDSolver,'AcceleratedRestart','True');\ninvoke(FDSolver,'FreqDistAdaptMode','Distributed');\ninvoke(FDSolver,'NewIterativeSolver','True');\ninvoke(FDSolver,'TDCompatibleMaterials','False');\ninvoke(FDSolver,'ExtrudeOpenBC','False');\ninvoke(FDSolver,'SetOpenBCTypeHex','Default');\ninvoke(FDSolver,'SetOpenBCTypeTet','Default');\ninvoke(FDSolver,'AddMonitorSamples','True');\ninvoke(FDSolver,'CalcStatBField','False');\ninvoke(FDSolver,'CalcPowerLoss','True');\ninvoke(FDSolver,'CalcPowerLossPerComponent','False');\ninvoke(FDSolver,'StoreSolutionCoefficients','True');\ninvoke(FDSolver,'UseDoublePrecision','False');\ninvoke(FDSolver,'UseDoublePrecision_ML','True');\ninvoke(FDSolver,'MixedOrderSrf','False');\ninvoke(FDSolver,'MixedOrderTet','False');\ninvoke(FDSolver,'PreconditionerAccuracyIntEq','0.15');\ninvoke(FDSolver,'MLFMMAccuracy','Default');\ninvoke(FDSolver,'MinMLFMMBoxSize','0.3');\ninvoke(FDSolver,'UseCFIEForCPECIntEq','true');\n\n\ninvoke(FDSolver,'UseFastRCSSweepIntEq','false'); \ninvoke(FDSolver,'UseSensitivityAnalysis','False');\n% invoke(FDSolver,'SweepErrorThreshold','True','0.01');\ninvoke(FDSolver,'RemoveAllStopCriteria','Hex');\ninvoke(FDSolver,'AddStopCriterion','All S-Parameters','0.01','2','Hex','True');\ninvoke(FDSolver,'AddStopCriterion','Reflection S-Parameters','0.01','2','Hex','False');\ninvoke(FDSolver,'AddStopCriterion','Transmission S-Parameters','0.01','2','Hex','False');\ninvoke(FDSolver,'RemoveAllStopCriteria','Tet');\n\ninvoke(FDSolver,'AddStopCriterion','All S-Parameters','0.01','2','Tet','True');\ninvoke(FDSolver,'AddStopCriterion','Reflection S-Parameters','0.01','2','Tet','False');\ninvoke(FDSolver,'AddStopCriterion','Transmission S-Parameters','0.01','2','Tet','False');\n% invoke(FDSolver,'All Probes','0.05','2','Tet','True');\ninvoke(FDSolver,'RemoveAllStopCriteria','Srf');\n\ninvoke(FDSolver,'AddStopCriterion','All S-Parameters','0.01','2','Srf','True');\ninvoke(FDSolver,'AddStopCriterion','Reflection S-Parameters','0.01','2','Srf','False');\ninvoke(FDSolver,'AddStopCriterion','Transmission S-Parameters','0.01','2','Srf','False');\ninvoke(FDSolver,'SweepMinimumSamples','3');\ninvoke(FDSolver,'SetNumberOfResultDataSamples','1001');\n\ninvoke(FDSolver,'SetResultDataSamplingMode','Automatic');\ninvoke(FDSolver,'SweepWeightEvanescent','1.0');\ninvoke(FDSolver,'AccuracyROM','1e-4');\ninvoke(FDSolver,'AddSampleInterval','','','1','Automatic','True');\ninvoke(FDSolver,'AddSampleInterval',num2str(startFreq),num2str(endFreq),num2str(samples),'Automatic','False');\n% invoke(FDSolver,'AddSampleInterval','','','','Automatic','False');\ninvoke(FDSolver,'MPIParallelization','False');\ninvoke(FDSolver,'UseDistributedComputing','False');\ninvoke(FDSolver,'NetworkComputingStrategy','RunRemote');\ninvoke(FDSolver,'NetworkComputingJobCount','3');\ninvoke(FDSolver,'LimitCPUs','True');\ninvoke(FDSolver,'MaxCPUs','96');\ninvoke(FDSolver,'MaximumNumberOfCPUDevices','2');\n\n \nIESolver = invoke(mws,'IESolver');\ninvoke(IESolver,'Reset'); \ninvoke(IESolver,'UseFastFrequencySweep','True'); \ninvoke(IESolver,'UseIEGroundPlane','False'); \n% invoke(IESolver,'SetRealGroundMaterialName',''); \ninvoke(IESolver,'CalcFarFieldInRealGround','False'); \ninvoke(IESolver,'RealGroundModelType','Auto'); \ninvoke(IESolver,'PreconditionerType','Auto'); \ninvoke(IESolver,'ExtendThinWireModelByWireNubs','False');\n\n\nIESolver = invoke(mws,'IESolver');\ninvoke(IESolver,'SetFMMFFCalcStopLevel','0');\ninvoke(IESolver,'SetFMMFFCalcNumInterpPoints','6');\ninvoke(IESolver,'UseFMMFarfieldCalc','True');\ninvoke(IESolver,'SetCFIEAlpha','0.500000');\ninvoke(IESolver,'LowFrequencyStabilization','False');\ninvoke(IESolver,'LowFrequencyStabilizationML','True');\ninvoke(IESolver,'Multilayer','False');\ninvoke(IESolver,'SetiMoMACC_I','0.0001');\n\ninvoke(IESolver,'SetiMoMACC_M','0.0001');\ninvoke(IESolver,'DeembedExternalPorts','True');\ninvoke(IESolver,'SetOpenBC_XY','True');\ninvoke(IESolver,'OldRCSSweepDefintion','False');\ninvoke(IESolver,'SetAccuracySetting','Custom');\ninvoke(IESolver,'CalculateSParaforFieldsources','True');\n\ninvoke(IESolver,'ModeTrackingCMA','True');\ninvoke(IESolver,'NumberOfModesCMA','3');\ninvoke(IESolver,'StartFrequencyCMA','-1.0');\ninvoke(IESolver,'SetAccuracySettingCMA','Default');\ninvoke(IESolver,'FrequencySamplesCMA','0');\ninvoke(IESolver,'SetMemSettingCMA','Auto');\n\n\n\n\nFDSolver = invoke(mws,'FDSolver');\ninvoke(FDSolver,'Start');\n \n\n\n\nend\n", "meta": {"author": "simos421", "repo": "CST-MATLAB-API", "sha": "a6019ad6f33fa14ebfd459579b6e7151dd3d4ece", "save_path": "github-repos/MATLAB/simos421-CST-MATLAB-API", "path": "github-repos/MATLAB/simos421-CST-MATLAB-API/CST-MATLAB-API-a6019ad6f33fa14ebfd459579b6e7151dd3d4ece/Simulation/CstDefineFrequencydomainSolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1810293721243513}} {"text": "function output = callsdpt330(interfacedata)\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc = interfacedata.c;\nK = interfacedata.K;\nx0 = interfacedata.x0;\nub = interfacedata.ub;\nlb = interfacedata.lb;\n\n% Bounded variables converted to constraints\nif ~isempty(ub)\n [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\n% Convert from internal (sedumi) format\n[C,A,b,blk] = sdpt3struct2sdpt3block(F_struc,c,K);\n\n% To be sure\nglobal CACHE_SIZE % cache size in kbytes \nglobal LOOP_LEVEL % loop unrolling level\nCACHE_SIZE = options.sdpt3.CACHE_SIZE; \nLOOP_LEVEL = options.sdpt3.LOOP_LEVEL;\n\nA = svec(blk,A,ones(size(blk,1),1));\n\nif options.savedebug\n save sdpt3debug blk A C b x0 options.sdpt3\nend\n\nshowprogress('Calling SDPT3',options.showprogress);\n\nsolvertime = tic;\nif options.verbose==0\n evalc('[obj,X,y,Z,gaphist,infeashist,info,Xiter,yiter,Ziter] = sqlp(blk,A,C,b,[],x0,[],options.sdpt3);');\nelse\n [obj,X,y,Z,gaphist,infeashist,info,Xiter,yiter,Ziter] = sqlp(blk,A,C,b,[],x0,[],options.sdpt3);\nend\nsolvertime = toc(solvertime);\n\n% Create dual variable in internal format\nD_struc = [];\nif K.l>0\n D_struc = [D_struc;X{1}(:)];\n if length(X)>1\n X = {X{2:end}};\n end\nend\nif K.q(1)>0\n D_struc = [D_struc;X{1}(:)];\n if length(X)>1\n X = {X{2:end}};\n end\nend\nif K.r(1)>0\n D_struc = [D_struc;X{1}(:)];\n if length(X)>1\n X = {X{2:end}};\n end\nend\nif K.s(1)>0\n top = 1;\n j = 1;\n for i = 1:1:length(K.s)\n Xi = X{j}(top:top+K.s(i)-1,top:top+K.s(i)-1);\n D_struc = [D_struc;Xi(:)];\n top = top + K.s(i);\n if top>length(X{j})\n j = j + 1;\n top = 1;\n end\n end\nend\n\nx = y; % Our notation do not coincide ...\n\n% Convert error code\nswitch info(1)\n case 0\n problem = 0; % No problems detected\n case -1 \n problem = 5; % Lack of progress\n case {-2,-3,-4,-5}\n problem = 4; % Numerical problems\n case -6\n problem = 3; % Maximum iterations exceeded\n case -10\n problem = 7; % YALMIP sent incorrect input to solver\n case 1\n problem = 2; % Dual feasibility\n case 2\n problem = 1; % Primal infeasibility \n otherwise\n problem = -1; % Unknown error\nend\ninfostr = yalmiperror(problem,interfacedata.solver.tag);\n\nif options.savesolveroutput\n solveroutput.obj = obj;\n solveroutput.X = X;\n solveroutput.y = y;\n solveroutput.Z = Z;\n solveroutput.gaphist = gaphist;\n solveroutput.infeashist = infeashist;\n solveroutput.info = info;\n solveroutput.Xiter = Xiter;\n solveroutput.yiter = yiter;\n solveroutput.Ziter = Ziter;\nelse\n solveroutput = [];\nend\n\nif options.savesolverinput\n solverinput.blk = blk;\n solverinput.A = A;\n solverinput.C = C;\n solverinput.b = b;\n solverinput.X0 = [];\n solverinput.y0 = x0;\n solverinput.Z0 = [];\n solverinput.options = options.sdpt3;\nelse\n solverinput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(x(:),D_struc,[],problem,infostr,solverinput,solveroutput,solvertime);\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/solvers/callsdpt330.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.18096805628845195}} {"text": "function z = uminus( x )\n\n% Disciplined convex programming information for UMINUS (-):\n% Unary minus may be used in DCPs without restrictions---with the\n% understanding, of course, that it produces a result with the \n% opposite cuvature to its argument; i.e., the negative of a convex\n% expression is concave, and vice versa.\n%\n% Disciplined geometric programming information for UMINUS(-):\n% Negation of non-constant values may not be used in disciplined\n% geometric programs.\n\nz = cvx( x.size_, -x.basis_ );\ntt = cvx_isvalid( z, true );\nif ~all( tt ),\n cvx_dcp_error( '-', 'unary', cvx_subsref( x, ~tt ) );\nend\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/builtins/@cvx/uminus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18090453788727195}} {"text": "function [ DetectionReview ] = DetectionReview(obj,event )\n%UNTITLED Summary of this function goes here\n% Detailed explanation goes here\n%obj = findobj('tag','EventExplorerMaster'); \nFO = guidata(obj); \n%% Select the time windows to look at \n%User input for this\nnumwins = 30; %number of windows to look at. determine to maximize sampling or have user input (FO.uinput.field?)\n%Selecting from events:\n%randevents = randsample(FO.EventTimes,numevents);\n%Selecting from random times (RestrictInts takes way too long...)\nset(findobj(FO.fig,'Type','uicontrol'),'Enable','off');\ndrawnow;\nif ~isempty(FO.detectionints)\n [status,interval,index] = InIntervals(FO.data.lfp.timestamps,double(FO.detectionints));\n restrictedtimes = FO.data.lfp.timestamps(status);\nelse\n restrictedtimes = FO.data.lfp.timestamps;\nend\n\n%use InIntervals\nset(findobj(FO.fig,'Type','uicontrol'),'Enable','on');\nrandevents = randsample(restrictedtimes,numwins);\n%Find any events that are within winsize of another event to remove them?\n%Also should look at windows in which no events were detected? Maybe just\n%random windows in the detectionwin\ncloseevents = abs(diff(randevents))0 && QUITLOOP~=true\n %EventUI(FO) %function that will run the user interface\n thiseventtime = randevents(counter); \n FO.currevent = thiseventtime; guidata(FO.fig, FO);\n viewinfo = EventVewPlot;\n uiwait(FO.fig) %Wait here until the user clicks quit or next\n \n lookedatwins = [lookedatwins; viewinfo.thiseventwin];\n inwinevents = viewinfo.inwinevents;\n \n \n %Tally the user selections for that window\n obj = findobj('tag','EventExplorerMaster'); FO = guidata(obj);\n if ~isempty(FO.markedevents)\n FO.markedevents(isnan(FO.markedevents(:,1)))=[]; %remove nans - bug fix\n miss = [miss; FO.markedevents(FO.markedevents(:,3)==1,1)];\n %This is messy to account for interp errors with 0-1 reference points\n if isempty(FO.markedevents(FO.markedevents(:,3)==3,1))\n newfalsealarms = [];\n elseif length(FO.markedevents(FO.markedevents(:,3)==3,1))==1 && length(inwinevents)==1\n newfalsealarms = inwinevents;\n else\n newfalsealarms = interp1(inwinevents,inwinevents,...\n FO.markedevents(FO.markedevents(:,3)==3,1),'nearest');\n end\n falsealarm = [falsealarm; newfalsealarms];\n end\n hit = [hit; inwinevents(~ismember(inwinevents,falsealarm))];\n FO.markedevents = []; guidata(FO.fig, FO); %reset the marked events\n \n counter = counter-1;\n set(correcttext, 'String',['Correct: ',num2str(length(hit))]);\n set(misstext, 'String', ['Miss: ',num2str(length(miss))]);\n set(FAtext, 'String', ['FA: ',num2str(length(falsealarm))]);\n set(countetext, 'String', ['Windows Remaining: ',num2str(counter)]);\nend\n%Calculate total number of miss,hit,FA\nnumMiss = length(miss);\nnumHit = length(hit);\nnumFA = length(falsealarm); \n\n%Calculate total amount of time/percentage of detection time (detectionintervals) looked at\n\n%Put things in the output structure\nDetectionReview.lookedatwins = lookedatwins;\nDetectionReview.miss = miss; \nDetectionReview.hit = hit;\nDetectionReview.falsealarm = falsealarm;\nDetectionReview.estMissperc = numMiss./(numHit+numMiss);\nDetectionReview.estFAperc = numFA./(numHit+numFA);\nDetectionReview.ReviewDate = today;\nDetectionReview.EventsType = FO.EventName;\n\n%UI: Done! Would you like to save the results to (eventsfilename?)\n%Make function that does this: SaveResults(FO,EEoutput)\nif isfield(FO,'eventsfilename')\n button = questdlg(['Event Review Complete! Would you like to add the results to ',...\n FO.eventsfilename,'?'],'Good Job!');\n switch button\n case 'Yes'\n %Load the events file, add the field, save the events file\n try %Only do this if the correct named structure lives in the file\n eventsfile = load(FO.eventsfilename,FO.EventName);\n eventsfile.(FO.EventName).EventExplorer.DetectionReview = DetectionReview;\n save(FO.eventsfilename,'-struct','eventsfile',FO.EventName,'-append')\n catch\n warndlg({' Save failed... ',[FO.eventsfilename,' may not ',...\n 'contain a structure titled ',FO.EventName,'.'],...\n 'Or you may not have sudo priviliges...?'},'Oh No!')\n end\n end\nend\n\n%% Return to explorer mode\nFO.viewmode = 'events';\nFO.currentuseraction = 'none';\nFO.currevent = 1;\nset(FO.EventPanel,'Visible','off')\nFO.DetectionReview = DetectionReview;\nguidata(FO.fig, FO); %Save the detection review back to GUI data\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/GUITools/EventExplorer/EEhelpers/DetectionReview.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18088620739097117}} {"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": "% run_hd_specialproc_auto.m\n% Jamie Near, Sunnybrook Research Institute 2021.\n% \n% USAGE:\n% [out1,out2,out1_w,out2_w]=run_hd_specialproc_auto(filestring,VoxIDs,aaDomain,tmaxin,iterin);\n% \n% DESCRIPTION:\n% Processing script for Siemens Hadamard-encoded SPECIAL (HD-SPECIAL) MRS \n% data in .dat format (twix raw data). Includes combination of reciever \n% channels, removal of bad averages, frequency drift correction, \n% leftshifting, and Hadamard Reconstruction.\n% \n% INPUTS:\n% filestring = String variable for the name of the directory containing\n% the water suppressed HD-SPECIAL .dat file. Water unsuppressed\n% .dat file should be contained in [filestring '_w/'];\n% VoxIDs = (Optional) Two-element cell array with elements that are string variables \n% giving names to the voxel IDs. Default is {'Vox1','Vox2'} \n% aaDomain = (Optional) Perform the spectral registration (drift correction) using\n% the full spectrum ('t'), or only a limited frequency\n% range ('f'). Default is 'f'.\n% tmaxin = (Optional). Duration (in sec.) of the time domain signal\n% used in the spectral registration (drift correction).\n% Default is 0.2 sec.\n% iterin = (Optional). Maximum number of allowed iterations for the spectral\n% registration to converge. Default is 20.\n% \n% OUTPUTS:\n% out1 = Fully processed, water suppressed output spectrum from first voxel.\n% out2 = Fully processed, water suppressed output spectrum from second voxel. \n% out1_w = Fully processed, water unsuppressed output spectrum from first voxel.\n% out2_w = Fully processed, water unsuppressed output spectrum from second voxel. \n\n\nfunction [out1,out2,out1_w,out2_w]=run_hdspecialproc_auto(filestring,VoxIDs,aaDomain,tmaxin,iterin)\n\nif nargin<5\n iterin=20;\n if nargin<4\n tmaxin=0.2;\n if nargin<3\n aaDomain='f';\n if nargin<2\n VoxIDs={'Vox1','Vox2'};\n end\n end\n end\nend\n\n\n%Ensure that filestring is an absolute path, otherwise you can get yourself\n%in a tangle later inserting figures at the report stage.\nif ~java.io.File(filestring).isAbsolute\n filestring = cd(cd(filestring)); \nend\n\n%make a new directory for the output report and figures:\nreportDir = fullfile(filestring,'report');\nmkdir(reportDir);\nreportFigsDir = fullfile(filestring,'report','figs');\nmkdir(reportFigsDir);\n\n%Find the filename of the SPECIAL dataset\nclose all\nunixString1=fullfile(filestring,'*.dat');\n[filename]=dir(unixString1);\nfilename=filename.name(1:end);\n\nunixStringw=fullfile([filestring '_w'],'*.dat');\n[filenamew]=dir(unixStringw);\nif ~isempty(filenamew)\n filenamew=filenamew.name(1:end);\n water=true\nelse\n water=false\n out_w=struct();\n out_w_noproc=struct();\nend\n\n%read in the data:\nout_raw=io_loadspec_twix(fullfile(filestring,filename));\n\n%load water unsuppressed data and find the coil phases:\nif water\n disp('***FOUND WATER UNSUPPRESSED DATA***');\n out_w_raw=io_loadspec_twix(fullfile([filestring '_w/'], filenamew));\n coilcombos1=op_getcoilcombos(op_combinesubspecs(op_fourStepCombine(out_w_raw,1),'diff'),2);\n coilcombos2=op_getcoilcombos(op_combinesubspecs(op_fourStepCombine(out_w_raw,3),'diff'),2);\nelse\n disp('***WATER UNSUPPRESSED DATA NOT FOUND***');\n coilcombos1=op_getcoilcombos_specReg(op_combinesubspecs(op_fourStepCombine(op_averaging(out_raw),1),'diff'),0,0.01,2);\n coilcombos2=op_getcoilcombos_specReg(op_combinesubspecs(op_fourStepCombine(op_averaging(out_raw),3),'diff'),0,0.01,2);\n out_w='';\n out_w_noproc='';\nend\n\n%now combine the coil channels:\n[out1_cc,fid1_pre,spec1_pre,ph1,sig1]=op_addrcvrs(out_raw,2,'w',coilcombos1);\n[out2_cc,fid2_pre,spec2_pre,ph2,sig2]=op_addrcvrs(out_raw,2,'w',coilcombos2);\nif water\n [out1_w_cc,fid1_w_pre,spec1_w_pre,ph1_w,sig1_w]=op_addrcvrs(out_w_raw,2,'w',coilcombos1);\n [out2_w_cc,fid2_w_pre,spec2_w_pre,ph2_w,sig2_w]=op_addrcvrs(out_w_raw,2,'w',coilcombos2);\nend\n\n%Do the hadamard reconstruction:\nout1_hd=op_fourStepCombine(out1_cc,1);\nout2_hd=op_fourStepCombine(out2_cc,3);\nif water\n out1_w_hd=op_fourStepCombine(out1_w_cc,1);\n out2_w_hd=op_fourStepCombine(out2_w_cc,3);\nend \n\n%make the un-processed spectra, which may be optionally output from this function:\nout1_noproc=op_combinesubspecs(op_averaging(out1_hd),'diff');\nout2_noproc=op_combinesubspecs(op_averaging(out2_hd),'diff');\nif water\n out1_w_noproc=op_combinesubspecs(op_averaging(out1_w_hd),'diff');\n out2_w_noproc=op_combinesubspecs(op_averaging(out2_w_hd),'diff');\nend\n\n%plot the data before and after coil phasing:\n%figure('position',[0 50 560 420]);\nh=figure('visible','off');\nsubplot(1,3,1);\nplot(out_raw.ppm,out_raw.specs(:,:,1,1));xlim([-1 7]);\nset(gca,'FontSize',12);\nset(gca,'XDir','reverse');\nxlabel('Frequency (ppm)','FontSize',10);\nylabel('Amplitude (a.u.)','FontSize',10);\ntitle('Before correction','FontSize',12);\nbox off;\nsubplot(1,3,2);\nplot(out_raw.ppm,spec1_pre(:,:,1,1));xlim([-1 7]);\nset(gca,'FontSize',12);\nset(gca,'XDir','reverse');\nxlabel('Frequency (ppm)','FontSize',10);\nylabel('Amplitude(a.u.)','FontSize',10);\ntitle('After correction','FontSize',12);\nbox off;\nsubplot(1,3,3);\nplot(out_raw.ppm,spec2_pre(:,:,1,1));xlim([-1 7]);\nset(gca,'FontSize',12);\nset(gca,'XDir','reverse');\nxlabel('Frequency (ppm)','FontSize',10);\nylabel('Amplitude(a.u.)','FontSize',10);\ntitle('After correction','FontSize',12);\nbox off;\nset(h,'PaperUnits','centimeters');\nset(h,'PaperPosition',[0 0 20 10]);\nsaveas(h,fullfile(reportFigsDir,'coilReconFig'),'jpg');\nsaveas(h,fullfile(reportFigsDir,'coilReconFig'),'fig');\nclose(h);\n\nif water\n %figure('position',[0 550 560 420]);\n h=figure('visible','off');\n subplot(1,3,1);\n plot(out_w_raw.ppm,out_w_raw.specs(:,:,1,1));xlim([4 5]);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude (a.u.)','FontSize',10);\n title('Before correction','FontSize',12);\n box off;\n subplot(1,3,2);\n plot(out_w_raw.ppm,spec1_w_pre(:,:,1,1));xlim([4 5]);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('After correction','FontSize',12);\n box off;\n subplot(1,3,3);\n plot(out_w_raw.ppm,spec2_w_pre(:,:,1,1));xlim([4 5]);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('After correction','FontSize',12);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 10]);\n saveas(h,fullfile(reportFigsDir,'coilReconFig_w'),'jpg');\n saveas(h,fullfile(reportFigsDir,'coilReconFig_w'),'fig');\n close(h);\nend\n\n%%%%%%%%%%%%%%%%%%%%%OPTIONAL ALIGNMENT OF SUBSPECTRA%%%%%%%%%%%%%%%%\nclose all;\nfs1_ai=[];\nphs1_ai=[];\nfs2_ai=[];\nphs2_ai=[];\nalignISIS='y'\nif strcmp(alignISIS,'y') || strcmp(alignISIS,'Y')\n %What we're actually doing is aligning the averages, then aligning the\n %subspectra, then aligning the averages again, and then aligning the\n %subspectra again. \n [out1_ai,fs1_temp,phs1_temp]=op_alignAverages(out1_hd,0.4,'y');\n [out2_ai,fs2_temp,phs2_temp]=op_alignAverages(out2_hd,0.4,'y');\n fs1_ai=fs1_temp;\n fs2_ai=fs2_temp;\n phs1_ai=phs1_temp;\n phs2_ai=phs2_temp;\n \n [out1_ai,fs1_temp,phs1_temp]=op_alignISIS(out1_ai,0.4);\n [out2_ai,fs2_temp,phs2_temp]=op_alignISIS(out2_ai,0.4);\n fs1_ai(:,2)=fs1_ai(:,2)+fs1_temp;\n fs2_ai(:,2)=fs2_ai(:,2)+fs2_temp;\n phs1_ai(:,2)=phs1_ai(:,2)+phs1_temp;\n phs2_ai(:,2)=phs2_ai(:,2)+phs2_temp;\n \n [out1_ai,fs1_temp,phs1_temp]=op_alignAverages(out1_ai,0.4,'y');\n [out2_ai,fs2_temp,phs2_temp]=op_alignAverages(out2_ai,0.4,'y');\n fs1_ai=fs1_ai+fs1_temp;\n fs2_ai=fs2_ai+fs2_temp;\n phs1_ai=phs1_ai+phs1_temp;\n phs2_ai=phs2_ai+phs2_temp;\n \n [out1_ai,fs1_temp,phs1_temp]=op_alignISIS(out1_ai,0.4);\n [out2_ai,fs2_temp,phs2_temp]=op_alignISIS(out2_ai,0.4);\n fs1_ai(:,2)=fs1_ai(:,2)+fs1_temp;\n fs2_ai(:,2)=fs2_ai(:,2)+fs2_temp;\n phs1_ai(:,2)=phs1_ai(:,2)+phs1_temp;\n phs2_ai(:,2)=phs2_ai(:,2)+phs2_temp;\n \n %for fs_ai and phs_ai, take the average across both subspecs:\n fs1_ai=mean(fs1_ai,2);\n fs2_ai=mean(fs2_ai,2);\n phs1_ai=mean(phs1_ai,2);\n phs2_ai=mean(phs2_ai,2);\n \n if water\n %Now repeat above for water unsuppressed data:\n [out1_w_ai,fs1_w_temp,phs1_w_temp]=op_alignAverages(out1_w_hd,0.4,'y');\n [out2_w_ai,fs2_w_temp,phs2_w_temp]=op_alignAverages(out2_w_hd,0.4,'y');\n fs1_w_ai=fs1_w_temp;\n fs2_w_ai=fs2_w_temp;\n phs1_w_ai=phs1_w_temp;\n phs2_w_ai=phs2_w_temp;\n \n [out1_w_ai,fs1_w_temp,phs1_w_temp]=op_alignISIS(out1_w_ai,0.4);\n [out2_w_ai,fs2_w_temp,phs2_w_temp]=op_alignISIS(out2_w_ai,0.4);\n fs1_w_ai(:,2)=fs1_w_ai(:,2)+fs1_w_temp;\n fs2_w_ai(:,2)=fs2_w_ai(:,2)+fs2_w_temp;\n phs1_w_ai(:,2)=phs1_w_ai(:,2)+phs1_w_temp;\n phs2_w_ai(:,2)=phs2_w_ai(:,2)+phs2_w_temp;\n \n [out1_w_ai,fs1_w_temp,phs1_w_temp]=op_alignAverages(out1_w_ai,0.4,'y');\n [out2_w_ai,fs2_w_temp,phs2_w_temp]=op_alignAverages(out2_w_ai,0.4,'y');\n fs1_w_ai=fs1_w_ai+fs1_w_temp;\n fs2_w_ai=fs2_w_ai+fs2_w_temp;\n phs1_w_ai=phs1_w_ai+phs1_w_temp;\n phs2_w_ai=phs2_w_ai+phs2_w_temp;\n \n [out1_w_ai,fs1_w_temp,phs1_w_temp]=op_alignISIS(out1_w_ai,0.4);\n [out2_w_ai,fs2_w_temp,phs2_w_temp]=op_alignISIS(out2_w_ai,0.4);\n fs1_w_ai(:,2)=fs1_w_ai(:,2)+fs1_w_temp;\n fs2_w_ai(:,2)=fs2_w_ai(:,2)+fs2_w_temp;\n phs1_w_ai(:,2)=phs1_w_ai(:,2)+phs1_w_temp;\n phs2_w_ai(:,2)=phs2_w_ai(:,2)+phs2_w_temp;\n \n %for fs_w_ai and phs_w_ai, take the average across both subspecs:\n fs1_w_ai=mean(fs1_w_ai,2);\n fs2_w_ai=mean(fs2_w_ai,2);\n phs1_w_ai=mean(phs1_w_ai,2);\n phs2_w_ai=mean(phs2_w_ai,2);\n end\n \n %Now check the plots to make sure that they look okay:\n %First make combined subspecs plots:\n out1_hd_temp=op_combinesubspecs(out1_hd,'diff');\n out2_hd_temp=op_combinesubspecs(out2_hd,'diff');\n out1_ai_cc_temp=op_combinesubspecs(out1_ai,'diff');\n out2_ai_cc_temp=op_combinesubspecs(out2_ai,'diff');\n if water\n out1_w_hd_temp=op_combinesubspecs(out1_w_hd,'diff');\n out2_w_hd_temp=op_combinesubspecs(out2_w_hd,'diff');\n out1_w_ai_cc_temp=op_combinesubspecs(out1_w_ai,'diff');\n out2_w_ai_cc_temp=op_combinesubspecs(out2_w_ai,'diff');\n end\n \n %Now plot them\n close all\n %figure('position',[0 0 560 420]);\n h=figure('visible','off');\n subplot(2,2,1);\n plot(out1_hd_temp.ppm,out1_hd_temp.specs);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs not aligned: (all averages)','FontSize',12);\n xlim([0.2 5.2]);\n box off;\n subplot(2,2,3);\n plot(out2_hd_temp.ppm,out2_hd_temp.specs);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs not aligned: (all averages)','FontSize',12);\n xlim([0.2 5.2]);\n box off;\n subplot(2,2,2);\n plot(out1_ai_cc_temp.ppm,out1_ai_cc_temp.specs);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs aligned: (all averages)','FontSize',12);\n xlim([0.2 5.2]);\n box off;\n subplot(2,2,4);\n plot(out2_ai_cc_temp.ppm,out2_ai_cc_temp.specs);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs aligned: (all averages)','FontSize',12);\n xlim([0.2 5.2]);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 15]);\n saveas(h,[filestring '/report/figs/alignSubSpecs_prePostFig'],'jpg');\n saveas(h,[filestring '/report/figs/alignSubSpecs_prePostFig'],'fig');\n close(h);\n \n \n if water\n %figure('position',[0 550 560 420]);\n h=figure('visible','off');\n subplot(2,2,1);\n plot(out1_w_hd_temp.ppm,out1_w_hd_temp.specs);\n xlim([3.7 5.7]);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs not aligned: (all averages)','FontSize',12);\n box off;\n subplot(2,2,3);\n plot(out2_w_hd_temp.ppm,out2_w_hd_temp.specs);\n xlim([3.7 5.7]);\n set(gca,'FontSize',12);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs not aligned: (all averages)','FontSize',12);\n box off;\n subplot(1,2,2);\n plot(out1_w_ai_cc_temp.ppm,out1_w_ai_cc_temp.specs);\n xlim([3.7 5.7]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs aligned: (all averages)','FontSize',12);\n box off;\n subplot(2,2,4);\n plot(out2_w_ai_cc_temp.ppm,out2_w_ai_cc_temp.specs);\n xlim([3.7 5.7]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Subspecs aligned: (all averages)','FontSize',12);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 15]);\n saveas(h,fullfile(reportFigsDir,'alignSubSpecs_w_prePostFig'),'jpg');\n saveas(h,fullfile(reportFigsDir,'alignSubSpecs_w_prePostFig'),'fig');\n close(h);\n end\n \n% figure('position',[570 50 560 420]);\n% subplot(2,1,1);\n% plot([1:length(fs_ai)],fs_ai);\n% xlabel('Scan Number');\n% ylabel('Frequency Drift (Hz)');\n% title('Estimated Frequency Drift');\n% subplot(2,1,2);\n% plot([1:length(phs_ai)],phs_ai);\n% xlabel('Scan Number');\n% ylabel('Phase Drift (Degrees)');\n% title('Estimated Phase Drift');\n \n \n %sat=input('are you satisfied with alignment of subspecs? ','s');\n sat='y';\n if strcmp(sat,'n') || strcmp(sat,'N')\n out1_ai=out1_hd;\n out2_ai=out2_hd;\n if water\n out1_w_ai=out1_w_hd;\n out2_w_ai=out2_w_hd;\n end\n end\n \nelse\n out1_ai=out1_hd;\n out2_ai=out2_hd;\n out1_w_ai=out1_w_hd;\n out2_w_ai=out2_w_hd;\n fs1_ai=zeros(size(out1_hd.fids,out1_hd.dims.averages),1);\n fs2_ai=zeros(size(out2_hd.fids,out2_hd.dims.averages),1);\n phs1_ai=zeros(size(out1_hd.fids,out1_hd.dims.averages),1);\n phs2_ai=zeros(size(out2_hd.fids,out2_hd.dims.averages),1);\nend\n \n\n%Now combine the subspecs\nout1_cs=op_combinesubspecs(out1_ai,'diff');\nout2_cs=op_combinesubspecs(out2_ai,'diff');\nif water\n out1_w_cs=op_combinesubspecs(out1_w_ai,'diff');\n out2_w_cs=op_combinesubspecs(out2_w_ai,'diff');\nend\n\n%%%%%%%%%%%%%%%%%%%%%END OF ALIGNMENT OF SUBSPECTRA%%%%%%%%%%%%%%%%%%\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%OPTIONAL REMOVAL OF BAD AVERAGES%%%%%%%%%%%%%%%%\nclose all;\nout1_cs2=out1_cs;\nout2_cs2=out2_cs;\nnBadAvgTotal1=0;\nnBadAvgTotal2=0;\nnbadAverages1=1;\nnbadAverages2=1;\nallAveragesLeft1=[1:out1_cs.sz(out1_cs.dims.averages)]';\nallAveragesLeft2=[1:out2_cs.sz(out2_cs.dims.averages)]';\nallBadAverages1=[];\nallBadAverages2=[];\nrmbadav='y';\nclose all;\nif rmbadav=='n' || rmbadav=='N'\n out1_rm=out1_cs;\n out2_rm=out2_cs;\n nsd='N/A';\nelse\n sat='n'\n while sat=='n'||sat=='N'\n nsd=3; %setting the number of standard deviations;\n iter1=1;\n iter2=1;\n nbadAverages1=1;\n nbadAverages2=1;\n nBadAvgTotal1=0;\n nBadAvgTotal2=0;\n allAveragesLeft1=[1:out1_cs.sz(out1_cs.dims.averages)]';\n allAveragesLeft2=[1:out2_cs.sz(out2_cs.dims.averages)]';\n allBadAverages1=[];\n allBadAverages2=[];\n out1_cs2=out1_cs;\n out2_cs2=out2_cs;\n while nbadAverages1>0;\n [out1_rm,metric1{iter1},badAverages1]=op_rmbadaverages(out1_cs2,nsd,'t');\n allBadAverages1=[allBadAverages1; allAveragesLeft1(badAverages1)];\n badavMask1_temp=zeros(length(allAveragesLeft1),1);\n badavMask1_temp(badAverages1)=1;\n allAveragesLeft1=allAveragesLeft1(~badavMask1_temp);\n nbadAverages1=numel(badAverages1);\n nBadAvgTotal1=nBadAvgTotal1+nbadAverages1;\n out1_cs2=out1_rm;\n iter1=iter1+1;\n disp([num2str(nbadAverages1) ' bad averages removed from spectrum #1 on this iteration.']);\n disp([num2str(nBadAvgTotal1) ' bad averages removed from spectrum #1 in total.']);\n close all;\n end\n while nbadAverages2>0;\n [out2_rm,metric2{iter2},badAverages2]=op_rmbadaverages(out2_cs2,nsd,'t');\n allBadAverages2=[allBadAverages2; allAveragesLeft2(badAverages2)];\n badavMask2_temp=zeros(length(allAveragesLeft2),1);\n badavMask2_temp(badAverages2)=1;\n allAveragesLeft2=allAveragesLeft2(~badavMask2_temp);\n nbadAverages2=numel(badAverages2);\n nBadAvgTotal2=nBadAvgTotal2+nbadAverages2;\n out2_cs2=out2_rm;\n iter2=iter2+1;\n disp([num2str(nbadAverages2) ' bad averages removed from spectrum #2 on this iteration.']);\n disp([num2str(nBadAvgTotal2) ' bad averages removed from spectrum #2 in total.']);\n close all;\n end\n \n \n %figure('position',[0 50 560 420]);\n h=figure('visible','off');\n subplot(2,2,1);\n plot(out1_cs.ppm,out1_cs.specs);xlim([1 5]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Before removal of bad averages:','FontSize',12);\n box off;\n subplot(2,2,3);\n plot(out2_cs.ppm,out2_cs.specs);xlim([1 5]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('Before removal of bad averages:','FontSize',12);\n box off;\n subplot(2,2,2);\n plot(out1_rm.ppm,out1_rm.specs);xlim([1 5]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('After removal of bad averages:','FontSize',12);\n box off;\n subplot(2,2,4);\n plot(out2_rm.ppm,out2_rm.specs);xlim([1 5]);\n set(gca,'FontSize',8);\n set(gca,'XDir','reverse');\n xlabel('Frequency (ppm)','FontSize',10);\n ylabel('Amplitude(a.u.)','FontSize',10);\n title('After removal of bad averages:','FontSize',12);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 15]);\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_prePostFig'),'jpg');\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_prePostFig'),'fig');\n close(h);\n \n %figure('position',[0 550 560 420]);\n h=figure('visible','off'); \n plot(1:out1_cs.sz(out1_cs.dims.averages),metric1{1},'.r','MarkerSize',16)\n hold on\n removedAvgs1 = find(~ismember(1:out1_cs.sz(out1_cs.dims.averages),allAveragesLeft1));\n plot(removedAvgs1,metric1{1}(removedAvgs1,1),'ko','MarkerSize',20)\n set(gca,'FontSize',8);\n xlabel('Scan Number','FontSize',10);\n ylabel('Deviation Metric','FontSize',10);\n legend('Original averages','Removed Avg')\n legend boxoff;\n title('Deviation Metric','FontSize',12);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 10]);\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_vox1_scatterFig1'),'jpg');\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_vox1_scatterFig1'),'fig');\n close(h);\n \n h=figure('visible','off'); \n plot(1:out2_cs.sz(out2_cs.dims.averages),metric2{1},'.r','MarkerSize',16)\n hold on\n removedAvgs2 = find(~ismember(1:out2_cs.sz(out2_cs.dims.averages),allAveragesLeft2));\n plot(removedAvgs2,metric2{1}(removedAvgs2,1),'ko','MarkerSize',20)\n set(gca,'FontSize',8);\n xlabel('Scan Number','FontSize',10);\n ylabel('Deviation Metric','FontSize',10);\n legend('Original averages','Removed Avg')\n legend boxoff;\n title('Deviation Metric','FontSize',12);\n box off;\n set(h,'PaperUnits','centimeters');\n set(h,'PaperPosition',[0 0 20 10]);\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_vox2_scatterFig'),'jpg');\n saveas(h,fullfile(reportFigsDir,'rmBadAvg_vox2_scatterFig'),'fig');\n close(h);\n \n %sat=input('are you satisfied with bad averages removal? ','s');\n sat='y';\n end\nend\n\nclose all;\n\n%Now remove the entries from fs_ai and phs_ai that correspond to\n%the bad-averages that were removed.\nBadAvgMask1=zeros(length(fs1_ai),1);\nBadAvgMask2=zeros(length(fs2_ai),1);\nBadAvgMask1(allBadAverages1)=1;\nBadAvgMask2(allBadAverages2)=1;\nsize(BadAvgMask1)\nsize(BadAvgMask2)\nsize(fs1_ai)\nsize(fs2_ai)\nfs1_ai=fs1_ai(~BadAvgMask1);\nfs2_ai=fs2_ai(~BadAvgMask2);\nphs1_ai=phs1_ai(~BadAvgMask1);\nphs2_ai=phs2_ai(~BadAvgMask2);\n\n%%%%%%%%%%%%%%%%%%%%END OF BAD AVERAGES REMOVAL%%%%%%%%%%%%%%%%%%%%\n\n%now align averages;\n%driftCorr=input('Would you like to perform the frequency drift correction? ','s');\ndriftCorr='y';\nif driftCorr=='n'|| driftCorr=='N'\n out1_aa=out1_rm;\n out2_aa=out2_rm;\n if water\n out1_w_aa=out1_w_cs;\n out2_w_aa=out2_w_cs;\n end\nelse\n sat='n'\n while sat=='n' || sat=='N'\n out1_rm2=out1_rm;\n out2_rm2=out2_rm;\n fsPoly1=100;\n fsPoly2=100;\n phsPoly1=1000;\n phsPoly2=1000;\n fsCum1=fs1_ai;\n fsCum2=fs2_ai;\n phsCum1=phs1_ai;\n phsCum2=phs2_ai;\n iter1=1;\n iter2=1;\n while (abs(fsPoly1(1))>0.001 || abs(phsPoly1(1))>0.01) && iter10.001 || abs(phsPoly2(1))>0.01) && iter22.85 & out1_av_zp.ppm<3.15,1))));\nindex2=find(abs(out2_av_zp.specs)==max(abs(out2_av_zp.specs(out2_av_zp.ppm>2.85 & out2_av_zp.ppm<3.15,1))));\nph01=-phase(out1_av_zp.specs(index1,1))*180/pi;\nph02=-phase(out2_av_zp.specs(index2,1))*180/pi;\nout1_ph=op_addphase(out1_av,ph01);\nout2_ph=op_addphase(out2_av,ph02);\nout1_noproc=op_addphase(op_leftshift(out1_noproc,out1_noproc.pointsToLeftshift),ph01);\nout2_noproc=op_addphase(op_leftshift(out2_noproc,out2_noproc.pointsToLeftshift),ph02);\n%And now for water unsuppressed data (use water peak):\nif water\n out1_w_av_zp=op_zeropad(out1_w_av,16);\n out2_w_av_zp=op_zeropad(out2_w_av,16);\n index1w=find(abs(out1_w_av_zp.specs)==max(abs(out1_w_av_zp.specs(out1_w_av_zp.ppm>4 & out1_w_av_zp.ppm<5.5))));\n index2w=find(abs(out2_w_av_zp.specs)==max(abs(out2_w_av_zp.specs(out2_w_av_zp.ppm>4 & out2_w_av_zp.ppm<5.5))));\n ph01w=-phase(out1_w_av_zp.specs(index1w))*180/pi;\n ph02w=-phase(out2_w_av_zp.specs(index2w))*180/pi;\n out1_w_ph=op_addphase(out1_w_av,ph01w);\n out2_w_ph=op_addphase(out2_w_av,ph02w);\n out1_w_noproc=op_addphase(op_leftshift(out1_w_noproc,out1_w_noproc.pointsToLeftshift),ph01w);\n out2_w_noproc=op_addphase(op_leftshift(out2_w_noproc,out2_w_noproc.pointsToLeftshift),ph02w);\n out1_w_ph_zp=op_addphase(out1_w_av_zp,ph01w);\n out2_w_ph_zp=op_addphase(out2_w_av_zp,ph02w);\nend\n\n%Frequency shift all spectra so that Creatine appears at 3.027 ppm:\n[~,frqShift1]=op_ppmref(out1_av_zp,2.9,3.1,3.027);\n[~,frqShift2]=op_ppmref(out2_av_zp,2.9,3.1,3.027);\nout1=op_freqshift(out1_ph,frqShift1);\nout2=op_freqshift(out2_ph,frqShift2);\nout1_noproc=op_freqshift(out1_noproc,frqShift1);\nout2_noproc=op_freqshift(out2_noproc,frqShift2);\n%And now for water unsuppressed data (user water peak and set to 4.65 ppm):\nif water\n [~,frqShift1w]=op_ppmref(out1_w_ph_zp,4,5.5,4.65);\n [~,frqShift2w]=op_ppmref(out2_w_ph_zp,4,5.5,4.65);\n out1_w=op_freqshift(out1_w_ph,frqShift1w);\n out2_w=op_freqshift(out2_w_ph,frqShift2w);\n out1_w_noproc=op_freqshift(out1_w_noproc,frqShift1w);\n out2_w_noproc=op_freqshift(out2_w_noproc,frqShift2w);\nend\n\n%Make figure to show the final spectrum:\nh=figure('visible','off');\nsubplot(1,2,1);\nplot(out1.ppm,real(out1.specs),'linewidth',2);xlim([0.2 5.2]);\nset(gca,'FontSize',8);\nset(gca,'XDir','reverse');\nxlabel('Frequency (ppm)','FontSize',10);\nylabel('Amplitude(a.u.)','FontSize',10);\nbox off;\nsubplot(1,2,2);\nplot(out2.ppm,real(out2.specs),'linewidth',2);xlim([0.2 5.2]);\nset(gca,'FontSize',8);\nset(gca,'XDir','reverse');\nxlabel('Frequency (ppm)','FontSize',10);\nylabel('Amplitude(a.u.)','FontSize',10);\nbox off;\ntitle('Result: Final Spectra','FontSize',12);\nset(h,'PaperUnits','centimeters');\nset(h,'PaperPosition',[0 0 20 10]);\nsaveas(h,fullfile(reportFigsDir,'finalSpecFig'),'jpg');\nsaveas(h,fullfile(reportFigsDir,'finalSpecFig'),'fig');\n\n\nwrt='y';\nif wrt=='y' || wrt=='Y'\n RF1=io_writelcm(out1,fullfile(filestring,[VoxIDs{1} '_lcm']),out1.te);\n RF2=io_writelcm(out2,fullfile(filestring,[VoxIDs{2} '_lcm']),out2.te);\n RF1=io_writelcm(out1_noproc,fullfile(filestring,[VoxIDs{1} '_unprocessed_lcm']),out1_noproc.te);\n RF2=io_writelcm(out2_noproc,fullfile(filestring,[VoxIDs{2} '_unprocessed_lcm']),out2_noproc.te);\n if water\n RF1=io_writelcm(out1_w,fullfile(filestring,[VoxIDs{1} '_w_lcm']),out1_w.te);\n RF2=io_writelcm(out2_w,fullfile(filestring,[VoxIDs{2} '_w_lcm']),out2_w.te);\n RF1=io_writelcm(out1_w_noproc,fullfile(filestring,[VoxIDs{1} '_w_unprocessed_lcm']),out1_w_noproc.te);\n RF2=io_writelcm(out2_w_noproc,fullfile(filestring,[VoxIDs{2} '_w_unprocessed_lcm']),out2_w_noproc.te);\n end\nend\n\nclose all\n\n%write an html report: \nfid=fopen(fullfile(reportDir,'report.html'),'w+');\nfprintf(fid,'');\nfprintf(fid,'\\n');\nlogoPath=which('FID-A_LOGO.jpg');\nfprintf(fid,'\\n ',logoPath);\nfprintf(fid,'\\n

FID-A Processing Report

');\nfprintf(fid,'\\n

Processing pipeline applied to HD-SPECIAL data using run_hdspecialproc_auto.m

');\nfprintf(fid,'\\n

FILENAME: %s/%s/%s

',fullfile(filestring,filename));\nfprintf(fid,'\\n

DATE: %s

',date);\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n\\n

Results of multi-coil combination:

');\nfprintf(fid,'\\n',fullfile(reportFigsDir,'coilReconFig.jpg'));\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n\\n

Results of alignment of SPECIAL sub-spectra:

');\nfprintf(fid,'\\n',fullfile(reportFigsDir,'alignSubSpecs_prePostFig.jpg'));\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n\\n

Results of removal of bad averages:

');\nfprintf(fid,'\\n

Original number of averages: \\t%5.6f

',out_raw.sz(out_raw.dims.averages));\nfprintf(fid,'\\n

Number of bad Averages removed from vox1: \\t%5.6f

',nBadAvgTotal1);\nfprintf(fid,'\\n

Number of bad Averages removed from vox2: \\t%5.6f

',nBadAvgTotal2);\nfprintf(fid,'\\n

Number of remaining averages in processed dataset (vox1): \\t%5.6f

',out1_rm.sz(out1_rm.dims.averages));\nfprintf(fid,'\\n

Number of remaining averages in processed dataset (vox2): \\t%5.6f

',out2_rm.sz(out2_rm.dims.averages));\nfprintf(fid,'\\n

Bad Averages Removal Threshold was: \\t%2.2f

',nsd);\nfprintf(fid,'\\n',fullfile(reportFigsDir,'rmBadAvg_prePostFig.jpg'),fullfile(reportFigsDir,'rmBadAvg_vox1_scatterFig.jpg'),fullfile(reportFigsDir,'rmBadAvg_vox2_scatterFig.jpg'));\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n\\n

Results of spectral registration:

');\nfprintf(fid,'\\n

Total frequency drift from vox1 was: \\t%5.6f

',max(totalFreqDrift1));\nfprintf(fid,'\\n

Total frequency drift from vox2 was: \\t%5.6f

',max(totalFreqDrift2));\nfprintf(fid,'\\n

Total phase drift from vox1 was: \\t%5.6f

',max(totalPhaseDrift1));\nfprintf(fid,'\\n

Total phase drift from vox2 was: \\t%5.6f

',max(totalPhaseDrift2));\nfprintf(fid,'\\n',fullfile(reportFigsDir,'alignAvgs_prePostFig.jpg'));\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n',fullfile(reportFigsDir,'freqDriftFig.jpg'),fullfile(reportFigsDir,'phaseDriftFig.jpg'));\nfprintf(fid,'\\n\\n

');\nfprintf(fid,'\\n\\n

Final Result:

');\nfprintf(fid,'\\n',fullfile(reportFigsDir,'finalSpecFig.jpg'));\nfclose(fid);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\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/exampleRunScripts/run_hdspecialproc_auto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18063512134453422}} {"text": "function nav=adjnav(nav,opt)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%adjust the wavelength of priority frequencies for BDS2 and BDS3\n%eph and geph struct to eph and geph matrix\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal glc\n\n%adjust eph\nif nav.n>0\n eph0=zeros(nav.n,40);\n for i=1:nav.n\n eph=nav.eph(i);\n eph0(i,:)=[eph.sat, eph.iode, eph.iodc, eph.sva, eph.svh, eph.week, eph.code, eph.flag, eph.toc.time, eph.toc.sec,...\n eph.toe.time, eph.toe.sec, eph.ttr.time, eph.ttr.sec, eph.A, eph.e, eph.i0, eph.OMG0, eph.omg, eph.M0,...\n eph.deln, eph.OMGd, eph.idot, eph.crc, eph.crs, eph.cuc, eph.cus, eph.cic, eph.cis, eph.toes,...\n eph.fit, eph.f0, eph.f1, eph.f2, eph.tgd, eph.Adot, eph.ndot];\n end\n nav=rmfield(nav,'eph');\n nav.eph=eph0;\nend\n\n%adjust geph\nif nav.ng>0\n geph0=zeros(nav.ng,22);\n for i=1:nav.ng\n geph=nav.geph(i);\n geph0(i,:)=[geph.sat, geph.iode, geph.frq, geph.svh, geph.sva, geph.age, geph.toe.time, geph.toe.sec, geph.tof.time, geph.tof.sec,...\n geph.pos', geph.vel', geph.acc', geph.taun,...\n geph.gamn, geph.dtaun];\n end\n nav=rmfield(nav,'geph');\n nav.geph=geph0;\nend\n\n% adjust wavelength\nbds_frq_flag=1;\nlam=nav.lam; nav=rmfield(nav,'lam'); nav.lam=zeros(glc.MAXSAT,glc.NFREQ);\nif glc.NFREQ>3&&(size(opt.bd2frq,2)<=3||size(opt.bd3frq,2)<=3)&&~isempty(strfind(opt.navsys,'C'))\n bds_frq_flag=0;\n fprintf('Warning:Specified frequency of BDS less than used number of frequency!\\n');\nend\nfor i=1:glc.MAXSAT\n [sys,prn]=satsys(i);\n if sys==glc.SYS_BDS\n if prn<19 %BD2\n if ~bds_frq_flag,continue;end\n frq=opt.bd2frq;\n for j=1:glc.NFREQ\n nav.lam(i,j)=lam(i,frq(j)); \n end\n else %BD3\n if ~bds_frq_flag,continue;end\n frq=opt.bd3frq;\n for j=1:glc.NFREQ\n nav.lam(i,j)=lam(i,frq(j)); \n end\n end\n else %GPS GLO GAL QZS\n nav.lam(i,:)=lam(i,1:3);\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/read_file/adjnav.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.180607597788038}} {"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 ap = context_rescore(train_set, train_year)\n% Train context rescoring SVMs and rescore the test predictions.\n% ap = context_rescore(train_set, train_year)\n%\n% Return value\n% ap AP scores for all classes after context rescoring\n%\n% Arguments\n% train_set Training dataset\n% train_year Training dataset year\n\n% AUTORIGHTS\n% -------------------------------------------------------\n% Copyright (C) 2011-2012 Ross Girshick\n% Copyright (C) 2008, 2009, 2010 Pedro Felzenszwalb, Ross Girshick\n% \n% This file is part of the voc-releaseX code\n% (http://people.cs.uchicago.edu/~rbg/latent/)\n% and is available under the terms of an MIT-like license\n% provided in COPYING. Please retain this notice and\n% COPYING if you use this file (or a portion of it) in\n% your project.\n% -------------------------------------------------------\n\nif nargin < 2\n conf = voc_config();\n train_year = conf.pascal.year;\n if nargin < 1\n train_set = conf.training.train_set_fg;\n end\nend\n\ncontext_train(train_set, train_year);\nap = context_test();\n", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/context/context_rescore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18022750008030256}} {"text": "function [newdata] = mne_compensate_to(data,to)\n%\n% [newdata] = mne_compensate_to(data,to)\n%\n% Apply compensation to the data as desired\n%\n\n\n%\n% Author : Matti Hamalainen, MGH Martinos Center\n% License : BSD 3-clause\n%\n%\n% Revision 1.4 2006/04/23 15:29:40 msh\n% Added MGH to the copyright\n%\n% Revision 1.3 2006/04/18 20:44:46 msh\n% Added reading of forward solution.\n% Use length instead of size when appropriate\n%\n% Revision 1.2 2006/04/14 15:49:49 msh\n% Improved the channel selection code and added ch_names to measurement info.\n%\n% Revision 1.1 2006/04/12 10:51:19 msh\n% Added projection writing and compensation routines\n%\n%\n\nme='MNE:mne_compensate_to';\n\nnewdata = data;\nnow = mne_get_current_comp(newdata.info);\n%\n% Are we there already?\n%\nif now == to\n fprintf(1,'Data are already compensated as desired\\n');\nend\n%\n% Make the compensator and apply it to all data sets\n%\ncomp = mne_make_compensator(newdata.info,now,to);\nfor k = 1:length(newdata.evoked)\n newdata.evoked(k).epochs = comp*newdata.evoked(k).epochs;\nend\n%\n% Update the compensation info in the channel descriptors\n%\nnewdata.info.chs = mne_set_current_comp(newdata.info.chs,to);\nreturn;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/mne/mne_compensate_to.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.180195337634345}} {"text": "function [dat, label, time, cfg] = preproc(dat, label, time, cfg, begpadding, endpadding)\n\n% PREPROC applies various preprocessing steps on a single piece of EEG/MEG data\n% that has been read from a data file.\n%\n% This low-level function serves as a subfunction for all FieldTrip modules that want\n% to preprocess the data, such as FT_PREPROCESSING, FT_ARTIFACT_XXX,\n% FT_TIMELOCKANALYSIS, etc. It ensures consistent handling of both MEG and EEG data\n% and consistency in the use of all preprocessing configuration options.\n%\n% Use as\n% [dat, label, time, cfg] = preproc(dat, label, time, cfg, begpadding, endpadding)\n%\n% The required input arguments are\n% dat Nchan x Ntime data matrix\n% label Nchan x 1 cell-array with channel labels\n% time Ntime x 1 vector with the latency in seconds\n% cfg configuration structure, see below\n% and the optional input arguments are\n% begpadding number of samples that was used for padding (see below)\n% endpadding number of samples that was used for padding (see below)\n%\n% The output is\n% dat Nchan x Ntime data matrix\n% label Nchan x 1 cell-array with channel labels\n% time Ntime x 1 vector with the latency in seconds\n% cfg configuration structure, optionally with extra defaults set\n%\n% Note that the number of input channels and the number of output channels can be\n% different, for example when the user specifies that he/she wants to add the\n% implicit EEG reference channel to the data matrix.\n%\n% The filtering of the data can introduce artifacts at the edges, hence it is better\n% to pad the data with some extra signal at the begin and end. After filtering, this\n% padding is removed and the other preprocessing steps are applied to the remainder\n% of the data. The input fields begpadding and endpadding should be specified in\n% samples. You can also leave them empty, which implies that the data is not padded.\n%\n% The configuration can contain\n% cfg.lpfilter = 'no' or 'yes' lowpass filter\n% cfg.hpfilter = 'no' or 'yes' highpass filter\n% cfg.bpfilter = 'no' or 'yes' bandpass filter\n% cfg.bsfilter = 'no' or 'yes' bandstop filter\n% cfg.dftfilter = 'no' or 'yes' line noise removal using discrete fourier transform\n% cfg.medianfilter = 'no' or 'yes' jump preserving median filter\n% cfg.lpfreq = lowpass frequency in Hz\n% cfg.hpfreq = highpass frequency in Hz\n% cfg.bpfreq = bandpass frequency range, specified as [low high] in Hz\n% cfg.bsfreq = bandstop frequency range, specified as [low high] in Hz\n% cfg.dftfreq = line noise frequencies for DFT filter, default [50 100 150] Hz\n% cfg.lpfiltord = lowpass filter order (default set in low-level function)\n% cfg.hpfiltord = highpass filter order (default set in low-level function)\n% cfg.bpfiltord = bandpass filter order (default set in low-level function)\n% cfg.bsfiltord = bandstop filter order (default set in low-level function)\n% cfg.medianfiltord = length of median filter\n% cfg.lpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n% cfg.hpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n% cfg.bpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n% cfg.bsfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls'\n% cfg.lpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!)\n% cfg.hpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!)\n% cfg.bpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!)\n% cfg.bsfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!)\n% cfg.lpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no')\n% cfg.hpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no')\n% cfg.bpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no')\n% cfg.bsinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no')\n% cfg.lpfiltdf = lowpass transition width (firws, overrides order, default set in low-level function)\n% cfg.hpfiltdf = highpass transition width (firws, overrides order, default set in low-level function)\n% cfg.bpfiltdf = bandpass transition width (firws, overrides order, default set in low-level function)\n% cfg.bsfiltdf = bandstop transition width (firws, overrides order, default set in low-level function)\n% cfg.lpfiltwintype = lowpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws)\n% cfg.hpfiltwintype = highpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws)\n% cfg.bpfiltwintype = bandpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws)\n% cfg.bsfiltwintype = bandstop window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws)\n% cfg.lpfiltdev = lowpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function)\n% cfg.hpfiltdev = highpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function)\n% cfg.bpfiltdev = bandpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function)\n% cfg.bsfiltdev = bandstop max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function)\n% cfg.dftreplace = 'zero' or 'neighbour', method used to reduce line noise, 'zero' implies DFT filter, 'neighbour' implies spectrum interpolation (default = 'zero')\n% cfg.dftbandwidth = bandwidth of line noise frequencies, applies to spectrum interpolation, in Hz (default = [1 2 3])\n% cfg.dftneighbourwidth = bandwidth of frequencies neighbouring line noise frequencies, applies to spectrum interpolation, in Hz (default = [2 2 2])\n% cfg.plotfiltresp = 'no' or 'yes', plot filter responses (firws, default = 'no')\n% cfg.usefftfilt = 'no' or 'yes', use fftfilt instead of filter (firws, default = 'no')\n% cfg.demean = 'no' or 'yes'\n% cfg.baselinewindow = [begin end] in seconds, the default is the complete trial\n% cfg.detrend = 'no' or 'yes', this is done on the complete trial\n% cfg.polyremoval = 'no' or 'yes', this is done on the complete trial\n% cfg.polyorder = polynome order (default = 2)\n% cfg.derivative = 'no' (default) or 'yes', computes the first order derivative of the data\n% cfg.hilbert = 'no', 'abs', 'complex', 'real', 'imag', 'absreal', 'absimag' or 'angle' (default = 'no')\n% cfg.rectify = 'no' or 'yes'\n% cfg.precision = 'single' or 'double' (default = 'double')\n% cfg.absdiff = 'no' or 'yes', computes absolute derivative (i.e.first derivative then rectify)\n%\n% Preprocessing options that you should only use for EEG data are\n% cfg.reref = 'no' or 'yes' (default = 'no')\n% cfg.refchannel = cell-array with new EEG reference channel(s)\n% cfg.refmethod = 'avg', 'median', 'rest', 'bipolar' or 'laplace' (default = 'avg')\n% cfg.groupchans = 'yes' or 'no', should channels be rereferenced in separate groups\n% for bipolar and laplace methods, this requires channnels to be\n% named using an alphanumeric code, where letters represent the\n% group and numbers represent the order of the channel whithin\n% its group (default = 'no')\n% cfg.leadfield = matrix or cell-array, this is required when refmethod is 'rest'\n% The leadfield can be a single matrix (channels X sources) which\n% is calculated by using the forward theory, based on the\n% electrode montage, head model and equivalent source model.\n% It can also be the output of FT_PREPARE_LEADFIELD based on a\n% realistic head model.\n% cfg.implicitref = 'label' or empty, add the implicit EEG reference as zeros (default = [])\n% cfg.montage = 'no' or a montage structure (default = 'no')\n%\n% See also FT_READ_DATA, FT_READ_HEADER\n\n% Copyright (C) 2004-2012, 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% compute fsample\nfsample = 1./nanmean(diff(time));\n\nif nargin<5 || isempty(begpadding)\n begpadding = 0;\nend\nif nargin<6 || isempty(endpadding)\n endpadding = 0;\nend\n\nif iscell(cfg)\n % recurse over the subsequent preprocessing stages\n if begpadding>0 || endpadding>0\n ft_error('multiple preprocessing stages are not supported in combination with filter padding');\n end\n for i=1:length(cfg)\n tmpcfg = cfg{i};\n if nargout==1\n [dat ] = preproc(dat, label, time, tmpcfg, begpadding, endpadding);\n elseif nargout==2\n [dat, label ] = preproc(dat, label, time, tmpcfg, begpadding, endpadding);\n elseif nargout==3\n [dat, label, time ] = preproc(dat, label, time, tmpcfg, begpadding, endpadding);\n elseif nargout==4\n [dat, label, time, tmpcfg] = preproc(dat, label, time, tmpcfg, begpadding, endpadding);\n cfg{i} = tmpcfg;\n end\n end\n % ready with recursing over the subsequent preprocessing stages\n return\nend\n\n% set the defaults for the rereferencing options\ncfg.reref = ft_getopt(cfg, 'reref', 'no');\ncfg.refchannel = ft_getopt(cfg, 'refchannel', {});\ncfg.refmethod = ft_getopt(cfg, 'refmethod', 'avg');\ncfg.implicitref = ft_getopt(cfg, 'implicitref', []);\ncfg.leadfield = ft_getopt(cfg, 'leadfield', []);\ncfg.groupchans = ft_getopt(cfg, 'groupchans', 'no');\n% set the defaults for the signal processing options\ncfg.polyremoval = ft_getopt(cfg, 'polyremoval', 'no');\ncfg.polyorder = ft_getopt(cfg, 'polyorder', 2);\ncfg.detrend = ft_getopt(cfg, 'detrend', 'no');\ncfg.demean = ft_getopt(cfg, 'demean', 'no');\ncfg.baselinewindow = ft_getopt(cfg, 'baselinewindow', 'all');\ncfg.dftfilter = ft_getopt(cfg, 'dftfilter', 'no');\ncfg.dftfreq = ft_getopt(cfg, 'dftfreq', [50 100 150]);\ncfg.lpfilter = ft_getopt(cfg, 'lpfilter', 'no');\ncfg.hpfilter = ft_getopt(cfg, 'hpfilter', 'no');\ncfg.bpfilter = ft_getopt(cfg, 'bpfilter', 'no');\ncfg.bsfilter = ft_getopt(cfg, 'bsfilter', 'no');\ncfg.lpfiltord = ft_getopt(cfg, 'lpfiltord', []);\ncfg.hpfiltord = ft_getopt(cfg, 'hpfiltord', []);\ncfg.bpfiltord = ft_getopt(cfg, 'bpfiltord', []);\ncfg.bsfiltord = ft_getopt(cfg, 'bsfiltord', []);\ncfg.lpfilttype = ft_getopt(cfg, 'lpfilttype', 'but');\ncfg.hpfilttype = ft_getopt(cfg, 'hpfilttype', 'but');\ncfg.bpfilttype = ft_getopt(cfg, 'bpfilttype', 'but');\ncfg.bsfilttype = ft_getopt(cfg, 'bsfilttype', 'but');\nif strcmp(cfg.lpfilttype, 'firws'), cfg.lpfiltdir = ft_getopt(cfg, 'lpfiltdir', 'onepass-zerophase'); else, cfg.lpfiltdir = ft_getopt(cfg, 'lpfiltdir', 'twopass'); end\nif strcmp(cfg.hpfilttype, 'firws'), cfg.hpfiltdir = ft_getopt(cfg, 'hpfiltdir', 'onepass-zerophase'); else, cfg.hpfiltdir = ft_getopt(cfg, 'hpfiltdir', 'twopass'); end\nif strcmp(cfg.bpfilttype, 'firws'), cfg.bpfiltdir = ft_getopt(cfg, 'bpfiltdir', 'onepass-zerophase'); else, cfg.bpfiltdir = ft_getopt(cfg, 'bpfiltdir', 'twopass'); end\nif strcmp(cfg.bsfilttype, 'firws'), cfg.bsfiltdir = ft_getopt(cfg, 'bsfiltdir', 'onepass-zerophase'); else, cfg.bsfiltdir = ft_getopt(cfg, 'bsfiltdir', 'twopass'); end\ncfg.lpinstabilityfix = ft_getopt(cfg, 'lpinstabilityfix', 'no');\ncfg.hpinstabilityfix = ft_getopt(cfg, 'hpinstabilityfix', 'no');\ncfg.bpinstabilityfix = ft_getopt(cfg, 'bpinstabilityfix', 'no');\ncfg.bsinstabilityfix = ft_getopt(cfg, 'bsinstabilityfix', 'no');\ncfg.lpfiltdf = ft_getopt(cfg, 'lpfiltdf', []);\ncfg.hpfiltdf = ft_getopt(cfg, 'hpfiltdf', []);\ncfg.bpfiltdf = ft_getopt(cfg, 'bpfiltdf', []);\ncfg.bsfiltdf = ft_getopt(cfg, 'bsfiltdf', []);\ncfg.lpfiltwintype = ft_getopt(cfg, 'lpfiltwintype', 'hamming');\ncfg.hpfiltwintype = ft_getopt(cfg, 'hpfiltwintype', 'hamming');\ncfg.bpfiltwintype = ft_getopt(cfg, 'bpfiltwintype', 'hamming');\ncfg.bsfiltwintype = ft_getopt(cfg, 'bsfiltwintype', 'hamming');\ncfg.lpfiltdev = ft_getopt(cfg, 'lpfiltdev', []);\ncfg.hpfiltdev = ft_getopt(cfg, 'hpfiltdev', []);\ncfg.bpfiltdev = ft_getopt(cfg, 'bpfiltdev', []);\ncfg.bsfiltdev = ft_getopt(cfg, 'bsfiltdev', []);\ncfg.plotfiltresp = ft_getopt(cfg, 'plotfiltresp', 'no');\ncfg.usefftfilt = ft_getopt(cfg, 'usefftfilt', 'no');\ncfg.medianfilter = ft_getopt(cfg, 'medianfilter', 'no');\ncfg.medianfiltord = ft_getopt(cfg, 'medianfiltord', 9);\ncfg.hilbert = ft_getopt(cfg, 'hilbert', 'no');\ncfg.derivative = ft_getopt(cfg, 'derivative', 'no');\ncfg.rectify = ft_getopt(cfg, 'rectify', 'no');\ncfg.boxcar = ft_getopt(cfg, 'boxcar', 'no');\ncfg.absdiff = ft_getopt(cfg, 'absdiff', 'no');\ncfg.precision = ft_getopt(cfg, 'precision', []);\ncfg.conv = ft_getopt(cfg, 'conv', 'no');\ncfg.montage = ft_getopt(cfg, 'montage', 'no');\ncfg.dftinvert = ft_getopt(cfg, 'dftinvert', 'no');\ncfg.standardize = ft_getopt(cfg, 'standardize', 'no');\ncfg.denoise = ft_getopt(cfg, 'denoise', '');\ncfg.subspace = ft_getopt(cfg, 'subspace', []);\ncfg.custom = ft_getopt(cfg, 'custom', '');\ncfg.resample = ft_getopt(cfg, 'resample', '');\n\n% test whether the MATLAB signal processing toolbox is available\nif strcmp(cfg.medianfilter, 'yes') && ~ft_hastoolbox('signal')\n ft_error('median filtering requires the MATLAB signal processing toolbox');\nend\n\n% do a sanity check on the filter configuration\nif strcmp(cfg.bpfilter, 'yes') && ...\n (strcmp(cfg.hpfilter, 'yes') || strcmp(cfg.lpfilter,'yes'))\n ft_error('you should not apply both a bandpass AND a lowpass/highpass filter');\nend\n\n% do a sanity check on the hilbert transform configuration\nif strcmp(cfg.hilbert, 'yes') && ~strcmp(cfg.bpfilter, 'yes')\n ft_warning('Hilbert transform should be applied in conjunction with bandpass filter')\nend\n\n% do a sanity check on hilbert and rectification\nif strcmp(cfg.hilbert, 'yes') && strcmp(cfg.rectify, 'yes')\n ft_error('Hilbert transform and rectification should not be applied both')\nend\n\n% do a sanity check on the rereferencing/montage\nif ~strcmp(cfg.reref, 'no') && ~strcmp(cfg.montage, 'no')\n ft_error('cfg.reref and cfg.montage are mutually exclusive')\nend\n\n% lnfilter is no longer used\nif isfield(cfg, 'lnfilter') && strcmp(cfg.lnfilter, 'yes')\n ft_error('line noise filtering using the option cfg.lnfilter is not supported any more, use cfg.bsfilter instead')\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% do the rereferencing in case of EEG\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isempty(cfg.implicitref) && ~any(match_str(cfg.implicitref,label))\n label = {label{:} cfg.implicitref}';\n dat(end+1,:) = 0;\nend\n\nif strcmp(cfg.reref, 'yes')\n switch cfg.refmethod\n case {'avg', 'median'}\n % mean or median based derivation of specified or all channels\n cfg.refchannel = ft_channelselection(cfg.refchannel, label);\n refindx = match_str(label, cfg.refchannel);\n if isempty(refindx),ft_error('reference channel was not found');end\n dat = ft_preproc_rereference(dat, refindx, cfg.refmethod);\n \n case {'rest'}\n cfg.refchannel = ft_channelselection(cfg.refchannel, label);\n refindx = match_str(label, cfg.refchannel);\n if isempty(refindx)\n ft_error('reference channel was not found')\n end\n \n if isempty(cfg.leadfield)\n ft_error('A leadfield is required to re-refer to REST');\n end\n % check the leadfield, apparently the code contributor here wants to\n % support 3 case, either a matrix, a struct, or a cell-array. Yet the\n % original code is almost impossible to parse, with a lot of try and\n % catch statements, so the current version below is an attempt to clean\n % this up\n if isnumeric(cfg.leadfield)\n Nchann_lf = size(cfg.leadfield,1); % No. of channels in leadfield\n lf_label = {};\n G = cfg.leadfield;\n elseif isstruct(cfg.leadfield)\n Nchann_lf = numel(cfg.leadfield.label);\n lf_label = cfg.leadfield.label;\n G = cat(2, cfg.leadfield.leadfield{:});\n elseif iscell(cfg.leadfield)\n Nchann_lf = size(cfg.leadfield{1},1); % No. of channels in leadfield\n lf_label = {};\n G = cat(2, cfg.leadfield{:});\n end\n \n if Nchann_lf ~= length(label)\n ft_error('channels in the leadfield are not equal to those in the data');\n end\n \n if ~isempty(lf_label)\n [indx1, indx2] = match_str(lf_label(refindx), label(refindx));\n if ~isequal(indx1, indx2)\n ft_error('The order in leadfield may be NOT the same as in the data, please check the leadfield!');\n end\n else\n ft_warning('There is no label info in the leadfield, there is no guarantee that the order of the channels in leadfield is the same as in the data');\n end\n \n dat = ft_preproc_rereference(dat, refindx, cfg.refmethod, [], G); % re-referencing\n label = label(refindx); % re-referenced channel labels\n \n case {'bipolar', 'laplace', 'doublebanana', 'longitudinal', 'circumferential', 'transverse'}\n % this is implemented as a montage that the user does not get to see\n tmpcfg = keepfields(cfg, {'refmethod', 'implicitref', 'refchannel', 'channel', 'groupchans'});\n tmpcfg.showcallinfo = 'no';\n montage = ft_prepare_montage(tmpcfg);\n \n % convert the data temporarily to a raw structure\n tmpdata.trial = {dat};\n tmpdata.time = {time};\n tmpdata.label = label;\n \n % apply the montage to the data\n tmpdata = ft_apply_montage(tmpdata, montage, 'feedback', 'none');\n dat = tmpdata.trial{1}; % the number of channels can have changed\n label = tmpdata.label; % the output channels can be different than the input channels\n clear tmpdata\n \n otherwise\n ft_error('unsupported value for cfg.refmethod');\n end % switch refmethod\nend % if reref\n\nif ~strcmp(cfg.montage, 'no') && ~isempty(cfg.montage)\n % convert the data temporarily to a raw structure\n tmpdata.trial = {dat};\n tmpdata.time = {time};\n tmpdata.label = label;\n % apply the montage to the data\n tmpdata = ft_apply_montage(tmpdata, cfg.montage, 'feedback', 'none');\n dat = tmpdata.trial{1}; % the number of channels can have changed\n label = tmpdata.label; % the output channels can be different than the input channels\n clear tmpdata\nend\n\nif any(isnan(dat(:)))\n % filtering is not possible for at least a selection of the data\n ft_warning('FieldTrip:dataContainsNaN', 'data contains NaNs, not all processing methods are robust to NaNs, so the NaNs might spread');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% do the filtering on the padded data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isempty(cfg.denoise)\n hflag = isfield(cfg.denoise, 'hilbert') && strcmp(cfg.denoise.hilbert, 'yes');\n datlabel = match_str(label, cfg.denoise.channel);\n reflabel = match_str(label, cfg.denoise.refchannel);\n tmpdat = ft_preproc_denoise(dat(datlabel,:), dat(reflabel,:), hflag);\n dat(datlabel,:) = tmpdat;\nend\n\n% The filtering should in principle be done prior to the demeaning to\n% ensure that the resulting mean over the baseline window will be\n% guaranteed to be zero (even if there are filter artifacts).\n% However, the filtering benefits from the data being pulled towards zero,\n% causing fewer edge artifacts. That is why we start by removing the slow\n% drift, then filter, and then repeat the demean/detrend/polyremove. Note\n% that this might interfere with a situation where the requested baseline\n% window is not present in the local time axis of the trial, e.g. when the\n% trials are of different length\nif any(strcmp({cfg.polyremoval cfg.detrend cfg.demean}, 'yes'))\n if strcmp(cfg.polyremoval, 'yes') \n polyorder = cfg.polyorder;\n elseif strcmp(cfg.detrend, 'yes')\n polyorder = 1;\n elseif strcmp(cfg.demean, 'yes')\n polyorder = 0;\n end\n datorig = dat;\n nsamples = size(dat,2);\n begsample = 1 + begpadding;\n endsample = nsamples - endpadding;\n dat = ft_preproc_polyremoval(dat, polyorder, begsample, endsample); % this will also demean and detrend\n datdiff = datorig - dat;\nend\n\nif strcmp(cfg.medianfilter, 'yes'), dat = ft_preproc_medianfilter(dat, cfg.medianfiltord); end\nif strcmp(cfg.lpfilter, 'yes'), dat = ft_preproc_lowpassfilter(dat, fsample, cfg.lpfreq, cfg.lpfiltord, cfg.lpfilttype, cfg.lpfiltdir, cfg.lpinstabilityfix, cfg.lpfiltdf, cfg.lpfiltwintype, cfg.lpfiltdev, cfg.plotfiltresp, cfg.usefftfilt); end\nif strcmp(cfg.hpfilter, 'yes'), dat = ft_preproc_highpassfilter(dat, fsample, cfg.hpfreq, cfg.hpfiltord, cfg.hpfilttype, cfg.hpfiltdir, cfg.hpinstabilityfix, cfg.hpfiltdf, cfg.hpfiltwintype, cfg.hpfiltdev, cfg.plotfiltresp, cfg.usefftfilt); end\nif strcmp(cfg.bpfilter, 'yes'), dat = ft_preproc_bandpassfilter(dat, fsample, cfg.bpfreq, cfg.bpfiltord, cfg.bpfilttype, cfg.bpfiltdir, cfg.bpinstabilityfix, cfg.bpfiltdf, cfg.bpfiltwintype, cfg.bpfiltdev, cfg.plotfiltresp, cfg.usefftfilt); end\nif strcmp(cfg.bsfilter, 'yes')\n for i=1:size(cfg.bsfreq,1)\n % apply a bandstop filter for each of the specified bands, i.e. cfg.bsfreq should be Nx2\n dat = ft_preproc_bandstopfilter(dat, fsample, cfg.bsfreq(i,:), cfg.bsfiltord, cfg.bsfilttype, cfg.bsfiltdir, cfg.bsinstabilityfix, cfg.bsfiltdf, cfg.bsfiltwintype, cfg.bsfiltdev, cfg.plotfiltresp, cfg.usefftfilt);\n end\nend\nif strcmp(cfg.polyremoval, 'yes')\n % the begin and endsample of the polyremoval period correspond to the complete data minus padding\n nsamples = size(dat,2);\n begsample = 1 + begpadding;\n endsample = nsamples - endpadding;\n dat = ft_preproc_polyremoval(dat, cfg.polyorder, begsample, endsample);\nend\nif strcmp(cfg.detrend, 'yes')\n % the begin and endsample of the detrend period correspond to the complete data minus padding\n nsamples = size(dat,2);\n begsample = 1 + begpadding;\n endsample = nsamples - endpadding;\n dat = ft_preproc_detrend(dat, begsample, endsample);\nend\nif strcmp(cfg.demean, 'yes')\n if ischar(cfg.baselinewindow) && strcmp(cfg.baselinewindow, 'all')\n % the begin and endsample of the baseline period correspond to the complete data minus padding\n nsamples = size(dat,2);\n begsample = 1 + begpadding;\n endsample = nsamples - endpadding;\n dat = ft_preproc_baselinecorrect(dat, begsample, endsample);\n else\n % determine the begin and endsample of the baseline period and baseline correct for it\n begsample = nearest(time, cfg.baselinewindow(1));\n endsample = nearest(time, cfg.baselinewindow(2));\n if begsample==endsample && ...\n ((begsample==1 && time(begsample)>cfg.baselinewindow(1)) || (begsample==numel(time) && time(begsample)0 || endpadding>0)\n ft_error('Padding by data mirroring is not supported for spectrum interpolation.');\n end\n end\n if isfield(cfg, 'dftbandwidth')\n optarg = cat(2, optarg, {'dftbandwidth', cfg.dftbandwidth});\n end\n if isfield(cfg, 'dftneighbourwidth')\n optarg = cat(2, optarg, {'dftneighbourwidth', cfg.dftneighbourwidth});\n end\n dat = ft_preproc_dftfilter(dat, fsample, cfg.dftfreq, optarg{:});\n if strcmp(cfg.dftinvert, 'yes')\n dat = datorig - dat;\n end\nend\nif ~strcmp(cfg.hilbert, 'no')\n dat = ft_preproc_hilbert(dat, cfg.hilbert);\nend\nif strcmp(cfg.rectify, 'yes')\n dat = ft_preproc_rectify(dat);\nend\nif isnumeric(cfg.boxcar)\n numsmp = round(cfg.boxcar*fsample);\n if ~rem(numsmp,2)\n % the kernel should have an odd number of samples\n numsmp = numsmp+1;\n end\n % kernel = ones(1,numsmp) ./ numsmp;\n % dat = convn(dat, kernel, 'same');\n dat = ft_preproc_smooth(dat, numsmp); % better edge behavior\nend\nif isnumeric(cfg.conv)\n kernel = (cfg.conv(:)'./sum(cfg.conv));\n if ~rem(length(kernel),2)\n kernel = [kernel 0];\n end\n dat = convn(dat, kernel, 'same');\nend\nif strcmp(cfg.derivative, 'yes')\n dat = ft_preproc_derivative(dat, 1);\nend\nif strcmp(cfg.absdiff, 'yes')\n % this implements abs(diff(data), which is required for jump detection\n dat = abs([diff(dat, 1, 2) zeros(size(dat,1),1)]);\nend\nif strcmp(cfg.standardize, 'yes')\n dat = ft_preproc_standardize(dat, 1, size(dat,2));\nend\nif ~isempty(cfg.subspace)\n dat = ft_preproc_subspace(dat, cfg.subspace);\nend\nif ~isempty(cfg.custom)\n if ~isfield(cfg.custom, 'nargout')\n cfg.custom.nargout = 1;\n end\n if cfg.custom.nargout==1\n dat = feval(cfg.custom.funhandle, dat, cfg.custom.varargin);\n elseif cfg.custom.nargout==2\n [dat, time] = feval(cfg.custom.funhandle, dat, cfg.custom.varargin);\n end\nend\nif strcmp(cfg.resample, 'yes')\n if ~isfield(cfg, 'resamplefs')\n cfg.resamplefs = fsample./2;\n end\n if ~isfield(cfg, 'resamplemethod')\n cfg.resamplemethod = 'resample';\n end\n [dat ] = ft_preproc_resample(dat, fsample, cfg.resamplefs, cfg.resamplemethod);\n [time, dum, fsample] = ft_preproc_resample(time, fsample, cfg.resamplefs, cfg.resamplemethod);\nend\nif ~isempty(cfg.precision)\n % convert the data to another numeric precision, i.e. double, single or int32\n dat = cast(dat, cfg.precision);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% remove the filter padding and do the preprocessing on the remaining trial data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif begpadding~=0 || endpadding~=0\n dat = ft_preproc_padding(dat, 'remove', begpadding, endpadding);\n if strcmp(cfg.demean, 'yes') || nargout>2\n time = ft_preproc_padding(time, 'remove', begpadding, endpadding);\n end\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/spike/private/preproc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.18016402387663813}} {"text": "function GCO_SetDataCost(Handle,DataCost,Label)\n% GCO_SetDataCost Set the data cost of individual sites.\n% GCO_SetDataCost(Handle,DataCost) accepts a NumLabels-by-NumSites \n% int32 matrix where DataCost(k,i) is the cost of assigning\n% label k to site i. In this case, the MATLAB matrix is pointed to \n% by the C++ code, and so an int32 DataCost array is not copied.\n%\n% GCO_SetDataCost(Handle,DataCost,Label) accepts a 2-by-N int32 matrix\n% of (site,cost) pairs, i.e. DataCost(2,i) is the cost of assigning \n% Label to site DataCost(1,i). The site ids must be sorted in increasing \n% order. All ommitted site ids are assumed to be infeasible for Label.\n% This 'sparse' version of SetDataCost allows Expansion to run much \n% faster when labels are only feasible for a small subset of sites.\n% It is possible to assign infeasible labelings via GCO_SetLabeling,\n% but GCO_ComputeEnergy will add huge constants to represent each\n% infeasible assignment.\n%\n% SetDataCost can be called repeatedly, even after Expansion. \n%\n\nGCO_LoadLib();\nif (nargin < 2), error('Expected at least 2 arguments'); end\nif (~isnumeric(DataCost)), error('DataCost must be numeric'); end\nif (~isreal(DataCost)), error('DataCost cannot be complex'); end\nNumLabels = gco_matlab('gco_getnumlabels',Handle);\nNumSites = gco_matlab('gco_getnumsites', Handle);\nif (nargin == 2)\n Label = 0; % no specific label\n if (size(DataCost) ~= [ NumLabels NumSites ])\n error('DataCost size must be [ NumLabels NumSites ]');\n end\nelse\n if (Label < 1 || Label > NumLabels)\n error('Label must be in range 1..NumLabels');\n end\n if (size(DataCost,1) ~= 2)\n error('Sparse DataCost must contain two rows');\n end\nend\nif (~isa(DataCost,'int32'))\n if (NumSites*NumLabels > 200 || any(any(floor(DataCost) ~= DataCost)))\n warning('GCO:int32','DataCost converted to int32');\n end\n DataCost = int32(DataCost);\nend\ngco_matlab('gco_setdatacost',Handle,DataCost,int32(Label));\nend\n", "meta": {"author": "thfylsty", "repo": "Classic-and-state-of-the-art-image-fusion-methods", "sha": "5d9457df396f1ea6921e1b9b3703995205940862", "save_path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods", "path": "github-repos/MATLAB/thfylsty-Classic-and-state-of-the-art-image-fusion-methods/Classic-and-state-of-the-art-image-fusion-methods-5d9457df396f1ea6921e1b9b3703995205940862/SRCF_Image_Fuion_Codes/Utils/GCO/GCO_SetDataCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.1797683735089885}} {"text": "function write_gdf(filename, hdr, data);\n% WRITE_GDF(filename, header, data)\n% Writes a GDF file from the given header (only label, Fs, nChans are of interest)\n% and the data (unmodified). Digital and physical limits are derived from the data\n% via min and max operators. The GDF file will contain N records of 1 sample each,\n% where N is the number of columns in 'data'.\n \n% Copyright (C) 2010, Stefan Klanke\n% \n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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: write_gdf.m 2212 2010-11-27 11:55:07Z roboos $\n\n[nChans,N] = size(data);\nif hdr.nChans ~= nChans\n error 'Data dimension does not match header information';\nend\nfSample = real(hdr.Fs(1)); % make sure this is a scalar + real\n\nlabels = char(zeros(nChans, 16));\n% labels\nfor n=1:nChans\n ln = length(hdr.label{n});\n if ln > 16\n fprintf(1, 'Warning: truncating label %s to %s\\n', hdr.label{n}, hdr.label{n}(1:16));\n ln = 16;\n end\n labels(n,1:ln) = hdr.label{n}(1:ln);\nend\n\nif ~isreal(data)\n error 'Cannot write complex-valued data.';\nend\n\nswitch class(data)\n case 'int8'\n gdfType = 1;\n case 'uint8'\n gdfType = 2;\n case 'int16'\n gdfType = 3;\n case 'uint16'\n gdfType = 4;\n case 'int32'\n gdfType = 5;\n case 'uint32'\n gdfType = 6;\n case 'int64'\n gdfType = 7;\n case 'uint64'\n gdfType = 8;\n case 'single'\n gdfType = 16;\n case 'double'\n gdfType = 17;\n otherwise\n error 'Unrecognized data type';\nend\n\n% TODO: check if this makes sense\n% will be terrible for appending data...\ndigMin = double(min(data,[],2));\ndigMax = double(max(data,[],2));\nphysMin = digMin;\nphysMax = digMax;\n\n%struct GDF_Header {\n%\tchar version[8];\n%\tchar patient[66];\n% uint8_t reserved[10];\n%\tuint8_t smokingAlcoholDrugMedication;\n%\tuint8_t weight;\n%\tuint8_t height;\n%\tuint8_t genderHandedVisualHeart;\n%\tchar recordingId[64];\n%\tuint32_t recordingLocation[4];\n%\tuint32_t recordingTime[2];\n%\tuint32_t birthday[2];\n%\tuint16_t headerLengthInBlocks;\n%\tuint8_t patientClass[6];\n%\tuint64_t equipmentId;\n%\tuint8_t reserved2[6];\n%\tuint16_t headsize[3];\n%\tfloat posRefElec[3];\n%\tfloat posGroundElec[3];\n%\tint64_t numDataRecords;\n%\tuint32_t durDataRecord[2];\n%\tuint16_t numChannels;\n%\tuint16_t reserved3;\n \nfid = fopen(filename, 'wb', 'ieee-le');\n% first write fixed part\nfprintf(fid, 'GDF 2.20'); %version\nfwrite(fid, zeros(1,66), 'int8'); % patient\nfwrite(fid, zeros(1,10+4), 'uint8'); % reserved + smoking/weight/height/gender\nfwrite(fid, zeros(1,64), 'int8'); % recording ID\nfwrite(fid, zeros(1,4), 'uint32'); % recording location\nsecSince2000 = etime(clock, [2000 1 1 0 0 0]);\nfwrite(fid, secSince2000, 'uint32'); % recording time in seconds since 2000/1/1\nfwrite(fid, 0, 'int32'); % fractional part ignored\n\nfwrite(fid, zeros(1,2), 'uint32'); % birthday\nhdrLengthInBlocks = nChans + 1; % 256 bytes = 1 block per channel + 256 bytes for fixed header\nfwrite(fid, hdrLengthInBlocks, 'uint16');\nfwrite(fid, zeros(1,6), 'uint8'); % patient class\nfwrite(fid, 0, 'uint64'); % equipment ID\nfwrite(fid, zeros(1,6), 'uint8'); % reserved2\nfwrite(fid, zeros(1,3), 'uint16'); % headsize\nfwrite(fid, zeros(1,6), 'single'); % posRefElec + posGroundElec\n\nfwrite(fid, N, 'int64'); % numDataRecords = #samples\n[num,den] = rat(1.0/fSample); % sample rate as rational number\nfwrite(fid, num, 'uint32'); % nominator\nfwrite(fid, den, 'uint32'); % denominator\nfwrite(fid, nChans, 'uint16'); % number of channel\nfwrite(fid, zeros(1,1), 'uint16'); % reserved3\n\n% now variable part of header, 256 bytes per channel\nfwrite(fid, labels', 'char*1');\nfwrite(fid, zeros(80,nChans), 'uint8'); % Types\nfwrite(fid, zeros(6,nChans), 'uint8'); % PhysDim\nfwrite(fid, zeros(1,nChans), 'uint16'); % PhysDimCode\n\nfwrite(fid, physMin, 'double'); % physical minimum\nfwrite(fid, physMax, 'double'); % physical maximum\nfwrite(fid, digMin, 'double'); % digital minimum\nfwrite(fid, digMax, 'double'); % digital maximum\nfwrite(fid, zeros(68,nChans), 'uint8'); % pre-filter information\nfwrite(fid, zeros(nChans, 3), 'single'); % lowpass, highpass, notch\nfwrite(fid, ones(1, nChans), 'int32'); % samples per record = 1\nfwrite(fid, gdfType*ones(1, nChans), 'uint32'); % gdf data type\nfwrite(fid, zeros(nChans, 3), 'single'); % sensor position\nfwrite(fid, zeros(nChans, 20), 'uint8'); % sensor description\n\nfwrite(fid, data, class(data));\nfclose(fid);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/write_gdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17976837180848498}} {"text": "function p = remove_redundant(p);\n\nif isempty(p.F_struc)\n return\nend\n\nb = p.F_struc(1+p.K.f:p.K.l+p.K.f,1);\nA = -p.F_struc(1+p.K.f:p.K.l+p.K.f,2:end);\n\nredundant = find(((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <-1e-2));\n\nif length(redundant)>1\n p.InequalityConstraintState(redundant) = inf;\nend\n\nif p.options.bmibnb.lpreduce\n b = p.lpcuts(:,1);\n A = -p.lpcuts(:,2:end);\n redundant = find(((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <-1e-2));\n if length(redundant)>1\n p.lpcuts(redundant,:) = [];\n p.cutState(redundant) = [];\n end\nend\n\nif p.K.f > 0\n b = p.F_struc(1:p.K.f,1);\n A = -p.F_struc(1:p.K.f,2:end);\n s1 = ((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <1e-6);\n s2 = ((-A>0).*(-A)*(p.ub-p.lb) - ((-b)-(-A)*p.lb) <1e-6);\n redundant = find(s1 & s2);\n if length(redundant)>1\n p.EqualityConstraintState(redundant) = inf;\n end\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/modules/global/remove_redundant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17975275256144396}} {"text": "function splitNSx(splitCount)\n\n% splitNSx\n% \n% Opens and splits an NSx file in smaller pieces, timewise.\n%\n% Use splitNSx(splitCount)\n% \n% All input arguments are optional. Input arguments can be in any order.\n%\n% splitCount: Defines the number of splits.\n% DEFAULT: Splits the file in 2 pieces.\n%\n% Example 1: \n% splitNSx(4);\n%\n% In the example above, the user will be prompted to select a file. The\n% loaded file will be split in 4 samller files. For example, if the file\n% is 1 hour long then it will be split into four 15-minute files.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Kian Torab\n% support@blackrockmicro.com\n% Blackrock Microsystems\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Version History\n%\n% 1.0.0.0:\n% - Initial release.\n%\n% 1.1.0.0:\n% - Fixed a bug related to a case where initial timestamp of the first\n% data segment was not 0. \n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n\n% Validating input parameter\nif ~exist('splitCount', 'var')\n splitCount = 2;\nend\n\n% Getting the file name\n[fname, path] = getFile('*.nev', 'Choose an NSx file...');\nif fname == 0\n disp('No file was selected.');\n if nargout\n clear variables;\n end\n return;\nend\nfext = fname(end-3:end);\n\n\n\n% Loading the file\n%% Reading Basic Header from file into NSx structure.\nFID = fopen([path fname], 'r', 'ieee-le');\nBasicHeader = fread(FID, 336, '*uint8');\nTrackers.fExtendedHeader = double(typecast(BasicHeader(13:16), 'uint32'));\nTrackers.countPacketBytes = double(typecast(BasicHeader(17:20), 'uint32'));\n\n%% Doing Trackers\nfseek(FID, 0, 'eof');\nTrackers.fData = ftell(FID);\nTrackers.countDataPacket = (Trackers.fData - Trackers.fExtendedHeader)/Trackers.countPacketBytes;\n\n\nfseek(FID, Trackers.fExtendedHeader, 'bof');\ntRawData = fread(FID, [10 Trackers.countDataPacket], '10*uint8=>uint8', Trackers.countPacketBytes - 10);\nTimestamp = tRawData(1:4,:);\nTimestamp = typecast(Timestamp(:), 'uint32').';\n\nsplitPacketStarts = find(diff(Timestamp)<0);\nsplitPacketBytes = Trackers.countPacketBytes * splitPacketStarts;\n\n% Reading headers and seeking to beginning of data\nfseek(FID, 0, 'bof');\nfileHeader = fread(FID, Trackers.fExtendedHeader, '*uint8');\n\nfor idx = 1:length(splitPacketStarts)\n % Opening a file for saving\n FIDw = fopen([path fname(1:end-4) '-s' sprintf('%03d', idx) fname(end-3:end)], 'w+', 'ieee-le');\n fprintf('\\nReading segment %d... ', idx);\n % Reading the segment\n dataSegment = fread(FID, splitPacketBytes(idx), 'char');\n fprintf('Writing segment %d... ', idx);\n % Writing the segmented data into file\n fwrite(FIDw, fileHeader, 'char');\n fwrite(FIDw, dataSegment, 'char');\n % Clearing variables and closing file\n clear dataSegment;\n fclose(FIDw);\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/npmk/NEV Utilities/splitNEVResets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17975274408041142}} {"text": "function set1001a(m)\n% sets parameters of DT3152 according to\n% http://cmp.felk.cvut.cz/cmp/hardware/pulnix.html#TM-1001analog\n\n% m=openfg('DT3152');\n% setfg(m,'digioconfig',255);\n% setfg(m,'PCMode',1)\n% setfg(m,'PCValue',1)\n% setfg(m,'exposure',0)\n setfg(m,'InputChannel',0)\n setfg(m,'FrameType','NonInterlaced')\n setfg(m,'VideoType','Composite')\n setfg(m,'ClockSource','internal')\n setfg(m,'ClockFreq',20000000)\n setfg(m,'TotalPixPerLine',1272)\n \n setfg(m,'backporchstart',90)\n setfg(m,'clampstart',165)\n setfg(m,'clampend',170)\n \n \n setfg(m,'FirstActivePixel',235)\n setfg(m,'ActivePixelCount',988)\n\n setfg(m,'TotalLinesperFld',1050)\n setfg(m,'FirstActiveLine',30)\n setfg(m,'ActiveLineCount',1015)\n \n setfg(m,'FrameLeft',0)\n setfg(m,'HorFrameInc',1)\n setfg(m,'FrameWidth',988)\n setfg(m,'FrameTop',0)\n setfg(m,'VerFrameInc',1)\n setfg(m,'FrameHeight',1015)\n \n\n\n% setfg(m,'ExtOnLoToHi',0)\n% expozice=128+64+32;\t\t% nejdelsi\n% mod16 = 5;\n% mod81 = 0;\n% mod82 = 4;\n% mod83 = 2;\n% mod84 = 6;\n% mod8 = 1;\n% integracestart=0;\n% integracestop=8;\n% integracepovolena =0;\n% integracenepovolena=16; \n% integracezakazana=integracestop+integracenepovolena;\n% setfg(m,'digitalio',mod16+integracezakazana+expozice)\n\nsetfg(m, 'SyncMaster', 'Off')\nsetfg(m, 'SyncValue','VerFreq', 30)\t\t%TM9701\n%setfg(m, 'SyncValue','VerFreq', 15)\t\t%TM1001\nsetfg(m, 'SyncMaster', 'On')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1508-dtfgi/Camfiles/set9701aSyncMaster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1796691488880277}} {"text": "function [hdr, mrGrayFileName] = analyze2mrGray(analHeaderFileName,endianType);\n% function [V,mrGrayFileName]=analyze2mrGray(analHeaderFileName,endianType);\n% Converts Analyze7.5 images to Stanford VISTA lab / mrGray vAnatomy.dat format.\n% Analyze headers hold far more information that mrGray volumes. We just toss this \n% information out when we write the mrGray file, but this routine returns the \n% Analyze header info in 'V'.\n% Uses the SPM99 spm_vol command to parse the header. Uses misc. VISTA lab routines \n% to clip and write the volume.\n% See also mrGray2Analyze\n% If you pass in the (optional) endianType it will use this when reading 16bit data \n% files. \n%\n% HISTORY:\n% ARW 081701\n% ARW Added >16 bit data handling 082101\n% 02.07.16 RFD (bob@white.stanford.edu) Rewrote code in a more modular format.\n% Also added proper image reorientation to make SPM-style analyze format\n% files into mrGray orientation.\n\nif (~exist('endianType','var'))\n endianType='';\nend\nif (~exist('analHeaderFileName','var'))\n analHeaderFileName = '';\nend\n[img, mmPerPix, hdr] = loadAnalyze(analHeaderFileName, endianType);\n\n% to make analyze data the same orientation as vAnatomy, we reorient the data.\n% Note that we assume Analyze orientation code '0'- transverse, unflipped. \n% If that is the case, then the following will make the data look correct in mrGray.\n% It will even get left/right correct (left will be left and right right).\nimg = permute(img,[3,2,1]);\n\nmmPerPix = [mmPerPix(3),mmPerPix(2),mmPerPix(1)];\n% flip each slice ud (ie. flip along matlab's first dimension, which is our x-axis)\nfor(jj=1:size(img,3))\n img(:,:,jj) = flipud(squeeze(img(:,:,jj)));\nend\n% flip each slice lr(ie. flip along matlab's second dimension, which is our y-axis)\nfor(jj=1:size(img,3))\n img(:,:,jj) = fliplr(squeeze(img(:,:,jj)));\nend\n% flip along matlab's third dimension, which is our z-axis\n% NO NEED TO DO THIS IF DATA ARE IN STANDARD ANALYZE ORIENTATION\n% for(jj=1:size(img,1))\n% img(jj,:,:) = fliplr(squeeze(img(jj,:,:)));\n% end\n\n% launch a GUI to find the optimal clip values\nimg = makeClippedVolume(img);\n\n% Now write out a mrGray file \nmrGrayFileName = writeVolAnat(img, mmPerPix);\n\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/analyze/analyze2mrGrayAnatomy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17958973372898834}} {"text": " function st = nufft_table_change(st, om)\n% change to a new set of frequencies\n\nif ~isvar(st, 'phase_shift')\n\terror 'only done for \"table\" version'\nend\n\nst.om = om;\nst.M = nrow(om);\nst.phase_shift = exp(1i * (st.om * st.n_shift(:)));\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/nufft_table_change.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.17927716416084485}} {"text": "function keypointsAll= det2keypointsImgDPM(expidx,parts,annolist_gt,nDet)\n\nfprintf('det2keypointsImg()\\n');\n\nif (nargin < 4)\n nDet = 1;\nend\n\np = rcnn_exp_params(expidx);\nconf = rcnn_config('sub_dir', '/cachedir/test', 'exp_dir', [p.expDir '/' p.shortName]);\n\nif (isfield(p,'predDir') && ~bTrain)\n predDir = p.predDir;\nelse\n predDir = [conf.cache_dir '/pred'];\nend\n\nif (nDet == 1)\n keypointsAll = repmat(struct('imgname','','det',nan(16,3)), length(annolist_gt), 1);\nelse\n for imgidx = 1:length(annolist_gt)\n keypointsAll(imgidx).imgname = '';\n keypointsAll(imgidx).det = cell(16,1);\n end\nend\n\nif (isfield(p,'nProposals'))\n nProposals = p.nProposals;\nelse\n nProposals = inf;\nend\n\nif (isfield(p,'min_det_score'))\n min_det_score = p.min_det_score;\nelse\n min_det_score = -inf;\nend\n\nfor imgidx = 1:length(annolist_gt)\n \n fprintf('.');\n \n fname = [predDir '/imgidx_' padZeros(num2str(imgidx-1),5)];\n \n if (bNMS)\n load(fname,'aboxes');\n boxes = aboxes;\n else\n load(fname,'aboxes_nonms');\n boxes = aboxes_nonms;\n \n if (nms_thresh_det > 0)\n assert(expidx == 454 || expidx == 464 || expidx == 466 || expidx == 471);\n for i = 1:length(boxes)\n boxes{i}(:,1:4) = rcnn_scale_bbox(boxes{i}(:,1:4),1.0/p.scale,1000,1000);\n end\n idxsNMSall = [];\n for i = 1:length(boxes)\n I = nms_IoMin([boxes{i}(:,1:4) boxes{i}(:,5)], nms_thresh_det);\n idxsNMSall = sort(unique([idxsNMSall; I]));\n end\n for i = 1:length(boxes)\n boxes{i} = boxes{i}(idxsNMSall,:);\n end\n end\n if (isfield(p,'max_detections') && p.max_detections < inf)\n assert(expidx == 464 || expidx == 466 || expidx == 471);\n unProb = zeros(size(boxes{1},1),length(boxes));\n for i = 1:length(boxes)\n unProb(:,i) = boxes{i}(:,5);\n end\n scores = sort(reshape(unProb, size(unProb,1)*size(unProb,2),1));\n unProbThresh = unProb;\n j = 1;\n while (length(find(sum(unProbThresh,2) > 0)) > p.max_detections && j <= length(scores))\n unProbThresh = unProb;\n for cidx = 1:length(boxes)\n unProbThresh(unProb(:,cidx) < scores(j),cidx) = 0;\n end\n j = j + 1;\n % length(find(sum(unProbThresh,2) > 0))\n end\n min_det_score_found = scores(j);\n idxs = find(sum(unProbThresh,2) > 0);\n for i = 1:length(boxes)\n boxes{i} = boxes{i}(idxs,:);\n end\n end\n end\n \n keypointsAll(imgidx).imgname = annolist_gt(imgidx).image.name;\n assert(length(p.pidxs) == length(boxes));\n \n for i = 1:length(p.pidxs)\n \n pidx = p.pidxs(i);\n % part is a joint\n assert(parts(pidx+1).pos(1) == parts(pidx+1).pos(2));\n jidx = parts(pidx+1).pos(1);\n \n det = boxes{i};\n \n if (nDet == 1)\n \n maxtop = min(size(det,1),nProposals);\n [val,idx] = max(det(1:maxtop,5));\n x = mean(det(idx,[1 3]));\n y = mean(det(idx,[2 4]));\n \n if (val < min_det_score)\n x = inf;\n y = inf;\n end\n% maxtop = min(size(det,1),100);\n% [~,idxs] = sort(det(:,5),'descend');\n% det = det(idxs(1:maxtop),:);\n% x = mean(det(:,[1 3]),2);\n% y = mean(det(:,[2 4]),2);\n% keep = nms_dist([x,y,det(1:maxtop,end)],0.1,50);\n% det = det(keep,:);\n% [val,idx] = max(det(:,5));\n% x = mean(det(idx,[1 3]));\n% y = mean(det(idx,[2 4]));\n\n keypointsAll(imgidx).det(jidx+1,:) = [[x y] val];\n else\n score = det(:,5);\n [val,idxs] = sort(score,'descend');\n idxs = idxs(1:min(nDet,length(idxs)));\n % use score threshold\n idxs2 = find(score(idxs) >= min_det_score);\n idxs = idxs(idxs2);\n if (~isempty(idxs))\n x = mean(det(idxs,[1 3]),2);\n y = mean(det(idxs,[2 4]),2);\n keypointsAll(imgidx).det{jidx+1,:} = [[x y] det(idxs,5)];\n else\n keypointsAll(imgidx).det{jidx+1,:} = [[inf inf] min_det_score];\n end\n end\n \n end\n if (~mod(imgidx, 100))\n fprintf(' %d/%d\\n',imgidx,length(keypointsAll));\n end\nend\nfprintf(' done\\n');\n\nend", "meta": {"author": "eldar", "repo": "deepcut", "sha": "096e2d174ddf2fbdc61458d9e7e6c6e897eac16c", "save_path": "github-repos/MATLAB/eldar-deepcut", "path": "github-repos/MATLAB/eldar-deepcut/deepcut-096e2d174ddf2fbdc61458d9e7e6c6e897eac16c/lib/eval/det2keypointsImgDPM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17903828780010458}} {"text": "function AlignTsp2Whl(fbasename,colorvec,varargin)\n\n% USAGE:\n% AlignTsp2Whl(fbasename,colorvec)\n% \n% convert .tsp file to .whl file. Requires the .meta file\n% \n% INPUT:\n% 'fbasename': the file base names ('fbasename.tsp', etc.)\n% 'colorvec': a 2 value vector [colFront colRear] which defines which\n% color from [R G B] is the front and rear LEDs. Default: [1 3]\n% optionnal:\n% AlignTsp2Whl(fbasename,colorvec,frommpg)\n% if frommpg is set to 1 (default 0), the tracking is done from the video\n% \n% Adrien Peyrache and Antal Ber\u00e9nyi, 2012\n% This particular version is corrected by Adrien Peyrache, 2012.\n% It also includes 2 new things: NaN instead of -1 for interpolation and\n% video tracking for bad tsp files.\n% Oct 2013: Brendon Watson made somewhat robust to instances of recording system\n% crashes with blank .meta files\n\nfrommpg = 0;\nif ~isempty(varargin)\n frommpg = varargin{1};\nend\n\nif strcmp('.tsp',fbasename(end-3:end));\n tspfile = fbasename;\n fbasename = fbasename(1:end-4);\nelse\n tspfile = [fbasename '.tsp'];\nend\n\n% get timestamps and positions from tsp file\nif exist(tspfile,'file')\n tspdata=load(tspfile);\nelse\n error('Couldn''t do anything without the tsp file')\nend\n\nif size(tspdata,2)==1 || frommpg==1\n suffix = [];\n if exist([tspfile '.old'])\n suffix = 1;\n while exist([tspfile '.old. ' num2str(suffix)])\n suffix = suffix+1;\n end\n suffix = ['.' num2str(suffix)];\n end\n eval(['!cp ' tspfile ' ' tspfile '.old' suffix]);\n RecreateTspFile(fbasename);\n tspdata=load(tspfile);\nend\n\n%get length of dat file\n%infoFile = dir([fbasename '.dat']);\n%filelength=infoFile.bytes/(512*2);\n%clear infoFile\n%get start and end timestamp of dat file\nEndTimestamp = [];%set these up so can detect if problem w10389984000ith getting them from .meta\nStartTimestamp = [];\nChanNum = [];\nDatSize = [];\n\nfid=fopen([fbasename '.meta']);\ntline= fgetl(fid);\nwhile ischar(tline)\n try\n if strcmp(tline(1:20),'TimeStamp of the end')\n tline=tline(59:end);\n EndTimestamp=sscanf(tline,'%d',1);\n end\n end\n try\n if strcmp(tline(1:22),'TimeStamp of the start')\n tline=tline(61:end);\n StartTimestamp=sscanf(tline,'%d',1);\n end\n end\n try\n if strcmp(tline(1:9),'Number of')\n tline=tline(31:end);\n ChanNum=sscanf(tline,'%d',1);\n end\n end\n try\n if strcmp(tline(1:9),'File size')\n tline=tline(21:end);\n DatSize=sscanf(tline,'%lu',1);\n end\n end\n \n tline= fgetl(fid);\nend\nfclose(fid);\n\n%making up for problems reading parameters (basically if .meta isn't good,\n%but will address one at a time\nif isempty(EndTimestamp)\n EndTimestamp = tspdata(end,1);\nend\n\nif isempty(StartTimestamp)\n StartTimestamp = tspdata(1,1);\nend\n\nif isempty(ChanNum);\n fid=fopen([fbasename '.ini']);\n tline= fgetl(fid);\n while ischar(tline)\n try\n if strcmp(tline(1:14),'ChannelsToSave')\n tline=tline(16:end);\n ChanNum = sum(str2num(tline));\n end\n end\n tline= fgetl(fid);\n end\n fclose(fid);\nend\n\nif isempty(DatSize)\n DatSize = dir([fbasename,'.dat']);\n DatSize = DatSize.bytes;\nelse\n DatSize = double(DatSize);\nend\n\n\n\n%Calculate file length from dat file sample rat\nDatLength=DatSize/(ChanNum*2*20); %Dat file size in ms\n\n% TspLength=EndTimestamp-StartTimestamp; %Unused > problematic if crashes\n% yielding blank .meta files\n\ncolorvec = sort([2*colorvec-1 2*colorvec])+1;\n%remove lines from tspdata which has the same timestamp as the previous\n%does\nrepeatingts=find(tspdata(1:end-1,1)==tspdata(2:end,1))+1;\nfor r=size(repeatingts):-1:1\n tspdata(repeatingts(r),:)=[];\nend\n\n%Putting all bad tracked points at NaN\ntspdata(tspdata==-1)=NaN;\n\n%interpolate to 1 kHz - computer clock\nt=tspdata(1,1):tspdata(end,1);\ninterpTsp1kHz = zeros(length(t),7);\ninterpTsp1kHz(:,1)=t;\nwarning off %Doesn't like NaN but does well\ninterpTsp1kHz(:,2:end)=interp1(tspdata(:,1),tspdata(:,2:7),interpTsp1kHz(:,1));\nwarning on\n\nfor i=1:3%length(colorvec)\n minusonesegments(:,1)=tspdata(isnan(tspdata((2:end-1),i*2)),1);\n minusonesegments(:,2)=tspdata(find(isnan(tspdata((2:end-1),i*2)))+2,1);\n for j=1:size(minusonesegments,1)\n %Replace bad values by NaN so that interpolation ignores those\n %points.\n interpTsp1kHz(minusonesegments(j,1)-interpTsp1kHz(1,1)+1:minusonesegments(j,2)-interpTsp1kHz(1,1),i*2:i*2+1)=NaN;\n end\n clear minusonesegments\nend\n\n%align the beginning\nif (StartTimestamp= 1\n fprintf('%s: resuming by loading epoch %d\\n', mfilename, start) ;\n [net, state, stats] = loadState(modelPath(start)) ;\nelse\n state = [] ;\nend\n\nfor epoch=start+1:opts.numEpochs\n\n % Set the random seed based on the epoch and opts.randomSeed.\n % This is important for reproducibility, including when training\n % is restarted from a checkpoint.\n\n rng(epoch + opts.randomSeed) ;\n prepareGPUs(opts, epoch == start+1) ;\n\n % Train for one epoch.\n params = opts ;\n params.epoch = epoch ;\n params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n params.train = opts.train(randperm(numel(opts.train))) ; % shuffle\n params.train = params.train(1:min(opts.epochSize, numel(opts.train)));\n params.val = opts.val(randperm(numel(opts.val))) ;\n params.imdb = imdb ;\n params.getBatch = getBatch ;\n\n if numel(params.gpus) <= 1\n [net, state] = processEpoch(net, state, params, 'train') ;\n [net, state] = processEpoch(net, state, params, 'val') ;\n if ~evaluateMode\n saveState(modelPath(epoch), net, state) ;\n end\n lastStats = state.stats ;\n else\n spmd\n [net, state] = processEpoch(net, state, params, 'train') ;\n [net, state] = processEpoch(net, state, params, 'val') ;\n if labindex == 1 && ~evaluateMode\n saveState(modelPath(epoch), net, state) ;\n end\n lastStats = state.stats ;\n end\n lastStats = accumulateStats(lastStats) ;\n end\n\n stats.train(epoch) = lastStats.train ;\n stats.val(epoch) = lastStats.val ;\n clear lastStats ;\n if ~evaluateMode\n saveStats(modelPath(epoch), stats) ;\n end\n\n if params.plotStatistics\n switchFigure(1) ; clf ;\n plots = setdiff(...\n cat(2,...\n fieldnames(stats.train)', ...\n fieldnames(stats.val)'), {'num', 'time'}) ;\n for p = plots\n p = char(p) ;\n values = zeros(0, epoch) ;\n leg = {} ;\n for f = {'train', 'val'}\n f = char(f) ;\n if isfield(stats.(f), p)\n tmp = [stats.(f).(p)] ;\n values(end+1,:) = tmp(1,:)' ;\n leg{end+1} = f ;\n end\n end\n subplot(1,numel(plots),find(strcmp(p,plots))) ;\n plot(1:epoch, values','o-') ;\n xlabel('epoch') ;\n title(p) ;\n legend(leg{:}) ;\n grid on ;\n end\n drawnow ;\n print(1, modelFigPath, '-dpdf') ;\n end\n \n if ~isempty(opts.postEpochFn)\n if nargout(opts.postEpochFn) == 0\n opts.postEpochFn(net, params, state) ;\n else\n lr = opts.postEpochFn(net, params, state) ;\n if ~isempty(lr), opts.learningRate = lr; end\n if opts.learningRate == 0, break; end\n end\n end\nend\n\n% With multiple GPUs, return one copy\nif isa(net, 'Composite'), net = net{1} ; end\n\n% -------------------------------------------------------------------------\nfunction err = error_multiclass(params, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\n[~,labels]=max(labels,[],3);\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr=sum(sum(sum(error(:,:,1,:),1),2),4) ;\n\n\n% -------------------------------------------------------------------------\nfunction err = error_binary(params, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\nerror = bsxfun(@times, predictions, labels) < 0 ;\nerr = sum(error(:));\nerr = err/size(labels,3);\n\n% -------------------------------------------------------------------------\nfunction err = error_none(params, labels, res)\n% -------------------------------------------------------------------------\nerr = zeros(0,1) ;\n\n% -------------------------------------------------------------------------\nfunction [net, state] = processEpoch(net, state, params, mode)\n% -------------------------------------------------------------------------\n% Note that net is not strictly needed as an output argument as net\n% is a handle class. However, this fixes some aliasing issue in the\n% spmd caller.\n\n% initialize with momentum 0\nif isempty(state) || isempty(state.solverState)\n for i = 1:numel(net.layers)\n state.solverState{i} = cell(1, numel(net.layers{i}.weights)) ;\n state.solverState{i}(:) = {0} ;\n end\nend\n\n% move CNN to GPU as needed\nnumGpus = numel(params.gpus) ;\nif numGpus >= 1\n net =our_vl_simplenn_move(net, 'gpu') ;\n for i = 1:numel(state.solverState)\n for j = 1:numel(state.solverState{i})\n s = state.solverState{i}{j} ;\n if isnumeric(s)\n state.solverState{i}{j} = gpuArray(s) ;\n elseif isstruct(s)\n state.solverState{i}{j} = structfun(@gpuArray, s, 'UniformOutput', false) ;\n end\n end\n end\nend\nif numGpus > 1\n parserv = ParameterServer(params.parameterServer) ;\n vl_simplenn_start_parserv(net, parserv) ;\nelse\n parserv = [] ;\nend\n\n% profile\nif params.profile\n if numGpus <= 1\n profile clear ;\n profile on ;\n else\n mpiprofile reset ;\n mpiprofile on ;\n end\nend\n\nsubset = params.(mode) ;\nnum = 0 ;\nstats.num = 0 ; % return something even if subset = []\nstats.time = 0 ;\nadjustTime = 0 ;\nres = [] ;\nerror = [] ;\n\nif(size(params.imdb.images.labels,1)>1)\n density=mean(params.imdb.images.labels>0,2);\nelse\n density=0;\nend\n\nstart = tic ;\nfor t=1:params.batchSize:numel(subset)\n fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...\n fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;\n batchSize = min(params.batchSize, numel(subset) - t + 1) ;\n for s=1:params.numSubBatches\n % get this image batch and prefetch the next\n batchStart = t + (labindex-1) + (s-1) * numlabs ;\n batchEnd = min(t+params.batchSize-1, numel(subset)) ;\n batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n num = num + numel(batch) ;\n if numel(batch) == 0, continue ; end\n\n [im, labels] = params.getBatch(params.imdb, batch) ;\n\n if params.prefetch\n if s == params.numSubBatches\n batchStart = t + (labindex-1) + params.batchSize ;\n batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;\n else\n batchStart = batchStart + numlabs ;\n end\n nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n params.getBatch(params.imdb, nextBatch) ;\n end\n\n if numGpus >= 1\n im = gpuArray(im) ;\n end\n\n if strcmp(mode, 'train')\n dzdy = 1 ;\n evalMode = 'normal' ;\n else\n dzdy = [] ;\n evalMode = 'test' ;\n end\n net.layers{end}.class = labels ;\n net.layers{end}.iter=params.epoch;\n net.layers{end}.density=density;\n res=our_vl_simplenn(net, im, dzdy, res, ...\n 'accumulate', s ~= 1, ...\n 'mode', evalMode, ...\n 'conserveMemory', params.conserveMemory, ...\n 'backPropDepth', params.backPropDepth, ...\n 'sync', params.sync, ...\n 'cudnn', params.cudnn, ...\n 'parameterServer', parserv, ...\n 'holdOn', s < params.numSubBatches) ;\n\n % accumulate errors\n error = sum([error, [...\n sum(double(gather(res(end).x))) ;\n reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;\n end\n\n % accumulate gradient\n if strcmp(mode, 'train')\n if ~isempty(parserv), parserv.sync() ; end\n [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;\n \n labelNum=size(net.layers{end}.class,3);\n for lay=1:numel(net.layers) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if(strcmp(net.layers{lay}.type,'conv_mask'))\n if(isempty(net.layers{lay}.sliceMag))\n net.layers{lay}.sliceMag=zeros(size(res(lay).x,3),labelNum);\n end\n for lab=1:labelNum\n tmp=gather(max(max(res(lay).x(:,:,:,net.layers{end}.class(:,:,lab,:)==1),[],1),[],2));\n if(~isempty(tmp))\n %meantmp=sum(tmp,4)./max(sum(tmp>0,4),1);\n meantmp=mean(tmp,4);\n \n if(sum(net.layers{lay}.sliceMag(:,lab))==0)\n net.layers{lay}.sliceMag(:,lab)=max(meantmp(:),0.1);\n else\n tmptmp=0.9;\n meantmp(meantmp==0)=net.layers{lay}.sliceMag(meantmp==0);\n net.layers{lay}.sliceMag(:,lab)=net.layers{lay}.sliceMag(:,lab).*tmptmp+meantmp(:).*(1-tmptmp);\n end\n end\n end\n end\n end\n end\n \n % get statistics\n time = toc(start) + adjustTime ;\n batchTime = time - stats.time ;\n stats = extractStats(net, params, error / num) ;\n stats.num = num ;\n stats.time = time ;\n currentSpeed = batchSize / batchTime ;\n averageSpeed = (t + batchSize - 1) / time ;\n if t == 3*params.batchSize + 1\n % compensate for the first three iterations, which are outliers\n adjustTime = 4*batchTime - time ;\n stats.time = time + adjustTime ;\n end\n\n fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;\n for f = setdiff(fieldnames(stats)', {'num', 'time'})\n f = char(f) ;\n fprintf(' %s: %.3f', f, stats.(f)) ;\n end\n fprintf('\\n') ;\n\n % collect diagnostic statistics\n if strcmp(mode, 'train') && params.plotDiagnostics\n switchFigure(2) ; clf ;\n diagn = [res.stats] ;\n diagnvar = horzcat(diagn.variation) ;\n diagnpow = horzcat(diagn.power) ;\n subplot(2,2,1) ; barh(diagnvar) ;\n set(gca,'TickLabelInterpreter', 'none', ...\n 'YTick', 1:numel(diagnvar), ...\n 'YTickLabel',horzcat(diagn.label), ...\n 'YDir', 'reverse', ...\n 'XScale', 'log', ...\n 'XLim', [1e-5 1], ...\n 'XTick', 10.^(-5:1)) ;\n grid on ; title('Variation');\n subplot(2,2,2) ; barh(sqrt(diagnpow)) ;\n set(gca,'TickLabelInterpreter', 'none', ...\n 'YTick', 1:numel(diagnpow), ...\n 'YTickLabel',{diagn.powerLabel}, ...\n 'YDir', 'reverse', ...\n 'XScale', 'log', ...\n 'XLim', [1e-5 1e5], ...\n 'XTick', 10.^(-5:5)) ;\n grid on ; title('Power');\n subplot(2,2,3); plot(squeeze(res(end-1).x)) ;\n drawnow ;\n end\nend\n\n% Save back to state.\nstate.stats.(mode) = stats ;\nif params.profile\n if numGpus <= 1\n state.prof.(mode) = profile('info') ;\n profile off ;\n else\n state.prof.(mode) = mpiprofile('info');\n mpiprofile off ;\n end\nend\nif ~params.saveSolverState\n state.solverState = [] ;\nelse\n for i = 1:numel(state.solverState)\n for j = 1:numel(state.solverState{i})\n s = state.solverState{i}{j} ;\n if isnumeric(s)\n state.solverState{i}{j} = gather(s) ;\n elseif isstruct(s)\n state.solverState{i}{j} = structfun(@gather, s, 'UniformOutput', false) ;\n end\n end\n end\nend\n\nnet =our_vl_simplenn_move(net, 'cpu') ;\n\n% -------------------------------------------------------------------------\nfunction [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)\n% -------------------------------------------------------------------------\nnumGpus = numel(params.gpus) ;\notherGpus = setdiff(1:numGpus, labindex) ;\n\nfor l=numel(net.layers):-1:1\n for j=numel(res(l).dzdw):-1:1\n\n if ~isempty(parserv)\n tag = sprintf('l%d_%d',l,j) ;\n parDer = parserv.pull(tag) ;\n else\n parDer = res(l).dzdw{j} ;\n end\n\n if j == 3 && strcmp(net.layers{l}.type, 'bnorm')\n % special case for learning bnorm moments\n thisLR = net.layers{l}.learningRate(j) ;\n net.layers{l}.weights{j} = vl_taccum(...\n 1 - thisLR, ...\n net.layers{l}.weights{j}, ...\n thisLR / batchSize, ...\n parDer) ;\n else\n % Standard gradient training.\n thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;\n thisLR = params.learningRate * net.layers{l}.learningRate(j) ;\n\n if thisLR>0 || thisDecay>0\n % Normalize gradient and incorporate weight decay.\n parDer = vl_taccum(1/batchSize, parDer, ...\n thisDecay, net.layers{l}.weights{j}) ;\n\n if isempty(params.solver)\n % Default solver is the optimised SGD.\n % Update momentum.\n state.solverState{l}{j} = vl_taccum(...\n params.momentum, state.solverState{l}{j}, ...\n -1, parDer) ;\n\n % Nesterov update (aka one step ahead).\n if params.nesterovUpdate\n delta = params.momentum * state.solverState{l}{j} - parDer ;\n else\n delta = state.solverState{l}{j} ;\n end\n\n % Update parameters.\n net.layers{l}.weights{j} = vl_taccum(...\n 1, net.layers{l}.weights{j}, ...\n thisLR, delta) ;\n\n else\n % call solver function to update weights\n [net.layers{l}.weights{j}, state.solverState{l}{j}] = ...\n params.solver(net.layers{l}.weights{j}, state.solverState{l}{j}, ...\n parDer, params.solverOpts, thisLR) ;\n end\n end\n end\n\n % if requested, collect some useful stats for debugging\n if params.plotDiagnostics\n variation = [] ;\n label = '' ;\n switch net.layers{l}.type\n case {'conv','convt','conv_mask'}\n if isnumeric(state.solverState{l}{j})\n variation = thisLR * mean(abs(state.solverState{l}{j}(:))) ;\n end\n power = mean(res(l+1).x(:).^2) ;\n if j == 1 % fiters\n base = mean(net.layers{l}.weights{j}(:).^2) ;\n label = 'filters' ;\n else % biases\n base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;\n label = 'biases' ;\n end\n variation = variation / base ;\n label = sprintf('%s_%s', net.layers{l}.name, label) ;\n end\n res(l).stats.variation(j) = variation ;\n res(l).stats.power = power ;\n res(l).stats.powerLabel = net.layers{l}.name ;\n res(l).stats.label{j} = label ;\n end\n end\nend\n\n% -------------------------------------------------------------------------\nfunction stats = accumulateStats(stats_)\n% -------------------------------------------------------------------------\n\nfor s = {'train', 'val'}\n s = char(s) ;\n total = 0 ;\n\n % initialize stats stucture with same fields and same order as\n % stats_{1}\n stats__ = stats_{1} ;\n names = fieldnames(stats__.(s))' ;\n values = zeros(1, numel(names)) ;\n fields = cat(1, names, num2cell(values)) ;\n stats.(s) = struct(fields{:}) ;\n\n for g = 1:numel(stats_)\n stats__ = stats_{g} ;\n num__ = stats__.(s).num ;\n total = total + num__ ;\n\n for f = setdiff(fieldnames(stats__.(s))', 'num')\n f = char(f) ;\n stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;\n\n if g == numel(stats_)\n stats.(s).(f) = stats.(s).(f) / total ;\n end\n end\n end\n stats.(s).num = total ;\nend\n\n% -------------------------------------------------------------------------\nfunction stats = extractStats(net, params, errors)\n% -------------------------------------------------------------------------\nstats.lossForClassification = errors(1) ;\nfor i = 1:numel(params.errorLabels)\n stats.(params.errorLabels{i}) = errors(i+1) ;\nend\n\n% -------------------------------------------------------------------------\nfunction saveState(fileName, net, state)\n%if((fileName(end-4)=='5')||(fileName(end-4)=='0'))\n% -------------------------------------------------------------------------\nsave(fileName, 'net', 'state') ;\n%end\n\n% -------------------------------------------------------------------------\nfunction saveStats(fileName, stats)\n%if((fileName(end-4)=='5')||(fileName(end-4)=='0'))\n% -------------------------------------------------------------------------\nif exist(fileName)\n save(fileName, 'stats', '-append') ;\nelse\n save(fileName, 'stats') ;\nend\n%end\n\n% -------------------------------------------------------------------------\nfunction [net, state, stats] = loadState(fileName)\n% -------------------------------------------------------------------------\nload(fileName, 'net', 'state', 'stats') ;\nnet = vl_simplenn_tidy(net) ;\nif isempty(whos('stats'))\n error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...\n fileName) ;\nend\n\n% -------------------------------------------------------------------------\nfunction epoch = findLastCheckpoint(modelDir)\n% -------------------------------------------------------------------------\nlist = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;\ntokens = regexp({list.name}, 'net-epoch-([\\d]+).mat', 'tokens') ;\nepoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;\nepoch = max([epoch 0]) ;\n\n% -------------------------------------------------------------------------\nfunction switchFigure(n)\n% -------------------------------------------------------------------------\nif get(0,'CurrentFigure') ~= n\n try\n set(0,'CurrentFigure',n) ;\n catch\n figure(n) ;\n end\nend\n\n% -------------------------------------------------------------------------\nfunction clearMex()\n% -------------------------------------------------------------------------\n%clear vl_tmove vl_imreadjpeg ;\ndisp('Clearing mex files') ;\nclear mex ;\nclear vl_tmove vl_imreadjpeg ;\n\n% -------------------------------------------------------------------------\nfunction prepareGPUs(params, cold)\n% -------------------------------------------------------------------------\nnumGpus = numel(params.gpus) ;\nif numGpus > 1\n % check parallel pool integrity as it could have timed out\n pool = gcp('nocreate') ;\n if ~isempty(pool) && pool.NumWorkers ~= numGpus\n delete(pool) ;\n end\n pool = gcp('nocreate') ;\n if isempty(pool)\n parpool('local', numGpus) ;\n cold = true ;\n end\nend\nif numGpus >= 1 && cold\n fprintf('%s: resetting GPU\\n', mfilename) ;\n clearMex() ;\n if numGpus == 1\n disp(gpuDevice(params.gpus)) ;\n else\n spmd\n clearMex() ;\n disp(gpuDevice(params.gpus(labindex))) ;\n end\n end\nend\n", "meta": {"author": "zqs1022", "repo": "interpretableCNN", "sha": "6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823", "save_path": "github-repos/MATLAB/zqs1022-interpretableCNN", "path": "github-repos/MATLAB/zqs1022-interpretableCNN/interpretableCNN-6d7d1a6aaf0f1b2b03a3b54d4ac4803b3f1ce823/code/tool/main/our_cnn_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1788522504500009}} {"text": "% save the tracking results to txt required by the MOTChallenge\nfunction save_results(seq_name, file_name, bboxes, initialization_threshold, opt)\n\nnum_target = max(bboxes.id);\nlen_traj = zeros(num_target, 1);\nfor i = 1:num_target\n len_traj(i) = numel(find(bboxes.id == i & (bboxes.state == opt.STATE_TRACKED | bboxes.state == opt.STATE_ACTIVATED)));\nend\n\nfid = fopen(file_name, 'w');\nnum_bbox = numel(bboxes.x);\n\nfor i = 1:num_bbox\n % , , , , , , , , , \n if len_traj(bboxes.id(i)) > initialization_threshold && (bboxes.state(i) == opt.STATE_TRACKED || bboxes.state(i) == opt.STATE_ACTIVATED)\n fprintf(fid, '%d,%d,%f,%f,%f,%f,%f,%f,%f,%f\\n', ...\n bboxes.fr(i), bboxes.id(i), bboxes.x(i), bboxes.y(i), bboxes.w(i), bboxes.h(i), -1, -1, -1, -1);\n end\nend\n\nfclose(fid);", "meta": {"author": "jizhu1023", "repo": "DMAN_MOT", "sha": "b522fc5ae8d8152c43be14126c4d6160fdf289f8", "save_path": "github-repos/MATLAB/jizhu1023-DMAN_MOT", "path": "github-repos/MATLAB/jizhu1023-DMAN_MOT/DMAN_MOT-b522fc5ae8d8152c43be14126c4d6160fdf289f8/save_results.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 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 reducedisp_wfmeas(varargin);\n\n% REDUCEDISP_WFMEAS(STARTTIME,ENDTIME,SCNL,DIST,DS,DBOUT,FILT,TIMESTEP,ALGORITHM)\n% This function reads calibrated waveforms and write out a wfmeas\n% database table containing reduced displacement values. The reduced displacment \n% functionality requres the Antelope toolbox, the waveform object toolbox and the \n% filterobject toolbox.\n% \n% Example:\n% starttime = '12/01/2006 19:40:00';\t% formatted start time (string)\n% endtime = '12/31/2006 24:00:00';\t% formatted end data (string)\n% scnl = scnlobject('BEZB','HHZ')\n% dist = 5.224;\t\t\t% distance to assumed source (km)\n% ds = datasource('antelope','/home/admin/databases/PIRE/wf/pire_2006');\n% dbout = 'databases/BEZB_p5-10Hz'; \t% output db (string)\n% filt = filterobject('B',[0.5 10],4);\t% filter to apply to traces\n% Tstep = 600;\t\t\t\t% time step and window wdith\n% algorithm = 'BODY'; % algorithm (BODY or SURF)\n% reducedisp_wfmeas(starttime,endtime,scnl,dist,ds,dbout,filt,Tstep,algorithm);\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\nif numel(varargin) ~= 9\n error('Incorrect number of input arguments');\nelse\n T1 = varargin{1};\n T2 = varargin{2};\n scnl = varargin{3};\n distkm = varargin{4};\n ds = varargin{5};\n dbout = varargin{6};\n flt = varargin{7};\n Tstep = varargin{8};\n algorithm = varargin{9};\nend\n\n\n% PREP TIME PARAMETERS\nTstep = Tstep/86400;\t% time step between measurements in seconds\nTwin = Tstep; % could be used later to have different time steps and windows.\nTWstep = 6*3600/86400;\t% load 6 hr. waveforms at a time\ngapThresh = 0.5; % [<1.0] maximum allowable gap size (ratio to data length)\n\n\n% GET WAVEFORM TIMES (LARGE CHUCKS OF TIME)\n% round *up* the waveform start times the nearest Tstep\ntmod = mod(datenum(T1),Tstep);\nif tmod == 0\n\ttmod = Tstep;\nend;\nt1 = datenum(T1) + ( Tstep - tmod); \nNwf = floor( (datenum(T2)-t1(1)) / TWstep );\nt1 = t1(1) + TWstep*[0:Nwf-1];\nt2 = t1 + TWstep;\n\n\n\nfor i = 1:Nwf \n\n\t% LOAD WAVEFORM AND TEST FOR GOOD DATA\n \tPROCESS = 1;\n\ttry\n\t\tW = waveform(ds,scnl,t1(i),t2(i));\n\t\tif isempty(W) \n \t\tdisp(['Skipping ' datestr(t1(i),31) ' to ' datestr(t2(i),31) ' . Empty waveform.']);\n\t\t\tPROCESS = 0;\n \t\tend\n\tcatch\n\t\tdisp(['Skipping ' datestr(t1(i),31) ' to ' datestr(t2(i),31) ' . Problem loading waveform.']);\n \t\tPROCESS = 0;\n\tend\n \tif PROCESS\n\t\tif (get(W,'DURATION_EPOCH') < gapThresh*Tstep)\n \t\tdisp(['Skipping ' datestr(t1(i),31) ' to ' datestr(t2(i),31) '. Data is more than ' num2str(100*gapThresh) '% gaps.']);\n \t\t\tPROCESS = 0;\n\t\tend\n\tend\n\n\nif PROCESS\n\n % FILTER DATA\n % TODO: should be changed to be gap aware \n W = fillgaps(W,'meanAll'); \n W = demean(detrend(W));\n\t\tW = filtfilt(flt,W);\n \n % CREATE SUBSETS OF DATA\n Nwin = get(W,'DURATION') / Twin;\n To = get(W,'START_MATLAB');\n for ii = 1:Nwin\n Tbegin(ii) = To+(ii-1)*Tstep;\n Tend(ii) = To+(ii-1)*Tstep+Twin;\n end;\n w = extract(W,'TIME',Tbegin,Tend);\n\n % GET REDUCED DISPLACEMENT\n disp(['Calculating reduced displacements on ' datestr(t1(i),31) ' to ' datestr(t2(i),31) ' ...']);\n w = reducedisp_calc(w,distkm,algorithm);\n\n % WRITE DB TABLE\n disp(['Writing reduced displacements to ' dbout ' ...']);\n reducedisp_write_wfmeas(dbout,w,flt,algorithm);\n\n end;\n\nend;\n\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/contributed_antelope/reduced_displacement/reducedisp_wfmeas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.1785263952507634}} {"text": "% LFReadESLF.m - Read ESLF-encoded light fields\n% \n% Usage: \n% LF = LFReadESLF( FName )\n% LF = LFReadESLF( FName, [LensletSize_pix], [LoadAlpha], [] )\n%\n% This function reads the ESLF files commonly used to store light fields, e.g. those at\n% lightfields.stanford.edu.\n% \n% Inputs:\n% FName: path to input file\n% \n% Optional Inputs:\n% LensletSize_pix: number of pixels per lenslet, default 14\n% \n% LoadAlpha: default true; if true, aattempts to load an alpha channel from the ESLF and use as\n% a weight channel for the LF; useful for indicating empty subaperture images; use in\n% conjunction with png or other formats with alpha channels\n% \n% : additional options are passed to imread; useful examples: 'BackgroundColor'\n% \n% Outputs:\n% LF: a 4D light field with index order [t,s,v,u,c], where s,t are horizontal and vertical\n% subaperture index; u,v are horizontal and vertical pixel index; and c is colour channel.\n%\n% User guide: LFToolbox.pdf\n% See also: LFWriteESLF, LFReadGantryArray, LFUtilDecodeLytroFolder\n\n% Copyright (c) 2013-2020 Donald G. Dansereau\n\nfunction LF = LFReadESLF( FName, LensletSize_pix, LoadAlpha, varargin )\n\nLensletSize_pix = LFDefaultVal('LensletSize_pix', [14,14]);\nLoadAlpha = LFDefaultVal('LoadAlpha', true);\nNChans = 3;\n\nif( LoadAlpha )\n\t[Img,ColorMap, Alpha] = imread( FName, varargin{:} ); % note: requesting Alpha sets bg to black\n\tif( ~isempty(Alpha) )\n\t\tImg(:,:,NChans+1) = Alpha;\n\t\tNChans = NChans + 1;\n\tend\nelse\n\t[Img,ColorMap] = imread( FName, varargin{:} );\nend\n\nif( ~isempty(ColorMap) ) % indexed colour image\n\tImg = ind2rgb(Img, ColorMap); % todo[optimization] may wish to convert to uint8\nend\n\nImgSize = size(Img(:,:,1));\n\nLFSize(3:4) = ceil(ImgSize./LensletSize_pix);\nPadSize = LFSize(3:4) .* LensletSize_pix;\nPadAmt = PadSize-ImgSize;\n\nLFSize(1:2) = PadSize ./ LFSize(3:4);\nLFSize(5) = NChans;\n\nImgPad = padarray(Img, PadAmt, 0,'post');\n\nLF = reshape(ImgPad, LFSize([1,3,2,4,5]));\nLF = permute(LF, [1,3,2,4,5]);\n", "meta": {"author": "doda42", "repo": "LFToolbox", "sha": "5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e", "save_path": "github-repos/MATLAB/doda42-LFToolbox", "path": "github-repos/MATLAB/doda42-LFToolbox/LFToolbox-5dd4a8acf6555ae362a7c5b8d5bd4b9827790a4e/LFReadESLF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.17844959453746956}} {"text": "%==========================================================================\n% This is the testing code of IRCNN for color image demosaiking.\n%\n% @inproceedings{zhang2017learning,\n% title={Learning Deep CNN Denoiser Prior for Image Restoration},\n% author={Zhang, Kai and Zuo, Wangmeng and Gu, Shuhang and Zhang, Lei},\n% booktitle={IEEE Conference on Computer Vision and Pattern Recognition},\n% pages={3929--3938},\n% year={2017},\n% }\n%\n% If you have any question, please feel free to contact with .\n%\n% -----------McMaster18--------\n% --Set18----Color Demosaiking-\n% -----------------------------\n% 01.tif -- 30.26dB -- 0.93\n% 02.tif -- 35.26dB -- 0.94\n% 03.tif -- 34.69dB -- 0.97\n% 04.tif -- 38.37dB -- 0.99\n% 05.tif -- 35.09dB -- 0.95\n% 06.tif -- 39.19dB -- 0.97\n% 07.tif -- 39.66dB -- 0.98\n% 08.tif -- 39.44dB -- 0.97\n% 09.tif -- 38.64dB -- 0.96\n% 10.tif -- 39.51dB -- 0.97\n% 11.tif -- 40.46dB -- 0.97\n% 12.tif -- 38.86dB -- 0.96\n% 13.tif -- 40.71dB -- 0.95\n% 14.tif -- 38.99dB -- 0.96\n% 15.tif -- 39.47dB -- 0.96\n% 16.tif -- 34.39dB -- 0.95\n% 17.tif -- 34.79dB -- 0.96\n% 18.tif -- 36.21dB -- 0.96\n% Average PSNR and SSIM\n% 37.4447dB 0.9614\n\n% ----------Kodak24-----------------\n% ----Set24-----Color Demosaiking---\n% ----------------------------------\n% kodim01.png -- 40.30dB -- 0.99\n% kodim02.png -- 39.79dB -- 0.97\n% kodim03.png -- 43.63dB -- 0.98\n% kodim04.png -- 41.21dB -- 0.98\n% kodim05.png -- 39.24dB -- 0.99\n% kodim06.png -- 40.54dB -- 0.99\n% kodim07.png -- 43.26dB -- 0.99\n% kodim08.png -- 37.70dB -- 0.98\n% kodim09.png -- 42.07dB -- 0.97\n% kodim10.png -- 42.03dB -- 0.98\n% kodim11.png -- 40.55dB -- 0.98\n% kodim12.png -- 42.96dB -- 0.98\n% kodim13.png -- 36.94dB -- 0.98\n% kodim14.png -- 38.98dB -- 0.98\n% kodim15.png -- 40.59dB -- 0.97\n% kodim16.png -- 43.05dB -- 0.99\n% kodim17.png -- 41.38dB -- 0.98\n% kodim18.png -- 38.15dB -- 0.98\n% kodim19.png -- 40.63dB -- 0.98\n% kodim20.png -- 41.30dB -- 0.98\n% kodim21.png -- 40.27dB -- 0.98\n% kodim22.png -- 39.14dB -- 0.98\n% kodim23.png -- 43.05dB -- 0.98\n% kodim24.png -- 36.22dB -- 0.98\n% Average PSNR and SSIM\n% 40.5409dB 0.9806\n%\n% by Kai Zhang (1/2018)\n%==========================================================================\n\nclear; clc;\n\naddpath('utilities');\nimageSets = {'Set18','Set24'}; % testing dataset\nsetTest = imageSets(1); % select the dataset\n\nuseGPU = 1;\n\nfolderTest = 'testsets';\nfolderResult = 'results';\nfolderModel = 'models';\nif ~exist(folderResult,'file')\n mkdir(folderResult);\nend\nsetTestCur = cell2mat(setTest(1));\ndisp('--------------------------------------------');\ndisp(['----',setTestCur,'--Color Image Demosaiking--']);\ndisp('--------------------------------------------');\nfolderTestCur = fullfile(folderTest,setTestCur);\n\n% folder to store results\nfolderResultCur = fullfile(folderResult, ['Demosaik_',setTestCur]);\nif ~exist(folderResultCur,'file')\n mkdir(folderResultCur);\nend\n\n\n%% Noise level \nnoiselevel = 0; % default; noiselevel = 10; Isigma = 10/255; Msigma = 8;\n\n\n%% parameter setting in HQS (tune the following parameters to obtain the best results)\n%% -------------------important!------------------\n% Parameter settings of IRCNN\n% (1) image noise level: Isigma\nIsigma = 0.5/255; % default 0.5/255 for noise-free image, ****** from interval [1/255, 20/255] ******; e.g., 1/255, 2.55/255, 7/255, 11/255\n% (2) noise level of the last denoiser: Msigma\nMsigma = 2; % default 2 for noise-free image, ****** from {1 2 3 4 5 7 9 11 13 15} ******\n%--------------------------------------------------------\n\n%% load denoisers\nload(fullfile(folderModel,'modelcolor.mat'));\n\n%% default parameter setting in HQS\ntotalIter = 30; % default 30\nlamda = (Isigma^2)/3; % default 3, ****** from {1 2 3 4} ******\nmodelSigma1 = 49; % default 49\nmodelSigmaS = logspace(log10(modelSigma1),log10(Msigma),totalIter);\nrho = Isigma^2/((modelSigma1/255)^2);\n\nns = min(25,max(ceil(modelSigmaS/2),1));\nns = [ns(1)-1,ns];\n\next = {'*.jpg','*.png','*.bmp','*.tif'};\nfilepaths = [];\nfor i = 1 : length(ext)\n filepaths = cat(1,filepaths,dir(fullfile(folderTestCur, ext{i})));\nend\n\nPSNRs = zeros(1,length(filepaths));\nSSIMs = zeros(1,length(filepaths));\n\nfor i = 1 : length(filepaths)\n \n label = imread(fullfile(folderTestCur,filepaths(i).name));\n [~, Iname, ext] = fileparts(filepaths(i).name);\n label = im2single(label);\n \n % generate mask\n [B, y, mask] = mosaic_bayer(label, 'grbg', noiselevel);\n y = single(y);\n mask = single(mask);\n z = linearlcc(B, 0);\n z = single(z);\n \n z0 = z;\n if useGPU\n z = gpuArray(z);\n y = gpuArray(y);\n end\n \n for itern = 1:totalIter\n \n % step 1\n rho = lamda*255^2/(modelSigmaS(itern)^2);\n z = (y+rho*z)./(mask+rho);\n \n if ns(itern+1)~=ns(itern)\n [net] = loadmodel(modelSigmaS(itern),CNNdenoiser);\n net = vl_simplenn_tidy(net);\n if useGPU\n net = vl_simplenn_move(net, 'gpu');\n end\n end\n \n % step 2\n res = vl_simplenn(net, z,[],[],'conserveMemory',true,'mode','test');\n residual = res(end).x;\n z = z - residual;\n \n % imshow(z)\n % title(int2str(itern))\n % drawnow;\n end\n \n if useGPU\n output = im2uint8(gather(z));\n y = im2uint8(gather(y));\n end\n \n %output(mask==1) = y(mask==1);\n \n [PSNR_Cur,SSIM_Cur] = Cal_PSNRSSIM(im2uint8(label),output,10,10);\n \n PSNRs(i) = PSNR_Cur;\n SSIMs(i) = SSIM_Cur;\n \n imshow(cat(2,y,output));\n drawnow;\n pause(0.001);\n \n disp([filepaths(i).name,' -- ', num2str(PSNR_Cur,'%2.2f'),'dB -- ', num2str(SSIM_Cur,'%2.2f')]);\n % imwrite(y,fullfile(folderResultCur,[Iname,'_mosaik.png']));\n % imwrite(output,fullfile(folderResultCur,[Iname,'_ircnn.png']));\n \nend\n\ndisp('Average PSNR and SSIM')\ndisp([mean(PSNRs),mean(SSIMs)]);\n\n", "meta": {"author": "cszn", "repo": "IRCNN", "sha": "d9dcd537bdac3ae5b753296cd675db8a303c8f72", "save_path": "github-repos/MATLAB/cszn-IRCNN", "path": "github-repos/MATLAB/cszn-IRCNN/IRCNN-d9dcd537bdac3ae5b753296cd675db8a303c8f72/Demo_demosaiking.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.1784075118261639}} {"text": "function [biasFieldCorrected, varargout] = segment(this, varargin)\n% Segments brain images using SPM's unified segmentation approach.\n% This warps the brain into a standard space and segment it there using tissue\n% probability maps in this standard space.\n%\n% Since good warping and good segmentation are interdependent, this is done\n% iteratively until a good tissue segmentation is given by probality maps\n% that store how likely a voxel is of a certain tissue type\n% (either in native or standard space).\n% Furthermore, a deformation field from native to standard space (or back)\n% has then been found for warping other images of the same native space.\n%\n% Y = MrImage()\n% [biasFieldCorrected, tissueProbMaps, deformationFields, biasField] = ...\n% Y.segment(...\n% 'representationIndexArray', representationIndexArray, ...\n% 'spmParameterName1', spmParameterValue1, ...\n% ...\n% 'spmParameterNameN', spmParameterValueN)\n%\n% This is a method of class MrImageSpm4D.\n%\n% NOTE: If an nD image is given, then all dimension > 3 will be treated as\n% channels.\n%\n% IN\n% tissueTypes cell(1, nTissues) of strings to specify which\n% tissue types shall be written out:\n% 'GM' grey matter\n% 'WM' white matter\n% 'CSF' cerebrospinal fluid\n% 'bone' skull and surrounding bones\n% 'fat' fat and muscle tissue\n% 'air' air surrounding head\n%\n% default: {'GM', 'WM', 'CSF'}\n%\n% mapOutputSpace 'native' (default) or 'warped'/'mni'/'standard'\n% defines coordinate system in which images shall be\n% written out;\n% 'native' same space as image that was segmented\n% 'warped' standard Montreal Neurological Institute\n% (MNI) space used by SPM for unified segmentation\n% deformationFieldDirection determines which deformation field shall be\n% written out,if any\n% 'none' (default) no deformation fields are stored\n% 'forward' subject => mni (standard) space\n% 'backward'/'inverse' mni => subject space\n% 'both'/'all' = 'forward' and 'backward'\n% saveBiasField 0 (default) or 1\n% biasRegularisation describes the amount of expected bias field\n% default: 0.001 (light)\n% no: 0; extremely heavy: 10\n% biasFWHM full-width-at-half-maximum of the Gaussian\n% non-uniformity bias field (in mm)\n% default: 60 (mm)\n% fileTPM tissue probablity maps for each tissue class\n% default: SPM' TPMs in spm/tpm\n% mrfParameter strenght of the Markov Random Field cleanup\n% performed on the tissue class images\n% default: 1\n% cleanUp crude routine for extracting the brain from\n% segmented images ('no', 'light', 'thorough')\n% default: 'light'\n% warpingRegularization regularization for the different terms of the\n% registration\n% default: [0 0.001 0.5 0.05 0.2]\n% affineRegularisation regularisation for the initial affine registration\n% of the image to the tissue probability maps (i.e.\n% into standard space)\n% for example, the default ICBM template are slighlty\n% larger than typical brains, so greater zooms are\n% likely to be needed\n% default: ICBM spase template - European brains\n% smoothnessFwhm fudge factor to account for correlation between\n% neighbouring voxels (in mm)\n% default: 0 (for MRI)\n% samplingDistance approximate distance between sampled points when\n% estimating the model parameters (in mm)\n% default: 3\n%\n% Parameters for high-dim application:\n%\n% representationIndexArray: a selection (e.g. {'t', 1}) which is then\n% applied to obtain one nD image, where all\n% dimensions > 3 are treated as additional\n% channels\n% default representationIndexArray: all\n% dimensions not the imageSpaceDims\n% imageSpaceDims cell array of three dimLabels defining the\n% dimensions that define the physical space\n% the image is in\n% default imageSpaceDims: {'x', 'y', 'z'}\n% splitComplex 'ri' or 'mp'\n% If the data are complex numbers, real and\n% imaginary or magnitude and phase are\n% realigned separately.\n% default: mp (magnitude and p)\n% Typically, realigning the magnitude and\n% applying it to the phase data makes most\n% sense; otherwise, using real and imaginary\n% part, more global phase changes would\n% impact on estimation\n%\n% OUT\n% biasCorrected bias corrected images\n% tissueProbMaps (optional) cell(nTissues,1) of 3D MrImages\n% containing the tissue probability maps in the\n% respective order as volumes,\n% deformationFields (optional) cell(nDeformationFieldDirections,1)\n% if deformationFieldDirection is 'both', this cell\n% contains the forward deformation field in the first\n% entry, and the backward deformation field in the\n% second cell entry; otherwise, a cell with only one\n% element is returned\n% biasField (optional) bias field\n%\n% EXAMPLE\n% [biasFieldCorrected, tissueProbMaps, deformationFields, biasField] =\n% Y.segment();\n%\n% for 7T images stronger non-uniformity expected\n% [biasFieldCorrected, tissueProbMaps, deformationFields, biasField] = ...\n% m.segment('biasRegularisation', 1e-4, 'biasFWHM', 18, ...\n% 'cleanUp', 2, 'samplingDistance', 2);\n%\n% See also MrImage spm_preproc MrImageSpm4D.segment\n% Author: Saskia Bollmann & Lars Kasper\n% Created: 2019-12-23\n% Copyright (C) 2019 Institute for Biomedical Engineering\n% University of Zurich and ETH Zurich\n%\n% This file is part of the TAPAS UniQC Toolbox, which is released\n% under the terms of the GNU General Public License (GPL), version 3.\n% You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version).\n% For further details, see the file COPYING or\n% .\n\n% spm parameters (details above)\nspmDefaults.tissueTypes = {'WM', 'GM', 'CSF'};\nspmDefaults.mapOutputSpace = 'native';\nspmDefaults.deformationFieldDirection = 'none';\nspmDefaults.saveBiasField = 0;\nspmDefaults.biasRegularisation = 0.001;\nspmDefaults.biasFWHM = 60;\nspmDefaults.fileTPM = [];\nspmDefaults.mrfParameter = 1;\nspmDefaults.cleanUp = 'light';\nspmDefaults.warpingRegularization = [0 0.001 0.5 0.05 0.2];\nspmDefaults.affineRegularisation = 'mni';\nspmDefaults.smoothnessFwhm = 0;\nspmDefaults.samplingDistance = 3;\n\n[spmParameters, unusedVarargin] = tapas_uniqc_propval(varargin, spmDefaults);\n\n% for split/apply functionality\nmethodParameters = {spmParameters};\n\n% use cases: abs of complex, single index on many!\ndefaults.representationIndexArray = {{}}; % default: use all\ndefaults.imageSpaceDims = {};\ndefaults.splitComplex = 'mp';\n\nargs = tapas_uniqc_propval(unusedVarargin, defaults);\ntapas_uniqc_strip_fields(args);\n\n% set imageSpaceDims\nif isempty(imageSpaceDims)\n imageSpaceDims = {'x','y','z'};\nend\n\n% check whether real/complex\nisReal = isreal(this);\n\nif isReal\n splitComplexImage = this.copyobj();\nelse\n splitComplexImage = this.split_complex(splitComplex);\nend\n\n% prepare output container with right size\nvarargoutForMrImageSpm4D = cell(numel(representationIndexArray),nargout-1);\nhasArgOut = nargout > 1;\nhasBiasField = nargout > 3;\nfor iRepresentation = 1:numel(representationIndexArray)\n \n % apply selection\n inputSegment = splitComplexImage.select(...\n representationIndexArray{iRepresentation});\n \n % Merge all n>3 dims, which are not part of the representationIndexArray, into 4D array\n mergeDimLabels = setdiff(inputSegment.dimInfo.dimLabels, imageSpaceDims);\n % additional channels need to be in the t dimensions so they become part of\n % the same nifti file\n % empty mergeDimLabels just return the original object, e.g. for true 3D\n % images\n [mergedImage, newDimLabel] = ...\n inputSegment.merge(mergeDimLabels, 'dimLabels', 't');\n \n if hasArgOut\n [biasFieldCorrected{iRepresentation}, varargoutForMrImageSpm4D{iRepresentation, :}] = ...\n mergedImage.apply_spm_method_per_4d_split(@segment, ...\n 'methodParameters', methodParameters);\n else\n biasFieldCorrected{iRepresentation} = mergedImage.apply_spm_method_per_4d_split(@segment, ...\n 'methodParameters', methodParameters);\n end\n \n % un-do merge operation using combine\n if ~isempty(mergeDimLabels)\n % not necessary for 4D images - just reset dimInfo\n if numel(mergeDimLabels) == 1\n origDimInfo = inputSegment.dimInfo;\n biasFieldCorrected{iRepresentation}.dimInfo = origDimInfo;\n % also for the bias fields\n if hasBiasField\n varargoutForMrImageSpm4D{iRepresentation, 3}.dimInfo = origDimInfo;\n end\n else\n % created original dimInfo per split\n origDimInfo = inputSegment.dimInfo.split(mergeDimLabels);\n % un-do reshape\n split_array = biasFieldCorrected{iRepresentation}.split('splitDims', newDimLabel);\n split_array = reshape(split_array, size(origDimInfo));\n % add original dimInfo\n for nSplits = 1:numel(split_array)\n split_array{nSplits}.dimInfo = origDimInfo{nSplits};\n end\n % and combine\n biasFieldCorrected{iRepresentation} = split_array{1}.combine(split_array);\n \n % same for the bias fields\n if hasBiasField\n % un-do reshape\n split_array = varargoutForMrImageSpm4D{iRepresentation, 3}{1}.split('splitDims', newDimLabel);\n split_array = reshape(split_array, size(origDimInfo));\n % add original dimInfo\n for nSplits = 1:numel(split_array)\n split_array{nSplits}.dimInfo = origDimInfo{nSplits};\n end\n varargoutForMrImageSpm4D{iRepresentation, 3} = {split_array{1}.combine(split_array)};\n end\n end\n end\n \n if ~isReal\n % un-do complex split\n biasFieldCorrected{iRepresentation} = biasFieldCorrected{iRepresentation}.combine_complex();\n end\n \n % add representation index back to TPMs and deformation field to\n % combine them later\n if ~isempty(representationIndexArray{iRepresentation})\n for nOut = 1:nargout-2\n addDim = varargoutForMrImageSpm4D{iRepresentation, nOut}{1}.dimInfo.nDims + 1;\n dimLabels = representationIndexArray{iRepresentation}{1};\n % only pick the first one\n samplingPoints = representationIndexArray{iRepresentation}{2}(1);\n for nClasses = 1:numel(varargoutForMrImageSpm4D{iRepresentation, nOut})\n varargoutForMrImageSpm4D{iRepresentation, nOut}{nClasses}.dimInfo.add_dims(...\n addDim, 'dimLabels', dimLabels, ...\n 'samplingPoints', samplingPoints);\n end\n end\n end\nend\n\n% combine bias field corrected\nbiasFieldCorrected = biasFieldCorrected{1}.combine(biasFieldCorrected);\n\n% combine varargout\nfor nOut = 1:nargout-1\n toBeCombined = varargoutForMrImageSpm4D(:, nOut);\n % the TPMs are cell-arrays of images, so we need to combine them per\n % tissue class\n for nClasses = 1:numel(toBeCombined{1})\n for nCells = 1:size(toBeCombined, 1)\n thisCombine(nCells) = toBeCombined{nCells}(nClasses);\n end\n combinedImage{nClasses, 1} = thisCombine{1}.combine(thisCombine);\n end\n varargout{1, nOut} = combinedImage;\n clear toBeCombined thisCombine combinedImage;\nend\n\nend\n\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/UniQC/code/classes/@MrImage/segment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17840750143648454}} {"text": "\nfunction d2img = draw_2Dskeleton_ITOP(db,fileId,coord_pixel)\n \n db_path = strcat('/home/gyeongsikmoon/workspace/Data/Human_pose_estimation/ITOP/',db,'_view/','ITOP_',db,'_test_depth_map.h5');\n jointNum = 15;\n cubicSz = 2.0;\n imgHeight = 240;\n imgWidth = 320;\n\n annot_path = strcat('/home/gyeongsikmoon/workspace/Data/Human_pose_estimation/ITOP/',db,'_view/','ITOP_',db,'_test_labels.h5');\n \n coord_pixel = squeeze(coord_pixel);\n rgb_img = zeros(imgHeight,imgWidth,3);\n refDepths = zeros(1,jointNum);\n line_width = 6;\n\n gt = h5read(annot_path,'/real_world_coordinates',[1 1 fileId],[3 jointNum 1]);\n for jid = 1:jointNum\n refDepths(1,jid) = gt(3,jid,1);\n end\n refDepth = (min(refDepths(:)) + max(refDepths(:)))/2;\n\n img = h5read(db_path,'/data',[1 1 fileId],[imgWidth imgHeight 1]);\n img = permute(img,[2,1]);\n img(img==0) = refDepth+cubicSz/2;\n \n if strcmp(db,'top')\n mask = h5read(annot_path,'/segmentation',[1 1 fileId],[imgWidth imgHeight 1]);\n mask = permute(mask,[2,1]);\n img(mask==-1) = refDepth+cubicSz/2; \n end\n \n if strcmp(db,'side')\n if 1 <= min(coord_pixel(2,:)-15)\n img(1:round(min(coord_pixel(2,:)))-15,:) = refDepth+cubicSz/2;\n end\n if max(coord_pixel(2,:))+15 <= imgHeight\n img(round(max(coord_pixel(2,:)))+15:imgHeight,:) = refDepth+cubicSz/2;\n end\n if 1 <= min(coord_pixel(1,:)) - 15\n img(:,1:round(min(coord_pixel(1,:)))-15) = refDepth+cubicSz/2;\n end\n if max(coord_pixel(1,:)) + 15 <= imgWidth\n img(:,round(max(coord_pixel(1,:)))+15:imgWidth) = refDepth+cubicSz/2;\n end\n\n img(img < min(coord_pixel(3,:))-0.15) = refDepth+cubicSz/2;\n img(img > max(coord_pixel(3,:))+0.15) = refDepth+cubicSz/2;\n end\n \n img(img>refDepth+cubicSz/2) = refDepth + cubicSz/2;\n img(img.\n%\n% $Id$\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DEVELOPERS NOTE: This code is organized in a similar fashion for multiplot/singleplot/topoplot\n% and for ER/TFR and should remain consistent over those 6 functions.\n% Section 1: general cfg handling that is independent from the data\n% Section 2: data handling, this also includes converting bivariate (chan_chan and chancmb) into univariate data\n% Section 3: cfg handling that depends on the data\n% Section 4: actual plotting\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Section 1: general cfg handling that is independent from the data\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 varargin\nft_preamble provenance varargin\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n return\nend\n\n% this is needed for the figure title\nif isfield(cfg, 'dataname') && ~isempty(cfg.dataname)\n dataname = cfg.dataname;\nelseif isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile)\n dataname = cfg.inputfile;\nelseif nargin>1\n dataname = arrayfun(@inputname, 2:nargin, 'UniformOutput', false);\nelse\n dataname = {};\nend\n\n% make sure figure window titles are labeled appropriately, pass this onto the actual plotting function\ncfg.funcname = mfilename;\ncfg.dataname = dataname;\n\n% prepare the layout, this should be done only once\ntmpcfg = keepfields(cfg, {'layout', 'channel', 'rows', 'columns', 'commentpos', 'skipcomnt', 'scalepos', 'skipscale', 'projection', 'viewpoint', 'rotate', 'width', 'height', 'elec', 'grad', 'opto', 'linecolor', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ncfg.layout = ft_prepare_layout(tmpcfg, varargin{1});\n\n% call the common function that is shared between ft_topoplotER and ft_topoplotTFR\ncfg = topoplot_common(cfg, varargin{:});\n\n% remove this field again, it is only used for figure labels\ncfg = removefields(cfg, 'funcname');\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous varargin\nft_postamble provenance\nft_postamble savefig\n\n% add a menu to the figure, but only if the current figure does not have subplots\nmenu_fieldtrip(gcf, cfg, false);\n\nif ~ft_nargout\n % don't return anything\n clear cfg\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_topoplotER.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.1779431541998514}} {"text": "function p = remove_redundant(p);\n\nif isempty(p.F_struc)\n return\nend\n\nb = p.F_struc(1+p.K.f:p.K.l+p.K.f,1);\nA = -p.F_struc(1+p.K.f:p.K.l+p.K.f,2:end);\n\nredundant = find(((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <-1e-2));\n\nif length(redundant)>1\n p.InequalityConstraintState(redundant) = inf;\nend\n\nif p.options.bmibnb.lpreduce\n b = p.lpcuts(:,1);\n A = -p.lpcuts(:,2:end);\n redundant = find(((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <-1e-2));\n if length(redundant)>1\n p.lpcuts(redundant,:) = [];\n p.cutState(redundant) = [];\n end\nend\n\nif any(p.K.f)\n b = p.F_struc(1:p.K.f,1);\n A = -p.F_struc(1:p.K.f,2:end);\n s1 = ((A>0).*A*(p.ub-p.lb) - (b-A*p.lb) <1e-6);\n s2 = ((-A>0).*(-A)*(p.ub-p.lb) - ((-b)-(-A)*p.lb) <1e-6);\n redundant = find(s1 & s2);\n if length(redundant)>1\n p.EqualityConstraintState(redundant) = inf;\n end\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/remove_redundant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.1778790931392603}} {"text": "function [document, scores] = report_precision_recall(context, experiment, trackers, sequences, varargin)\n% report_overlap Generate a report using tracking precision recall methodology\n%\n% Performs tracking precision-recall analysis and generates a report based on the results.\n%\n% Input:\n% - context (structure): Report context structure.\n% - experiment (struct): An experiment structure.\n% - trackers (cell): An array of tracker structures.\n% - sequences (cell): An array of sequence structures.\n% - varargin[UseTags] (boolean): Analyze according to tags (otherwise according to sequences).\n% - varargin[HideLegend] (boolean): Hide legend in plots.\n%\n% Output:\n% - document (structure): Resulting document structure.\n% - scores (struct): A scores structure.\n%\n\nusetags = get_global_variable('report_tags', true);\nhidelegend = get_global_variable('report_lagend_hide', false);\nresolution = 100;\n\nfor i = 1:2:length(varargin)\n switch lower(varargin{i})\n case 'usetags'\n usetags = varargin{i+1};\n case 'resolutuion'\n resolution = varargin{i+1};\n case 'hidelegend'\n hidelegend = varargin{i+1};\n otherwise\n error(['Unknown switch ', varargin{i}, '!']) ;\n end\nend\n\n\nif ~strcmp(experiment.type, 'unsupervised')\n error('Tracking precision-recall analysis only suitable for unsupervised experiments!');\nend\n\ndocument = document_create(context, 'tpr', 'title', 'Tracking precision recall');\n\ntrackers_hash = md5hash(strjoin((cellfun(@(x) x.identifier, trackers, 'UniformOutput', false)), '-'), 'Char', 'hex');\nparameters_hash = md5hash(sprintf('%d%d', usetags, resolution));\n\ntags = {};\n\nif isempty(experiment.tags)\n usetags = false;\nend;\n\nif usetags && isfield(experiment, 'tags')\n tags = union(experiment.tags, {'all'});\n sequences_hash = md5hash(strjoin(tags, '-'), 'Char', 'hex');\nelse\n sequences_hash = md5hash(strjoin((cellfun(@(x) x.name, sequences, 'UniformOutput', false)), '-'), 'Char', 'hex');\nend;\n\ncache_identifier = sprintf('tpr_%s_%s_%s_%s', experiment.name, trackers_hash, sequences_hash, parameters_hash);\n\nresult = document_cache(context, cache_identifier, @analyze_precision_recall, experiment, trackers, ...\n sequences, 'Tags', tags, 'Resolution', resolution);\n\nif usetags\n % When using tags we have inserted a separate one for this\n mask = strcmp('tag_all', result.selectors);\n\n average_curve = result.curves(:, mask);\n average_measures = result.measures(:, mask);\n\n % Now remove the 'all' tag from results\n tag_curve = result.curves(:, ~mask);\n tag_measures = result.measures(:, ~mask);\n\n selector_tags = cat(2, result.selectors(~mask), result.selectors(mask));\n \nelse\n \n average_curve = cell(numel(trackers), 1);\n average_measures = zeros(numel(trackers), 3);\n \n for t = 1:numel(trackers)\n average_curve{t} = mean(cat(3, result.curves{t, :}), 3);\n f = 2 * (average_curve{t}(:, 1) .* average_curve{t}(:, 2)) ./ (average_curve{t}(:, 1) + average_curve{t}(:, 2));\n [average_measures(t, 1), idx] = max(f);\n average_measures(t, 2) = average_curve{t}(idx, 1);\n average_measures(t, 3) = average_curve{t}(idx, 2);\n end;\n \n tag_curve = result.curves;\n tag_measures = result.measures;\n \n selector_tags = result.selectors;\n \nend\n\nscores.name = 'TPR';\nscores.values = average_measures;\nscores.ids = {'f', 'tp', 'tr'};\nscores.names = {'F', 'TP', 'TR'};\nscores.order = {'descending', 'descending', 'descending'};\n\ntracker_labels = cellfun(@(x) iff(isfield(x.metadata, 'verified') && x.metadata.verified, [x.label, '*'], x.label), trackers, 'UniformOutput', 0);\n\nprint_text('Writing tracking precision-recall table ...');\n\ndocument.section('Experiment %s', experiment.name);\n\npr_plot(document, sprintf('%s_average', experiment.name), ...\n sprintf('Experiment %s (average)', experiment.name), ...\n trackers, average_curve, hidelegend);\n\ntable_data = highlight_best_rows(num2cell(cat(2, tag_measures(:, : , 1), average_measures(:, 1))), repmat({'descending'}, 1, size(tag_measures, 2) + 1));\n\ndocument.table(table_data, 'columnLabels', selector_tags, 'rowLabels', tracker_labels, 'title', 'Tracking precision-recall overview');\n\ndocument.subsection('Detailed plots');\n\nfor t = 1:size(tag_curve, 2)\n\n plot_title = sprintf('Tracking precision-recall plot for tag %s in experiment %s', ...\n selector_tags{t}, experiment.name);\n plot_id = sprintf('overlap_%s_%s', experiment.name, selector_tags{t});\n\n pr_plot(document, plot_id, plot_title, trackers, tag_curve(:, t), ~hidelegend);\n\nend;\n\ndocument.write();\n\nend\n\nfunction pr_plot(document, identifier, title, trackers, curves, hidelegend)\n\n handle = plot_blank('Visible', false, 'Title', 'Overlap', 'Width', 6, 'Height', 6); hold on;\n\n phandles = zeros(numel(trackers), 1);\n\n for t = 1:numel(curves)\n phandles(t) = plot(curves{t}(:, 2), curves{t}(:, 1), 'Color', trackers{t}.style.color);\n end;\n\n labels = cellfun(@(x) x.label, trackers, 'UniformOutput', false);\n\n if ~hidelegend\n legend(phandles, labels);\n end;\n\n xlabel('Tracking recall');\n ylabel('Tracking precision');\n xlim([0, 1]); \n ylim([0, 1]);\n hold off;\n document.figure(handle, identifier, title);\n\n close(handle);\nend\n", "meta": {"author": "votchallenge", "repo": "toolkit-legacy", "sha": "2fb78d5301dadc102fb329b3a3f1bb02c670e8ee", "save_path": "github-repos/MATLAB/votchallenge-toolkit-legacy", "path": "github-repos/MATLAB/votchallenge-toolkit-legacy/toolkit-legacy-2fb78d5301dadc102fb329b3a3f1bb02c670e8ee/report/report_precision_recall.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.17787908829250484}} {"text": "% sdae - training a stacked DAE (finetuning)\n% Copyright (C) 2011 KyungHyun Cho, Tapani Raiko, Alexander Ilin\n%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n%\nfunction [S] = sdae(S, patches, valid_patches, valid_portion);\n\nif nargin < 3\n early_stop = 0;\n valid_patches = [];\n valid_portion = 0;\nelse\n early_stop = 1;\n valid_err = -Inf;\n valid_best_err = -Inf;\nend\n\nactual_lrate = S.learning.lrate;\n\nn_samples = size(patches, 1);\n\nlayers = S.structure.layers;\nn_layers = length(layers);\n\nif layers(1) ~= size(patches, 2)\n error('Data is not properly aligned');\nend\n\nminibatch_sz = S.learning.minibatch_sz;\nn_minibatches = ceil(n_samples / minibatch_sz);\n\nn_epochs = S.iteration.n_epochs;\n\nmomentum = S.learning.momentum;\nweight_decay = S.learning.weight_decay;\n\nbiases_grad = cell(n_layers, 1);\nW_grad = cell(n_layers, 1);\nbiases_grad_old = cell(n_layers, 1);\nW_grad_old = cell(n_layers, 1);\nfor l = 1:n_layers\n biases_grad{l} = zeros(size(S.biases{l}))';\n if l < n_layers\n W_grad{l} = zeros(size(S.W{l}));\n end\n biases_grad_old{l} = zeros(size(S.biases{l}))';\n if l < n_layers\n W_grad_old{l} = zeros(size(S.W{l}));\n end\nend\n\nmin_recon_error = Inf;\nmin_recon_error_update_idx = 0;\nstopping = 0;\n\ndo_normalize = S.do_normalize;\ndo_normalize_std = S.do_normalize_std;\n\nif S.data.binary == 0\n if do_normalize == 1\n % make it zero-mean\n patches_mean = mean(patches, 1);\n patches = bsxfun(@minus, patches, patches_mean);\n end\n\n if do_normalize_std ==1\n % make it unit-variance\n patches_std = std(patches, [], 1);\n patches = bsxfun(@rdivide, patches, patches_std);\n end\nend\n\nanneal_counter = 0;\nactual_lrate0 = actual_lrate;\n\nif S.debug.do_display == 1\n figure(S.debug.display_fid);\nend\n\ntry\n use_gpu = gpuDeviceCount;\ncatch errgpu\n use_gpu = false;\n disp(['Could not use CUDA. Error: ' errgpu.identifier])\nend\n\nfor step=1:n_epochs\n if S.verbose\n fprintf(2, 'Epoch %d/%d: ', step, n_epochs)\n end\n if use_gpu\n % push\n for l = 1:n_layers\n if l < n_layers\n S.W{l} = gpuArray(single(S.W{l}));\n end\n S.biases{l} = gpuArray(single(S.biases{l}));\n end\n\n if S.adagrad.use\n for l = 1:n_layers\n if l < n_layers\n S.adagrad.W{l} = gpuArray(single(S.adagrad.W{l}));\n end\n S.adagrad.biases{l} = gpuArray(single(S.adagrad.biases{l}));\n end\n elseif S.adadelta.use\n for l = 1:n_layers\n if l < n_layers\n S.adadelta.gW{l} = gpuArray(single(S.adadelta.gW{l}));\n S.adadelta.W{l} = gpuArray(single(S.adadelta.W{l}));\n end\n S.adadelta.gbiases{l} = gpuArray(single(S.adadelta.gbiases{l}));\n S.adadelta.biases{l} = gpuArray(single(S.adadelta.biases{l}));\n end\n end\n end\n\n for mb=1:n_minibatches\n S.iteration.n_updates = S.iteration.n_updates + 1;\n\n % p_0\n v0 = patches((mb-1) * minibatch_sz + 1:min(mb * minibatch_sz, n_samples), :);\n mb_sz = size(v0,1);\n\n if use_gpu > 0\n v0 = gpuArray(single(v0));\n end\n\n % add error\n v0_clean = v0;\n\n if S.data.binary == 0 && S.noise.level > 0\n if use_gpu\n v0 = v0 + S.noise.level * gpuArray(randn(size(v0)));\n else\n v0 = v0 + S.noise.level * randn(size(v0));\n end\n end\n\n if S.noise.drop > 0\n mask = binornd(1, 1 - S.noise.drop, size(v0));\n v0 = v0 .* mask;\n clear mask;\n end\n\n h0e = cell(n_layers, 1);\n h0e{1} = v0;\n\n for l = 2:n_layers\n h0e{l} = bsxfun(@plus, h0e{l-1} * S.W{l-1}, S.biases{l}');\n\n if l < n_layers || S.bottleneck.binary\n h0e{l} = sigmoid(h0e{l}, S.hidden.use_tanh);\n end\n end\n\n h0d = cell(n_layers, 1);\n h0d{end} = h0e{end};\n\n for l = n_layers-1:-1:1\n h0d{l} = bsxfun(@plus, h0d{l+1} * S.W{l}', S.biases{l}');\n if l == 1 && S.data.binary\n h0d{l} = sigmoid(h0d{l});\n end\n if l > 1\n h0d{l} = sigmoid(h0d{l}, S.hidden.use_tanh);\n end\n end\n\n % compute reconstruction error\n hr = sdae_get_hidden(v0_clean, S);\n vr = sdae_get_visible(hr, S);\n\n if S.data.binary\n rerr = -mean(sum(v0_clean .* log(max(vr, 1e-16)) + (1 - v0_clean) .* log(max(1 - vr, 1e-16)), 2));\n else\n rerr = mean(sum((v0_clean - vr).^2,2));\n end\n if use_gpu > 0\n rerr = gather(rerr);\n end\n S.signals.recon_errors = [S.signals.recon_errors rerr];\n\n % reset gradients\n for l = 1:n_layers\n biases_grad{l} = 0 * biases_grad{l};\n if l < n_layers\n W_grad{l} = 0 * W_grad{l};\n end\n end\n\n % backprop\n deltad = cell(n_layers, 1);\n deltad{1} = h0d{1} - v0_clean;\n biases_grad{1} = mean(deltad{1}, 1);\n\n for l = 2:n_layers\n deltad{l} = deltad{l-1} * S.W{l-1};\n if l < n_layers || S.bottleneck.binary\n deltad{l} = deltad{l} .* dsigmoid(h0d{l}, S.hidden.use_tanh);\n end\n biases_grad{l} = mean(deltad{l}, 1);\n W_grad{l-1} = (deltad{l-1}' * h0d{l}) / (size(v0, 1));\n end\n\n deltae = cell(n_layers, 1);\n deltae{end} = deltad{end};\n\n for l = n_layers-1:-1:1\n deltae{l} = deltae{l+1} * S.W{l}';\n if l == 1 && S.data.binary\n deltae{l} = deltae{l} .* dsigmoid(h0e{l});\n end\n if l > 1\n deltae{l} = deltae{l} .* dsigmoid(h0e{l}, S.hidden.use_tanh);\n biases_grad{l} = biases_grad{l} + mean(deltae{l}, 1);\n end\n W_grad{l} = W_grad{l} + (h0e{l}' * deltae{l+1}) / (size(v0, 1));\n end\n\n % learning rate\n if S.adagrad.use\n % update\n for l = 1:n_layers\n biases_grad_old{l} = (1 - momentum) * biases_grad{l} + momentum * biases_grad_old{l};\n if l < n_layers\n W_grad_old{l} = (1 - momentum) * W_grad{l} + momentum * W_grad_old{l};\n end\n end\n\n for l = 1:n_layers\n if l < n_layers\n S.adagrad.W{l} = S.adagrad.W{l} + W_grad_old{l}.^2;\n end\n\n S.adagrad.biases{l} = S.adagrad.biases{l} + biases_grad_old{l}.^2';\n end\n\n for l = 1:n_layers\n S.biases{l} = S.biases{l} - S.learning.lrate * (biases_grad_old{l}' + ...\n weight_decay * S.biases{l}) ./ sqrt(S.adagrad.biases{l} + S.adagrad.epsilon);\n if l < n_layers\n S.W{l} = S.W{l} - S.learning.lrate * (W_grad_old{l} + ...\n weight_decay * S.W{l}) ./ sqrt(S.adagrad.W{l} + S.adagrad.epsilon);\n end\n end\n\n elseif S.adadelta.use\n % update\n for l = 1:n_layers\n biases_grad_old{l} = (1 - momentum) * biases_grad{l} + momentum * biases_grad_old{l};\n if l < n_layers\n W_grad_old{l} = (1 - momentum) * W_grad{l} + momentum * W_grad_old{l};\n end\n end\n\n if S.iteration.n_updates == 1\n adamom = 0;\n else\n adamom = S.adadelta.momentum;\n end\n\n for l = 1:n_layers\n if l < n_layers\n S.adadelta.gW{l} = adamom * S.adadelta.gW{l} + (1 - adamom) * W_grad_old{l}.^2;\n end\n\n S.adadelta.gbiases{l} = adamom * S.adadelta.gbiases{l} + (1 - adamom) * biases_grad_old{l}.^2';\n end\n\n for l = 1:n_layers\n dbias = -(biases_grad_old{l}' + ...\n weight_decay * S.biases{l}) .* (sqrt(S.adadelta.biases{l} + S.adadelta.epsilon) ./ ...\n sqrt(S.adadelta.gbiases{l} + S.adadelta.epsilon));\n S.biases{l} = S.biases{l} + dbias;\n\n S.adadelta.biases{l} = adamom * S.adadelta.biases{l} + (1 - adamom) * dbias.^2;\n clear dbias;\n\n if l < n_layers\n dW = -(W_grad_old{l} + ...\n weight_decay * S.W{l}) .* (sqrt(S.adadelta.W{l} + S.adadelta.epsilon) ./ ...\n sqrt(S.adadelta.gW{l} + S.adadelta.epsilon));\n S.W{l} = S.W{l} + dW;\n\n S.adadelta.W{l} = adamom * S.adadelta.W{l} + (1 - adamom) * dW.^2;\n\n clear dW;\n end\n\n end\n else\n if S.learning.lrate_anneal > 0 && (step >= S.learning.lrate_anneal * n_epochs)\n anneal_counter = anneal_counter + 1;\n actual_lrate = actual_lrate0 / anneal_counter;\n else\n if S.learning.lrate0 > 0\n actual_lrate = S.learning.lrate / (1 + S.iteration.n_updates / S.learning.lrate0);\n else\n actual_lrate = S.learning.lrate;\n end\n actual_lrate0 = actual_lrate;\n end\n\n S.signals.lrates = [S.signals.lrates actual_lrate];\n\n % update\n for l = 1:n_layers\n biases_grad_old{l} = (1 - momentum) * biases_grad{l} + momentum * biases_grad_old{l};\n if l < n_layers\n W_grad_old{l} = (1 - momentum) * W_grad{l} + momentum * W_grad_old{l};\n end\n end\n\n for l = 1:n_layers\n S.biases{l} = S.biases{l} - actual_lrate * (biases_grad_old{l}' + weight_decay * S.biases{l});\n if l < n_layers\n S.W{l} = S.W{l} - actual_lrate * (W_grad_old{l} + weight_decay * S.W{l});\n end\n end\n end\n\n if S.verbose == 1\n fprintf(2, '.');\n end\n\n if use_gpu > 0\n clear v0 h0d h0e v0_clean vr hr deltae deltad \n end\n\n if early_stop\n n_valid = size(valid_patches, 1);\n rndidx = randperm(n_valid);\n if use_gpu > 0\n v0valid = gpuArray(single(valid_patches(rndidx(1:round(n_valid * valid_portion)),:)));\n else\n v0valid = single(valid_patches(rndidx(1:round(n_valid * valid_portion)),:));\n end\n\n hr = sdae_get_hidden(v0valid, S);\n vr = sdae_get_visible(hr, S);\n\n if S.data.binary\n rerr = -mean(sum(v0valid .* log(max(vr, 1e-16)) + (1 - v0valid) .* log(max(1 - vr, 1e-16)), 2));\n else\n rerr = mean(sum((v0valid - vr).^2,2));\n end\n if use_gpu > 0\n rerr = gather(rerr);\n end\n\n S.signals.valid_errors = [S.signals.valid_errors rerr];\n\n if valid_err == -Inf\n valid_err = rerr;\n valid_best_err = rerr;\n else\n prev_err = valid_err;\n valid_err = 0.99 * valid_err + 0.01 * rerr;\n\n if step > S.valid_min_epochs && (1.1 * valid_best_err) < valid_err\n fprintf(2, 'Early-stop! %f, %f\\n', valid_err, prev_err);\n stopping = 1;\n break;\n end\n\n if valid_err < valid_best_err\n valid_best_err = valid_err;\n end\n end\n else\n if S.stop.criterion > 0\n if S.stop.criterion == 1\n if min_recon_error > S.signals.recon_errors(end)\n min_recon_error = S.signals.recon_errors(end);\n min_recon_error_update_idx = S.iteration.n_updates;\n else\n if S.iteration.n_updates > min_recon_error_update_idx + S.stop.recon_error.tolerate_count \n fprintf(2, '\\nStopping criterion reached (recon error) %f > %f\\n', ...\n S.signals.recon_errors(end), min_recon_error);\n stopping = 1;\n break;\n end\n end\n else\n error ('Unknown stopping criterion %d', S.stop.criterion);\n end\n end\n end\n\n if length(S.hook.per_update) > 1\n err = S.hook.per_update{1}(S, S.hook.per_update{2});\n\n if err == -1\n stopping = 1;\n break;\n end\n end\n \n if S.debug.do_display == 1 && mod(S.iteration.n_updates, S.debug.display_interval) == 0\n S.debug.display_function (S.debug.display_fid, S, v0, v1, h0, h1, W_grad, vbias_grad, hbias_grad);\n drawnow;\n end\n end\n\n if use_gpu > 0\n % pull\n for l = 1:n_layers\n if l < n_layers\n S.W{l} = gather(S.W{l});\n end\n S.biases{l} = gather(S.biases{l});\n end\n\n if S.adagrad.use\n for l = 1:n_layers\n if l < n_layers\n S.adagrad.W{l} = gather(S.adagrad.W{l});\n end\n S.adagrad.biases{l} = gather(S.adagrad.biases{l});\n end\n elseif S.adadelta.use\n for l = 1:n_layers\n if l < n_layers\n S.adadelta.W{l} = gather(S.adadelta.W{l});\n S.adadelta.gW{l} = gather(S.adadelta.gW{l});\n end\n S.adadelta.biases{l} = gather(S.adadelta.biases{l});\n S.adadelta.gbiases{l} = gather(S.adadelta.gbiases{l});\n end\n end\n end\n\n if length(S.hook.per_epoch) > 1\n err = S.hook.per_epoch{1}(S, S.hook.per_epoch{2});\n\n if err == -1\n stopping = 1;\n end\n end\n\n if stopping == 1\n break;\n end\n\n if S.verbose == 1\n fprintf(2, '\\n');\n end\n\n fprintf(2, 'Epoch %d/%d - recon_error: %f\\n', step, n_epochs, ...\n S.signals.recon_errors(end));\nend\n\nif use_gpu > 0\n % pull\n for l = 1:n_layers\n if l < n_layers\n S.W{l} = gather(S.W{l});\n end\n S.biases{l} = gather(S.biases{l});\n end\n\n if S.adagrad.use\n for l = 1:n_layers\n if l < n_layers\n S.adagrad.W{l} = gather(S.adagrad.W{l});\n end\n S.adagrad.biases{l} = gather(S.adagrad.biases{l});\n end\n elseif S.adadelta.use\n for l = 1:n_layers\n if l < n_layers\n S.adadelta.W{l} = gather(S.adadelta.W{l});\n S.adadelta.gW{l} = gather(S.adadelta.gW{l});\n end\n S.adadelta.biases{l} = gather(S.adadelta.biases{l});\n S.adadelta.gbiases{l} = gather(S.adadelta.gbiases{l});\n end\n end\nend\n\n\n", "meta": {"author": "kyunghyuncho", "repo": "deepmat", "sha": "6fd133406b5d78e1b87e2f736e27cfb2024807af", "save_path": "github-repos/MATLAB/kyunghyuncho-deepmat", "path": "github-repos/MATLAB/kyunghyuncho-deepmat/deepmat-6fd133406b5d78e1b87e2f736e27cfb2024807af/sdae.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1777370474255802}} {"text": "function colors2 = cluster_orthviews_classes(cl,classes,overlay,myview,domontage, varargin)\n% :Usage:\n% ::\n%\n% colors2 = cluster_orthviews_classes(cl,classes,overlay,myview,domontage, [orthview axis], [colors cell])\n%\n% Makes montage and cluster orthviews of classes of clusters in different\n% colors (hard coded colors right now).\n%\n% :Inputs:\n%\n% **cl:**\n% clusters structure with regions\n%\n% **classes:**\n% integers with classes (i.e., networks) to be color-coded on plot\n%\n% **overlay:**\n% anatomical underlay image\n%\n% **myview:**\n% if entered, shows centers on plot\n%\n% **domontage:**\n% if non-zero, make montages of networks\n%\n% **[orthview axis]:**\n% Optional; integer for which orthviews axis to use, 1:kk\n%\n% :Output:\n%\n% Cell of colors, in order, for use in other functions\n%\n% :Examples:\n% ::\n%\n% classes = c.ClusterSolution.classes;\n% overlay = EXPT.overlay;\n% cluster_orthviews_classes(cl,c.ClusterSolution.classes, EXPT.overlay, 'saggital', 0);\n% cluster_orthviews_classes(cl,c.ClusterSolution.classes, EXPT.overlay, 'axial', 0);\n% cluster_orthviews_classes(cl,c.ClusterSolution.classes, EXPT.overlay, 'coronal', 0);\n% cluster_orthviews_classes(cl,c.ClusterSolution.classes, EXPT.overlay, [], 0);\n%\n% ..\n% tor wager\n% Colors update, minor improvements, Jan 2010\n% ..\n\nwhichorth = 1;\nif ~isempty(varargin), whichorth = varargin{1}; end\n\nif length(varargin) > 1\n colors2 = varargin{2};\n disp('Using input colors: '); %colors2{:}\nelse\n % text colors no longer needed -- can handle string colors\n %colors = {'yo' 'bo' 'go' 'ro' 'co' 'mo' 'ko' 'r^' 'g^' 'b^' 'y^' 'c^' 'm^' 'k^'};\n disp('Using default colors. ');\n colors2 = {[1 1 0] [0 0 1] [0 1 0] [1 0 0] [1 .5 0] [0 1 1] [1 0 1] [.5 1 0] [0 .5 1] [0 1 .5] [1 0 .5]};\nend\n\nwhile length(colors2) < max(classes)\n colors2tmp = colors2;\n for jj = 1:length(colors2tmp)\n colors2tmp{jj}(colors2tmp{jj} > .8) = colors2tmp{jj}(colors2tmp{jj} > .8) - .2;\n colors2tmp{jj}(colors2tmp{jj} < .2) = colors2tmp{jj}(colors2tmp{jj} < .2) + .2;\n end\n colors2 = [colors2 colors2tmp];\nend\ncolors2 = colors2(1:max(classes));\n\n% orthviews\ncluster_orthviews(cl(classes==1),colors2(1),'overlay',overlay,'solid');\n\nfor i = 2:max(classes)\n cluster_orthviews(cl(classes==i),colors2(i),'add','solid', 'handle', whichorth);\nend\n\nif ~isempty(myview) && ischar(myview)\n cluster_orthviews_showcenters(cl,myview,overlay,0);\nend\n\nif domontage\n\n% montage: build function call\nstr = ['montage_clusters(overlay,'];\nfor i = 1:max(classes)\n clc{i} = cl(classes==i);\n str = [str 'clc{' num2str(i) '},'];\nend\nstr = [str '{'];\nfor i = 1:max(classes)\n %str = [str '''' colors2{i} '''']; % no longer need solid colors\n str = [str '[' num2str(colors2{i}) '] '];\n %if i ~= max(classes), str = [str ' ']; end\nend\nstr = [str '}, ''nooverlap'');'];\neval(str)\nend\n\nreturn\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/cluster_orthviews_classes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1774593916638945}} {"text": "function [ sicd_meta_current ] = sicd_update_meta_0_5( sicd_meta_0_5 )\n%SICD_UPDATE_META_0_5 Update a SICD metadata structure from version 0.5 to\n%current version (whatever that may be)\n%\n% Author: Wade Schwartzkopf, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\nsicd_meta_1_0 = sicd_meta_0_5;\n\n% Add RadarCollection.TxPolarization, now required, but optional prior to version 1.0\nif isfield(sicd_meta_0_5, 'RadarCollection') && ...\n ~isfield(sicd_meta_0_5.RadarCollection, 'TxPolarization') && ...\n isfield(sicd_meta_0_5.RadarCollection, 'RcvChannels') && ...\n isfield(sicd_meta_0_5.RadarCollection.RcvChannels, 'ChanParameters')\n if numel(sicd_meta_0_5.RadarCollection.RcvChannels.ChanParameters)==1\n sicd_meta_1_0.RadarCollection.TxPolarization = sicd_meta_0_5.RadarCollection.RcvChannels.ChanParameters.TxRcvPolarization(1);\n else\n sicd_meta_1_0.RadarCollection.TxPolarization = 'SEQUENCE';\n tx_pols = {sicd_meta_0_5.RadarCollection.RcvChannels.ChanParameters.TxRcvPolarization};\n tx_pols = unique(cellfun(@(x) x(1), tx_pols));\n for i = 1:numel(tx_pols)\n sicd_meta_1_0.RadarCollection.TxSequence.TxStep(i).TxPolarization = tx_pols(i);\n end\n % Note: If there are multiple waveforms and multiple polarizations,\n % there is no deconfliction done here.\n end\nend\n\n% RadarCollection.Area.Corner was optional in version 0.5, but required in\n% version 1.0. Fortunately, Corner is easily derived from Plane.\nif isfield(sicd_meta_0_5, 'RadarCollection') && ...\n isfield(sicd_meta_0_5.RadarCollection, 'Area') && ...\n ~isfield(sicd_meta_0_5.RadarCollection.Area, 'Corner') && ...\n isfield(sicd_meta_0_5.RadarCollection.Area, 'Plane')\n try % If Plane substructure is misformed, this may fail\n plane = sicd_meta_0_5.RadarCollection.Area.Plane; % For concise notation\n ref_pt = [plane.RefPt.ECF.X plane.RefPt.ECF.Y plane.RefPt.ECF.Z];\n x_uvect = [plane.XDir.UVectECF.X plane.XDir.UVectECF.Y plane.XDir.UVectECF.Z];\n y_uvect = [plane.YDir.UVectECF.X plane.YDir.UVectECF.Y plane.YDir.UVectECF.Z];\n x_offsets = [plane.XDir.FirstLine plane.XDir.FirstLine ...\n plane.XDir.NumLines plane.XDir.NumLines];\n y_offsets = [plane.YDir.FirstSample plane.YDir.NumSamples ...\n plane.YDir.NumSamples plane.YDir.FirstSample];\n for i = 1:4\n acp = ref_pt + x_uvect * plane.XDir.LineSpacing * double(x_offsets(i) - plane.RefPt.Line) + ...\n y_uvect * plane.YDir.SampleSpacing * double(y_offsets(i) - plane.RefPt.Sample);\n sicd_meta_1_0.RadarCollection.Area.Corner.ACP(i) = ...\n cell2struct(num2cell(ecf_to_geodetic(acp)),{'Lat','Lon','HAE'});\n end\n end\nend\n\n% PolarizationHVAnglePoly no longer a valid field in version 1.0.\nif isfield(sicd_meta_0_5, 'RadarCollection') && ...\n isfield(sicd_meta_0_5.RadarCollection, 'PolarizationHVAnglePoly')\n sicd_meta_1_0.RadarCollection = rmfield(sicd_meta_1_0.RadarCollection, 'PolarizationHVAnglePoly');\nend\n\n% Antenna.Tx/Rcv/TwoWay.HPBW no longer a valid field in version 1.0.\nif isfield(sicd_meta_0_5, 'Antenna')\n if isfield(sicd_meta_0_5.Antenna, 'Tx') && ...\n isfield(sicd_meta_0_5.Antenna.Tx, 'HPBW')\n sicd_meta_1_0.Antenna.Tx = rmfield(sicd_meta_0_5.Antenna.Tx, 'HPBW');\n end\n if isfield(sicd_meta_0_5.Antenna, 'Rcv') && ...\n isfield(sicd_meta_0_5.Antenna.Rcv, 'HPBW')\n sicd_meta_1_0.Antenna.Rcv = rmfield(sicd_meta_0_5.Antenna.Rcv, 'HPBW');\n end\n if isfield(sicd_meta_0_5.Antenna, 'TwoWay') && ...\n isfield(sicd_meta_0_5.Antenna.TwoWay, 'HPBW')\n sicd_meta_1_0.Antenna.TwoWay = rmfield(sicd_meta_0_5.Antenna.TwoWay, 'HPBW');\n end\nend\n\n% NoiseLevel got its own substructure between SICD 0.5 and SICD 1.0\nif isfield(sicd_meta_0_5, 'Radiometric') && ...\n isfield(sicd_meta_0_5.Radiometric, 'NoisePoly')\n sicd_meta_1_0.Radiometric.NoiseLevel.NoisePoly = ...\n sicd_meta_0_5.Radiometric.NoisePoly;\n sicd_meta_1_0.Radiometric = rmfield(sicd_meta_1_0.Radiometric, 'NoisePoly');\n if isfield(sicd_meta_0_5.Radiometric, 'NoiseLevelType')\n sicd_meta_1_0.Radiometric.NoiseLevel.NoiseLevelType = ...\n sicd_meta_0_5.Radiometric.NoiseLevelType;\n else\n % Even if NoiseLevelType wasn't given, we know that relative noise\n % levels should be 1 at SCP.\n if abs(sicd_meta_0_5.Radiometric.NoisePoly(1)-1)0 doses are normalized to norm (100%)\n% VOI is an OPTIONAL cell array which contain the patients VOIs as read by dicomrt_loadVOI\n% voi2plot is an OPTIONAL vector pointing to the number of VOIs to be displayed\n%\n% Example:\n%\n% dicomrt_isosurface(A,xmesh,ymesh,zmesh,[100 90],60,A_voi,[1 2 3])\n%\n% overlay 2 isosurfaces for matrix A at the 100% and 90% levels. Dose is normalised to 60Gy (100%).\n% The figure also shows VOIs # 1 2 and 3.\n%\n% See also dicomrt_loaddose, dicomrt_loadmcdose, dicomrt_contourslice, dicomrt_dosediff\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument and set-up some parameters and variables\nerror(nargchk(6,8,nargin))\n\n% Check case and set-up some parameters and variables\n[dose_temp,type_dose,doselabel,PatientPosition]=dicomrt_checkinput(inputdose);\ndose=dicomrt_varfilter(dose_temp);\n\n% Check normalization\nif norm>0\n dose=dose./norm.*100;\nend\n\n% Initialize plot parameters: \ncolor = char('r','g','b','c','m','y','k','w');\nline = char('-','--',':','-.');\nmarker = char('+','o','*','x','s','d','^');\nwidth = [0.5,1.0,1.5,2.0,2.5,3.0];\nalphal=[0.1:0.1:1.0];\n\n% Set isolevels display\n[contourcolor,doseareas,transl]=dicomrt_setisolevels(norm,dose_temp);\n\n% Fetching legend information\nlegend_matrix=char(num2str(levels'));\n\n% Rendering 3D dose \nhandle=figure;\nset(handle,'Name',['dicomrt_isosurface: ',inputname(1)]);\ngrid on;\nhold\n\nif exist('VOI')~=1 % No VOI is defined\n if length(levels)==1\n [n,p] = histc(levels,doseareas);\n handle = patch(isosurface(dose_xmesh,dose_ymesh,dose_zmesh,dose,levels));\n isonormals(dose_xmesh,dose_ymesh,dose_zmesh,dose,handle);\n set(handle,'FaceColor',contourcolor(p),'EdgeColor','None','FaceAlpha',0.5);\n view(30,30); \n legend(handle,[int2str(levels)]);\n xlabel('X axis (cm)','Fontsize',12)\n ylabel('Y axis (cm)','Fontsize',12)\n zlabel('Z axis (cm)','Fontsize',12)\n elseif length(levels)~=1\n for i=1:length(levels)\n [n,p] = histc(levels(i),doseareas);\n if p==0\n p=1;\n end\n handle = patch(isosurface(dose_xmesh,dose_ymesh,dose_zmesh,dose,levels(i)));\n isonormals(dose_xmesh,dose_ymesh,dose_zmesh,dose,handle);\n set(handle,'FaceColor',contourcolor(p),'EdgeColor','None','FaceAlpha',transl(p));\n end\n legend(legend_matrix); \n view(30,30);\n xlabel('X axis (cm)','Fontsize',12)\n ylabel('Y axis (cm)','Fontsize',12)\n zlabel('Z axis (cm)','Fontsize',12)\n end\n title(['Isosurface plot for: ',inputname(1)],'interpreter','none','FontSize',16);\nelseif exist('VOI')==1 & exist('voi2plot')==1 % VOI was defined\n % Set VOI display parameters\n colorselect =7;\n lineselect =1;\n linewidth =1;\n if length(levels)==1\n [n,p] = histc(levels,doseareas); \n if p==0\n p=1;\n end\n handle = patch(isosurface(dose_xmesh,dose_ymesh,dose_zmesh,dose,levels));\n isonormals(dose_xmesh,dose_ymesh,dose_zmesh,dose,handle);\n set(handle,'FaceColor',contourcolor(p),'EdgeColor','None','FaceAlpha',0.5);\n view(30,30); \n legend(handle,[int2str(levels)]);\n xlabel('X axis (cm)','Fontsize',12)\n ylabel('Y axis (cm)','Fontsize',12)\n zlabel('Z axis (cm)','Fontsize',12)\n elseif length(levels)~=1\n for i=1:length(levels)\n [n,p] = histc(levels(i),doseareas);\n if p==0\n p=1;\n end\n handle = patch(isosurface(dose_xmesh,dose_ymesh,dose_zmesh,dose,levels(i)));\n isonormals(dose_xmesh,dose_ymesh,dose_zmesh,dose,handle);\n set(handle,'FaceColor',contourcolor(p),'EdgeColor','None','FaceAlpha',transl(p));\n end\n legend(legend_matrix);\n view(30,30);\n xlabel('X axis (cm)','Fontsize',12)\n ylabel('Y axis (cm)','Fontsize',12)\n zlabel('Z axis (cm)','Fontsize',12)\n end\n title(['Isosurface plot: ',inputname(1)],'interpreter','none','FontSize',16);\n % Plot VOIs\n dicomrt_rendervoi(VOI,voi2plot,1,1,1);\nelse\n error('dicomrt_isosurface: VOI or voi2plot is missing. Exit now !');\nend\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/dicomrt-toolbox-v2/display/dicomrt_isosurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.17742093378693527}} {"text": "function [] = aps_modis(start_step,end_step)\n% [] = aps_modis(start_step,end_step)\n% Computes the MODIS delays based on the OSCAR service provied by JPL \n%\n% Copyright (C) 2015 Bekaert David - University of Leeds\n% Email: eedpsb@leeds.ac.uk or davidbekaert.com\n% \n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License along\n% with this program; if not, write to the Free Software Foundation, Inc.,\n% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n%\n% By David Bekaert - University of Leeds\n% May 2014\n%\n% Modifications:\n% DB\t05/2014 \tStart from the MERIS scrip the program the function\n% DB 07/2014 Have re-visualization of sounding data when already\n% processed\n% DB 08/2014 Include SAR varying conversion factors\n% DB 08/2014 Include option to use MODIS recalibrated data\n% DB 09/2014 Check if conversion factors are known before\n% DB 04/2015 Fix in case filename grd is not starting with OSCAR_Modis*grd\n% DB 02/2016 Include aps_systemcall and suppress filename output.\n\n\n\n%% loading the StaMPS variables\ncurdir = pwd;\n\nif start_step==0\n % get the data from the OSCAR webite (JPL) \n aps_modis_Python\nend\n\nif start_step==1 \n % Compute the MERIS conversion factors from the sounding data\n fprintf('\\n\\nStep 1: Compute the spectrometer conversion factors from the sounding data \\n')\n\n \n % getting parameters from parms_aps file\n sounding_dir = getparm_aps('sounding_dir',1);\n start_date = getparm_aps('sounding_start_date',1);\n end_date = getparm_aps('sounding_end_date',1); \n time_stamp = getparm_aps('sounding_time_stamp',1);\n sounding_ifg_dates = getparm_aps('sounding_ifg_dates',1);\n start_year_str = start_date(1:4);\n end_year_str = end_date(1:4);\n start_str = start_date(5:6);\n end_str = end_date(5:6);\n time_stamp_str = [];\n for k=1:size(time_stamp,1)\n if k>1\n time_stamp_str = [time_stamp_str '_' time_stamp(k,:)];\n else\n time_stamp_str = [time_stamp(k,:)];\n end\n end\n \n % see if the filename already exist\n if strcmp(sounding_ifg_dates,'y')\n savename = [sounding_dir filesep 'Spectrometer' filesep 'Spectrometer_sensitivity_SAR_dates_1month_' time_stamp_str 'Hr_' num2str(start_year_str) start_str '_' num2str(end_year_str) end_str '.mat'];\n else\n savename = [sounding_dir filesep 'Spectrometer' filesep 'Spectrometer_sensitivity_' time_stamp_str 'Hr_' num2str(start_year_str) start_str '_' num2str(end_year_str) end_str '.mat'];\n end\n \n if exist(savename,'file')==2\n % check if user wants to visualize or re-run the data\n str = '';\n while strcmpi(str,'y')~=1 && strcmpi(str,'n')~=1\n str = input(['This file already exist, do you want to re-process the data? [y/n] \\n'],'s');\n end\n\n if strcmpi(str,'y')\n rerun_flag =1;\n else\n sounding_spectrometer_sens_display\n rerun_flag =0;\n end \n else\n rerun_flag =1;\n end\n \n if rerun_flag ==1;\n sounding_spectrometer_sens;\n end\nend\n\nif start_step<=2 && end_step >=2\n % SAR delays using MODIS data\n fprintf('\\n\\nStep 2: Compute MODIS tropospheric delay for individual dates\\n')\n \n % generating a file list of the files to be processed:\n modis_datapath = getparm_aps('modis_datapath',1);\n command_str = 'echo files > modis_batch_file.txt';\n command_str2 = ['ls -d ' modis_datapath filesep '2*' filesep '*.grd >> modis_batch_file.txt'];\n\n \n aps_systemcall(command_str);\n aps_systemcall(command_str2);\n \n % running the MODIS computation on the file list\n aps_modis_SAR('modis_batch_file.txt')\nend\nif start_step<=3 && end_step >=3\n fprintf('\\n\\nStep 3: Computes MODIS tropospheric delay for interferograms\\n')\n aps_modis_InSAR\nend\n\n\ncd(curdir)\n\n\n\n", "meta": {"author": "dbekaert", "repo": "TRAIN", "sha": "6c93feb95ae95eaf4c8468e89ec0b8325eac946f", "save_path": "github-repos/MATLAB/dbekaert-TRAIN", "path": "github-repos/MATLAB/dbekaert-TRAIN/TRAIN-6c93feb95ae95eaf4c8468e89ec0b8325eac946f/matlab/aps_modis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17722765278866937}} {"text": "function [img, scale, im_scaled_size] = prepare_img_blob(img, scale, mean_pix, max_size)\n% \n% This file is part of the code that implements the following paper:\n% Title : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% Authors : Spyros Gidaris, Nikos Komodakis\n% Institution: Universite Paris Est, Ecole des Ponts ParisTech\n% ArXiv link : http://arxiv.org/abs/1511.07763\n% code : https://github.com/gidariss/LocNet\n%\n% Part of the code in this file comes from the Faster R-CNN code and the matlab\n% re-implementation of Fast-RCNN (https://github.com/ShaoqingRen/faster_rcnn)\n% \n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2016 Spyros Gidaris\n% \n% Title : \"LocNet: Improving Localization Accuracy for Object Detection\"\n% ArXiv link: http://arxiv.org/abs/1511.07763\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n\nif numel(mean_pix) == 1, mean_pix = [mean_pix, mean_pix, mean_pix]; end\nassert(numel(mean_pix)==3);\n\nim_height = size(img, 1);\nim_width = size(img, 2);\n% get the image size of the scaled image\nim_scaled_size = prepare_img_blob_size([im_height, im_width], scale, max_size);\nscale = min(im_scaled_size);\n\n% scale image\nif (scale <= 224)\n img = imresize(img, [im_scaled_size(1), im_scaled_size(2)], 'bilinear');\nelse\n img = imresize(img, [im_scaled_size(1), im_scaled_size(2)], 'bilinear', 'antialiasing', false);\nend\n\nimg = single(img); % transform to single precision \nimg = img(:,:,[3 2 1]); % transform from RGB -> BGR (necessary for Caffe)\n% subtruct the mean pixel from the image\nimg = bsxfun(@minus, img, reshape(mean_pix, [1, 1, 3]));\nimg = permute(img, [2 1 3]); % permute from [Height x Width x 3] to [Width x Height x 3] (necessary for Caffe)\nend", "meta": {"author": "gidariss", "repo": "LocNet", "sha": "a4678b87d9e63dcea07d9afd978d1223174d8be3", "save_path": "github-repos/MATLAB/gidariss-LocNet", "path": "github-repos/MATLAB/gidariss-LocNet/LocNet-a4678b87d9e63dcea07d9afd978d1223174d8be3/code/generic/prepare_img_blob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.17722764091258653}} {"text": "function loser = updategrid(x, minHoleTime, minHoleSize, maxHoleTime, maxHoleSize)\nglobal F\nglobal alive\nglobal snakeSize\nglobal holeCountDown\nglobal lastPos\n\n\nres = size(F);\nloser = 0;\nfor i = alive\n pixels = getpixels(x(i,:), snakeSize);\n index1 = size(F,1) * lastPos(:,i*2) + lastPos(:,i*2-1); \n index2 = size(F,1) * pixels(:,2) + pixels(:,1); \n F(index1) = 0;\n \n if any(pixels(:) < 1) || any(pixels(:,1) >= res(1)) || any(pixels(:,2) >= res(2))\n loser = i;\n alive(alive == i) = [];\n F(index1) = i;\n return\n end\n if sum(full(F(index2))) > 1\n alive(alive == i) = [];\n F(index1) = i;\n return\n end\n \n F(index2) = i;\n if holeCountDown(i,1) ~= 0\n F(index1) = i;\n else\n F(index1) = 0;\n holeCountDown(i,1) = 1;\n holeCountDown(i,2) = holeCountDown(i,2) - 1;\n end\n if holeCountDown(i,2) == 0\n F(index2) = i;\n holeCountDown(i,1) = round(rand() * (maxHoleTime - minHoleTime)) + minHoleTime;\n holeCountDown(i,2) = round(rand() * (maxHoleSize - minHoleSize)) + minHoleSize;\n end\n lastPos(:,i*2-1:i*2) = pixels;\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/33762-zatackaachtung-die-kurve-for-matlab/updategrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.1766465676791043}} {"text": "%RNA production medium test\n%\n% Author: Jared Jacobs, jmjacobs@stanford.edu\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 9/10/2010\nclassdef RNA_Test < TestCase\n properties\n simulation\n end\n \n methods\n function this = RNA_Test(name)\n this = this@TestCase(name);\n end\n \n function setUp(this)\n sim = edu.stanford.covert.cell.sim.SimulationFixture.load([], {\n 'Metabolism'\n 'Transcription'\n 'RNAProcessing'\n 'RNAModification'\n 'tRNAAminoacylation'\n 'RNADecay'\n });\n \n this.simulation = sim;\n end\n \n function testRnaProduction(this)\n import edu.stanford.covert.util.ConstantUtil;\n \n %% references\n sim = this.simulation;\n %this.seedSimulation(sim, 10);\n %sim.applyOptions('verbosity', 1);\n \n g = sim.gene;\n mass = sim.state('Mass');\n m = sim.state('Metabolite');\n rna = sim.state('Rna');\n time = sim.state('Time');\n pm = sim.state('ProteinMonomer');\n pc = sim.state('ProteinComplex');\n transcription = sim.process('Transcription');\n \n %% constants\n rnaMWs = rna.molecularWeights(rna.aminoacylatedIndexs);\n \n %% turn off decay\n rna.decayRates(setdiff(1:end, rna.intergenicIndexs)) = 0;\n \n %% keep track of initial state\n initRNAs = ...\n + rna.counts(rna.matureIndexs, sim.compartment.cytosolIndexs) ...\n + rna.counts(rna.aminoacylatedIndexs, sim.compartment.cytosolIndexs);\n initRNAs(setdiff(1:end, rna.matureMRNAIndexs)) = ...\n initRNAs(setdiff(1:end, rna.matureMRNAIndexs)) + ...\n sum(pc.proteinComplexComposition(setdiff(1:end, g.mRNAIndexs), :, :), 3) * sum(pc.counts(pc.matureIndexs, :) + pc.counts(pc.boundIndexs, :), 2);\n \n initMonomers = ...\n + pm.counts(pm.matureIndexs, :) ...\n + pm.counts(pm.boundIndexs, :);\n initComplexs = ...\n + pc.counts(pc.matureIndexs, :) ...\n + pc.counts(pc.boundIndexs, :);\n \n %% simulate\n iterMax = 1000;\n \n ntps = zeros(4, iterMax);\n if sim.verbosity > 0\n fprintf('%5s %6s %6s %6s %6s\\n', 'Iter ', ' ATP ', ' CTP ', ' GTP ', ' UTP ');\n fprintf('%5s %6s %6s %6s %6s\\n', '=====', '======', '======', '======', '======');\n end\n for i = 1:iterMax\n if sim.verbosity > 0 && mod(i, 100) == 1\n fprintf('%5d %6d %6d %6d %6d\\n', i, ...\n transcription.substrates(transcription.substrateIndexs_ntp(1)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(2)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(3)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(4)));\n end\n \n %mock protein synthesis\n pm.counts(pm.matureIndexs, :) = ...\n + pm.counts(pm.matureIndexs, :) ...\n + pm.randStream.stochasticRound(initMonomers * log(2) / time.cellCycleLength * exp(i * log(2) / time.cellCycleLength));\n pc.counts(pc.matureIndexs, :) = ...\n + pc.counts(pc.matureIndexs, :) ....\n + pc.randStream.stochasticRound(initComplexs * log(2) / time.cellCycleLength * exp(i * log(2) / time.cellCycleLength));\n \n %simulate \n sim.evolveState();\n \n ntps(:, i) = transcription.substrates(transcription.substrateIndexs_ntp);\n end\n \n newRNAs = ...\n - initRNAs ...\n + rna.counts(rna.matureIndexs, sim.compartment.cytosolIndexs) ...\n + rna.counts(rna.aminoacylatedIndexs, sim.compartment.cytosolIndexs);\n newRNAs(setdiff(1:end, rna.matureMRNAIndexs)) = ...\n newRNAs(setdiff(1:end, rna.matureMRNAIndexs)) + ...\n sum(pc.proteinComplexComposition(setdiff(1:end, g.mRNAIndexs), :, :), 3) * sum(initComplexs, 2);\n \n %% assertions\n \n %NTPs are limiting\n assertIn(min(min(ntps(:, end-100+1:end))), [0 max(2000, min(ntps(:, 1)))]);\n \n %NTPs are mostly used -- not too many are free\n assertIn(...\n (m.counts(m.ntpIndexs([2 4]), sim.compartment.cytosolIndexs)' * m.molecularWeights(m.ntpIndexs([2 4]))) / ...\n (rna.counts(:, sim.compartment.cytosolIndexs)' * rna.molecularWeights), ...\n [0 0.03]);\n \n %mature/aminoacylated RNA counts increased\n assertAllEqual(true, newRNAs >= 0);\n assertElementsAlmostEqual(newRNAs' * rnaMWs / ConstantUtil.nAvogadro, ...\n (exp(iterMax * log(2) / time.cellCycleLength) - 1) * ...\n mass.initialFractionNTPsInRNAs * mass.cellInitialDryWeight * mass.dryWeightFractionRNA, ...\n 'relative', 2.5e-1, 0);\n \n assertIn(sum(sum(rna.counts(rna.nascentIndexs, :))), [0 20]);\n assertIn(sum(sum(rna.counts(rna.processedIndexs, :))), [0 40]);\n assertIn(sum(sum(rna.counts(rna.intergenicIndexs, :))), [0 10]);\n assertAllEqual(0, rna.counts(rna.boundIndexs, :));\n assertAllEqual(0, rna.counts(rna.damagedIndexs, :));\n assertAllEqual(0, rna.counts(rna.misfoldedIndexs, :));\n \n %RNA production matches expectations\n rates = rna.nascentRNAMatureRNAComposition * transcription.computeRNAPolymeraseTUBindingProbabilities();\n rates = rates(:, 1);\n assertIn(corr(rates, newRNAs), [0.50 1]);\n assertIn(180 / pi * acos(rates' * newRNAs / ...\n (sqrt(rates' * rates) * sqrt(newRNAs' * newRNAs))), ...\n [0 60]);\n end\n \n function testRnaProductionAndDecay(this)\n import edu.stanford.covert.util.ConstantUtil;\n \n %% references\n sim = this.simulation;\n %sim.applyOptions('verbosity', 1);\n this.seedSimulation(sim, 1000);\n \n g = sim.gene;\n comp = sim.compartment;\n mass = sim.state('Mass');\n m = sim.state('Metabolite');\n rna = sim.state('Rna');\n time = sim.state('Time');\n pm = sim.state('ProteinMonomer');\n pc = sim.state('ProteinComplex');\n rnaPol = sim.state('RNAPolymerase');\n transcript = sim.state('Transcript');\n transcription = sim.process('Transcription');\n \n %% keep track of initial state\n initRNAs = ...\n + rna.counts(rna.matureIndexs, comp.cytosolIndexs) ...\n + rna.counts(rna.aminoacylatedIndexs, comp.cytosolIndexs);\n initRNAs(setdiff(1:end, rna.matureMRNAIndexs)) = ...\n initRNAs(setdiff(1:end, rna.matureMRNAIndexs)) + ...\n sum(pc.proteinComplexComposition(setdiff(1:end, g.mRNAIndexs), :, :), 3) * ...\n sum(pc.counts(pc.matureIndexs, :) + pc.counts(pc.boundIndexs, :), 2);\n initMonomers = ...\n + pm.counts(pm.matureIndexs, :) ...\n + pm.counts(pm.boundIndexs, :);\n initComplexs = ...\n + pc.counts(pc.matureIndexs, :) ...\n + pc.counts(pc.boundIndexs, :);\n \n %% simulate\n iterMax = 30000;\n \n rnaExp = zeros(size(initRNAs));\n rnaProd = zeros(size(rna.nascentIndexs));\n oldNascentRNAs = transcription.RNAs;\n rnaPolStateOcc = zeros(4, iterMax);\n ntps = zeros(4, iterMax);\n ndps = zeros(4, iterMax);\n nmps = zeros(4, iterMax);\n phosphates = zeros(3, iterMax);\n boundTUs = zeros(numel(rna.nascentIndexs), iterMax);\n rnaDryWt = zeros(1, iterMax);\n transcriptDryWt = zeros(1, iterMax);\n nucDryWt = zeros(1, iterMax);\n if sim.verbosity > 0\n fprintf('%5s %6s %6s %6s %6s\\n', 'Iter ', ' ATP ', ' CTP ', ' GTP ', ' UTP ');\n fprintf('%5s %6s %6s %6s %6s\\n', '=====', '======', '======', '======', '======');\n end\n for i = 1:iterMax\n if sim.verbosity > 0 && mod(i, 100) == 1\n fprintf('%5d %6d %6d %6d %6d\\n', i, ...\n transcription.substrates(transcription.substrateIndexs_ntp(1)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(2)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(3)), ...\n transcription.substrates(transcription.substrateIndexs_ntp(4)));\n end\n \n %mock protein synthesis\n pm.counts(pm.matureIndexs, :) = ...\n + pm.counts(pm.matureIndexs, :) ...\n + pm.randStream.stochasticRound(initMonomers * log(2) / time.cellCycleLength * exp(i * log(2) / time.cellCycleLength));\n pc.counts(pc.matureIndexs, :) = ...\n + pc.counts(pc.matureIndexs, :) + ...\n + pc.randStream.stochasticRound(initComplexs * log(2) / time.cellCycleLength * exp(i * log(2) / time.cellCycleLength));\n \n %simulate\n sim.evolveState();\n \n %store data\n rnaExp = rnaExp ...\n + rna.counts(rna.matureIndexs, comp.cytosolIndexs) ...\n + rna.counts(rna.aminoacylatedIndexs, comp.cytosolIndexs);\n rnaExp(setdiff(1:end, rna.matureMRNAIndexs)) = ...\n rnaExp(setdiff(1:end, rna.matureMRNAIndexs)) + ...\n sum(pc.proteinComplexComposition(setdiff(1:end, g.mRNAIndexs), :, :), 3) * sum(initComplexs, 2);\n rnaProd = rnaProd + max(0, transcription.RNAs - oldNascentRNAs);\n oldNascentRNAs = transcription.RNAs;\n rnaPolStateOcc(:, i) = [\n rnaPol.nActive\n rnaPol.nSpecificallyBound\n rnaPol.nNonSpecificallyBound\n rnaPol.nFree\n ];\n ntps(:, i) = transcription.substrates(transcription.substrateIndexs_ntp);\n ndps(:, i) = m.counts(m.ndpIndexs, comp.cytosolIndexs);\n nmps(:, i) = m.counts(m.nmpIndexs, comp.cytosolIndexs);\n phosphates(:, i) = m.counts([m.diphosphateIndexs; m.phosphateIndexs; m.hydrogenIndexs], comp.cytosolIndexs);\n boundTUs(:, i) = histc(transcript.boundTranscriptionUnits(rnaPol.states >= rnaPol.activelyTranscribingValue), (1:numel(rna.nascentIndexs))');\n \n rnaDryWt(:, i) = rna.dryWeight(1);\n transcriptDryWt(:, i) = transcript.dryWeight;\n nucDryWt(:, i) = (...\n + ntps(:, i)' * m.molecularWeights(m.ntpIndexs) ...\n + ndps(:, i)' * m.molecularWeights(m.ndpIndexs) ...\n + nmps(:, i)' * m.molecularWeights(m.nmpIndexs)) / ConstantUtil.nAvogadro;\n end\n \n %% assertions\n \n %NTPs are limiting\n assertIn(min(min(ntps(:, end-100+1:end))), [0 exp(log(2) * iterMax / time.cellCycleLength) * min(ntps(:, 1))]);\n assertIn(min(min(ndps(:, end-100+1:end))), [0 exp(log(2) * iterMax / time.cellCycleLength) * min(ndps(:, 1))]);\n assertIn(min(min(nmps(:, end-100+1:end))), [0 exp(log(2) * iterMax / time.cellCycleLength) * min(nmps(:, 1))]);\n assertIn(min(transcriptDryWt(:, end-100+1:end)), [0 2.5 * exp(log(2) * iterMax / time.cellCycleLength) * transcriptDryWt(1)]);\n \n %NTPs are mostly used -- not too many are free\n assertIn(...\n (m.counts(m.ntpIndexs([2 4]), comp.cytosolIndexs)' * m.molecularWeights(m.ntpIndexs([2 4]))) / ...\n ((rna.dryWeight(1) + transcript.dryWeight) * edu.stanford.covert.util.ConstantUtil.nAvogadro), ...\n [0 0.05]);\n \n rnas = ...\n + rna.counts(rna.matureIndexs, comp.cytosolIndexs) ...\n + rna.counts(rna.aminoacylatedIndexs, comp.cytosolIndexs);\n rnas(setdiff(1:end, rna.matureMRNAIndexs)) = ...\n rnas(setdiff(1:end, rna.matureMRNAIndexs)) + ...\n sum(pc.proteinComplexComposition(setdiff(1:end, g.mRNAIndexs), :, :), 3) * sum(initComplexs, 2);\n assertElementsAlmostEqual(rnas' * rna.molecularWeights(rna.aminoacylatedIndexs) / edu.stanford.covert.util.ConstantUtil.nAvogadro, ...\n exp(iterMax * log(2) / time.cellCycleLength) * mass.cellInitialDryWeight * mass.dryWeightFractionRNA, ...\n 'relative', 2e-1, 0);\n \n %total NTP incorporation similar to production by metabolism\n assertElementsAlmostEqual(...\n (edu.stanford.covert.util.ComputationUtil.invertCompositionMatrix(rna.nascentRNAMatureRNAComposition) * ...\n (mass.cellInitialDryWeight * mass.dryWeightFractionRNA * edu.stanford.covert.util.ConstantUtil.nAvogadro / ...\n (rna.expression(rna.matureIndexs)' * rna.molecularWeights(rna.matureIndexs)) * rna.expression(rna.matureIndexs) .* ...\n (log(2) / time.cellCycleLength + rna.decayRates(rna.matureIndexs))))' * rna.lengths(rna.nascentIndexs) * ...\n time.cellCycleLength / log(2) * (exp(log(2) / time.cellCycleLength * iterMax)-1), ...\n rnaProd' * rna.lengths(rna.nascentIndexs), ...\n 'relative', 0.40);\n \n %RNA expression matches expectations\n assertIn(corr(rna.expression(rna.matureIndexs), rnaExp), [0.9 1]);\n assertIn(180 / pi * acos(rna.expression(rna.matureIndexs)' * rnaExp / ...\n (sqrt(rna.expression(rna.matureIndexs)' * rna.expression(rna.matureIndexs)) * sqrt(rnaExp' * rnaExp))), ...\n [0 20]);\n \n %RNA polymerase occupancy matches expectations\n assertElementsAlmostEqual(rnaPol.stateExpectations, ...\n sum(rnaPolStateOcc, 2) / sum(rnaPolStateOcc(:)), ...\n 'relative', 0.75, 0.20); %todo: tighten\n \n %RNAs matured\n assertIn(sum(sum(rna.counts(rna.nascentIndexs, :))), [0 20]);\n assertIn(sum(sum(rna.counts(rna.processedIndexs, :))), [0 30]);\n assertIn(sum(sum(rna.counts(rna.intergenicIndexs, :))), [0 10]);\n assertAllEqual(0, rna.counts(rna.boundIndexs, :));\n assertAllEqual(0, rna.counts(rna.damagedIndexs, :));\n assertAllEqual(0, rna.counts(rna.misfoldedIndexs, :));\n end\n \n function sim = seedSimulation(~, sim, seed)\n if sim.verbosity > 0\n fprintf('Seed: %d\\n', seed)\n end\n \n sim.applyOptions('seed', seed);\n sim.seedRandStream();\n \n for i = 1:numel(sim.states)\n o = sim.states{i};\n o.seed = seed;\n o.seedRandStream();\n end\n \n for i = 1:numel(sim.processes)\n o = sim.processes{i};\n o.seed = seed;\n o.seedRandStream();\n end\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src_test/+edu/+stanford/+covert/+cell/+sim/RNA_Test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17660771963230626}} {"text": "% fig2: anat averages from paired regressors: sensory/motor correlations\n% plots a pair of regressors in a graded double colormap, saves as tiff\n% stacks, and also saves anat average plot as tiff file.\n% (compare to fig2A_correlation_1reg_with_hist for more details)\n\nclear all; close all; clc\n\noutputDir = GetOutputDataDir;\n\n%% Init load\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\n%% set params\nthres_reg_const = 0.5;\n% M_reg_thres = {0.5,0.5,0.5};\n\nfor setflag = 7\n % reset\n ResetDisplayParams(hfig);\n \n switch setflag\n case 1 % Phototaxis\n% stimrange = 1;\nM_stimrange = GetStimRange('P');\n M_regtypeflag = [1,1,2]; % 0 for VAR, 1 for stim and 2 for motor\n M_reg_name = {'PT','HalfField','PT_SwimLR'};\n M_reg_range = {[3,2],[5,6],[1,3]};\n M_fishrange = {[1:18],[1:7],[1:3,5:18]};\n n_reg = length(M_reg_name);\n \n case 2 % OMR\n% stimrange = 2;\nM_stimrange = GetStimRange('O');\n M_regtypeflag = [1,1,2]; % 1 for stim and 0 for motor\n M_reg_name = {'OMR_FwBw','OMR_LR','OMR_SwimLR'};\n M_reg_range = {[7,6],[9,8],[1,3]};\n M_fishrange = {[8:18],[8:18],[8:18]};\n n_reg = length(M_reg_name);\n \n case 3 % Looming\n% stimrange = 5;\nM_stimrange = GetStimRange('L');\n M_regtypeflag = [1,2]; % 1 for stim and 0 for motor\n M_reg_name = {'Loom_LR','Loom_SwimLR'};\n M_reg_range = {[11,12],[1,3]};\n M_fishrange = {[9:15,17:18],[9:15,17:18]};\n n_reg = length(M_reg_name);\n \n case 4 % Dark Flash (black-white)\n% stimrange = 3;\nM_stimrange = GetStimRange('D');\n M_regtypeflag = [1,2]; % 1 for stim and 0 for motor\n M_reg_name = {'DF_BW','DF_SwimLR'};\n M_reg_range = {[1,4],[1,3]};\n M_fishrange = {[12:15,17:18],[12:15,17:18]};\n n_reg = length(M_reg_name);\n \n% % from VAR:\n\n case 5 % ABN\n M_regtypeflag = [0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'ABN_reg0.5_defstimrange_test'};\n M_clus_range = {[12,1]};\n M_fishrange = {[1:12,14:18]};\n n_reg = length(M_reg_name);\n case 6 % Fw\n M_regtypeflag = [0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'Fw_reg0.5_defS'}; \n M_clus_range = {[11,4]};\n M_fishrange = {[1:18]};\n n_reg = length(M_reg_name);\n \n case 7 % left HBO\n M_regtypeflag = [0,0];\n M_stimrange = GetStimRange();%('2');\n M_reg_name = {'HBO-L2_reg0.5_defS','HBO-R2_reg0.5_defS'}; \n M_clus_range = {[10,2],[10,3]};\n M_fishrange = {[1:3,5:18],[1:3,5:18]};\n n_reg = length(M_reg_name);\n end\n M_fishrange_im = M_fishrange;\n \n %% Load fish\n range = 1:18;\n IM_full = cell(n_reg,max(range));\n %%\n \n% [M_fishrange_im,fishrange_load] = CheckIfLoadFish(M_fishrange,M_ClusterIDs,M_stimrange);\n% [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,M_ClusterIDs{i_set},M_stimrange{i_set});\n for i_fish = range\n if ismember(i_fish,cell2mat(M_fishrange))\n ClusterIDs = [1,1];%GetClusterIDs('all');\n stimrange = M_stimrange{i_fish}; \n % load fish data\n if isempty(stimrange)\n [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs);\n else\n [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs,stimrange);\n end\n end\n \n %% Load stim/motor\n for i_set = 1:n_reg\n \n if ~ismember(i_fish,M_fishrange{i_set})\n continue;\n end\n \n reg_thres = thres_reg_const; %M_reg_thres{i_set};\n \n % get stim/motor regressors\n if M_regtypeflag(i_set)==0\n ClusterIDs = M_clus_range{i_set};%[12,1];% GetClusterIDs('all');\n [cIX,gIX] = LoadCluster_Direct(i_fish,ClusterIDs(1),ClusterIDs(2));\n M = UpdateIndices_Manual(hfig,cIX,gIX);\n Reg = FindClustermeans(gIX,M);\n \n elseif M_regtypeflag(i_set)==1\n fishset = getappdata(hfig,'fishset');\n [~,names,regressors] = GetStimRegressor(stim,fishset,i_fish);\n \n reg_range = M_reg_range{i_set}; % left/right pair\n Reg = regressors(reg_range,:);\n \n elseif M_regtypeflag(i_set)==2\n isMotorseed = 0;\n setappdata(hfig,'isMotorseed',isMotorseed);\n [~,~,behavior] = UpdateTimeIndex(hfig); \n [~,names,regressors] = GetMotorRegressor(behavior,i_fish); \n \n reg_range = M_reg_range{i_set}; % left/right pair\n Reg = regressors(reg_range,:);\n end\n \n % code adapted from 'best regressor regression' code 'AllRegsRegression'\n\n Corr = corr(Reg',M_0');\n [corr_max,IX_regtype] = max(Corr,[],1);\n cIX = find(corr_max>reg_thres)';\n gIX_offset = IX_regtype(cIX)';\n clrIX = MapXto1Dcolormap(corr_max(cIX),[reg_thres,1],64);\n \n if isempty(cIX)\n M_fishrange_im{i_set} = setdiff(M_fishrange_im{i_set} ,i_fish);\n continue;\n end\n \n gIX = clrIX+(gIX_offset-1)*64;\n numK = length(unique(gIX));\n \n %% make double colormap - ??\n clr1 = [1,0,0];\n clr1_ = [0.7,0.5,0.5];\n clr2 = [0,1,1];\n clr2_ = [0.5,0.7,0.7];\n numC = 64;\n clrmap1 = Make1DColormap([clr1_;clr1],numC);\n clrmap2 = Make1DColormap([clr2_;clr2],numC);\n clrmap = [clrmap1;clrmap2];\n \n %% make figure\n I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX,clrmap);\n [h,im_full] = DrawCellsOnAnat(I);\n \n % % add 2 colorbars\n % % AddColorbarToAnat(clrmap,cmin,cmax)\n % % colormap(clrmap1);\n % % caxis([reg_thres,1])\n % % colorbar('Location','manual','Position',[0.8,0.7,0.05,0.15],'Units','normalized')\n % ax = axes('Position',[0.75,0.8,0.05,0.15],'Units','normalized');\n % DrawCustomColorbar(clrmap1,[reg_thres,1],2,ax);\n %\n % ax = axes('Position',[0.9,0.8,0.05,0.15],'Units','normalized');\n % DrawCustomColorbar(clrmap2,[reg_thres,1],2,ax);\n %\n %% save figure\n close(h);\n IM_full{i_set,i_fish} = im_full;\n \n end\n end\n \n %% save as tiff stack\n for i_set = 1:n_reg\n range_im = M_fishrange_im{i_set};\n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_allfish.tiff']);\n IM = IM_full(i_set,range_im);\n \n SaveImToTiffStack(IM,tiffdir);\n end\n \n %% [for later] plot from tiff stack\n isPlotfromtiffstack = 0;\n \n if isPlotfromtiffstack\n IM_full = cell(n_reg,18);\n for i_set = 1:n_reg\n %% get tiff-stack path\n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_allfish.tiff']);\n \n %% load\n \n for i_fish = 1:18\n im = double(imread(tiffdir,i_fish))./255;\n IM_full{i_set,i_fish} = im(317:1236,1:621,:);\n end\n end\n end\n \n %% make average plots\n % M_k_scale = {1,1.5,1};\n % M_k_contrast = {1.2,1.5,1.2};\n \n for i_set = 1:n_reg;\n range_im = M_fishrange_im{i_set};%[1:3,5:7];%[1:3,5:18];\n cellarray = IM_full(i_set,range_im);\n \n % adjust params for visualization\n k_scale = 0.4;%1/1.5;%M_k_scale{i_set};\n k_contrast = 1;%M_k_contrast{i_set};\n \n [h_anat,im_avr] = AverageAnatPlot(cellarray,k_contrast,k_scale);\n \n tiffdir = fullfile(outputDir,[M_reg_name{i_set},'_avr.tiff']);\n imwrite(im_avr, tiffdir, 'compression','none','writemode','overwrite');\n end\n \nend\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/Regression/arc code/fig2D_Batch_correlation_2regs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.17659609062668594}} {"text": "function show_map(calc_type, in2, compare_window_dur) \n % ZMAP script show_map.m. Creates Dialog boxes for Z-map calculation\n % does the calculation and makes displays the map\n % stefan wiemer 11/94\n %\n % make dialog interface and call maxzlta\n %\n % turned into function by Celso G Reyes 2017\n \n %FIXME (maybe) changing compare_window_dur doesn't change the global version.\n \n % Input Rubberband\n %\n report_this_filefun();\n \n % compare_window_dur is shared among the parts of this function\n it=[]\n \n \n if in2 ~= 'calma'\n create_the_figure(calc_type)\n else\n do_calma(calc_type)\n end\n \n function create_the_figure(calc_type)\n %initial values\n ZG=ZmapGlobal.Data; % used by get_zmap_globals\n ZG.compare_window_dur_v3 = years(1.5);\n it = t0b +1;\n figure(mess);\n clf\n set(gca,'visible','off')\n set(gcf,'Units','pixel','NumberTitle','off','Name','Input Parameters');\n \n set(gcf,'pos',[ ZG.welcome_pos, ZG.welcome_len +[200, -50]]);\n \n \n % creates a dialog box to input some parameters\n %\n add_timecut_controls(it)\n \n if calc_type == \"rub\" || calc_type == \"lta\"\n add_compareduration_controls(compare_window_dur)\n end\n \n uicontrol('Style','Pushbutton',...\n 'Position', [.60 .05 .15 .15 ],...\n 'Units','normalized',...\n 'Callback',@(~,~)close(),...\n 'String','Cancel');\n \n uicontrol('Style','Pushbutton',...\n 'Position',[.25 .05 .15 .15 ],...\n 'Units','normalized',...\n 'callback',@cb_go,...\n 'String','Go');\n \n set(gcf,'visible','on');\n watchoff\n end\n \n function do_calma(calc_type)\n % check if time are with limits\n %\n if ~exist('it', 'var')\n it = t0b + (teb-t0b)/2;\n end\n if it + compare_window_dur > teb || it < t0b\n errordlg('Time out of limits')\n in2 = 'nocal';\n show_map\n end\n \n \n % initial parameter\n winlen_days = floor(compare_window_dur/ZG.bin_dur); \n ti = floor((it -t0b)/days(ZG.bin_dur));\n [len, ncu] = size(cumuall); \n len = len-2;\n var1 = zeros(1,ncu);\n var2 = zeros(1,ncu);\n mean1 = zeros(1,ncu);\n mean2 = zeros(1,ncu);\n as = zeros(1,ncu);\n \n \n % loop over all grid points for percent\n %\n %\n switch calc_type\n case 'per'\n [as, strib, stri2] = calc_percent_change(); \n case 'rub'\n [as, var1, var2] = calc_rubberband(ncu, ti, winlen_days);\n case 'ast'\n [as, var1, var2] = calc_ast(ncu, ti, len);\n case 'lta'\n [as, var1, var2] = calc_lta(ncu, ti, winlen_days, len, cumuall);\n case 'maz'\n [maxlta, maxlta2, mean1, mean2] = calc_maz(ncu, cumuall, len);\n otherwise\n error('ZMAP:show_map:unknownOperation','not sure which operation to do')\n end\n \n %normalisation of lap1\n normlap1=nan(length(tmpgri(:,1)),1)\n normlap2=nan(length(tmpgri(:,1)),1)\n \n lv = logical(ll) ; % having to do with the grid(?)\n normlap2(lv)= as(:);\n %construct a matrix for the color plot\n valueMap=reshape(normlap2,length(yvect),length(xvect));\n \n \n [n1, n2] = size(cumuall);\n s = cumuall(n1,:);\n normlap2(lv)= s(:);\n %construct a matrix for the color plot\n r = reshape(normlap2, length(yvect), length(xvect));\n ZG.tresh_km = max(r(:));\n % find max and min of data for automatic scaling\n %\n ZG.maxc = max(valueMap(:));\n ZG.maxc = fix(max(valueMap(:)))+1;\n ZG.minc = min(valueMap(:));\n ZG.minc = fix(min(valueMap(:)))-1;\n %plot imge\n %\n det = 'nop';\n old = valueMap;\n view_max(valueMap,gx,gy,stri,'nop')\n \n\n end\n \n function add_timecut_controls(default_value)\n uicontrol('Style','edit',... # was inp2_field\n 'Position',[.80 .775 .18 .15],...\n 'Units','normalized',...\n 'String',num2str(default_value),...\n 'callback',@cb_timecut_year);\n \n text(... #was txt2\n 'Position',[0. 0.9 0 ],...\n 'FontWeight','bold',...\n 'FontSize',ZmapGlobal.Data.fontsz.m ,...\n 'String','Please input time of cut in years (e.g. 86.5):');\n end\n \n function add_compareduration_controls(compare_window_dur)\n text(... # was txt3\n 'Position', [0. 0.65 0 ],...\n 'FontWeight', 'bold',...\n 'FontSize', ZmapGlobal.Data.fontsz.m ,...\n 'String', 'Please input window length in years (e.g. 1.5):');\n uicontrol('Style', 'edit',...\n 'Position', [.80 .575 .18 .15],...\n 'Units', 'normalized',...\n 'String', num2str(years(compare_window_dur)),...\n 'callback', @cb_window_duration_edit);\n end\n \n %% callbacks\n \n function cb_timecut_year(mysrc,~)\n it = str2double(mysrc.String);\n end\n \n function cb_window_duration_edit(mysrc,~)\n compare_window_dur = years(str2double(mysrc.String));\n end\n \n function cb_go(mysrc, myevt)\n watchon;\n drawnow;\n do_calma(calc_type);\n end\nend\n\n%% calculation functions\n\nfunction [as, strib, stri2] = calc_percent_change(cumuall, ti, len)\n for i = ncu:-1:1\n mean1(i) = mean(cumuall(1:ti,i));\n mean2(i) = mean(cumuall(ti:len,i));\n end %for i\n \n as = -((mean1-mean2)./mean1)*100;\n \n strib = 'Change in Percent';\n stri2 = ['ti=' num2str(ti*days(ZG.bin_dur) + t0b) ];\nend\n\nfunction [as, var1, var2] = calc_rubberband(ncu, ti, winlen_days)\n for i = ncu:-1:1\n mean1(i) = mean(cumuall(1:ti,i));\n mean2(i) = mean(cumuall(ti+1:ti+winlen_days,i));\n var1(i) = cov(cumuall(1:ti,i));\n var2(i) = cov(cumuall(ti+1:ti+winlen_days,i));\n end % for i ;\n as = (mean1 - mean2)./(sqrt(var1/ti+var2/winlen_days));\nend\n\nfunction [as, var1, var2] = calc_ast(ncu, ti, len)\n for i = ncu:-1:1\n mean1(i) = mean(cumuall(1:ti,i));\n var1(i) = cov(cumuall(1:ti,i));\n mean2(i) = mean(cumuall(ti+1:len,i));\n var2(i) = cov(cumuall(ti+1:len,i));\n end\n as = (mean1 - mean2)./(sqrt(var1/ti+var2/(len-ti)));\nend\n\nfunction [as, var1, var2] = calc_lta(ncu, ti, winlen_days, len, cumuall)\n mean1 = mean([cumuall(1:ti-1,:) ; cumuall(ti+winlen_days+1:len,:)]);\n mean2 = mean(cumuall(ti:ti+winlen_days,:));\n for i = ncu : -1 : 1\n var1(i) = cov([cumuall(1:ti-1,i) ; cumuall(ti+winlen_days+1:len,i)]);\n var2(i) = cov(cumuall(ti:ti+winlen_days,i));\n end % for i\n as = (mean1 - mean2)./(sqrt(var1/(len-winlen_days)+var2/winlen_days));\nend\n\nfunction [maxlta, maxlta2, mean1, mean2] = calc_maz(ncu, cumuall, len)\n maxlta = zeros(1,ncu);\n maxlta = maxlta -5;\n mean1 = mean(cumuall(1:len,:));\n wai = waitbar(0,'Please wait...');\n set(wai,'Color',[0.8 0.8 0.8], 'NumberTitle','off', 'Name','Percent done');\n \n for i = ncu:-1:1\n var1(i) = cov(cumuall(1:len,i));\n end\n \n for ti = 1:step: len - winlen_days\n waitbar(ti/len)\n mean1 = mean(cumuall(1:len,:));\n mean2 = mean(cumuall(ti:ti+winlen_days,:));\n for i = 1:ncu\n var1(i) = cov(cumuall(1:len,i));\n var2(i) = cov(cumuall(ti:ti+winlen_days,i));\n end\n as = (mean1 - mean2)./(sqrt(var1/len+var2/winlen_days));\n maxlta2 = [maxlta ; as ];\n maxlta = max(maxlta2);\n end\n %as = reshape(maxlta,length(gy),length(gx));\n close(wai)\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/show_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.17659609062668588}} {"text": "function [windowsOut,scoreOut]=mvg_runObjectDetection(img,config)\n% function [windowsOut,scoreOut]=mvg_runObjectDetection(img,config)\n% returns a set of candidate windows which are prominent to contain \n% objects over broad variety of classes.\n%\n% Inputs:\n% img, imgRow*imgCol*3, double, is the input color image.\n% config, struct, contains the parameter settings. See below for formatting \n% details. If undefined, default configuration will be used.\n%\n% Outputs:\n% windowsOut, numWindows*4, double, is a matrix containing the candidate \n% windows. Each row corresponds to one\n% window in format:\n% windowsOut(i,:)=[xmin,ymin,xmax,ymax];\n% scoreOut, numWindows*1, double, is a vector of objectness scores associated\n% with each window in windowsOut. i:th entry\n% corresponds to i:th row in windowsOut.\n%\n% Example usage:\n% >>img=imread('exampleImage.jpg');\n% >>[windowsOut,scoreOut]=mvg_runObjectDetection(img);\n% >>mvg_drawWindows(img,windowsOut((1:10),:));\n\n% This program implements the method described in:\n%\n% Rahtu E. & Kannala J. & Blaschko M. B. \n% Learning a Category Independent Object Detection Cascade. \n% Proc. International Conference on Computer Vision (ICCV 2011).\n\n% 2011 MVG, Oulu, Finland, Esa Rahtu and Juho Kannala \n% 2011 VGG, Oxford, UK, Matthew Blaschko\n\n%% Default configuration (for details, please refer to the paper above)\n% The parameters you most likely need to change are config.NMS.numberOfOutputWindows that\n% defines the number of output windows and config.NMS.trhNMSb, which defines the non-maxima\n% suppression threshold (0.4-0.6 gives better recall with lower overlaps, 0.6-> gives better reall with high overlaps).\nif ~exist('config','var') || isempty(config)\n %% Initial window sampling parameters\n % General\n config.InitialWindows.loadInitialWindows=false; % false->nothing is loaded, true->load initial windows from the file given in storage parameter below (overrides all other initial window settings)\n config.InitialWindows.windowTypes={'Prior','Superpix'}; % Methods for generating the initial windows\n config.InitialWindows.numInitialWindows=100000; % The number of initial windows returned\n % Superpixel windows\n config.InitialWindows.numberOfConnectedSuperpix=3; % The maximum number of connected superpixels used with the initial windows\n % Prior windows\n config.InitialWindows.windowPriorDistribution='ICCV_windowPriorDistribution.mat'; % mat-file or the structure containing the distribution of prior windows\n\n %% Feature parameters\n config.Features.loadFeatureScores=false; % false->nothing is loaded, true->load feature scores from the file given in storage parameter below (overrides all other initial feature settings)\n config.Features.featureTypes={'SS','WS','BE','BI'}; % Feature to be computed from initial windows\n config.Features.featureWeights=[1.685305e+00, 7.799898e-02, 3.020189e-01, -7.056292e-04]; % Relative feature weights (same ordering as with the features above)\n \n %% NMS parameters\n config.NMS.NMStype='NMSab'; % The type of Non-Maximum-Suppression used\n config.NMS.numberOfOutputWindows=1000; % Number of output windows retuned\n config.NMS.numberOfIntermediateWindows=10001; % Number of windows after NMSa algorithm\n config.NMS.trhNMSa=0; % Threshold for NMSa method\n config.NMS.trhNMSb=0.75; % Threshold for NMSb method\n \n %% Storage parameters (file names with full path, set empty if nothing will be stored or loaded)\n config.Storage.initialWindows=[];\n config.Storage.features=[];\n config.Storage.outputWindows=[];\n \n %% General parameters\n config.verbose=0; % 0->show nothing, 1->display progress \nend\n\n%% Initialize\n% General\ntimeStamp=clock;\nconfig.Features.verbose=config.verbose;\nconfig.NMS.imageSize=[size(img,1),size(img,2)];\n\n% Check loading paramets\nif config.Features.loadFeatureScores && ~config.InitialWindows.loadInitialWindows\n error('If you load feature scores, also corresponding windows must be loaded. Otherwise windows and scores do not match!');\nend\n\n% Ensure superpixel representation exists if it is needed anywhere in the algorithm \nif (sum(strcmp('Superpix',config.InitialWindows.windowTypes))>eps && ~config.InitialWindows.loadInitialWindows) || ((sum(strcmp('SS',config.Features.featureTypes))>eps || sum(strcmp('BI',config.Features.featureTypes))) && ~config.Features.loadFeatureScores)\n % Compute superpixels if they are not in config.superPixels\n if ~isfield(config,'superPixels')\n % Display\n if config.verbose>eps\n fprintf('\\nComputing superpixels...\\n');\n intermediateTimeStamp=clock;\n end\n % Compute superpixels\n config.superPixels=mvg_computeSuperpixels(img);\n % Display\n if config.verbose>eps\n fprintf('Superpixels computed! Time taken %1.2f sec.\\n',etime(clock,intermediateTimeStamp));\n end\n end\n % Store superpixels for initial windows and feature scoring\n config.InitialWindows.superPixels=config.superPixels;\n config.Features.superPixels=config.superPixels;\nend\n\n%% Load or make initial windows \nif config.InitialWindows.loadInitialWindows\n % Display\n if config.verbose>eps\n fprintf('\\nLoading initial windows from:\\n%s...\\n',config.Storage.initialWindows);\n end\n \n % Load data\n load(config.Storage.initialWindows,'windows','configInitialWindows');\n\n % Reset initial window config\n config.InitialWindows=configInitialWindows;\n \nelse\n % Display\n if config.verbose>eps\n fprintf('\\nCreating initial windows...\\n');\n intermediateTimeStamp=clock;\n end\n % Make windows\n windows=mvg_makeInitialWindows(img,config.InitialWindows);\n % Display\n if config.verbose>eps\n fprintf('Initial windows done! Time taken %1.2f sec.\\n',etime(clock,intermediateTimeStamp));\n end\n % Store initial windows\n if ~isempty(config.Storage.initialWindows)\n % Display\n if config.verbose>eps\n fprintf('Storing initial windows to:\\n%s\\n',config.Storage.initialWindows);\n end\n % Store initial windows\n configInitialWindows=config.InitialWindows;\n save(config.Storage.initialWindows,'windows','configInitialWindows');\n end\nend\n\n\n%% Load or compute feature scores \nif config.Features.loadFeatureScores\n % Display\n if config.verbose>eps\n fprintf('\\nLoading feature scores from:\\n%s...\\n',config.Storage.features);\n end\n \n % Load data\n load(config.Storage.features,'featureScores','configFeature');\n \n % Reset initial window config\n config.Features=configFeature;\n \nelse\n % Display\n if config.verbose>eps\n fprintf('\\nComputing feature scores...\\n');\n intermediateTimeStamp=clock;\n end\n % Run score computation\n featureScores=mvg_computeFeatureScores(img,windows,config.Features);\n % Display\n if config.verbose>eps\n fprintf('Features computed! Time taken %1.2f sec.\\n',etime(clock,intermediateTimeStamp));\n end\n % Store feature scores\n if ~isempty(config.Storage.features)\n % Display\n if config.verbose>eps\n fprintf('Storing feature scores to:\\n%s\\n',config.Storage.features);\n end\n % Store feature scores\n configFeature=config.Features;\n save(config.Storage.features,'featureScores','configFeature');\n end\nend\n\n\n%% Make combined score\n% Display\nif config.verbose>eps\n fprintf('\\nComputing combined scores...\\n');\n intermediateTimeStamp=clock;\nend\n% Compute linear combination\ncombinedScores=(config.Features.featureWeights*featureScores')';\n% Display\nif config.verbose>eps\n fprintf('Combined score computed! Time taken %1.2f sec.\\n',etime(clock,intermediateTimeStamp));\nend\n\n%% Run NMS to get indices to selected windows\n% Display\nif config.verbose>eps\n fprintf('\\nSelecting final output windows...\\n');\n intermediateTimeStamp=clock;\nend\n% Run NMS\nselectedId=mvg_runWindowNMS(windows,combinedScores,config.NMS);\n% Display\nif config.verbose>eps\n fprintf('Final windows selected! Time taken %1.2f sec.\\n',etime(clock,intermediateTimeStamp));\nend\n\n%% Take selected window coordinates and scores\nwindowsOut=windows(selectedId,:);\nif nargout>1\n scoreOut=combinedScores(selectedId);\nend\n% Store output windows\nif ~isempty(config.Storage.outputWindows)\n % Display\n if config.verbose>eps\n fprintf('Storing output windows to:\\n%s\\n',config.Storage.outputWindows);\n end\n % Store feauture scores\n save(config.Storage.outputWindows,'windowsOut','scoreOut','config');\nend\n\n\n%% Print done\nif config.verbose>eps\n fprintf('Done!\\n');\n fprintf('Total time taken: %1.2f sec.\\n',etime(clock,timeStamp));\nend\n\n\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/rahtu/rahtuObjectness/mvg_runObjectDetection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17655183648477224}} {"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": "function ExportAedat2(aedat)\n\n%{\nThis function exports data to a .aedat file in format version 2.\nThe .aedat file format is documented here:\nhttp://inilabs.com/support/software/fileformat/\n\nJust merges polarity, frame and imu6 at the moment.\n\nIf there is a timestamp reset, events before and after it will be mixed\ntogether. Make sure to cut out time before any resets, or otherwise\nmonotonise the timestamps for each data type separately before applying\nthis function.\n\n%}\n\n%% validation of parameters\n\ndbstop if error\n\nif ~exist('aedat', 'var')\n error('Missing input')\nend\n\nif ~isfield(aedat, 'exportParams') || ~isfield(aedat.exportParams, 'filePath')\n error('Missing parameter exportParams.filePath')\nend\n\n% For source, use an override if it has been given. This allows data from\n% one sensor to masquerade as data from another sensor.\n\nif isfield(aedat.exportParams, 'source')\n source = aedat.exportParams.source;\nelse\n source = aedat.info.source;\nend\n\n%% General preparation\n\n% Create overall containers\nallTimeStamps = uint32([]);\nallSamples = uint32([]);\n\n% Declare function for finding specific event types in eventTypes cell array\ncellFind = @(string)(@(cellContents)(strcmp(string, cellContents)));\n\n%% Polarity\n\nif isfield(aedat.data, 'polarity') ...\n && (~isfield(aedat.exportParams, 'dataTypes') ...\n || any(cellfun(cellFind('polarity'), aedat.exportParams.dataTypes)))\n \n \n disp('Preparing polarity data ...')\n \n if strcmp(source, 'Dvs128')\n % In the 32-bit address:\n % bit 1 (1-based) is polarity\n % bit 2-8 is x\n % bit 9-15 is y\n % bit 16 is special\n \n yShiftBits = 8;\n xShiftBits = 1;\n polShiftBits = 0;\n else % Default to DAVIS\n % In the 32-bit address:\n % bit 32 (1-based) being 1 indicates an APS sample\n % bit 11 (1-based) being 1 indicates a special event\n % bits 11 and 32 (1-based) both being zero signals a polarity event\n \n yShiftBits = 22;\n xShiftBits = 12;\n polShiftBits = 11;\n end\n \n y = bitshift(uint32(aedat.data.polarity.y), yShiftBits);\n x = bitshift(uint32(aedat.data.polarity.x), xShiftBits);\n pol = bitshift(uint32(aedat.data.polarity.polarity), polShiftBits);\n allSamples = [allSamples; y + x + pol];\n allTimeStamps = [allTimeStamps; uint32(aedat.data.polarity.timeStamp)];\nend\n\n%% Frame\n\nif isfield(aedat.data, 'frame') ...\n && (~isfield(aedat.exportParams, 'dataTypes') ...\n || any(cellfun(cellFind('frame'), aedat.exportParams.dataTypes)))\n disp('Preparing frame data ...')\n yShiftBits = 22;\n xShiftBits = 12;\n % frameShiftBits = 0;\n frameFlagShiftBits = 31;\n signalFlagShiftBits = 10;\n \n frameData = aedat.data.frame;\n \n numFrames = frameData.numEvents;\n xDim = aedat.info.deviceAddressSpace(1);\n yDim = aedat.info.deviceAddressSpace(2);\n numPixels = xDim * yDim;\n \n % Allocate horizontal vectors to hold output data.\n % Why are the vectors that big? The factor of 2 is because\n % we insert dummy 'reset' frames prior to each frame.\n samples = uint32(zeros(1, 2 * numFrames * numPixels));\n timeStamps = uint32(zeros(2 * numFrames * numPixels, 1));\n \n % The output vector is twice as big again because samples and timeStamps\n % will be interspersed in the 'output' vector.\n y = repmat(uint32(yDim - 1 : -1 : 0)', xDim * numFrames * 2, 1); % y ramps down\n x = repmat(uint32(0 : xDim - 1), yDim, numFrames * 2); % but x ramps up\n x = x(:);\n % in bit 11 (1-based) 1 means signal read and 0 means reset read.\n signalFlag = repmat([zeros(numPixels, 1, 'uint32'); ...\n bitshift(ones(numPixels, 1, 'uint32'), signalFlagShiftBits)], ...\n numFrames, 1);\n % The last event mask is synonymous with the sample from x=0 y=0; data is\n % therefore ordered backwards.\n for frameIndex = 1 : numFrames\n samplesTemp = frameData.samples{frameIndex}(:);\n samplesTemp = samplesTemp(end : -1 : 1);\n samples((frameIndex * 2 - 1) * numPixels + 1 : frameIndex * 2 * numPixels) ...\n = samplesTemp ;\n timeStamps((frameIndex - 1) * 2 * numPixels + 1 : frameIndex * 2 * numPixels) ...\n = frameData.timeStampStart(frameIndex);\n end\n frameFlag = bitshift(1, frameFlagShiftBits, 'uint32');\n y = bitshift(y, yShiftBits, 'uint32');\n x = bitshift(x, xShiftBits, 'uint32');\n % samples should now be in the range 0-1023 (10-bit).\n % subtract samples from 1023. This has the effect of leaving all the reset\n % frame samples at 1023 - the highest value, against which the signal frames\n % will later be subtracted.\n samples = 1023 - samples';\n \n allSamples = [allSamples; frameFlag + y + x + signalFlag + samples];\n allTimeStamps = [allTimeStamps; timeStamps];\nend\n\n%% IMU6\n\n\nif isfield(aedat.data, 'imu6') ...\n && (~isfield(aedat.exportParams, 'dataTypes') ...\n || any(cellfun(cellFind('imu6'), aedat.exportParams.dataTypes)))\n disp('Preparing imu6 data ...')\n \n imuFlag = uint32(0);\n imuFlag = bitset(imuFlag, 31+1);\n imuFlag = bitset(imuFlag, 11+1);\n imuFlag = bitset(imuFlag, 10+1);\n accelXFlag = bitshift(uint32(0), 28);\n accelYFlag = bitshift(uint32(1), 28);\n accelZFlag = bitshift(uint32(2), 28);\n temperatureFlag = bitshift(uint32(3), 28);\n gyroXFlag = bitshift(uint32(4), 28);\n gyroYFlag = bitshift(uint32(5), 28);\n gyroZFlag = bitshift(uint32(6), 28);\n \n accelX = convertAccelUint32(aedat.data.imu6.accelX);\n accelX = accelX + imuFlag + accelXFlag;\n \n accelY = convertAccelUint32(aedat.data.imu6.accelY);\n accelY = accelY + imuFlag + accelYFlag;\n \n accelZ = convertAccelUint32(aedat.data.imu6.accelZ);\n accelZ = accelZ + imuFlag + accelZFlag;\n \n temp = aedat.data.imu6.temperature; % conversion from g to full scale, and shift bits\n temp = int16((temp - 35) * 340); % conversion from K to full scale 16 range\n temp = [temp zeros(aedat.data.imu6.numEvents, 1, 'int16')];\n temp = temp';\n temp = temp(:);\n temp = typecast(temp, 'uint32');\n temp = bitshift(temp, 12); % shift bits\n temp = temp + imuFlag + temperatureFlag;\n \n gyroX = convertGyroUint32(aedat.data.imu6.gyroX);\n gyroX = gyroX + imuFlag + gyroXFlag;\n \n gyroY = convertGyroUint32(aedat.data.imu6.gyroY);\n gyroY = gyroY + imuFlag + gyroYFlag;\n \n gyroZ = convertGyroUint32(aedat.data.imu6.gyroZ);\n gyroZ = gyroZ + imuFlag + gyroZFlag;\n \n allData = [accelX accelY accelZ temp gyroX gyroY gyroZ];\n allData = allData';\n allData = allData(:);\n \n timeStamps = uint32(aedat.data.imu6.timeStamp(:));\n timeStamps = repmat(timeStamps', 7 , 1);\n timeStamps = timeStamps(:);\n \n allSamples = [allSamples; allData];\n allTimeStamps = [allTimeStamps; timeStamps];\nend\n\n%% Sort the events by timestamp\n\ndisp('Sorting events ...')\n\n[allTimeStamps, sortIndex] = sort(allTimeStamps);\nallSamples = allSamples(sortIndex);\n\noutput = zeros(1, length(allSamples) * 2, 'uint32');\n\noutput(1:2:end) = allSamples;\noutput(2:2:end) = allTimeStamps; % set even elements to timestamps\n\n%% Write to file\n\ndisp('Writing to file ...')\n\n% Create the file\nf = fopen(aedat.exportParams.filePath, 'w', 'b');\n\nif ~isfield(aedat.exportParams, 'noHeader') || aedat.exportParams.noHeader == false\n \n % CRLF \\r\\n is needed to not break header parsing in jAER\n fprintf(f,'#!AER-DAT2.0\\r\\n');\n fprintf(f,'# This is a raw AE data file created by an export function in the AedatTools library\\r\\n');\n fprintf(f,'# Data format is int32 address, int32 timestamp (8 bytes total), repeated for each event\\r\\n');\n fprintf(f,'# Timestamps tick is 1 us\\r\\n');\n fprintf(f,['# AEChip: ' source '\\r\\n']);\n fprintf(f,'# End of ASCII Header\\r\\n');\nend\n\n% write addresses and timestamps\ncount = fwrite(f, output, 'uint32', 0, 'b') / 2; % write 4 byte data\nfclose(f);\nfprintf('wrote %d events to %s\\n', count, aedat.exportParams.filePath);\n\n\n\nfunction accel = convertAccelUint32(accel)\n% Conversion from g to full scale, and shift bits\naccel = int16(accel * 8192); % conversion from g to full scale 16 range\naccel = [accel zeros(numel(accel), 1, 'int16')];\naccel = accel';\naccel = accel(:);\naccel = typecast(accel, 'uint32');\naccel = bitshift(accel, 12); % shift bits\n\n\nfunction gyro = convertGyroUint32(gyro)\ngyro = int16(gyro * 65.5);\ngyro = [gyro zeros(numel(gyro), 1, 'int16')];\ngyro = gyro';\ngyro = gyro(:);\ngyro = typecast(gyro, 'uint32');\ngyro = bitshift(gyro, 12); % shift bits\n", "meta": {"author": "panpanfei", "repo": "Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "sha": "aabdd6ae323726132b0e0592ce151461e3ad7c5a", "save_path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera", "path": "github-repos/MATLAB/panpanfei-Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera/Bringing-a-Blurry-Frame-Alive-at-High-Frame-Rate-with-an-Event-Camera-aabdd6ae323726132b0e0592ce151461e3ad7c5a/event_cvpr_github/read_data/code/AedatTools-master/Matlab/ExportAedat2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.17643453595025213}} {"text": "function varargout = process_canoltymap( varargin )\n% This function generates Canolty like maps (Science 2006, figure 1) for the input signal. \n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Esther Florin, Sylvain Baillet, 2011-2013\n% Francois Tadel, 2013-2014\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok\n % Description the process\n sProcess.Comment = 'Canolty maps';\n sProcess.Category = 'File';\n sProcess.SubGroup = 'Frequency';\n sProcess.Index = 661;\n % Definition of the input accepted by this process\n sProcess.InputTypes = {'raw', 'data', 'results', 'matrix'};\n sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq', 'timefreq'};\n sProcess.nInputs = 1;\n sProcess.nMinFiles = 1;\n sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Resting#Canolty_maps';\n % ==== INPUT ====\n sProcess.options.label_in.Comment = 'Input options:';\n sProcess.options.label_in.Type = 'label';\n % === TIME WINDOW\n sProcess.options.timewindow.Comment = 'Time window: ';\n sProcess.options.timewindow.Type = 'timewindow';\n sProcess.options.timewindow.Value = [];\n % === SENSOR SELECTION\n sProcess.options.target_data.Comment = 'Sensor types or names (empty=all): ';\n sProcess.options.target_data.Type = 'text';\n sProcess.options.target_data.Value = 'MEG, EEG';\n sProcess.options.target_data.InputTypes = {'data', 'raw'};\n % === SCOUTS SELECTION\n sProcess.options.scouts.Comment = 'Use scouts';\n sProcess.options.scouts.Type = 'scout_confirm';\n sProcess.options.scouts.Value = {};\n sProcess.options.scouts.InputTypes = {'results'};\n % === SCOUT FUNCTION ===\n sProcess.options.scoutfunc.Comment = {'Mean', 'Max', 'PCA', 'Std', 'All', 'Scout function:'};\n sProcess.options.scoutfunc.Type = 'radio_line';\n sProcess.options.scoutfunc.Value = 1;\n sProcess.options.scoutfunc.InputTypes = {'results'};\n % === SCOUT TIME ===\n sProcess.options.scouttime.Comment = {'Before', 'After', 'When to apply the scout function:'};\n sProcess.options.scouttime.Type = 'radio_line';\n sProcess.options.scouttime.Value = 1;\n sProcess.options.scouttime.InputTypes = {'results'};\n % === ROW NAMES\n sProcess.options.target_tf.Comment = 'Row names or indices (empty=all): ';\n sProcess.options.target_tf.Type = 'text';\n sProcess.options.target_tf.Value = '';\n sProcess.options.target_tf.InputTypes = {'timefreq', 'matrix'};\n \n % ==== ESTIMATOR ====\n sProcess.options.label_method.Comment = '
Estimator options:';\n sProcess.options.label_method.Type = 'label';\n % === EPOCH TIME\n sProcess.options.epochtime.Comment = 'Epoch time: ';\n sProcess.options.epochtime.Type = 'range';\n sProcess.options.epochtime.Value = {[-1, 1], 'ms', []};\n % === NESTING FREQ\n sProcess.options.lowfreq.Comment = 'Nesting frequency (low): ';\n sProcess.options.lowfreq.Type = 'value';\n sProcess.options.lowfreq.Value = {4, 'Hz', 2};\n % === MAX_BLOCK_SIZE\n sProcess.options.max_block_size.Comment = 'Number of signals to process at once: ';\n sProcess.options.max_block_size.Type = 'value';\n sProcess.options.max_block_size.Value = {100, ' ', 0};\n \n % ==== OUTPUT ====\n sProcess.options.label_out.Comment = '
Output configuration:';\n sProcess.options.label_out.Type = 'label';\n % === SAVE AVERAGED LOW-FREQ SIGNALS\n sProcess.options.save_erp.Comment = 'Save averaged low frequency signals';\n sProcess.options.save_erp.Type = 'checkbox';\n sProcess.options.save_erp.Value = 1;\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok\n Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFile = Run(sProcess, sInput) %#ok\n % Get options\n if ~isempty(sProcess.options.timewindow.Value) && iscell(sProcess.options.timewindow.Value)\n OPTIONS.TimeWindow = sProcess.options.timewindow.Value{1};\n else\n OPTIONS.TimeWindow = [];\n end\n OPTIONS.EpochTime = sProcess.options.epochtime.Value{1};\n OPTIONS.LowFreq = sProcess.options.lowfreq.Value{1};\n OPTIONS.MaxSignals = sProcess.options.max_block_size.Value{1};\n OPTIONS.SaveErp = sProcess.options.save_erp.Value;\n % Get target\n if ismember(sInput.FileType, {'data','raw'}) && isfield(sProcess.options, 'target_data') && ~isempty(sProcess.options.target_data.Value)\n OPTIONS.Target = sProcess.options.target_data.Value;\n elseif ismember(sInput.FileType, {'timefreq', 'matrix'}) && isfield(sProcess.options, 'target_tf') && ~isempty(sProcess.options.target_tf.Value)\n OPTIONS.Target = sProcess.options.target_tf.Value;\n else\n OPTIONS.Target = [];\n end\n OutputFile = {};\n \n % ===== GET SCOUTS OPTIONS =====\n if strcmpi(sInput.FileType, 'results') && isfield(sProcess.options, 'scouts') && isfield(sProcess.options.scouts, 'Value')\n % Override scouts function\n switch (sProcess.options.scoutfunc.Value)\n case 1, OPTIONS.ScoutFunc = 'mean';\n case 2, OPTIONS.ScoutFunc = 'max';\n case 3, OPTIONS.ScoutFunc = 'pca';\n case 4, OPTIONS.ScoutFunc = 'std';\n case 5, OPTIONS.ScoutFunc = 'all';\n end\n % Scout function order\n switch (sProcess.options.scouttime.Value)\n case 1, OPTIONS.ScoutTime = 'before';\n case 2, OPTIONS.ScoutTime = 'after';\n end\n % Perform some checks\n if strcmpi(OPTIONS.ScoutTime, 'before') && ismember(OPTIONS.ScoutFunc, {'max', 'std'})\n bst_report('Error', sProcess, [], 'Scout functions MAX and STD should not be applied before estimating the PAC.');\n return;\n end\n if strcmpi(OPTIONS.ScoutTime, 'after') && strcmpi(OPTIONS.ScoutFunc, 'pca')\n bst_report('Error', sProcess, [], 'Scout function PCA cannot be applied after estimating the PAC.');\n return;\n end\n % Selected scouts\n AtlasList = sProcess.options.scouts.Value;\n % Set input/output scouts functions\n if ~isempty(AtlasList)\n OPTIONS.Target = AtlasList;\n % Apply function before: get all the scouts time series in advance\n if strcmpi(OPTIONS.ScoutTime, 'before')\n LoadOptions.TargetFunc = OPTIONS.ScoutFunc;\n % Apply function after: Get all the time series of all the scouts\n elseif strcmpi(OPTIONS.ScoutTime, 'after')\n LoadOptions.TargetFunc = 'all';\n end\n end\n end\n \n % === READ INPUT DATA ===\n % Options for LoadInputFile()\n LoadOptions.LoadFull = 0; % Load kernel-based results as kernel+data\n LoadOptions.IgnoreBad = 0; % Ignore the bad channels\n LoadOptions.ProcessName = func2str(sProcess.Function);\n % Load input signals \n [sMat, nSignals, iRows] = bst_process('LoadInputFile', sInput.FileName, OPTIONS.Target, OPTIONS.TimeWindow, LoadOptions);\n if isempty(sMat.Data)\n return;\n end\n % Default time window\n if isempty(OPTIONS.TimeWindow)\n OPTIONS.TimeWindow = [sMat.Time(1), sMat.Time(end)];\n end\n % Get sampling frequency\n sRate = 1 / (sMat.Time(2) - sMat.Time(1));\n % Low frequency comment\n if (length(OPTIONS.LowFreq) == 1)\n strFreq = [num2str(round(OPTIONS.LowFreq * 100) / 100), 'Hz'];\n else\n strFreq = '';\n end\n % Replicate low frequency if only one was provided for all the signals\n if (length(OPTIONS.LowFreq) == 1) && (nSignals > 1)\n OPTIONS.LowFreq = repmat(OPTIONS.LowFreq, nSignals, 1);\n % Select only a subset of the low frequencies\n elseif ~isempty(OPTIONS.Target) && ~isempty(iRows) && (length(OPTIONS.LowFreq) ~= length(iRows)) && (max(iRows) < length(OPTIONS.LowFreq))\n OPTIONS.LowFreq = OPTIONS.LowFreq(iRows);\n % Check for compatible size of LowFreq array\n elseif (length(OPTIONS.LowFreq) ~= nSignals)\n bst_report('Error', sProcess, sInput, sprintf('The size of the low-frequency array (%d) does not match the number of signals to process (%d).', length(OPTIONS.LowFreq), nSignals));\n return;\n end\n \n % ===== CALCULATE CANOLTY MAPS =====\n % Number of blocks of signals\n MAX_BLOCK_SIZE = OPTIONS.MaxSignals;\n nBlocks = ceil(nSignals / MAX_BLOCK_SIZE);\n TF = [];\n ERP = [];\n % Process each block of signals\n for iBlock = 1:nBlocks\n bst_progress('inc', round(iBlock/nBlocks*100)); \n % Indices of the signals\n iSignals = (iBlock-1)*MAX_BLOCK_SIZE+1 : min(iBlock*MAX_BLOCK_SIZE, nSignals);\n % Get signals to process\n if ~isempty(sMat.ImagingKernel)\n Fblock = sMat.ImagingKernel(iSignals,:) * sMat.Data;\n else\n Fblock = sMat.Data(iSignals,:);\n end\n % Calculate canolty map signal\n [TFblock, ERPblock, TimeVectorOut, Freqs, errMsg] = Compute(Fblock, sRate, OPTIONS.LowFreq(iSignals), OPTIONS.EpochTime);\n if ~isempty(errMsg)\n bst_report('Error', sProcess, sInput, errMsg);\n return;\n end\n % Initialize output variable\n if isempty(TF)\n TF = zeros(nSignals, size(TFblock,2), size(TFblock,3));\n ERP = zeros(nSignals, size(TFblock,2));\n end\n % Copy block results to output variable\n TF(iSignals,:,:) = TFblock;\n ERP(iSignals,:) = ERPblock;\n end\n \n % ===== UNCONSTRAINED SOURCES =====\n % Unconstrained sources => SUM for each point\n if ismember(sMat.DataType, {'results','scout','matrix'}) && ~isempty(sMat.nComponents) && (sMat.nComponents ~= 1)\n [TF, tmp, tmp] = bst_source_orient([], sMat.nComponents, sMat.GridAtlas, TF, 'sum', sMat.DataType, sMat.RowNames);\n [ERP, sMat.GridAtlas, sMat.RowNames] = bst_source_orient([], sMat.nComponents, sMat.GridAtlas, ERP, 'mean', sMat.DataType, sMat.RowNames);\n end\n \n % ===== PROCESS SCOUTS =====\n % Get scouts\n isScout = ~isempty(OPTIONS.Target) && (isstruct(OPTIONS.Target) || iscell(OPTIONS.Target)) && isfield(sMat, 'Atlas') && isfield(sMat.Atlas, 'Scouts') && ~isempty(sMat.Atlas.Scouts); \n if isScout\n sScouts = sMat.Atlas.Scouts;\n end\n % If the scout function has to be applied AFTER the PAC computation\n if isScout && strcmpi(OPTIONS.ScoutTime, 'after') && ~strcmpi(OPTIONS.ScoutFunc, 'all')\n nScouts = length(sScouts);\n TF_scouts = zeros(nScouts, size(TF,2), size(TF,3));\n ERP_scouts = zeros(nScouts, size(ERP,2));\n % Vertices\n iVerticesAll = [1, cumsum(cellfun(@length, {sScouts.Vertices})) + 1];\n % For each unique row name: compute a measure over the clusters values\n for iScout = 1:nScouts\n iScoutVert = iVerticesAll(iScout):iVerticesAll(iScout+1)-1;\n % Process scouts for the TF maps\n F = reshape(TF(iScoutVert,:,:), length(iScoutVert), []);\n F = bst_scout_value(F, OPTIONS.ScoutFunc);\n TF_scouts(iScout,:,:) = reshape(F, [1, size(TF,2), size(TF,3)]);\n % Process scouts for the ERP map\n ERP_scouts(iScout,:) = bst_scout_value(ERP(iScoutVert,:), OPTIONS.ScoutFunc);\n end\n % Save only the requested rows\n sMat.RowNames = {sScouts.Label}';\n TF = TF_scouts;\n ERP = ERP_scouts;\n end\n \n % ===== COMMENT =====\n Comment = 'Canolty maps';\n % Time window (RAW only)\n if ~isempty(strfind(sInput.Condition, '@raw'))\n if ~isempty(strFreq)\n Comment = [Comment, sprintf('(%ds-%ds,%s)', round(OPTIONS.TimeWindow), strFreq)];\n else\n Comment = [Comment, sprintf('(%ds-%ds)', round(OPTIONS.TimeWindow))];\n end\n elseif ~isempty(strFreq)\n Comment = [Comment '(' strFreq ')'];\n end\n % Scouts\n if isScout && (length(sScouts) < 6)\n Comment = [Comment, ':'];\n for is = 1:length(sScouts)\n Comment = [Comment, ' ', sScouts(is).Label];\n end\n Comment = [Comment, ', ', OPTIONS.ScoutFunc];\n if ~strcmpi(OPTIONS.ScoutFunc, 'All')\n Comment = [Comment, ' ' OPTIONS.ScoutTime];\n end\n % Single input\n elseif (length(sMat.RowNames) == 1)\n if iscell(sMat.RowNames)\n Comment = [Comment, ': ' sMat.RowNames{1}];\n else\n Comment = [Comment, ': #', num2str(sMat.RowNames(1))];\n end\n end\n \n % ===== SAVE TF FILE =====\n % Get the study filename\n sStudy = bst_get('Study', sInput.iStudy);\n % Convert row indices to row names\n if iscell(sMat.RowNames)\n Description = sMat.RowNames;\n else\n Description = cell(length(sMat.RowNames), 1);\n for iRow = 1:length(sMat.RowNames)\n Description{iRow} = num2str(sMat.RowNames(iRow));\n end\n end\n % Create new output structure\n sOutput = db_template('timefreqmat');\n sOutput.TF = TF;\n sOutput.CanoltyERP = ERP;\n sOutput.Comment = Comment;\n sOutput.DataType = sMat.DataType;\n sOutput.RowNames = sMat.RowNames;\n sOutput.Time = TimeVectorOut;\n sOutput.Freqs = round(Freqs .* 100) / 100;\n sOutput.Measure = 'other';\n sOutput.Method = 'canolty';\n sOutput.DataFile = sInput.FileName;\n sOutput.SurfaceFile = sMat.SurfaceFile;\n sOutput.Atlas = [];\n sOutput.Options = OPTIONS;\n sOutput.CanoltyERP = ERP;\n if ~isempty(sMat.GridLoc)\n sOutput.GridLoc = sMat.GridLoc;\n end\n if ~isempty(sMat.GridAtlas)\n sOutput.GridAtlas = sMat.GridAtlas;\n end\n % Output filename\n OutputFile = bst_process('GetNewFilename', bst_fileparts(sStudy.FileName), 'timefreq_canolty');\n % Save file\n bst_save(OutputFile, sOutput, 'v6');\n % Add file to database structure\n db_add_data(sInput.iStudy, OutputFile, sOutput);\n \n % ===== SAVE MATRIX FILE =====\n if OPTIONS.SaveErp\n % Comment\n ErpComment = sMat.Comment;\n iBar = find(ErpComment == '|', 1, 'last');\n if ~isempty(iBar)\n ErpComment = ErpComment(1:iBar-1);\n end\n ErpComment = [ErpComment ' | ' strrep(Comment, 'Canolty maps', 'Canolty ERP')];\n % Create new output structure\n sOutput = db_template('matrixmat');\n sOutput.Value = ERP;\n sOutput.Comment = ErpComment;\n sOutput.Time = TimeVectorOut;\n sOutput.Description = Description;\n sOutput.Options = OPTIONS;\n % Output filename\n OutputFileERP = bst_process('GetNewFilename', bst_fileparts(sStudy.FileName), 'matrix_canolty');\n % Save file\n bst_save(OutputFileERP, sOutput, 'v6');\n % Add file to database structure\n db_add_data(sInput.iStudy, OutputFileERP, sOutput);\n end\nend\n\n\n \n%% ===== COMPUTE CANOLTY MAPS =====\nfunction [TF, ERP, TimeOut, chirp_center_high, errMsg] = Compute( F, sRate, lowfreq, EpochTime)\n nTime = size(F,2);\n errMsg = '';\n \n % ===== CREATE CHIRPLETS =====\n % Definitions\n fmin = 1;\n fmax = 250;\n numfreqs = 70;\n fstep = 0.75;\n % Calculate center frequencies\n temp1 = (0:numfreqs-1) * fstep;\n temp2 = logspace(log10(fmin), log10(fmax), numfreqs);\n temp2 = (temp2-temp2(1)) * ((temp2(end)-temp1(end)) / temp2(end)) + temp2(1);\n chirp_center_high = temp1 + temp2;\n % Delete the frequencies that are too high for the sampling frequency\n chirp_center_high(chirp_center_high >= sRate/3) = [];\n % Calculate chirplets\n [chirpF_high, Freqs] = bst_chirplet(sRate, nTime, chirp_center_high);\n\n % ===== INITIALIZE RETURNED VARIABLES =====\n % Generate epoch indices\n iEpochTime = round(EpochTime(1)*sRate):round(EpochTime(2)*sRate);\n if isempty(iEpochTime)\n errMsg = 'Invalid epoch time';\n end\n % Output time vector\n TimeOut = iEpochTime / sRate;\n % Initialize returned variable\n TF = zeros(size(F,1), length(TimeOut), length(chirp_center_high));\n ERP = zeros(size(F,1), length(TimeOut));\n\n % ===== FFT OF SIGNALS =====\n % Transform sensor time series into analytic signals\n F_fft = fft(F, length(Freqs), 2);\n % This step scales analytic signal such that: real(analytic_signal) = raw_signal\n % but note that analytic signal energy is double that of raw signal energy\n F_fft(:,Freqs<0) = 0;\n F_fft(:,Freqs>0) = 2 * F_fft(:,Freqs>0);\n\n % ===== LOOP ON SIGNALS =====\n for iSource = 1:size(F,1)\n % === DETECT MIN/MAX LOW FREQ ===\n % Calculate one chirplet for the low frequency\n [chirpF_low, Freqs] = bst_chirplet(sRate, nTime, lowfreq(iSource));\n % Filter again: Positive version of the signal\n fs_low = bst_freqfilter(F(iSource,:), chirpF_low, Freqs);\n % Detection of phase maxima of theta filtered signal (POSITIVE)\n [tmp, iMaxTheta] = find_maxima(angle(fs_low));\n\n % === FILTER GAMMA ===\n % Filter source signal using all the low-frequency chirplet\n fs_high = bst_freqfilter(F(iSource,:), chirpF_high, Freqs, F_fft(iSource,:));\n % Magnitude\n fs_high = abs(fs_high);\n % Zscore normalization\n fs_high = process_baseline_norm('Compute', fs_high, fs_high, 'zscore');\n\n % === EPOCH ===\n % Makes sure all triggers allow full epoch\n iMaxTheta(iMaxTheta <= abs(iEpochTime(1))) = [];\n iMaxTheta(iMaxTheta >= nTime - iEpochTime(end)) = [];\n % Loop on every peak of theta\n for i = 1:length(iMaxTheta)\n % Find epoch indices\n iTime = iMaxTheta(i) + iEpochTime;\n % Phase-triggered ERP of raw signal\n ERP(iSource,:) = ERP(iSource,:) + F(iSource, iTime) ./ length(iMaxTheta);\n % Phase-triggered time-frequency amplitude values (normalized)\n TF(iSource,:,:) = TF(iSource,:,:) + fs_high(1,iTime,:) ./ length(iMaxTheta);\n end\n end\nend\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_canoltymap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17612673957284203}} {"text": "% readneurolocs() - read neuroscan polar location file (.asc)\n%\n% Usage:\n% >> CHANLOCS = readneurolocs( filename );\n% >> CHANLOCS = readneurolocs( filename, method, 'key1', val1, ...);\n%\n% Inputs:\n% filename - file name or matlab cell array { names x_coord y_coord }\n% method - [1 2, 3, 4 or 5] different import methods\n%\n% Optional inputs:\n% same as caliblocs()\n% note that if no optional input are provided, re-centering will be\n% performed automatically and re-scaling of coordinates will be\n% performed for '.asc' files (not '.dat' files).\n%\n% Outputs:\n% CHANLOCS - EEGLAB channel location data structure. See\n% help readlocs()\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 4 March 2003\n%\n% See also: readlocs()\n\n% Copyright (C) 2003 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction chanlocs = readneurolocs( filename, method, varargin)\n\nif nargin < 1\n help readneurolocs;\n return;\nend\nif nargin < 2\n plottag = 0;\nend\n\nif nargin < 2\n disp('There are 5 methods to import Neuroscan files, if one does not work, try others')\n try\n chanlocs = readneurolocs( filename, 1);\n return\n catch\n disp('Import method 1 failed, trying method 2');\n try\n chanlocs = readneurolocs( filename, 2);\n return\n catch\n disp('Import method 2 failed, trying method 3');\n try\n chanlocs = readneurolocs( filename, 3);\n return\n catch\n disp('Import method 3 failed, trying method 4');\n try\n chanlocs = readneurolocs( filename, 4);\n return\n catch\n disp('Import method 3 failed, trying method 5');\n try\n chanlocs = readneurolocs( filename, 5);\n return\n catch\n error('No import method worked');\n end\n end\n end\n end\n end\nend\n\n% try new method\nif method == 1\n locs = readtable(filename, 'filetype', 'text', 'Delimiter', { ';' ' ' '\\t' }, 'ConsecutiveDelimitersRule', 'join');\n locs = table2cell(locs);\n\n if mod(size(locs,1),2) == 1\n error('Issue with file format')\n end\n halfHeight = size(locs,1)/2;\n loc1 = locs(1:halfHeight,:);\n loc2 = locs(halfHeight+1:end,:);\n x = [loc2{:,3}]; x = x-0.5;\n y = [loc2{:,4}]; y = y-0.5;\n radius = sqrt(x.^2 + y.^2);\n theta = atan2d(x, y);\n\n for iChan = 1:halfHeight\n chanlocs(iChan).label = loc1{iChan,2};\n chanlocs(iChan).theta = theta(iChan);\n chanlocs(iChan).radius = radius(iChan);\n end\n chanlocs = convertlocs( chanlocs, 'topo2all');\n return\nelseif method == 2\n % read location file\n % ------------------\n if ischar(filename)\n locs = loadtxt( filename, 'delim', 9 );\n end\n\n if ~ischar(filename) || locs{1,1}(1) == ';' || size(locs,2) < 5\n if ~ischar(filename)\n names = filename{1};\n x = filename{2};\n y = filename{3};\n else\n if locs{1,1}(1) == ';'\n % remove trailing control channels\n % --------------------------------\n while isnumeric( locs{end,1} ) & locs{end,1} ~= 0\n locs = locs(1:end-1,:);\n end\n\n % find first numerical index\n % --------------------------\n index = 1;\n while ischar( locs{index,1} ) && index < size(locs,1)\n index = index + 1;\n end\n\n % extract location array\n % ----------------------\n nchans = size( locs, 1 ) - index +1;\n chans = [locs{end-nchans+1:end, 1:5}];\n chans = reshape(chans,nchans,5); %% Added this line in order to get x = chans(:,3)\n names = locs(end-nchans*2+1: end-nchans, 2);\n for index = 1:length(names)\n if ~ischar(names{index})\n names{index} = int2str(names{index});\n end\n end\n x = chans(:,3);\n y = -chans(:,4);\n else\n [tmp2 tmpind] = sort( [ locs{:,1} ]);\n locs = locs(tmpind,:);\n y = [ locs{:,end} ];\n x = [ locs{:,end-1} ];\n x = x/513.1617*44;\n y = y/513.1617*44;\n names = locs(:,end-2);\n end\n end\n\n % second solution using angle\n % ---------------------------\n [phi,theta] = cart2pol(x, y);\n phi = phi/pi*180;\n\n % convert to other types of coordinates\n % -------------------------------------\n labels = names';\n labels = cellfun(@num2str, labels, 'UniformOutput', false);\n chanlocs = struct('labels', labels', 'sph_theta_besa', mattocell(theta)', 'sph_phi_besa', mattocell(phi)'); %% labels instead of labels(:)\n chanlocs = convertlocs( chanlocs, 'sphbesa2all');\n\n for index = 1:length(chanlocs)\n chanlocs(index).labels = num2str(chanlocs(index).labels);\n end\n\n % re-calibration\n % --------------\n chanlocs = adjustlocs(chanlocs, 'autoscale', 'on', 'autorotate', 'off', varargin{:});\n end\nelseif method == 3\n chanlocs = readneurodat( filename);\nelseif method == 4\n % read location file\n % ------------------\n if ischar(filename)\n locs = loadtxt( filename, 'delim', [9 ' ']);\n end\n\n if size(locs,2) == 5\n % 5 rows, xyz positions\n for index = 1:size(locs,1)\n locs{index,3} = - locs{index,3};\n end\n chanlocs = struct('labels', locs(:,1), 'type', locs(:,2), 'X', locs(:,4), 'Y', locs(:,3), 'Z', locs(:,5));\n chanlocs = convertlocs( chanlocs, 'cart2all');\n elseif size(locs,2) == 4\n chanlocs = readlocs(filename, 'filetype', 'custom', 'format', { 'labels' '-Y' 'X' 'Z' });\n end\nelseif method == 5\n chanlocs = readlocs(filename, 'filetype', 'custom', 'format', { 'labels' 'ignore' '-Y' 'X' 'Z' });\nend\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/readneurolocs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.1760155003012239}} {"text": "clear; clc;\n\naddpath(genpath('../libs/exportFig'));\naddpath(genpath('../libs/fun4MeanShift'));\naddpath(genpath('../libs/layerExt'));\naddpath(genpath('../libs/layerExt'));\npath_to_matconvnet = '../libs/matconvnet-1.0-beta23_modifiedDagnn';\nrun(fullfile(path_to_matconvnet, 'matlab', 'vl_setupnn'));\naddpath(genpath(fullfile('dependencies', 'matconvnet','examples')));\n%% read matconvnet model\nload('imdb_complete_on_server.mat');\nimdb.meta.meanvalue = reshape(imdb.meta.meanvalue,[1 1 3]);\n\n% set GPU\ngpuId = 1;\ngpuDevice(gpuId);\n\nmodelName = 'basemodel_resnet101_div4_loopNum0.mat';\nnetbasemodel = load( fullfile('./basemodel', modelName) );\nnetbasemodel = dagnn.DagNN.loadobj(netbasemodel);\nnetbasemodel.move('gpu') ;\n\nnetbasemodel.removeLayer('obj_MM');\nnetbasemodel.removeLayer('obj_reg');\nnetbasemodel.removeLayer('output_cosSim');\nnetbasemodel.removeLayer('output_l2norm');\n\n%netbasemodel.mode = 'test' ;\nnetbasemodel.mode = 'normal' ;\nnet.conserveMemory = 1;\nsName = 'res9_conv';\n\nlName = 'output_l2norm';\nnetbasemodel.addLayer(lName, L2normalization(), sName, lName) ;\nsName = lName;\noutputIdx_l2norm = netbasemodel.layers(netbasemodel.getLayerIndex('output_l2norm')).outputIndexes;\nnetbasemodel.vars(outputIdx_l2norm).precious = 1;\n\nloopNum = 16; % let it loop and visualize the intermediate results\npredInstanceMaskMat_loop0 = cell(1,3);\npredInstanceMaskMat_loops = cell(loopNum,3);\n\nsName_l2norm = lName;\nfor loopIdx = 1:loopNum\n [netbasemodel, sName, sName_l2norm] = addOneLoop_forMeanShiftGrouping(netbasemodel, sName_l2norm, loopIdx);\n\n keepLayerName = sprintf('loop%d_meanshift_S_is_XX', loopIdx);\n netbasemodel.layers(netbasemodel.getLayerIndex(keepLayerName)).block.analyzeGradient = false;\n\n keepLayerName = sprintf('loop%d_meanshift_Y_l2norm', loopIdx);\n netbasemodel.vars(netbasemodel.layers(netbasemodel.getLayerIndex(keepLayerName)).outputIndexes).precious = 1;\n\n rmLayerName = sprintf('loop%d_meanshift_cosSim', loopIdx);\n netbasemodel.removeLayer(rmLayerName); % remove layer\nend\n%% visualize single image\nprefix4saving = './results/'; % all visual results are saved here\nif ~isdir(prefix4saving)\n mkdir(prefix4saving);\nend\npath_to_image = './images/';\nimgList = dir(fullfile(path_to_image, '*jpg'));\nfor idx = 1:length(imgList)\n fprintf('%d %s\\n', idx, imgList(idx).name)\n cur_path_to_image = fullfile(path_to_image, imgList(idx).name);\n imgOrg = imread(cur_path_to_image);\n \n [~,curFileName,curFileExt] = fileparts(cur_path_to_image); \n cur_path_to_annot = fullfile(path_to_image, [curFileName,'.mat']);\n cur_segMap = load(cur_path_to_annot);\n cur_instMap = cur_segMap.gtMat.instMap;\n cur_segMap = cur_segMap.gtMat.segMap; \n gtOrg = cur_instMap;\n \n sz = size(gtOrg);\n reSZ = round(sz/8)*8;\n \n img = imresize(imgOrg, reSZ);\n im = bsxfun(@minus, single(img), imdb.meta.meanvalue) ;\n inputs = {'data', gpuArray(single(im))};\n \n netbasemodel.eval(inputs) ;\n %% gather result\n feaMap = gather(netbasemodel.vars(outputIdx_l2norm).value);\n feaMapSize = size(feaMap);\n predInstanceMaskMat_loop0{1} = reshape(feaMap, [], size(feaMap,3));\n rng(777); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loop0{1} = predInstanceMaskMat_loop0{1}*randProj;\n predInstanceMaskMat_loop0{1} = reshape( predInstanceMaskMat_loop0{1}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loop0{1} = rescaleFeaMap(predInstanceMaskMat_loop0{1});\n predInstanceMaskMat_loop0{1} = imresize(predInstanceMaskMat_loop0{1}, [sz(1),sz(2)]);\n \n rng(77); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loop0{2} = reshape(feaMap, [], size(feaMap,3));\n predInstanceMaskMat_loop0{2} = predInstanceMaskMat_loop0{2}*randProj;\n predInstanceMaskMat_loop0{2} = reshape( predInstanceMaskMat_loop0{2}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loop0{2} = rescaleFeaMap(predInstanceMaskMat_loop0{2});\n predInstanceMaskMat_loop0{2} = imresize(predInstanceMaskMat_loop0{2}, [sz(1),sz(2)]);\n \n rng(7); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loop0{3} = reshape(feaMap, [], size(feaMap,3));\n predInstanceMaskMat_loop0{3} = predInstanceMaskMat_loop0{3}*randProj;\n predInstanceMaskMat_loop0{3} = reshape( predInstanceMaskMat_loop0{3}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loop0{3} = rescaleFeaMap(predInstanceMaskMat_loop0{3});\n predInstanceMaskMat_loop0{3} = imresize(predInstanceMaskMat_loop0{3}, [sz(1),sz(2)]);\n \n for loopidx = 1:loopNum\n keepLayerName = sprintf('loop%d_meanshift_Y_l2norm', loopIdx);\n keepLayerName = netbasemodel.layers(netbasemodel.getLayerIndex(keepLayerName)).outputIndexes;\n feaMap = gather(netbasemodel.vars(keepLayerName).value);\n feaMapSize = size(feaMap);\n predInstanceMaskMat_loops{loopidx,1} = reshape(feaMap, [], size(feaMap,3));\n rng(777); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loops{loopidx,1} = predInstanceMaskMat_loops{loopidx,1}*randProj;\n predInstanceMaskMat_loops{loopidx,1} = reshape( predInstanceMaskMat_loops{loopidx,1}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loops{loopidx,1} = rescaleFeaMap(predInstanceMaskMat_loops{1});\n predInstanceMaskMat_loops{loopidx,1} = imresize(predInstanceMaskMat_loops{loopidx,1}, [sz(1),sz(2)]);\n \n rng(77); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loops{loopidx,2} = reshape(feaMap, [], size(feaMap,3));\n predInstanceMaskMat_loops{loopidx,2} = predInstanceMaskMat_loops{loopidx,2}*randProj;\n predInstanceMaskMat_loops{loopidx,2} = reshape( predInstanceMaskMat_loops{loopidx,2}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loops{loopidx,2} = rescaleFeaMap(predInstanceMaskMat_loops{loopidx,2});\n predInstanceMaskMat_loops{loopidx,2} = imresize(predInstanceMaskMat_loops{loopidx,2}, [sz(1),sz(2)]);\n \n rng(7); randProj = randn(feaMapSize(3), 3);\n predInstanceMaskMat_loops{loopidx,3} = reshape(feaMap, [], size(feaMap,3));\n predInstanceMaskMat_loops{loopidx,3} = predInstanceMaskMat_loops{loopidx,3}*randProj;\n predInstanceMaskMat_loops{loopidx,3} = reshape( predInstanceMaskMat_loops{loopidx,3}, [feaMapSize(1), feaMapSize(2), 3] );\n predInstanceMaskMat_loops{loopidx,3} = rescaleFeaMap(predInstanceMaskMat_loops{loopidx,3});\n predInstanceMaskMat_loops{loopidx,3} = imresize(predInstanceMaskMat_loops{loopidx,3}, [sz(1),sz(2)]);\n end\n \n %% show figures\n imgFig = figure(1);\n set(imgFig, 'Position', [100 100 1500 800]) % [1 1 width height]\n subplot(2,3,1);\n imshow(uint8(img)); title('original image');\n subplot(2,3,2);\n imagesc(gtOrg); axis off image; title('instance mask');\n subplot(2,3,4);\n imagesc(predInstanceMaskMat_loop0{1}); axis off image; title('Loop-0 randProj 3-dim')\n subplot(2,3,5);\n imagesc(predInstanceMaskMat_loop0{2}); axis off image; title('Loop-0 randProj 3-dim')\n subplot(2,3,6);\n imagesc(predInstanceMaskMat_loop0{3}); axis off image; title('Loop-0 randProj 3-dim')\n export_fig(sprintf('%s/id%d_summary.jpg', prefix4saving, idx));\n \n imgFig3 = figure(2);\n set(imgFig3, 'Position', [100 100 1000 1000]) % [1 1 width height]\n winH = 4;\n winW = 3;\n curWinIdx = 1;\n for loopidx = 1:5:loopNum\n subplot(winH,winW,curWinIdx); curWinIdx = curWinIdx + 1;\n imagesc(predInstanceMaskMat_loops{loopidx,1}); axis off image; title(sprintf('Loop-%d randProj (3-dim)',loopidx))\n subplot(winH,winW,curWinIdx); curWinIdx = curWinIdx + 1;\n imagesc(predInstanceMaskMat_loops{loopidx,2}); axis off image; title(sprintf('Loop-%d randProj (3-dim)',loopidx))\n subplot(winH,winW,curWinIdx); curWinIdx = curWinIdx + 1;\n imagesc(predInstanceMaskMat_loops{loopidx,3}); axis off image; title(sprintf('Loop-%d randProj (3-dim)',loopidx))\n end\n export_fig(sprintf('%s/id%d_summaryLoops.jpg', prefix4saving, idx)); \nend\n%% leaving blank\n", "meta": {"author": "aimerykong", "repo": "Recurrent-Pixel-Embedding-for-Instance-Grouping", "sha": "748ade6b969c7861c2a9009cd0f0ffb27004677c", "save_path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping", "path": "github-repos/MATLAB/aimerykong-Recurrent-Pixel-Embedding-for-Instance-Grouping/Recurrent-Pixel-Embedding-for-Instance-Grouping-748ade6b969c7861c2a9009cd0f0ffb27004677c/demo3_objectness_proposal_detection/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.1760154967563854}} {"text": "function [F,TimeVector] = in_fread_fif(sFile, iEpoch, SamplesBounds, iChannels)\n% IN_READ_FIF: Read a block of recordings from a FIF file\n%\n% USAGE: [F,TimeVector] = in_fread_fif(sFile, iEpoch, SamplesBounds, iChannels)\n% [F,TimeVector] = in_fread_fif(sFile, iEpoch, SamplesBounds) : Read all the channels\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2009-2019\n\nif (nargin < 4)\n iChannels = [];\nend\n\n% Epoched data\n% if isempty(SamplesBounds) || ~isfield(sFile.header, 'raw') || isempty(sFile.header.raw)\nif ~isfield(sFile.header, 'raw') || isempty(sFile.header.raw)\n % Use data already read\n if isfield(sFile.header, 'epochData') && ~isempty(sFile.header.epochData)\n F = permute(sFile.header.epochData(iEpoch,:,:), [2,3,1]);\n TimeVector = linspace(sFile.epochs(iEpoch).times(1), sFile.epochs(iEpoch).times(2), size(F,2));\n % Read data from file\n else\n sfid = fopen(sFile.filename, 'r', sFile.byteorder);\n [F, TimeVector] = fif_read_evoked(sFile, sfid, iEpoch);\n fclose(sfid);\n end\n % Specific selection of channels\n if ~isempty(iChannels)\n F = F(iChannels, :);\n end\n % Specific time selection\n if ~isempty(SamplesBounds)\n iTime = SamplesBounds - round(sFile.epochs(iEpoch).times(1) .* sFile.prop.sfreq) + 1;\n F = F(:, iTime(1):iTime(2));\n TimeVector = TimeVector(iTime(1):iTime(2));\n end\n % Calibration matrix\n Calibration = diag([sFile.header.info.chs.cal]);\n% Raw data\nelse\n % If time not specified, read the entire file\n if isempty(SamplesBounds)\n % Multiple files\n if isfield(sFile.header, 'fif_headers') && (length(sFile.header.fif_headers) > 1)\n SamplesBounds = [sFile.header.fif_headers{1}.raw.first_samp, sFile.header.fif_headers{end}.raw.last_samp];\n % Single file\n else\n SamplesBounds = [sFile.header.raw.first_samp, sFile.header.raw.last_samp];\n end\n end\n % If there are multiple FIF files: check in which one the data should be read\n if isfield(sFile.header, 'fif_list') && isfield(sFile.header, 'fif_times') && (length(sFile.header.fif_list) >= 2)\n % Check if all the samples are gathered from the same file\n fif_samples = round(sFile.header.fif_times .* sFile.prop.sfreq);\n iFile = find((SamplesBounds(1) >= fif_samples(:,1)) & (SamplesBounds(2) <= fif_samples(:,2)));\n % If this requires reading multiple files, call this function recursively\n if isempty(iFile)\n F = [];\n TimeVector = [];\n % Select the files to read from\n iFileStart = find((SamplesBounds(1) >= fif_samples(:,1)) & (SamplesBounds(1) <= fif_samples(:,2)));\n iFileStop = find((SamplesBounds(2) >= fif_samples(:,1)) & (SamplesBounds(2) <= fif_samples(:,2)));\n for iFile = iFileStart:iFileStop\n % Create local structures for this file\n sFile_i = sFile;\n sFile_i.header = sFile.header.fif_headers{iFile};\n % Read the samples available in this file\n SamplesBounds_i = [max(min(SamplesBounds(1), fif_samples(iFile,2)), fif_samples(iFile,1)), ...\n max(min(SamplesBounds(2), fif_samples(iFile,2)), fif_samples(iFile,1))];\n [F_i,TimeVector_i] = in_fread_fif(sFile, iEpoch, SamplesBounds_i, iChannels);\n % Concatenate with previous files\n F = [F, F_i];\n TimeVector = [TimeVector, TimeVector_i];\n end\n return;\n else\n FifFile = sFile.header.fif_list{iFile(1)};\n sFile.header = sFile.header.fif_headers{iFile};\n end\n else\n FifFile = sFile.filename;\n end\n % Read block of data\n sfid = fopen(FifFile, 'r', sFile.byteorder);\n [F, TimeVector] = fif_read_raw_segment(sFile, sfid, SamplesBounds, iChannels);\n fclose(sfid);\n % Calibration matrix\n Calibration = diag([sFile.header.info.chs.range] .* [sFile.header.info.chs.cal]);\nend\n\n% Apply calibration\nif ~isempty(iChannels)\n F = Calibration(iChannels,iChannels) * F;\nelse\n F = Calibration * F;\nend\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_fif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.17589391641260146}} {"text": "%%***********************************************************************\n%% validate: validate data\n%%\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%***********************************************************************\n\n function [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": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sdpt3/Solver/validate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.1758939058936961}} {"text": "function AutoClustering(fbasename,elec,varargin)\n\n% USAGE:\n% clu = AutoClustering(fbasename,elec)\n% \n% AutoClustering automtically cleans the clu file defined by fbasename and\n% electrode numbers. The program will look for the files\n% fbasename.fet/res/spk.elec in the current folder.\n% \n% INPUT:\n% fbasename: char array\n% elec: a vector of electrode numbers\n%\n% optional:\n% AutoClustering(fbasename,elec,dim)\n% where dim is the number of channels in electro group (if not\n% defined, will read the first line of the fet file\n% \n% AutoClustering is meant to clean the output of KlustaKwik. The first\n% thing it does is to separate electrical artifacts and MUA from putative\n% isolated units. To do so, it sorts out units which have no clear\n% refractory period (based on Hill, Mehta and Kleinfeld, J Neurosci.,\n% 2012). Threshold can be set in the parameter section of this file\n% (\"Rogue spike threshold\"). Then, it separates electrical\n% artifats from MUA based on the assumption that electrical artifacts are\n% highly correlated on thel different channels: the average waveform of at\n% least one channel has to be different from the across-channel average\n% waveform by a certrain amount of total variance (can be set in the\n% parameter section, \"Deviation from average spike threshold\")\n%\n% Once the program has determined which of the clusters are putative\n% isolated units, it tries to merge them based on waveform similarity\n% (mahalanobis distance) and quality of the refractory period in the new\n% merged cluster (or \"Inter Common Spike Interval\" from MS Fee et al. J \n% Neurosci. Meth., 1996)\n%\n% Adrien Peyrache, 2012\n% David Tingley, 2017 updated for Intan system and new functionality\n\n% The default behavior of this program is to take the output from KlustaKwik \n% or the newer klusta-3.0 (.kwik) algorithms, organize this data for easier \n% manual cluster cutting, and save to the klusta-3.0 (.kwik) format\n\nif ~isempty(dir('*kwik'))\n if nargin < 1 \n basepath = pwd;\n name = dir('*alg*');\n s = split(name.name,'.');\n fbasename = s{1};\n elec = str2num(s{end});\n end\n \ndbstop if error\n% Parameters\n% Number recording sites\nif ~isempty(varargin)\n dim = varargin{1};\n dim = dim(:);\n if any(double(int16(dim))~=dim)\n error('Number of dimensions must be an integer')\n end\n if size(dim,1) ~= length(elec) && length(dim) ~=1\n error('Number of dimensions must be a vector of the same length as electrode vecotr or a single value')\n end\n if length(dim) == 1\n dim = dim*ones(length(elec),1);\n end\nelse\n dim = zeros(length(elec),1);\nend\n\n% an ugly list of heuristics that should eventually be cleaned up...\n\nsamplingRate = 20000;\n% Load spike waveforms? Used for detection of electrical artifacts\nloadspk = 0;\n% Refractory period in msec\ntR = 1.5./1000;\n% Censored period in msec (specific to the spike detection process)\ntC = 0.01./1000;\n% Rogue spike threshold (for MUA); value between 0 an 1\nrogThres = 1.5;\n% Relative deviation (from 0 to 1) from average spike threshold (for electrical artifacts)\n% =1000 => bypass it\ndevMinThres = .3;\ndevMaxThres = 10;\n\n% other arbitrary thresholds..\npowThresh = .85;\nisoMinTresh = 1;\nlratioMinThresh = 10e-5;\nisoMaxTresh = 2000;\nlratioMaxThresh = 1000;\n\n% Do Merging?\ndoMerge = 1;\n% overwrite clu file\nrewriteclu= 1;\n% Write a log file?\nWriteLogFile = 1;\n\nif WriteLogFile\n tic;\n log = [];\nend\n\nelec = elec(:)';\nif length(elec)>1\n for eIx=1:length(elec)\n AutoClustering(fbasename,elec(eIx),dim(eIx));\n end\nelse\n % Load fet, clu, res, and waveforms\n fprintf('Sorting electrode %i of %s\\n',elec,fbasename)\n if 1 %~exist([fbasename '_sh' num2str(elec) '.res.' num2str(elec)]) & ~exist([fbasename '.res.' num2str(elec)])\n if exist([fbasename '_sh' num2str(elec) '.kwik']) > 0\n tkwik = fullfile(pwd,[fbasename '_sh' num2str(elec) '.kwik']);\n cd ..; basepath = pwd; cd(num2str(elec));\n else\n tkwik = fullfile(pwd,num2str(elec),[fbasename '_sh' num2str(elec) '.kwik']);\n basepath = pwd; \n end\n kwikinfo = h5info(tkwik,['/channel_groups/' num2str(elec) '/clusters/original']);\n if ~loadspk\n [fet clu res ~] = ConvertKlusta2Matlab(elec,basepath,fbasename,0,0,1);\n elseif loadspk \n [fet clu res wav] = ConvertKlusta2Matlab(elec,basepath,fbasename,1,0,1);\n end\n clu_orig = clu;\n clu = double(clu);\n cluster_names = unique(clu);\n else\n error('check the below code for compatibility...')\n fet = LoadFeatures(fbasename,elec,dim);\n clu = load([fbasename '.clu.' num2str(elec)]);\n clu = clu(2:end);\n res = load([fbasename '.res.' num2str(elec)])/20;\n if loadspk\n wav = LoadSpikeWaveforms([fbasename '.spk.' num2str(elec)],dim,32);\n end\n end\n \n %Power of each waveform - UNUSED so far\n% pw = sqrt(sum(sum(wav.^2,2),3));\n % Percentile of the power\n% p = prctile(pw,0.99);\n nFeats = size(fet,2); % to calculate accurate stats, we should have more rows than features for all cells\n \n % devFromMean quantifies how much the spike are different on\n % the different channels (what is the maximal distance from the averaged\n % spike)\n\n for ii=1:length(cluster_names)\n rg = double(res(clu==cluster_names(ii)))./samplingRate;\n if loadspk\n m = squeeze(mean(wav(clu==cluster_names(ii),:,:)));\n y = pdist(m,'euclidean')./max(sqrt(sum(m.^2,2)));\n devFromMean(ii) = max(y);\n end\n fractRogue(ii) = FractionRogueSpk(rg,tR,tC); \n% meanPw(ii) = nanmean(pw(clu==cluster_names(ii)))/nanmean(pw); \n end\n if loadspk\n ff = find([devFromMean < devMinThres |...\n devFromMean > devMaxThres]); % enforces variability across channels (muscle)\n else\n ff = [];\n end\n \n fff = find([fractRogue > rogThres]); % enforces refractory period \n\n for ii=1:length(cluster_names)\n if length(find(clu==cluster_names(ii))) > nFeats\n [L(ii) LRatio(ii)] = L_Ratio(fet,find(clu==cluster_names(ii)));\n iso(ii) = IsolationDistance(fet,find(clu==cluster_names(ii)));\n else\n L(ii)=nan;LRatio(ii)=nan;iso(ii)=nan; % not enough spikes to quantify anything...\n end\n end\n % Here let's toss out clusters that are clearly muscle/electrical\n % we have: fractRogue, devFromMean, LRatio, and iso to use\n f = find([LRatio lratioMaxThresh &...\n iso < isoMinTresh |...\n iso > isoMaxTresh]); % finds large artefacts \n noiseIx = find(ismember(clu,cluster_names(unique([f,ff,fff]))));\n\n \n % takes all muscle/electrical artefact and merges to a single\n % garbage cluster\n badCluIdx = unique(clu(noiseIx));\n for ii=1:length(badCluIdx)\n log = [log sprintf('%d -> %d; Looks like muscle or electrical artifact\\n',badCluIdx(ii),0)];\n end\n clu(noiseIx) = 0;\n cluster_names = unique(clu);\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Display intermediary results\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if 0\n for i=1:length(cluster_names)\n subplot(2,2,1)\n m = squeeze(mean(wav(clu==cluster_names(i),:,:)));\n plot(m'); title(['Deviation from mean wf: ' num2str(devFromMean(i))])\n subplot(2,2,2)\n rg = double(res(clu==cluster_names(i)))./samplingRate;\n dt = diff(rg);\n hist(dt(dt<.1),1000); title(['Fraction Rogue: ' num2str(fractRogue(i))]);\n subplot(2,2,3)\n title(['L-Ratio: ' num2str(LRatio(i)) ' IsoDist: ' num2str(iso(i))])\n subplot(2,2,4)\n if ismember(cluster_names(i),unique(clu(noiseIx)))\n title('tossing');\n else\n title('keeping');\n end\n% title(num2str(d(:,i)'))\n pause\n end\n end\n \n %reorder clusters here\n [clu log] = renumberclu(clu,log);\n \n % Here we select only clusters that correspond to putative units and that\n % have at least 20 spikes (otherwise errormatrix calculation fails)\n h = hist(clu,length(unique(clu)))';\n goodCluIx = ismember(clu,find(cluster_names < 1000 & h>nFeats)); \n goodCluIx(noiseIx) = 0;\n \n if length(unique(clu(goodCluIx)))>1 % if we have more than one putative cluster...\n newclu = clu(goodCluIx);\n newres = res(goodCluIx);\n newfet = fet(goodCluIx,:);\n if doMerge % merge similar clusters which are neither noise nor MUA\n try\n [newclu mergehistory] = mergeclu_slow(newclu,newres,newfet,tR,tC,rogThres,samplingRate);\n % log changes\n log = [log sprintf('merge_slow.m was run\\n')];\n for ii=1:size(mergehistory,1)\n log = [log sprintf('%d + %d -> %d\\n',mergehistory(ii,1),mergehistory(ii,2),mergehistory(ii,3))];\n end\n catch\n warning(['merging failed: ' lasterr])\n end \n else % if we're not going to try merging, the resort clusters by similarity\n em = errormatrix(fet(goodCluIx,:),newclu);\n ems = max(em,em'); \n y = squareform((1-ems)-diag(diag(1-ems)),'tovector');\n Z = linkage(y);\n [T,perm] = dendrogram_struct(Z,0);\n cluIx = unique(newclu);\n for ii=1:length(cluIx)\n newclu = updateclu(newclu,cluIx(perm(ii)),max(cluIx)+ii+1);\n end\n end\n clu(goodCluIx) = newclu; % re-insert any merges or resorting of cluster ID's \n end \n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Display final results (requires function CrossCorr, not in the\n % toolbox)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if 0\n cluIx = unique(newclu(newclu>1));\n for x=1:length(cluIx)\n rgx = res(newclu==cluIx(x));\n [ax,b] = CrossCorr(rgx*10,rgx*10,1,60);ax(b==0)=0;\n for y=x+1:length(cluIx)\n rgy = res(newclu==cluIx(y));\n [ay,b] = CrossCorr(rgy*10,rgy*10,1,60);ay(b==0)=0;\n [fxy fcorr] = crossrefract(rgx,rgy);\n [h,b] = CrossCorr(rgx*10,rgy*10,1,60);ac(b==0)=0;\n figure(1),clf\n subplot(1,3,1)\n bar(b,ax,1)\n subplot(1,3,2)\n bar(b,h,1)\n title([fxy fcorr])\n subplot(1,3,3)\n bar(b,ay,1)\n pause\n end\n end\n end\n\n % reorder clusters here\n [clu log] = renumberclu(clu,log);\n disp(log)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Write new clu file\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if rewriteclu\n kwikinfo = h5info(tkwik,['/channel_groups/' num2str(elec) '/clusters/main']);\n kwikinfo_original = h5info(tkwik,['/channel_groups/' num2str(elec) '/clusters/original']);\n \n if length(cluster_names) > length(kwikinfo_original.Groups)\n% kwikinfo = h5info(tkwik,['/channel_groups/' num2str(elec) '/clusters/main']);\n error('we added to the number of clusters?')\n end\n % rewrite cluster ID's\n h5write(tkwik,['/channel_groups/' num2str(elec) '/spikes/clusters/main'],uint32(clu));\n \n% I need to change autoclustering to selectively delete cluster groups that no longer have units....\n % delete all old cluster gropus from /main\n% fid = H5F.open(kwikinfo.Filename,'H5F_ACC_RDWR','H5P_DEFAULT');\n% for gg = 1:length(kwikinfo.Groups)\n% H5L.delete(fid,[kwikinfo.Groups(gg).Name],'H5P_DEFAULT')\n% end\n% H5F.close(fid)\n % copy cluster groups from /original to /main for new clusters\n fid = H5F.open(tkwik,'H5F_ACC_RDWR','H5P_DEFAULT');\n for i =1:length(cluster_names) % rewrite cluster groups\n try % this may fail if something didn't get deleted... that's ok\n H5L.copy(fid,kwikinfo_original.Groups(i).Name,...\n fid,[kwikinfo.Name '/' num2str(cluster_names(i))],...\n 'H5P_DEFAULT','H5P_DEFAULT')\n catch\n disp([ num2str(cluster_names(i)) ' cluster group already exists'])\n end\n if doMerge\n h5writeatt(tkwik,['/channel_groups/' num2str(elec) '/clusters/main/'...\n num2str(cluster_names(i))],'cluster_group',3) % a human has not looked at these results, everything should be 'unsorted' (3 in .kwik format)\n end\n end\n H5F.close(fid)\n \n if exist([num2str(elec) '/nohup.out']) && exist([num2str(elec) '/' fbasename '_sh' num2str(elec) '.klg.' num2str(elec)])\n if exist([fbasename '_sh' num2str(elec) '.kwik']) > 0\n fileID = fopen('nohup.out','a');\n klgID = fopen([fbasename '_sh' num2str(elec) '.klg.' num2str(elec)],'a');\n else\n fileID = fopen([num2str(elec) '/nohup.out'],'a');\n klgID = fopen([num2str(elec) '/' fbasename '_sh' num2str(elec) '.klg.' num2str(elec)],'a');\n end\n fmt = 'this elec has been autoclustered';\n fprintf(fileID,fmt);\n fprintf(klgID,fmt);\n fclose(klgID);\n fclose(fileID); % write to both nohup and .klg. log files\n else\n klgID = fopen([fbasename '_sh' num2str(elec) '.klg.' num2str(elec)],'a');\n fmt = 'this elec has been autoclustered';\n fprintf(klgID,fmt);\n fclose(klgID);\n warning('could not find nohup.out log file')\n end\n end\n\n if WriteLogFile\n % Create (of overwrite) a log file\n fid = fopen([fbasename '.alg.' num2str(elec)],'w');\n time_tot = toc;\n fprintf(fid,[log 'That took %f seconds\\n'],time_tot);\n end\nend\n\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/preprocessing/autoClustering/AutoClustering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.17573260439903315}} {"text": "function out=bgsubtractbyhand(in,peval)\n% out=bgsubtractbyhand(in,peval.bg)\nmfprintf(peval.fid,'Background (%g) subtracted and clipped by hand.\\n',peval.bg)\nout=max(in-peval.bg,eps);", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/image_proc/bgsubtractbyhand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17568444184045473}} {"text": "function reverse_mask(inname,outname)\n% Changes 1 and greater's to 0's in an .img file, and vice versa\n% NaNs are still NaNs.\n%\n% :Usage:\n% ::\n%\n% reverse_mask(inname,outname)\n\nQ = spm_imcalc_ui(inname,outname,'abs(i1) < eps');\n\nreturn\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Image_computation_tools/reverse_mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1756844350197216}} {"text": "function [cfg] = ft_topoplotTFR(cfg, varargin)\n\n% FT_TOPOPLOTTFR plots the topographic distribution over the head\n% of a 3-dimensional data representations such as time-frequency\n% representation of the power or coherence spectrum.\n%\n% Use as\n% ft_topoplotTFR(cfg, freq)\n%\n% The input freq structrure should contain a time-resolved power or\n% coherence spectrum from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES.\n%\n% The configuration can have the following parameters\n% cfg.parameter = field that contains the data to be plotted as color, for example 'avg', 'powspctrm' or 'cohspctrm' (default is automatic)\n% cfg.maskparameter = field in the data to be used for masking of data. It should have alues between 0 and 1, where 0 corresponds to transparent.\n% cfg.xlim = limit for 1st dimension in data (e.g., time), can be 'maxmin' or [xmin xmax] (default = 'maxmin')\n% cfg.ylim = limit for 2nd dimension in data (e.g., freq), can be 'maxmin' or [ymin ymax] (default = 'maxmin')\n% cfg.zlim = limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin')\n% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details\n% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'\n% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE\n% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')\n% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')\n% cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP\n% cfg.marker = 'on', 'labels', 'numbers', 'off'\n% cfg.markersymbol = channel marker symbol (default = 'o')\n% cfg.markercolor = channel marker color (default = [0 0 0] (black))\n% cfg.markersize = channel marker size (default = 2)\n% cfg.markerfontsize = font size of channel labels (default = 8 pt)\n% cfg.highlight = 'off', 'on', 'labels', 'numbers'\n% cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION\n% cfg.highlightsymbol = highlight marker symbol (default = 'o')\n% cfg.highlightcolor = highlight marker color (default = [0 0 0] (black))\n% cfg.highlightsize = highlight marker size (default = 6)\n% cfg.highlightfontsize = highlight marker size (default = 8)\n% cfg.hotkeys = enables hotkeys (pageup/pagedown/m) for dynamic zoom and translation (ctrl+) of the color limits\n% cfg.colorbar = 'yes'\n% 'no' (default)\n% 'North' inside plot box near top\n% 'South' inside bottom\n% 'East' inside right\n% 'West' inside left\n% 'NorthOutside' outside plot box near top\n% 'SouthOutside' outside bottom\n% 'EastOutside' outside right\n% 'WestOutside' outside left\n% cfg.colorbartext = string indicating the text next to colorbar\n% cfg.interplimits = limits for interpolation (default = 'head')\n% 'electrodes' to furthest electrode\n% 'head' to edge of head\n% cfg.interpolation = 'linear','cubic','nearest','v4' (default = 'v4') see GRIDDATA\n% cfg.style = plot style (default = 'both')\n% 'straight' colormap only\n% 'contour' contour lines only\n% 'both' (default) both colormap and contour lines\n% 'fill' constant color between lines\n% 'blank' only the head shape\n% cfg.gridscale = scaling grid size (default = 67)\n% determines resolution of figure\n% cfg.shading = 'flat' or 'interp' (default = 'flat')\n% cfg.comment = 'no', 'auto' or 'xlim' (default = 'auto')\n% 'auto': date, xparam, yparam and parameter limits are printed\n% 'xlim': only xparam limits are printed\n% 'ylim': only yparam limits are printed\n% cfg.commentpos = string or two numbers, position of the comment (default = 'leftbottom')\n% 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom'\n% 'title' to place comment as title\n% 'layout' to place comment as specified for COMNT in layout\n% [x y] coordinates\n% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes')\n% In a interactive plot you can select areas and produce a new\n% interactive plot when a selected area is clicked. Multiple areas\n% can be selected by holding down the SHIFT key.\n% cfg.directionality = '', 'inflow' or 'outflow' specifies for\n% connectivity measures whether the inflow into a\n% node, or the outflow from a node is plotted. The\n% (default) behavior of this option depends on the dimor\n% of the input data (see below).\n% cfg.layout = specify the channel layout for plotting using one of\n% the supported ways (see below).\n% cfg.interpolatenan = string 'yes', 'no' (default = 'yes')\n% interpolate over channels containing NaNs\n%\n% For the plotting of directional connectivity data the cfg.directionality\n% option determines what is plotted. The default value and the supported\n% functionality depend on the dimord of the input data. If the input data\n% is of dimord 'chan_chan_XXX', the value of directionality determines\n% whether, given the reference channel(s), the columns (inflow), or rows\n% (outflow) are selected for plotting. In this situation the default is\n% 'inflow'. Note that for undirected measures, inflow and outflow should\n% give the same output. If the input data is of dimord 'chancmb_XXX', the\n% value of directionality determines whether the rows in data.labelcmb are\n% selected. With 'inflow' the rows are selected if the refchannel(s) occur in\n% the right column, with 'outflow' the rows are selected if the\n% refchannel(s) occur in the left column of the labelcmb-field. Default in\n% this case is '', which means that all rows are selected in which the\n% refchannel(s) occur. This is to robustly support linearly indexed\n% undirected connectivity metrics. In the situation where undirected\n% connectivity measures are linearly indexed, specifying 'inflow' or\n% 'outflow' can result in unexpected behavior.\n%\n% The layout defines how the channels are arranged. You can specify the\n% layout in a variety of ways:\n% - you can provide a pre-computed layout structure (see prepare_layout)\n% - you can give the name of an ascii layout file with extension *.lay\n% - you can give the name of an electrode file\n% - you can give an electrode definition, i.e. \"elec\" structure\n% - you can give a gradiometer definition, i.e. \"grad\" structure\n% If you do not specify any of these and the data structure contains an\n% electrode or gradiometer structure, that will be used for creating a\n% layout. If you want to have more fine-grained control over the layout\n% of the subplots, you should create your own layout file.\n%\n% To facilitate data-handling and distributed computing you can use\n% cfg.inputfile = ...\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. For this particular function, the input should be\n% structured as a cell-array.\n%\n% See also FT_TOPOPLOTER, FT_TOPOPLOTIC, FT_SINGLEPLOTTFR, FT_MULTIPLOTTFR, FT_PREPARE_LAYOUT\n\n% Undocumented options:\n%\n% It is possible to use multiple highlight-selections (e.g.: multiple\n% statistical clusters of channels) To do this, all the content of\n% the highlight-options (including cfg.highlight) should be placed\n% in a cell-array (even if the normal content was already in a\n% cell-array). Specific marker settings (e.g. color, size) are defaulted\n% when not present.\n%\n% Example (3 selections):\n% cfg.highlight = {'labels', 'labels', 'numbers'}\n% cfg.highlightchannel = {{'MZF03','MZC01','MRT54'}, [1:5], 'C*'}\n% cfg.highlightsymbol = {'o',[],'+'} % the empty option will be defaulted\n% cfg.highlightcolor = {'r',[0 0 1]}; % the missing option will be defaulted\n% cfg.highlightsize = []; % will be set to default, as will the missing cfg.highlightfontsize\n%\n% Other options:\n% cfg.labeloffset (offset of labels to their marker, default = 0.005)\n\n% Copyright (C) 2005-2017, F.C. Donders Centre\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DEVELOPERS NOTE: This code is organized in a similar fashion for multiplot/singleplot/topoplot\n% and for ER/TFR and should remain consistent over those 6 functions.\n% Section 1: general cfg handling that is independent from the data\n% Section 2: data handling, this also includes converting bivariate (chan_chan and chancmb) into univariate data\n% Section 3: cfg handling that depends on the data\n% Section 4: actual plotting\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Section 1: general cfg handling that is independent from the data\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 varargin\nft_preamble provenance varargin\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n return\nend\n\n% this is needed for the figure title\nif isfield(cfg, 'dataname') && ~isempty(cfg.dataname)\n dataname = cfg.dataname;\nelseif isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile)\n dataname = cfg.inputfile;\nelseif nargin>1\n dataname = arrayfun(@inputname, 2:nargin, 'UniformOutput', false);\nelse\n dataname = {};\nend\n\n% make sure figure window titles are labeled appropriately, pass this onto the actual plotting function\ncfg.funcname = mfilename;\ncfg.dataname = dataname;\n\n% prepare the layout, this should be done only once\ntmpcfg = keepfields(cfg, {'layout', 'channel', 'rows', 'columns', 'commentpos', 'skipcomnt', 'scalepos', 'skipscale', 'projection', 'viewpoint', 'rotate', 'width', 'height', 'elec', 'grad', 'opto', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ncfg.layout = ft_prepare_layout(tmpcfg, varargin{1});\n\n% call the common function that is shared between ft_topoplotER and ft_topoplotTFR\n[cfg] = topoplot_common(cfg, varargin{:});\n\n% remove this field again, it is only used for figure labels\ncfg = removefields(cfg, 'funcname');\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous varargin\nft_postamble provenance\nft_postamble savefig\n\n% add a menu to the figure, but only if the current figure does not have subplots\nmenu_fieldtrip(gcf, cfg, false);\n\nif ~ft_nargout\n % don't return anything\n clear cfg\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_topoplotTFR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1756844350197216}} {"text": "function [feat] = batch_feature(filelist, imgset, feature, c)\n%\n% Copyright Aditya Khosla http://mit.edu/khosla\n%\n% Please cite this paper if you use this code in your publication:\n% A. Khosla, J. Xiao, A. Torralba, A. Oliva\n% Memorability of Image Regions\n% Advances in Neural Information Processing Systems (NIPS) 2012\n%\n\nif(~exist('c', 'var'))\n c = conf();\nend\n\np = c.feature_config.(feature);\nif(isfield(p, 'dictionary_size') && isfield(p, 'dictionary_file'))\n\tfeature_file = sprintf(p.([imgset '_file']), c.cache, p.dictionary_size);\n\tbatch_folder = [c.cache '/' imgset '_' feature '_' num2str(p.dictionary_size) '/'];\nelse\n feature_file = sprintf(p.([imgset '_file']), c.cache);\n\tbatch_folder = [c.cache '/' imgset '_' feature '_' num2str(p.feature_size) '/'];\nend\n\nif(exist(feature_file, 'file'))\n load(feature_file);\n return;\nend\n\nnum_batches = ceil(length(filelist)/c.batch_size);\nbatch_idx = arrayfun(@(x) (x-1)*c.batch_size+1:min(x*c.batch_size, length(filelist)), 1:num_batches, 'UniformOutput', false);\nbatch_order = randperm(num_batches);\nbatch_files = cell(num_batches, 1);\n\nvprintf(c.verbosity, 0, 'Processing filelist (%s, %s): batch %d of %d\\r', imgset, feature, 0, num_batches);\nfor b=1:num_batches\n this_batch = batch_idx{batch_order(b)};\n batch_file = [batch_folder num2str(batch_order(b)) '.mat'];\n batch_files{batch_order(b)} = batch_file;\n vprintf(c.verbosity, 0, 'Processing filelist (%s, %s): batch %d of %d\\r', imgset, feature, b, num_batches);\n if(~exist(batch_file, 'file'))\n parsaveFeat(batch_file, [], []);\n poolfeat = filelist_feature('', filelist(this_batch), feature, c);\n parsaveFeat(batch_file, poolfeat, this_batch);\n end\nend\nvprintf(c.verbosity, 0, '\\n');\n\nif(nargout>0)\n feat = cell(num_batches, 1);\n for i=1:num_batches\n tmp = load(batch_files{i});\n feat{i} = tmp.poolfeat;\n end\n feat = cell2mat(feat);\nelse\n feat = {};\nend\n\nif exist('OCTAVE_VERSION','builtin')\n save(feature_file, 'feat', 'batch_files', '-v7');\nelse\n % -v7.3 is used for storing large files\n save(feature_file, 'feat', 'batch_files', '-v7.3');\nend\n", "meta": {"author": "adikhosla", "repo": "feature-extraction", "sha": "290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8", "save_path": "github-repos/MATLAB/adikhosla-feature-extraction", "path": "github-repos/MATLAB/adikhosla-feature-extraction/feature-extraction-290f3e54cfcb319ca6d1a82f8a0cea4fc31190f8/util/batch_feature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17568443160935512}} {"text": "function el = export_CT_image_module_field(args)\n%\"export_CT_image_module_field\"\n% Given a single scan, return a properly populated CT_image module tag\n% for use with any Composite Image IOD. See CT_image_module_tags.m.\n%\n% For speed, tag must be a decimal representation of the 8 digit\n% hexidecimal DICOM tag desired, ie instead of '00100010', pass\n% hex2dec('00100010');\n%\n% Arguments are passed in a structure, arg:\n% arg.tag = decimal tag of field to fill\n% arg.data = CERR structure(s) to fill from\n% arg.template = an empty template of the module created by the\n% function build_module_template.m\n%\n% This function requires arg.data = {scanInfoS, scanS};\n%\n%JRA 06/19/06\n%NAV 07/19/16 updated to dcm4che3\n% replaced ml2dcm_Element to data2dcmElement\n%\n%Usage:\n% el = export_CT_image_module_field(args)\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%Init output element to empty.\nel = [];\n\n%Unpack input parameters.\ntag = args.tag;\nscanInfoS = args.data{1};\nscanS = args.data{2};\ntemplate = args.template;\n\nswitch tag\n %Class 1 Tags -- Required, must have data.\n case 524296 %0008,0008 Image Type\n data = {'ORIGINAL', 'PRIMARY', 'AXIAL'};\n el = data2dcmElement(data, tag);\n\n case 2621442 %0028,0002 Samples per Pixel\n data = 1; %1 image plane in all CT/MR images.\n el = data2dcmElement(data, tag);\n \n case 2621444 %0028,0004 Photometric Interpretation\n data = 'MONOCHROME2'; %CT/MR have 0 black, maxVal white.\n el = data2dcmElement(data, tag);\n \n case 2621456 %0028,0010 Rows\n data = scanInfoS.sizeOfDimension1;\n el = data2dcmElement(data, tag);\n\n case 2621457 %0028,0011 Columns\n data = scanInfoS.sizeOfDimension2; \n el = data2dcmElement(data, tag);\n \n case 2621696 %0028,0100 Bits Allocated\n data = 16; %C.8.2.1.1.4 of PS 3.3 - 2006 \n el = data2dcmElement(data, tag);\n \n case 2621697 %0028,0101 Bits Stored\n %C.8.2.1.1.4 of PS 3.3 - 2006 \n %Sloppy, consider revising.\n bools = [scanS.scanInfo.zValue] == scanInfoS.zValue;\n vals = scanS.scanArray(:,:,bools);\n maxV = max(vals(:));\n log2s = log2(double(maxV));\n mostSignificantBit = floor(max(log2s)) + 1;\n data = max(mostSignificantBit, 12);\n data = min(data, 16); \n el = data2dcmElement(data, tag);\n\n case 2621698 %0028,0102 High Bit\n %C.8.2.1.1.4 of PS 3.3 - 2006 \n %Sloppy, consider revising. \n bools = [scanS.scanInfo.zValue] == scanInfoS.zValue;\n vals = scanS.scanArray(:,:,bools);\n maxV = max(vals(:));\n log2s = log2(double(maxV));\n mostSignificantBit = floor(max(log2s)) + 1;\n data = max(mostSignificantBit, 12);\n data = min(data, 16); \n data = data - 1;\n el = data2dcmElement(data, tag);\n \n case 2625618 %0028,1052 Rescale Intercept\n ctO = scanInfoS.CTOffset;\n data = -ctO; %CERR exports stored values as 1*HU + CTOffset.\n el = data2dcmElement(data, tag);\n\n case 2625619 %0028,1053 Rescale Slope\n %data = 1;\n %data = scanInfoS.rescaleSlope;\n data = args.data{3}; %APA: factor for conversion to uint16 for modalities other than CT\n bools = [scanS.scanInfo.zValue] == scanInfoS.zValue;\n data = data(bools);\n data = data(1); % handle multiple slices at same z-location\n el = data2dcmElement(data, tag);\n \n %Class 2 Tags -- Must be present, can be NULL. \n case 1572960 %0018,0060 KVP\n\n %el = org.dcm4che3.data.Attributes;\n %el.setString(tag, template.getVR(tag), template.getString(tag));\n %data = args.data{1};\n data = [];\n el = data2dcmElement(data, tag);\n \n \n case 2097170 %0020,0012 Acqusition Number\n\n %el = org.dcm4che3.data.Attributes;\n %el.setString(tag, template.getVR(tag), template.getString(tag));\n %data = args.data{1};\n data = [];\n el = data2dcmElement(data, tag);\n\n \n %Class 3 Tags -- presence is optional, currently undefined.\n case 1572898 %0018,0022 Scan Options\n case 1573008 %0018,0090 Data Collection Diameter\n case 1577216 %0018,1100 Reconstruction Diameter\n case 1577232 %0018,1110 Distance Source to Detector\n case 1577233 %0018,1111 Distance Source to Patient\n case 1577248 %0018,1120 Gantry/Detector Tilt\n case 1577264 %0018,1130 Table Height\n case 1577280 %0018,1140 Rotation Direction\n case 1577296 %0018,1150 Exposure Time\n case 1577297 %0018,1151 X-ray Tube Current\n case 1577298 %0018,1152 Exposure\n case 1577299 %0018,1153 Exposure in microAs\n case 1577312 %0018,1160 Filter Type\n case 1577328 %0018,1170 Generator Power\n case 1577360 %0018,1190 Focal Spot\n case 1577488 %0018,1210 Convolution Kernal\n case 1610501 %0018,9305 Revolution Time\n case 1610502 %0018,9306 Single Collimation Width\n case 1610503 %0018,9307 Total Collimation Width\n case 1610505 %0018,9309 Table Speed\n case 1610512 %0018,9310 Table Feed per Rotation\n case 1610513 %0018,9311 CT Pitch Factor\n case 1610531 %0018,9323 Exposure Modulation Type\n case 1610532 %0018,9324 Estimated Dose Saving\n case 1610565 %0018,9345 CTDIvol\n \n %Class 1C Tags\n \n %Class 2C Tags \n \n otherwise\n warning(['No methods exist to populate DICOM image_pixel module field ' dec2hex(tag,8) '.']);\n return;\nend", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/ML_Dicom/Export/modules/export_CT_image_module_field.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17540525341937901}} {"text": "function [orig, data] = load_curry_data_file(datafile)\n\n[PathName, FileName, Extension] = fileparts(datafile);\n\nif isempty(PathName)\n % the dataset is in the current working directory, refer to this with a .\n % to ensure proper path detection later on\n PathName = '.';\nend\n\nFileName = [FileName, Extension];\nPathName = [PathName filesep]; % add the / or \\\n\n% loads Curry dat/dap/rs3 files into MATLAB and displays their waveforms\n%{\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% ask user to specify file\nTitle = 'Open Curry Data File';\n\n[FileName,PathName,FilterIndex] = uigetfile({'*.cdt;*.dat' 'All Curry Data Files';'*.cdt' 'Curry 8 Data Files'; '*.dat' 'Curry 7 Data Files'},Title,pwd);\n\nif ( FilterIndex == 0 )\n return;\nend\n\nif ( FileName == 0 )\n msgbox('Invalid File Name',Title,'error');\n return;\nend\n%}\n\nLength = size(FileName,2);\nDataFile = [PathName,FileName];\nExtension = FileName(Length-2:Length);\n\nif ( strcmpi ( Extension,'dat' ) )\n BaseName = [PathName,FileName(1:Length-4)];\n ParameterFile = [BaseName,'.dap'];\n LabelFile = [BaseName,'.rs3'];\n EventFile = [BaseName,'.cef'];\n EventFile2 = [BaseName,'.ceo'];\nelseif ( strcmpi ( Extension,'cdt' ) )\n ParameterFile = [PathName,FileName,'.dpa'];\n LabelFile = [PathName,FileName,'.dpa'];\n EventFile = [PathName,FileName,'.cef'];\n EventFile2 = [PathName,FileName,'.ceo'];\nelse\n %msgbox('Unsupported File Name (choose a .cdt or .dat file)',Title,'error');\n error('Unsupported File Name (choose a .cdt or .dat file)');\nend\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% open parameter file\nfid = fopen_or_error(ParameterFile,'rt');\ncell = textscan(fid,'%s','whitespace','','endofline',char(167));\nfclose(fid);\ncont = cell2mat(cell{1});\n\n% check for compressed file format\nctok = 'DataGuid';\nix = strfind(cont,ctok);\nif ~isempty ( ix )\n text = sscanf(cont(ix+numel(ctok):end),' = %s'); \n if (strcmp(text, '{2912E8D8-F5C8-4E25-A8E7-A1385967DA09}') == 1)\n msgbox('Unsupported data format (compressed). Use Curry to convert this file to Raw Float format.',Title, 'error')\n return;\n end\nend\n\n% read parameters from parameter file\n% tokens (second line is for Curry 6 notation)\ntok = { 'NumSamples'; 'NumChannels'; 'NumTrials'; 'SampleFreqHz'; 'TriggerOffsetUsec'; 'DataFormat'; 'DataSampOrder'; 'SampleTimeUsec';\n 'NUM_SAMPLES';'NUM_CHANNELS';'NUM_TRIALS';'SAMPLE_FREQ_HZ';'TRIGGER_OFFSET_USEC';'DATA_FORMAT';'DATA_SAMP_ORDER'; 'SAMPLE_TIME_USEC'};\n\n% scan in cell 1 for keywords - all keywords must exist!\nnt = size(tok,1);\na = zeros(nt,1);\nfor i = 1:nt\n ctok = tok{i,1};\n ix = strfind(cont,ctok);\n if ~isempty ( ix )\n text = sscanf(cont(ix+numel(ctok):end),' = %s'); % skip =\n if strcmp ( text,'ASCII' ) || strcmp ( text,'CHAN' ) % test for alphanumeric values\n a(i) = 1;\n else \n c = sscanf(text,'%f'); % try to read a number\n if ~isempty ( c )\n a(i) = c; % assign if it was a number\n end\n end\n end \nend\n\n% derived variables. numbers (1) (2) etc are the token numbers\nnSamples = a(1)+a(1+nt/2);\nnChannels = a(2)+a(2+nt/2);\nnTrials = a(3)+a(3+nt/2);\nfFrequency = a(4)+a(4+nt/2);\nfOffsetUsec = a(5)+a(5+nt/2);\nnASCII = a(6)+a(6+nt/2);\nnMultiplex = a(7)+a(7+nt/2);\nfSampleTime = a(8)+a(8+nt/2);\n\nif ( fFrequency == 0 && fSampleTime ~= 0 )\n fFrequency = 1000000 / fSampleTime;\nend\n\n% try to guess number of samples based on datafile size\nif nSamples < 0\n if nASCII == 1\n msgbox('Number of samples cannot be guessed from ASCII data file. Use Curry to convert this file to Raw Float format.',Title,'error');\n return;\n else\n fileInfo = dir(DataFile);\n fileSize = fileInfo.bytes;\n nSamples = fileSize / (4 * nChannels * nTrials);\n end \nend\n\n%Search for Impedance Values\ntixstar = strfind(cont,'IMPEDANCE_VALUES START_LIST');\ntixstop = strfind(cont,'IMPEDANCE_VALUES END_LIST');\n\nimpedancelist = []; \nimpedancematrix = [];\n\nif (~isempty(tixstar)) && (~isempty(tixstop))\n text = cont(tixstar:tixstop-1);\n tcell = textscan(text,'%s');\n tcell = tcell{1,1};\n for tcC = 1:size(tcell,1)\n tcell{tcC} = str2num(tcell{tcC}); % data was read in as strings - force to numbers\n if ~isempty(tcell{tcC}) % skip if it is not a number\n impedancelist(end+1) = tcell{tcC};\n end\n end\n\n % Curry records last 10 impedances\n impedancematrix = reshape(impedancelist,[(size(impedancelist,2)/10),10])';\n impedancematrix(impedancematrix == -1) = NaN; % screen for missing\nend\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% open label file\nfid = fopen_or_error(LabelFile,'rt');\ncell = textscan(fid,'%s','whitespace','','endofline',char(167));\nfclose(fid);\ncont = cell2mat(cell{1});\n\n% read labels from label file\n% initialize labels\nlabels = num2cell(1:nChannels);\n\nfor i = 1:nChannels\n text = sprintf('EEG%d',i);\n labels(i) = cellstr(text);\nend\n\n% scan in cell 1 for LABELS (occurs four times per channel group)\nix = strfind(cont,[char(10),'LABELS']);\nnt = size(ix,2);\nnc = 0;\n\nfor i = 4:4:nt % loop over channel groups\n newlines = ix(i-1) + strfind(cont(ix(i-1)+1:ix(i)),char(10)); % newline\n last = nChannels - nc;\n for j = 1:min(last,size(newlines,2)-1) % loop over labels\n text = cont(newlines(j)+1:newlines(j+1)-1);\n if isempty(strfind(text,'END_LIST'))\n nc = nc + 1;\n labels(nc) = cellstr(text);\n else \n break\n end\n end \nend\n\n% read sensor locations from label file\n% initialize sensor locations\nsensorpos = zeros(3,0);\n\n% scan in cell 1 for SENSORS (occurs four times per channel group)\nix = strfind(cont,[char(10),'SENSORS']);\nnt = size(ix,2);\nnc = 0;\n\nfor i = 4:4:nt % loop over channel groups\n newlines = ix(i-1) + strfind(cont(ix(i-1)+1:ix(i)),char(10)); % newline\n last = nChannels - nc;\n for j = 1:min(last,size(newlines,2)-1) % loop over labels\n text = cont(newlines(j)+1:newlines(j+1)-1);\n if isempty(strfind(text,'END_LIST'))\n nc = nc + 1;\n tcell = textscan(text,'%f'); \n posx = tcell{1}(1);\n posy = tcell{1}(2);\n posz = tcell{1}(3);\n sensorpos = cat ( 2, sensorpos, [ posx; posy; posz ] );\n else \n break\n end\n end \nend\n\n%Search for Epoch Labels\ntixstar = strfind(cont,'EPOCH_LABELS START_LIST');\ntixstop = strfind(cont,'EPOCH_LABELS END_LIST');\n\nepochlabelslist = []; \n\nif (~isempty(tixstar)) && (~isempty(tixstop))\n text = cont(tixstar:tixstop-1);\n tcell = textscan(text,'%s', 'delimiter','\\n','whitespace','', 'headerlines', 1);\n epochlabelslist = tcell{1,1};\nend\n\n%Search for Epoch Information\ntixstar = strfind(cont,'EPOCH_INFORMATION START_LIST');\ntixstop = strfind(cont,'EPOCH_INFORMATION END_LIST');\n\nepochinformationlist = []; \n\nif (~isempty(tixstar)) && (~isempty(tixstop))\n text = cont(tixstar:tixstop-1);\n tcell = textscan(text,'%d%d%d%d%d%d%d', 'delimiter','\\n','headerlines', 1);\n epochinformationlist = cell2mat(tcell);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% read events from event file\n% initialize events\nne = 0; % number of events\nevents = zeros(4,0);\nannotations = cellstr('empty');\n\n% find appropriate file\nfid = fopen(EventFile,'rt');\n\nif fid < 0\n fid = fopen(EventFile2,'rt');\nend\n\nif fid >= 0\n cell = textscan(fid,'%s','whitespace','','endofline',char(167));\n fclose(fid);\n cont = cell2mat(cell{1});\n\n % scan in cell 1 for NUMBER_LIST (occurs five times)\n ix = strfind(cont,'NUMBER_LIST');\n \n newlines = ix(4) - 1 + strfind(cont(ix(4):ix(5)),char(10)); % newline\n last = size(newlines,2)-1;\n for j = 1:last % loop over labels\n text = cont(newlines(j)+1:newlines(j+1)-1);\n tcell = textscan(text,'%d'); \n sample = tcell{1}(1); % access more content using different columns\n type = tcell{1}(3);\n startsample = tcell{1}(5);\n endsample = tcell{1}(6);\n ne = ne + 1;\n events = cat ( 2, events, [ sample; type; startsample; endsample ] );\n end\n \n % scan in cell 1 for REMARK_LIST (occurs five times)\n ix = strfind(cont,'REMARK_LIST');\n na = 0;\n \n newlines = ix(4) - 1 + strfind(cont(ix(4):ix(5)),char(10)); % newline\n last = size(newlines,2)-1;\n for j = 1:last % loop over labels\n text = cont(newlines(j)+1:newlines(j+1)-1);\n na = na + 1;\n annotations(na) = cellstr(text);\n end \nend\n\nif nargout>1\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % read data file\n if nASCII == 1\n fid = fopen_or_error(DataFile,'rt');\n cell = textscan(fid,'%f',nChannels*nSamples*nTrials);\n fclose(fid);\n data = reshape([cell{1}],nChannels,nSamples*nTrials);\n else\n fid = fopen_or_error(DataFile,'rb');\n data = fread(fid,[nChannels,nSamples*nTrials],'float32');\n fclose(fid);\n end\n \n if nSamples*nTrials ~= size(data,2)\n msgbox('Inconsistent number of samples. File may be displayed incompletely.', 'WARNING', 'warn')\n nSamples = size(data,2)/nTrials;\n end\n % transpose?\n if nMultiplex == 1\n data = data';\n end\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% time axis\ntime = linspace(fOffsetUsec/1000,fOffsetUsec/1000+(nSamples*nTrials-1)*1000/fFrequency,nSamples*nTrials);\n\n%{\n% simple plot\nsubplot(2,1,1);\nplot(time,data); \n\n% stacked plot\nsubplot(2,1,2);\nrange = max([abs(min(min(data))) abs(max(max(data)))]);\nshift = linspace((nChannels-1)*range*0.3,0,nChannels);\nplot(time,data+repmat(shift,nSamples*nTrials,1)');\nset(gca,'ytick',flip(shift),'yticklabel',flip(labels),'GridLineStyle',':','XGrid','on','YGrid','off');\nylim([min(min(data+repmat(shift,nSamples*nTrials,1)')) max(max(data+repmat(shift,nSamples*nTrials,1)'))]);\n%}\n\n\norig = [];\norig.nSamples = nSamples;\norig.nChannels = nChannels;\norig.nTrials = nTrials;\norig.fFrequency = fFrequency;\norig.fOffsetUsec = fOffsetUsec;\norig.nASCII = nASCII;\norig.nMultiplex = nMultiplex;\norig.fSampleTime = fSampleTime;\norig.events = events;\norig.labels = labels;\norig.time = time;\norig.impedancematrix = impedancematrix;\norig.sensorpos = sensorpos;\norig.epochlabelslist = epochlabelslist;\norig.epochinformationlist = epochinformationlist;\norig.ne = ne;\norig.events = events;\norig.annotations = annotations;\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/load_curry_data_file.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.175405253419379}} {"text": "classdef PTKDicomImage < PTKImage\n % PTKDicomImage. A class for holding a 3D medical image volume.\n %\n % PTKDicomImage is inherited from the fundamental PTKImage image class \n % used by the TD MIM Toolkit. It provides additional routines and\n % metadata associated with medical imaging data, most commonly imported\n % from the DICOM standard.\n %\n % In general, you do not need to create PTKDicomImages using the\n % constructor. You should import data using function such as\n % MimLoadImageFromDicomFiles() which correctly set the metadata.\n % Thereafter, use .Copy() to make copies of the image, and .BlankCopy()\n % followed by .ChangeRawImage() to create derived images. See PTKImage.m\n % for an example of creating functions which modify images contained in\n % PTKImage classes.\n %\n %\n % Licence\n % -------\n % Part of the TD MIM Toolkit. https://github.com/tomdoel\n % Author: Tom Doel, Copyright Tom Doel 2014. www.tomdoel.com\n % Distributed under the MIT licence. Please see website for details.\n %\n \n properties (SetAccess = private)\n Modality\n RescaleSlope\n RescaleIntercept\n RescaleUnits = ''\n IsCT = false\n IsMR = false\n MetaHeader\n StudyUid\n end\n \n methods (Static)\n function new_dicom_image = CreateDicomImageFromMetadata(original_image, metadata, slice_thickness, global_origin_mm, padding_value, reporting)\n\n % Our voxel size should be equal to SpacingBetweenSlices. However, \n % some scanners incorrectly set SpacingBetweenSlices as the\n % gap between slices, instead of the centre-to-centre distance.\n % To ensure correct reconstruction interval, should really use\n % patient image Position tag (0020,0032)\n % http://www.itk.org/pipermail/insight-users/2005-September/014\n % 711.html\n voxelsize_z = slice_thickness;\n \n if ndims(original_image.RawImage) > 3\n reporting.ShowWarning('PTKDicomImage:ColourDicomImageNotSupported', 'Colour Dicom images are not supported. Converting to greyscale', []);\n original_image.RawImage = mean(original_image.RawImage, 4);\n end\n \n if isfield(metadata, 'PixelSpacing')\n voxel_size = [metadata.PixelSpacing' voxelsize_z];\n else\n reporting.ShowWarning('PTKDicomImage:NoPixelSpacing', 'Could not determine the pixel size from the image. I am assuming 1x1mm');\n voxel_size = [1 1 voxelsize_z];\n end\n \n if isfield(metadata, 'ImageOrientationPatient')\n [new_dimension_order, flip] = MimImageCoordinateUtilities.GetDimensionPermutationVectorFromDicomOrientation(metadata.ImageOrientationPatient, reporting);\n if isa(original_image, 'CoreWrapper')\n original_image.RawImage = permute(original_image.RawImage, new_dimension_order);\n for dimension_index = 1 : 3\n if flip(dimension_index)\n original_image.RawImage = flipdim(original_image.RawImage, dimension_index);\n end\n end\n else\n original_image = permute(original_image, new_dimension_order);\n for dimension_index = 1 : 3\n if flip(dimension_index)\n original_image = flipdim(original_image, dimension_index);\n end\n end\n end\n voxel_size = voxel_size(new_dimension_order);\n end\n if ~isempty(global_origin_mm)\n global_origin_mm = global_origin_mm([2 1 3]);\n end\n \n if isfield(metadata, 'RescaleSlope')\n rescale_slope = metadata.RescaleSlope;\n else\n rescale_slope = [];\n end\n \n if isfield(metadata, 'RescaleIntercept')\n rescale_intercept = metadata.RescaleIntercept;\n else\n rescale_intercept = [];\n end\n\n if isa(original_image, 'CoreWrapper')\n new_dicom_image = PTKDicomImage( ...\n original_image.RawImage, rescale_slope, rescale_intercept, voxel_size, metadata.Modality, metadata.StudyInstanceUID, metadata ...\n );\n else\n new_dicom_image = PTKDicomImage( ...\n original_image, rescale_slope, rescale_intercept, voxel_size, metadata.Modality, metadata.StudyInstanceUID, metadata ...\n );\n end\n patient_name = '';\n study_description = '';\n series_description = '';\n if isfield(metadata, 'PatientName')\n if isfield(metadata.PatientName, 'FamilyName')\n patient_name = ['', metadata.PatientName.FamilyName, ' '];\n end\n end\n if isfield(metadata, 'StudyDescription')\n study_description = ['/ ', metadata.StudyDescription, ' '];\n end\n if isfield(metadata, 'SeriesDescription')\n series_description = ['/ ', metadata.SeriesDescription, ' '];\n end\n \n new_dicom_image.Title = [patient_name, study_description, series_description];\n new_dicom_image.GlobalOrigin = global_origin_mm;\n new_dicom_image.PaddingValue = padding_value;\n end\n end\n \n methods\n % The meta_data argument is optional, and is only used for saving DICOM\n % files. Other arguments are compulsory\n function obj = PTKDicomImage(original_image, rescale_slope, rescale_intercept, voxel_size, modality, study_uid, meta_data)\n \n obj = obj@PTKImage(original_image, PTKImageType.Grayscale, voxel_size);\n \n obj.StudyUid = study_uid;\n obj.Modality = modality;\n \n if exist('meta_data', 'var')\n obj.MetaHeader = meta_data;\n end\n\n if strcmp(modality, 'CT')\n obj.IsCT = true;\n obj.RescaleSlope = rescale_slope;\n obj.RescaleIntercept = rescale_intercept;\n obj.RescaleUnits = 'HU';\n elseif strcmp(modality, 'MR') \n obj.IsMR = true;\n obj.RescaleSlope = [];\n obj.RescaleIntercept = [];\n end\n end\n \n function [value, units] = GetRescaledValue(obj, global_coords)\n if obj.IsCT && CoreCompareUtilities.CompareEnumName(obj.ImageType, PTKImageType.Grayscale)\n value = obj.GreyscaleToHounsfield(obj.GetVoxel(global_coords));\n units = obj.RescaleUnits;\n else\n [value, units] = GetRescaledValue@PTKImage(obj, global_coords);\n end\n end\n \n function units_rescaled = GrayscaleToRescaled(obj, units_greyscale)\n if obj.IsCT\n units_rescaled = obj.GreyscaleToHounsfield(units_greyscale);\n else\n units_rescaled = units_greyscale;\n end\n end\n\n function units_greyscale = RescaledToGrayscale(obj, units_rescaled)\n if obj.IsCT\n units_greyscale = obj.HounsfieldToGreyscale(units_rescaled);\n else\n units_greyscale = units_rescaled;\n end\n end\n\n function units_greyscale = HounsfieldToGreyscale(obj, units_hu)\n % Conversion from Hounsfield units to image raw intensity values:\n if obj.IsCT\n if isempty(obj.RescaleIntercept) || isempty(obj.RescaleSlope)\n units_greyscale = units_hu;\n else\n units_greyscale = (units_hu - cast(obj.RescaleIntercept, 'like', units_hu)/cast(obj.RescaleSlope, 'like', units_hu));\n end\n else\n error('The HounsfieldToGreyscale() method was called, but this is not a CT image'); \n end\n end\n \n function units_hu = GreyscaleToHounsfield(obj, units_greyscale)\n if isempty(obj.RescaleSlope) || isempty(obj.RescaleIntercept)\n units_hu = units_greyscale;\n return;\n end\n % Conversion from image raw intensity values to Hounsfield units:\n if obj.IsCT\n units_hu = int16(units_greyscale)*obj.RescaleSlope + obj.RescaleIntercept;\n else\n error('The HounsfieldToGreyscale() method was called, but this is not a CT image'); \n end\n end\n \n function units_rescaled = RescaledToGreyscale(obj, units_rescaled)\n if obj.IsCT || obj.IsMR\n units_rescaled = obj.HounsfieldToGreyscale(units_rescaled);\n else\n error('The RescaledToGreyscale() method was called, but this is not a CT or MR image'); \n end\n \n end\n\n function copy = Copy(obj)\n copy = PTKDicomImage(obj.RawImage, obj.RescaleSlope, obj.RescaleIntercept, obj.VoxelSize, obj.Modality, obj.StudyUid, obj.MetaHeader);\n metaclass = ?PTKDicomImage;\n property_list = metaclass.Properties;\n for i = 1 : length(property_list)\n property = property_list{i};\n if (~property.Dependent) && (~property.Constant)\n copy.(property.Name) = obj.(property.Name);\n end\n end\n end\n \n function copy = BlankCopy(obj)\n copy = PTKDicomImage([], obj.RescaleSlope, obj.RescaleIntercept, obj.VoxelSize, obj.Modality, obj.StudyUid, obj.MetaHeader);\n metaclass = ?PTKDicomImage;\n property_list = metaclass.Properties;\n for i = 1 : length(property_list)\n property = property_list{i};\n if (~property.Dependent) && (~property.Constant) && (~strcmp(property.Name, 'RawImage'))\n copy.(property.Name) = obj.(property.Name);\n end\n end\n end\n \n function is_equal = eq(obj, other)\n metaclass = ?PTKImage;\n property_list = metaclass.Properties;\n for i = 1 : length(property_list)\n property = property_list{i};\n if (~property.Dependent) && (~ismember(property.Name, obj.PropertiesToIgnoreOnComparison))\n if ~isequal(other.(property.Name), obj.(property.Name))\n is_equal = false;\n return;\n end\n end\n end\n is_equal = true;\n end \n end\nend\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/mim/Library/Types/PTKDicomImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.17540525223093673}} {"text": "function [bbci, data]= bbci_calibrate_NIRS(bbci, data)\n%BBCI_CALIBRATE_NIRS - Calibrate for ERP-design with NIRS\n%\n%This function is called by bbci_calibrate \n%(if BBCI.calibate.analyze_fcn is set to @bbci_calibrate_NIRS_ERP).\n%Via BBCI.calibrate.settings, the details can be specified, se below.\n%\n%Synopsis:\n% [BBCI, DATA]= bbci_calibrate_NIRS_ERP(BBCI, DATA)\n% \n%Arguments:\n% BBCI - the field 'calibrate.settings' holds parameters specific to\n% calibrate CSP-based BCI processing.\n% DATA - holds the calibration data\n% \n%Output:\n% BBCI - Updated BBCI structure in which all necessary fields for\n% online operation are set, see bbci_apply_structures.\n% DATA - As input but added some information of the analysis that might\n% be reused in a second run\n%\n%BBCI.calibrate.settings may include the following parameters:\n% visu_clab: Clab used for visualization\n% lp: butterworth lowpass filter frequency\n% derivative use derivative (slope) of signal as feature\n% classes: [1x2 CELL of CHAR] Names of the two classes, which are to be\n% discriminated. For classes = 'auto', all pairs of available classes\n% are investigated, and the one with best xvalidation performance is\n% chosen. Default is 'auto'. **** TO BE IMPLEMENTED ****\n% Display options:\n% zscore: (for display purposes) channels are normalized to zero mean\n% and unit variance \n% grid: provide a string specifying the grid layout for grid_plot\n%\n% ------------\n% ival: [1x2 DOUBLE] interval on which CSP is performed, 'auto' means\n% automatic selection. Default is 'auto'.\n% band: [1x2 DOUBLE] frequency band on which CSP is performed, 'auto' means\n% automatic selection. Default is 'auto'.\n% clab: [CELL] Labels of the channels that are used for classification,\n% default {'*'}.\n% nPatters: [INT>0] number of CSP patterns which are considered from each\n% side of the eigenvalue spectrum. Note, that not neccessarily all of\n% these are used for classification, see settings.pattern.\n% Default is 3.\n% patterns: [1xN DOUBLE or 'auto'] vector specifying the indices of the\n% CSP filters that should be used for classification; 'auto' means\n% automatic selection. Default is 'auto'.\n% model: [CHAR or CELL] Classification model.\n% Default {'RLDAshrink', 'gamma',0, store_means',1, 'scaling',1}.\n% reject_artifacts:\n% reject_channels:\n% reject_artifacts_opts: cell array of options which are passed to \n% reject_varEventsAndChannels.\n% check_ival: interval which is checked for artifacts\n% do_laplace: do Laplace spatial filtering for automatic selection\n% of ival/band. If opt.do_laplace is set to 0, the default value of\n% will also be set to opt.visu_laplace 0 (but can be overwritten).\n% visu_laplace: do Laplace filtering for grid plots of Spectra/ERDs.\n% If visu_laplace is a string, it is passed to proc_laplace. This\n% can be used to use alternative geometries, like 'vertical'.\n% visu_band: Frequency range for which spectrum is shown.\n% visu_ival: Time interval for which ERD/ERS curves are shown.\n% grd: grid to be used in the grid plots of spectra and ERDs.\n%\n%Only the figures of the chosen class combination are visible, while the\n%others are hidden. In order to make them visible, type\n%>> set(cat(2, data.all_results.figure_handles), 'Visible','on')\n%\n%You might like to modify bbci.feature.ival after running this function.\n\n\ncalibrate = bbci.calibrate;\nopt= calibrate.settings;\n[opt, isdefault]= ...\n set_defaults(opt, ...\n 'classes', 'auto', ...\n 'clab', {'*'}, ...\n 'classifier','RLDAshrink',...\n 'ref_ival',[-2000 0], ...\n 'ival',[-2000,10000], ...\n 'nIvals', 5, ...\n 'signal','both', ...\n 'doLowpass', 1, ...\n 'derivative', 0, ...\n 'baseline',1, ...\n 'zscore',1, ...\n 'grid',[] , ...\n 'spectra', 1, ...\n 'plot',1 ...\n );\n\n\nopt_grid = {'scaleGroup' 'all'};\nopt_tit = {'Fontsize' 10 'Fontweight' 'bold'};\n\n%% Build dummy grid for grid_plot\nclab = strhead(data.cnt.clab(1:end/2));\nclab = {'scale',clab{:},'legend'};\nii=1;\ngrd = '';\nfor r=1:ceil(sqrt(numel(clab)-2)) % nr of rows\n for c=1:ceil(sqrt(numel(clab)-2))\n if ii<=numel(clab)\n grd = [grd clab{ii} ','];\n else\n grd = [grd '_,'];\n end\n ii=ii+1;\n end\n grd= [grd(1:end-1) '\\n']; \nend\ngrd = sprintf(grd);\nmnt= mnt_setGrid(data.mnt, grd);\n\n%% *** Preprocessing ***\nif ~isempty(opt.clab)\n data.cnt= proc_selectChannels(data.cnt,opt.clab);\nend\n\n% LP filter data [IS IT POSSIBLE TO SET BBCI.SIGNAL AND DO THIS\n% AUTOMATICALLY?]\nif opt.doLowpass\n fprintf('Lowpass filtering signal\\n')\n [filt_b,filt_a]=butter(3, opt.lp*2/data.cnt.fs,'low');\n data.cnt = proc_filtfilt(data.cnt,filt_b,filt_a);\nend\n\n% oxy = dat;\n% oxy.x = oxy.x(:,1:end/2);\n% oxy.clab = oxy.clab(:,1:end/2);\n% deoxy = dat;\n% deoxy.x = dat.x(:,end/2+1:end);\n% deoxy.clab = deoxy.clab(:,end/2+1:end);\n\nif opt.spectra\n % Spectra\n spec_band = [0.01 3]; % Frequency band for spectrum plot\n spec_win = kaiser(250,2); % window for proc_spectrumspecoxy = proc_spectrum(oxy, spec_band,spec_win);\n spec = proc_spectrum(data.cnt, spec_band,spec_win);\nend\n\n% derivative feat?\nif opt.derivative\n fprintf('Calculating derivative of NIRS signal\\n')\n\n data.cnt.x=diff(data.cnt.x);\n% deoxy.x=diff(deoxy.x); %*data.cnt.fs;\n% oxy.x=diff(oxy.x); \nend\n\n%% Epoch data\ndata.cnt = cntToEpo(data.cnt,data.mrk,opt.ival);\n \n% baseline\nif opt.baseline \n fprintf('Performing baseline correction\\n')\n data.cnt = proc_baseline(data.cnt,opt.ref_ival);\nend\n\n% oxy.clab = untex(oxy.clab);\n% deoxy.clab = untex(deoxy.clab);\n% \n%% *** Neurophysiology ***\n% Split in oxy/deoxy or WL1/WL2\n% oxy = data.cnt;\n% oxy.x = oxy.x(:,1:end/2,:);\n% oxy.clab = oxy.clab(:,1:end/2);\n% deoxy = data.cnt;\n% deoxy.x = data.cnt.x(:,end/2+1:end,:);\n% deoxy.clab = deoxy.clab(:,end/2+1:end);\n\nopt_tit = {'Fontsize' 10 'Fontweight' 'bold'};\n\n%% make plots\nif opt.plot\n %% Power spectrum of CNT data\n if opt.spectra\n fig_set(2),clf\n subplot(2,1,1)\n plot(spec.t,spec.x(:,1:end/2)), title(strtail(spec.clab{1}),opt_tit{:})\n xlabel(sprintf('Frequency [%s]',spec.xUnit)),ylabel(sprintf('Power [%s]',spec.yUnit))\n subplot(2,1,2)\n plot(spec.t,spec.x(:,1:end/2)), title(strtail(spec.clab{1}),opt_tit{:})\n xlabel(sprintf('Frequency [%s]',spec.xUnit)),ylabel(sprintf('Power [%s]',spec.yUnit))\n annotation('textbox',[.01 .9 .1 .1 ],'String','Power spectra of CNT data ');\n end\n\n %% z-score normalization \n if opt.zscore\n fprintf('Calculating z-scores\\n')\n m= mean(data.cnt.x,1); % mean\n s= std(data.cnt.x,1); % std\n len_x = length(data.cnt.x);\n data.cnt.x= (data.cnt.x - repmat(m,[len_x 1])) ./ repmat(s,[len_x 1]);\n clear m s \n end\n\n %% Grid plot -- signal\n fig_set(1),clf\n H = grid_plot(proc_selectChannels(data.cnt,1:numel(data.cnt.clab)/2), mnt, defopt_scalp_power,opt_grid{:});\n set(gcf,'Name',['Epoched signal ' strtail(data.cnt.clab{1})])\n % printFigure(['grid_oxy' saveapp], [36 20], opt_fig); \n\n fig_set(2),clf\n H = grid_plot(proc_selectChannels(data.cnt,(numel(data.cnt.clab)/2)+1:numel(data.cnt.clab)), mnt, defopt_scalp_power,opt_grid{:});\n set(gcf,'Name',['Epoched signal ' strtail(data.cnt.clab{end})])\n % printFigure(['grid_deoxy' saveapp], [36 20], opt_fig);\n\n %% R-Square plots\n dat_r = proc_r_square_signed(data.cnt,'multiclass_policy','pairwise');\n npairs = size(dat_r.y,1);\n nclab = numel(data.cnt.clab)/2;\n for ii=1:npairs\n for od=[1 2] %oxy-deoxy\n figure\n imagesc(dat_r.x(:,(od-1)*nclab+1:od*nclab,ii)')\n title([dat_r.className{ii} ' ' strtail(dat_r.clab{od*nclab})],opt_tit{:})\n ylabel('Channel',opt_tit{:}),xlabel('Time',opt_tit{:})\n xt= str2num(get(gca,'XTickLabel'));\n % yt= str2num(get(gca,'YTickLabel'));\n set(gca,'XTickLabel',dat_r.t(xt))\n % set(gca,'YTickLabel',strhead(oxy_r.clab))\n colorbar\n end\n end\n clear dat_r\n\n %% Wavelets\n spec = proc_selectChannels(data.cnt,1:nclab);\n spec = proc_specgram(spec, [0.01 3]);\n\n % data.cnt = proc_selectChannels(data.cnt,1:nclab);\n % wave_band = [.01:.4:3];\n % for w=wave_band\n % if w==wave_band(1)\n % wave = proc_wavelets(data.cnt,w,'vectorize',1);\n % else\n % w1 = proc_wavelets(data.cnt,w,'vectorize',1);\n % end\n % end\nend\n%% *** Classification ***\n% BBCI.FEATURE selection\nbbci.feature.fcn = {@proc_jumpingMeans};\n\n% class combination\nif isequal(opt.classes, 'auto'),\n class_combination= nchoosek(1:size(data.mrk.y,1), 2);\nelse\n class_combination= find(ismember(data.mrk_all.className, opt.classes,'legacy'));\n if length(class_combination) < length(opt.classes),\n error('Not all specified classes were found.');\n end\n if length(class_combination) ~= 2,\n error('This calibration is only for binary classification.');\n end\nend\n\nival_cfy={};\n\nfor ci= 1:size(class_combination,1)\n \n fv=proc_selectClasses(data.cnt,class_combination(ci,:));\n fprintf('\\nComparing classes %s vs %s.',fv.className{1},fv.className{2})\n \n % find the feature/time intervals\n fvr = proc_r_square_signed(fv);\n [ival_cfy{ci},nfo]= select_time_intervals(fvr,'nIvals',opt.nIvals,'clab_pick_peak', fv.clab,...\n 'visualize',0,'intersample_timing',1);\n\n bbci.feature.param = { {ival_cfy{ci}} };\n % Get feature vector ans train classifier\n fv = bbci_calibrate_evalFeature(fv, bbci.feature);\n\n bbci.classifier.C= trainClassifier(fv, opt.classifier);\n\n \n% % Xvalidation\n% [loss, loss_std]= xvalidation(fv, opt.classifier, ...\n% 'sample_fcn', {'divisions', [opt.nShuffles opt.nFolds]},'save_classifier',0);\n% \n% mean_loss(ci)= loss;\n% std_loss(ci)= loss_std;\n \n cfy_fields= {'signal', 'feature', 'classifier', 'quit_condition'};\n bbci_all(ci)= struct_copyFields(bbci, cfy_fields);\n\n clear fv*\nend\n\n%% Choose best binary combination of classes\n% Copy parameters into BBCI struct\n\nnComb= size(class_combination,1);\nif nComb > 1,\n% [dummy, bi]= min(mean_loss + 0.1*std_loss);\nbi=2;\n bbci= struct_copyFields(bbci, bbci_all(bi), cfy_fields);\n% bbci.feature.param = { {ival_cfy{ci}} };\nend\n\ncomb = class_combination(bi,:);\nfprintf('Chosen (best) combination: classes %s vs %s.\\n',data.cnt.className{comb(1)},data.cnt.className{comb(2)})\nbbci.classifier.classes=data.cnt.className(comb);\n%% Set the BBCI struct\n\n% BBCI.SIGNAL preprocessing (really just for online data?)\n% bbci.signal.clab = opt.clab; \nbbci.signal.clab = data.cnt.clab;\n\n% data.signal.clab = opt.clab;\nbbci.signal.proc = {};\n% if ~isempty(opt.clab)\n% bbci.signal.proc = {bbci.signal.proc{:} {@proc_selectChannels,opt.clab}};\n% end\nif opt.doLowpass\n bbci.signal.proc = {bbci.signal.proc{:} {@proc_filtfilt,filt_b,filt_a}};\nend\nif opt.derivative\n bbci.signal.proc = {bbci.signal.proc{:} {@diff}};\nend\n\n% SOMEWHERE: proc_baseline ?\n\n% BBCI.FEATURE selection\nbbci.feature.ival = opt.ival;\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/online/calibration/bbci_calibrate_NIRS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.17534289327014718}} {"text": "function events = in_events_bids(sFile, EventFile)\n% IN_EVENTS_BIDS: Read a BIDS _events.tsv file (columns \"onset\", \"duration\", \"trial_type\").\n%\n% OUTPUT:\n% - events(i): array of structures with following fields (one structure per event type) \n% |- label : Identifier of event #i\n% |- samples : Array of unique time indices for event #i in the corresponding raw file\n% |- times : Array of unique time latencies (in seconds) for event #i in the corresponding raw file\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2019-2022\n\n% Read tsv file\n% https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/05-task-events.html\n% trial_type would be a subset of possible events that identify trial category.\n% value can be numbers or strings identifying the event.\n% Only 'onset' and 'duration' are required.\nMarkers = in_tsv(EventFile, {'onset', 'duration', 'trial_type', 'channel', 'value'}, 0);\nif isempty(Markers) || isempty(Markers{1,1})\n events = [];\n return;\nend\n% Standardize empty/missing values to empty char.\nMarkers(cellfun(@(c) (isequal(c,'n/a') || isequal(c,'N/A') || isempty(c)), Markers(:))) = {''};\n% If there is no trial_type and no value information: use the filename as the event name\nif all(cellfun(@isempty, Markers(:,3)) & cellfun(@isempty, Markers(:,5)))\n [fPath, fbase, fExt] = bst_fileparts(EventFile);\n Markers(:,3) = repmat({fbase}, size(Markers(:,3)));\nelseif all(cellfun(@isempty, Markers(:,3)))\n Markers(:,3) = Markers(:,5);\nelseif ~all(cellfun(@isempty, Markers(:,5)))\n % Both columns contain data\n for iM = 1:size(Markers, 1)\n if isempty(Markers{iM,3})\n Markers{iM,3} = Markers{iM,5};\n elseif ~isempty(Markers{iM,5})\n % Merge\n Markers{iM,3} = [Markers{iM,3} '-' Markers{iM,5}];\n end\n end\nend\n% List of events from trial_type and/or value\nuniqueEvt = unique(Markers(:,3)');\n\n% Initialize returned structure\nevents = repmat(db_template('event'), [1, length(uniqueEvt)]);\n% Create events list\nfor iEvt = 1:length(uniqueEvt)\n % Find all the occurrences of event #iEvt\n iMrk = find(strcmpi(Markers(:,3)', uniqueEvt{iEvt}));\n % Get event onsets and durations\n onsets = cellfun(@(c)sscanf(c,'%f',1), Markers(iMrk,1), 'UniformOutput', 0);\n durations = cellfun(@(c)sscanf(c,'%f',1), Markers(iMrk,2), 'UniformOutput', 0);\n channels = Markers(iMrk,4)';\n % Find and reject events with no latency\n iEmpty = find(cellfun(@isempty, onsets));\n if ~isempty(iEmpty)\n iMrk(iEmpty) = [];\n onsets(iEmpty) = [];\n durations(iEmpty) = [];\n channels(iEmpty) = [];\n end\n % Channel names\n for iOcc = 1:length(channels)\n if (isempty(channels{iOcc}) || strcmpi(channels{iOcc}, 'n/a'))\n channels{iOcc} = [];\n else\n channels{iOcc} = {channels{iOcc}};\n end\n end\n % Add event structure\n events(iEvt).label = uniqueEvt{iEvt};\n events(iEvt).epochs = ones(1, length(iMrk));\n events(iEvt).times = [onsets{:}];\n % Convert latencies from the first sample in the file to the real timing \n % See specs: https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/05-task-events.html\n events(iEvt).times = events(iEvt).times + sFile.prop.times(1);\n % Extended events if durations are defined for all the markers\n if all(~cellfun(@isempty, durations)) && all(~cellfun(@(c)isequal(c,0), durations))\n events(iEvt).times(2,:) = events(iEvt).times + [durations{:}];\n end\n % Make the function independent of sFile\n if ~isempty(sFile)\n events(iEvt).times = round(events(iEvt).times .* sFile.prop.sfreq) ./ sFile.prop.sfreq;\n end\n events(iEvt).reactTimes = [];\n events(iEvt).select = 1;\n events(iEvt).channels = channels;\n events(iEvt).notes = [];\nend\n\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_events_bids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1752485510176972}} {"text": "function view_varmap(lab1,valueMap, newgri, sor)\n % view_maxz plots the maxz LTA values calculated\n % with maxzlta.m or other similar values as a color map\n % needs valueMap, gx, gy, stri\n %\n % define size of the plot etc.\n %\n ZG=ZmapGlobal.Data;\n % Prmap = nan(size(valueMap));\n \n % Find out if figure already exists\n %\n bmap=findobj('Type','Figure','-and','Name','variance-value-map');\n \n \n % Set up the Seismicity Map window Enviroment\n %\n if isempty(bmap)\n bmap = figure_w_normalized_uicontrolunits( ...\n 'Name','variance-value-map',...\n 'NumberTitle','off', ...\n 'NextPlot','new', ...\n 'backingstore','on',...\n 'Visible','off', ...\n 'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));\n \n lab1 = 'b-value:';\n \n create_my_menu();\n \n re4 = valueMap;\n \n colormap(jet)\n ZG.tresh_km = nan; \n minpe = nan; \n Mmin = nan;\n \n end % This is the end of the figure setup\n \n % Now lets plot the color-map of the z-value\n %\n figure(bmap);\n delete(findobj(bmap,'Type','axes'));\n % delete(sizmap);\n ax = reset(gca);\n cla(ax)\n set(ax,'NextPlot','replace')\n watchon;\n set(ax,'visible','off',...\n 'FontSize',ZmapGlobal.Data.fontsz.s,...\n 'FontWeight','normal',...\n 'LineWidth',1,...\n 'Box','on','SortMethod','childorder')\n \n % find max and min of data for automatic scaling\n ZG.maxc = fix(max(valueMap(:))+1);\n ZG.minc = fix(min(valueMap(:)))-1;\n \n % set values gretaer ZG.tresh_km = nan\n %\n re4 = valueMap;\n \n % plot image\n %\n orient(ax,'landscape')\n \n ax.Position = [0.12, 0.10, 0.8, 0.8];\n set(gca,'NextPlot','add')\n pcolor(ax, gx,gy,re4);\n \n axis(ax, [min(gx) max(gx) min(gy) max(gy)])\n axis(ax,'image')\n set(gca,'NextPlot','add')\n \n shading(ax, ZG.shading_style);\n\n % make the scaling for the recurrence time map reasonable\n\n fix_caxis.ApplyIfFrozen(ax); \n \n title(ax, sprintf('%s ; %g to %g',name, t0b, teb),...\n 'FontSize',ZmapGlobal.Data.fontsz.s,...\n 'Color','k',...\n 'FontWeight','normal')\n \n xlabel(ax, 'Longitude [deg]','FontWeight','normal','FontSize',ZmapGlobal.Data.fontsz.s)\n ylabel(ax, 'Latitude [deg]','FontWeight','normal','FontSize',ZmapGlobal.Data.fontsz.s)\n \n % plot overlay\n %\n set(ax,'NextPlot','add')\n zmap_update_displays();\n \n set(ax,'NextPlot','add')\n quiver(ax, newgri(:,1),newgri(:,2), -cos(sor(:,SA*2)*pi/180), sin(sor(:,SA*2)*pi/180),0.8,'.', ...\n 'LineWidth',1, 'Color','k')\n \n set(ax,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,...\n 'FontWeight','normal',...\n 'LineWidth',1,...\n 'Box','on',...\n 'TickDir','out');\n \n h1 = ax;\n hzma = ax;\n \n % Create a colorbar\n %\n h5 = colorbar('horiz');\n set(h5,'Pos',[0.35 0.06 0.4 0.02],...\n 'FontWeight','normal',...\n 'FontSize',ZmapGlobal.Data.fontsz.s,...\n 'TickDir','out')\n \n \n axes('position', [0.00, 0.0, 1 1])\n axis('off')\n % Text Object Creation\n text(...\n 'Units','normalized',...\n 'Position',[ 0.33 0.06 0 ],...\n 'HorizontalAlignment','right',...\n 'FontSize',ZmapGlobal.Data.fontsz.s,....\n 'FontWeight','normal',...\n 'String','Variance');\n \n % Make the figure visible\n %\n set(gca,'FontSize',ZmapGlobal.Data.fontsz.s,...\n 'FontWeight','normal','LineWidth',1,...\n 'Box','on','TickDir','out');\n set(gcf,'color','w');\n figure(bmap);\n axes(h1)\n watchoff(bmap)\n \n \n %% ui functions\n function create_my_menu()\n add_menu_divider();\n \n options = uimenu('Label',' Select ');\n uimenu(options,'Label','Refresh ','MenuSelectedFcn',@cb_refresh)\n uimenu(options,'Label','Select EQ in Circle',...\n 'MenuSelectedFcn',@select_in_circle)\n uimenu(options,'Label','Select EQ in Circle - Constant R',...\n 'MenuSelectedFcn',@cb_select_in_constr)\n \n uimenu(options,'Label','Select EQ in Polygon -new ',...\n 'MenuSelectedFcn',@cb_select_in_polygon_new)\n \n op1 = uimenu('Label',' Maps ');\n \n uimenu(op1,'Label','Variance map',...\n 'MenuSelectedFcn',@cb_variancemap)\n uimenu(op1,'Label','Resolution map',...\n 'MenuSelectedFcn',@cb_resolutionmap)\n uimenu(op1,'Label','Plot map on top of topography ',...\n 'MenuSelectedFcn',@cb_plot_on_topography)\n \n uimenu(op1,'Label','Histogram ','MenuSelectedFcn',@(~,~)zhist())\n \n add_display_menu(1)\n end\n \n %% callback functions\n \n function cb_refresh(~,~)\n view_varmap(lab1, re4);\n end\n \n function select_in_circle(~,~)\n h1 = gca;\n met = 'ni';\n ZG=ZmapGlobal.Data;\n ZG.hold_state=false;\n circle;\n watchon;\n doinvers_michael;\n watchoff;\n end\n \n function cb_select_in_constr(~,~)\n h1 = gca;\n met = 'ra';\n ZG=ZmapGlobal.Data;\n ZG.hold_state=false;\n circle;\n watchon;\n doinvers_michael;\n watchoff;\n end\n \n function cb_select_in_polygon_new(~,~)\n cufi = gcf;\n ZG=ZmapGlobal.Data;\n ZG.hold_state=false;\n selectp;\n watchon;\n doinvers_michael;\n watchoff;\n end\n \n function cb_variancemap(~,~)\n view_varmap('b-value',r);\n end\n \n function cb_resolutionmap(~,~)\n view_varmap('Radius', rama);\n end\n \n function cb_plot_on_topography(~,~)\n dramap_z('stress2','w',valueMap);\n end\n\nend\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/view_varmap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.1752485492968764}} {"text": "\n\n\n%%% test the model performance\n\n\n% clear; clc;\nformat compact;\n\naddpath(fullfile('data','utilities'));\n% folderTest = fullfile('data','Test','Set12'); %%% test dataset\nfolderTest = fullfile('data','Test','Set68'); %%% test dataset\n\nshowResult = 1;\nuseGPU = 1;\npauseTime = 0;\n\nmodelName = 'model_64_25_Res_Bnorm_Adam';\nepoch = 1;\nnoiseSigma = 25; %%% image noise level\n\n\n%%% load Gaussian denoising model\nload(fullfile('data',modelName,[modelName,'-epoch-',num2str(epoch),'.mat']));\nnet = vl_simplenn_tidy(net);\nnet.layers = net.layers(1:end-1);\n\n%%%\nnet = vl_simplenn_tidy(net);\n\n% for i = 1:size(net.layers,2)\n% net.layers{i}.precious = 1;\n% end\n\n%%% move to gpu\nif useGPU\n net = vl_simplenn_move(net, 'gpu') ;\nend\n\n%%% read images\next = {'*.jpg','*.png','*.bmp'};\nfilePaths = [];\nfor i = 1 : length(ext)\n filePaths = cat(1,filePaths, dir(fullfile(folderTest,ext{i})));\nend\n\n%%% PSNR and SSIM\nPSNRs = zeros(1,length(filePaths));\nSSIMs = zeros(1,length(filePaths));\n\nfor i = 1:length(filePaths)\n \n %%% read images\n label = imread(fullfile(folderTest,filePaths(i).name));\n [~,nameCur,extCur] = fileparts(filePaths(i).name);\n label = im2double(label);\n \n randn('seed',0);\n input = single(label + noiseSigma/255*randn(size(label)));\n \n %%% convert to GPU\n if useGPU\n input = gpuArray(input);\n end\n \n res = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test');\n output = input - res(end).x;\n \n %%% convert to CPU\n if useGPU\n output = gather(output);\n input = gather(input);\n end\n \n %%% calculate PSNR and SSIM\n [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);\n if showResult\n imshow(cat(2,im2uint8(label),im2uint8(input),im2uint8(output)));\n title([filePaths(i).name,' ',num2str(PSNRCur,'%2.2f'),'dB',' ',num2str(SSIMCur,'%2.4f')])\n drawnow;\n pause(pauseTime)\n end\n PSNRs(i) = PSNRCur;\n SSIMs(i) = SSIMCur;\nend\n\ndisp([mean(PSNRs),mean(SSIMs)]);\n\n\n\n\n", "meta": {"author": "cszn", "repo": "DnCNN", "sha": "e93b27812d3ff523a3a79d19e5e50d233d7a8d0a", "save_path": "github-repos/MATLAB/cszn-DnCNN", "path": "github-repos/MATLAB/cszn-DnCNN/DnCNN-e93b27812d3ff523a3a79d19e5e50d233d7a8d0a/TrainingCodes/DnCNN_TrainingCodes_v1.0/Demo_Test_model_64_25_Res_Bnorm_Adam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1752485441769108}} {"text": "function [ir,x0,delay] = ir_nfchoa(X,head_orientation,xs,src,sofa,conf)\n%IR_NFCHOA binaural simulation of NFCHOA\n%\n% Usage: [ir,x0,delay] = ir_nfchoa(X,head_orientation,xs,src,sofa,conf)\n%\n% Input parameters:\n% X - listener position / m\n% head_orientation - orientation of the listener with [phi theta] /\n% (rad, rad)\n% xs - virtual source position / m\n% src - source type: 'pw' -plane wave\n% 'ps' - point source\n% sofa - impulse response data set for the secondary sources\n% conf - configuration struct (see SFS_config)\n%\n% Output parameters:\n% ir - impulse response for the desired HOA synthesis\n% (nx2 matrix)\n% x0 - secondary sources\n% delay - delay added by driving function / s\n%\n% IR_NFCHOA(X,head_orientation,xs,src,L,sofa,conf) calculates a binaural room\n% impulse response for a virtual source at xs for a virtual NFCHOA array and\n% a listener located at X.\n%\n% See also: ssr_brs_nfchoa, ir_nfchoa, ir_point_source, auralize_ir\n\n%*****************************************************************************\n% The MIT License (MIT) *\n% *\n% Copyright (c) 2010-2019 SFS Toolbox Developers *\n% *\n% Permission is hereby granted, free of charge, to any person obtaining a *\n% copy of this software and associated documentation files (the \"Software\"), *\n% to deal in the Software without restriction, including without limitation *\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n% and/or sell copies of the Software, and to permit persons to whom the *\n% Software is furnished to do so, subject to the following conditions: *\n% *\n% The above copyright notice and this permission notice shall be included in *\n% all copies or substantial portions of the Software. *\n% *\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *\n% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *\n% DEALINGS IN THE SOFTWARE. *\n% *\n% The SFS Toolbox allows to simulate and investigate sound field synthesis *\n% methods like wave field synthesis or higher order ambisonics. *\n% *\n% https://sfs.readthedocs.io sfstoolbox@gmail.com *\n%*****************************************************************************\n\n\n%% ===== Checking of input parameters ==================================\nnargmin = 6;\nnargmax = 6;\nnarginchk(nargmin,nargmax);\nif conf.debug\n isargposition(X);\n isargxs(xs);\n isargvector(head_orientation);\n isargpositivescalar(L);\n isargchar(src);\n isargstruct(config);\nend\n\n\n%% ===== Variables ======================================================\n% Loudspeaker positions\nx0 = secondary_source_positions(conf);\n\n\n%% ===== BRIR ===========================================================\n% Calculate driving function\n[d,~,delay] = driving_function_imp_nfchoa(x0,xs,src,conf);\n% Generate the impulse response for NFCHOA\nir = ir_generic(X,head_orientation,x0,d,sofa,conf);\n", "meta": {"author": "sfstoolbox", "repo": "sfs-matlab", "sha": "02194f0243d1ead26572f760032c40527718919d", "save_path": "github-repos/MATLAB/sfstoolbox-sfs-matlab", "path": "github-repos/MATLAB/sfstoolbox-sfs-matlab/sfs-matlab-02194f0243d1ead26572f760032c40527718919d/SFS_binaural_synthesis/ir_nfchoa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.2814055953761018, "lm_q1q2_score": 0.1751635347525318}} {"text": "% dipplot() - Visualize EEG equivalent-dipole locations and orientations \n% in the MNI average MRI head or in the BESA spherical head model. \n% Usage:\n% >> dipplot( sources, 'key', 'val', ...);\n% >> [sources X Y Z XE YE ZE] = dipplot( sources, 'key', 'val', ...);\n%\n% Inputs:\n% sources - structure array of dipole information: can contain\n% either BESA or DIPFIT dipole information. BESA dipole\n% information are still supported but may disapear in the \n% future. For DIPFIT\n% sources.posxyz: contains 3-D location of dipole in each \n% column. 2 rows indicate 2 dipoles.\n% sources.momxyz: contains 3-D moments for dipoles above.\n% sources.rv : residual variance from 0 to 1.\n% other fields : used for graphic interface.\n%\n% Optional input:\n% 'rvrange' - [min max] or [max] Only plot dipoles with residual variace\n% within the given range. Default: plot all dipoles.\n% 'summary' - ['on'|'off'|'3d'] Build a summary plot with three views (top, \n% back, side). {default: 'off'}\n% 'mri' - Matlab file containing an MRI volume and a 4-D transformation\n% matrix to go from voxel space to electrode space:\n% mri.anatomy contains a 3-D anatomical data array\n% mri.transfrom contains a 4-D homogenous transformation matrix.\n% 'coordformat' - ['MNI'|'spherical'] Consider that dipole coordinates are in\n% MNI or spherical coordinates (for spherical, the radius of the \n% head is assumed to be 85 (mm)). See also function sph2spm().\n% 'transform' - [real array] traditional transformation matrix to convert\n% dipole coordinates to MNI space. Default is assumed from \n% 'coordformat' input above. Type help traditional for more \n% information.\n% 'image' - ['besa'|'mri'] Background image. \n% 'mri' (or 'fullmri') uses mean-MRI brain images from the Montreal \n% Neurological Institute. This option can also contain a 3-D MRI\n% volume (dim 1: left to right; dim 2: anterior-posterior; dim 3: \n% superior-inferior). Use 'coregist' to coregister electrodes\n% with the MRI. {default: 'mri'} \n% 'verbose' - ['on'|'off'] comment on operations on command line {default:\n% 'on'}.\n% 'plot' - ['on'|'off'] only return outputs {default: 'off'}.\n%\n% Plotting options:\n% 'color' - [cell array of color strings or (1,3) color arrays]. For\n% exemple { 'b' 'g' [1 0 0] } gives blue, green and red. \n% Dipole colors will rotate through the given colors if\n% the number given is less than the number of dipoles to plot.\n% A single number will be used as color index in the jet colormap.\n% 'view' - 3-D viewing angle in cartesian coords.,\n% [0 0 1] gives a sagittal view, [0 -1 0] a view from the rear;\n% [1 0 0] gives a view from the side of the head.\n% 'mesh' - ['on'|'off'] Display spherical mesh. {Default is 'on'}\n% 'meshdata' - [cell array|'file_name'] Mesh data in a cell array { 'vertices'\n% data 'faces' data } or a boundary element model filename (the \n% function will plot the 3rd mesh in the 'bnd' sub-structure).\n% 'axistight' - ['on'|'off'] For MRI only, display the closest MRI\n% slide. {Default is 'off'}\n% 'gui' - ['on'|'off'] Display controls. {Default is 'on'} If gui 'off', \n% a new figure is not created. Useful for incomporating a dipplot \n% into a complex figure.\n% 'num' - ['on'|'off'] Display component number. Take into account\n% dipole size. {Default: 'off'}\n% 'cornermri' - ['on'|'off'] force MRI images to the corner of the MRI volume\n% (usefull when background is not black). Default: 'off'.\n% 'drawedges' - ['on'|'off'] draw edges of the 3-D MRI (black in axistight,\n% white otherwise.) Default is 'off'.\n% 'projimg' - ['on'|'off'] Project dipole(s) onto the 2-D images, for use\n% in making 3-D plots {Default 'off'}\n% 'projlines' - ['on'|'off'] Plot lines connecting dipole with 2-D projection.\n% Color is dashed black for BESA head and dashed black for the\n% MNI brain {Default 'off'}\n% 'projcol' - [color] color for the projected line {Default is same as dipole}\n% 'dipolesize' - Size of the dipole sphere(s). This option may also contain one\n% value per dipole {Default: 30}\n% 'dipolelength' - Length of the dipole bar(s) {Default: 1}\n% 'pointout' - ['on'|'off'] Point the dipoles outward. {Default: 'off'}\n% 'sphere' - [float] radius of sphere corresponding to the skin. Default is 1.\n% 'spheres' - ['on'|'off'] {default: 'off'} plot dipole markers as 3-D spheres. \n% Does not yet interact with gui buttons, produces non-gui mode.\n% 'spheresize' - [real>0] size of spheres (if 'on'). {default: 5}\n% 'normlen' - ['on'|'off'] Normalize length of all dipoles. {Default: 'off'}\n% 'dipnames' - [cell array] cell array of string with a name for each dipole (or\n% pair of dipole).\n% 'holdon' - ['on'|'off'] create a new dipplot figure or plot dipoles within an\n% an existing figure. Default is 'off'.\n%\n% Outputs:\n% sources - EEG.source structure with two extra fiels 'mnicoord' and 'talcoord'\n% containing the MNI and talairach coordinates of the dipoles. Note\n% that for the BEM model, dipoles are already in MNI coordinates.\n% X,Y,Z - Locations of dipole heads (Cartesian coordinates in MNI space). \n% If there is more than one dipole per components, the last dipole \n% is returned.\n% XE,YE,ZE - Locations of dipole ends (Cartesian coordinates). The same\n% remark as above applies.\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 1st July 2002\n%\n% Notes: See DIPFIT web tutorial at sccn.ucsd.edu/eeglab/dipfittut/dipfit.html\n% for more details about MRI co-registration etc...\n%\n% Example:\n% % define dipoles\n% sources(1).posxyz = [-59 48 -28]; % position for the first dipole\n% sources(1).momxyz = [ 0 58 -69]; % orientation for the first dipole\n% sources(1).rv = 0.036; % residual variance for the first dipole\n% sources(2).posxyz = [74 -4 -38]; % position for the second dipole\n% sources(2).momxyz = [43 -38 -16]; % orientation for the second dipole\n% sources(2).rv = 0.027; % residual variance for the second dipole\n%\n% % plot of the two dipoles (first in green, second in blue)\n% dipplot( sources, 'color', { 'g' 'b' }); \n%\n% % To make a stereographic plot\n% figure( 'position', [153 553 1067 421]; \n% subplot(1,3,1); dipplot( sources, 'view', [43 10], 'gui', 'off');\n% subplot(1,3,3); dipplot( sources, 'view', [37 10], 'gui', 'off');\n%\n% % To make a summary plot\n% dipplot( sources, 'summary', 'on', 'num', 'on');\n%\n% See also: eeglab(), dipfit()\n\n% old options\n% -----------\n% 'std' - [cell array] plot standard deviation of dipoles. i.e.\n% { [1:6] [7:12] } plot two elipsoids that best fit all the dipoles\n% from 1 to 6 and 7 to 12 with radius 1 standard deviation.\n% { { [1:6] 2 'linewidth' 2 } [7:12] } do the same but now the\n% first elipsoid is 2 standard-dev and the lines are thicker.\n\n% Copyright (C) 2002 Arnaud Delorme\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n% README -- Plotting strategy:\n% - All buttons have a tag 'tmp' so they can be removed\n% - The component-number buttons have 'userdata' equal to 'editor' and \n% can be found easily by other buttons find('userdata', 'editor')\n% - All dipoles have a tag 'dipoleX' (X=their number) and can be made \n% visible/invisible\n% - The gcf object 'userdat' field stores the handle of the dipole that \n% is currently being modified\n% - Gca 'userdata' stores imqge names and position\n\nfunction [outsources, XX, YY, ZZ, XO, YO, ZO] = dipplot( sourcesori, varargin )\n \n DEFAULTVIEW = [0 0 1];\n \n if nargin < 1\n help dipplot;\n return;\n end;\n \n % reading and testing arguments\n % -----------------------------\n sources = sourcesori;\n if ~isstruct(sources)\n updatedipplot(sources(1)); \n % sources countain the figure handler\n return\n end;\n \n % key type range default\n g = finputcheck( varargin, { 'color' '' [] [];\n 'axistight' 'string' { 'on' 'off' } 'off';\n 'coordformat' 'string' { 'MNI' 'spherical' 'CTF' 'auto' } 'auto';\n 'drawedges' 'string' { 'on' 'off' } 'off';\n 'mesh' 'string' { 'on' 'off' } 'off';\n 'gui' 'string' { 'on' 'off' } 'on';\n 'summary' 'string' { 'on2' 'on' 'off' '3d' } 'off';\n 'verbose' 'string' { 'on' 'off' } 'on';\n 'view' 'real' [] [0 0 1];\n 'rvrange' 'real' [0 Inf] [];\n 'transform' 'real' [0 Inf] [];\n 'normlen' 'string' { 'on' 'off' } 'off';\n 'num' 'string' { 'on' 'off' } 'off';\n 'cornermri' 'string' { 'on' 'off' } 'off';\n 'mri' { 'string' 'struct' } [] '';\n 'dipnames' 'cell' [] {};\n 'projimg' 'string' { 'on' 'off' } 'off';\n 'projcol' '' [] [];\n 'projlines' 'string' { 'on' 'off' 'z' 'x' 'y' } 'off';\n 'pointout' 'string' { 'on' 'off' } 'off';\n 'holdon' 'string' { 'on' 'off' } 'off';\n 'dipolesize' 'real' [0 Inf] 30;\n 'dipolelength' 'real' [0 Inf] 1;\n 'sphere' 'real' [0 Inf] 1;\n 'spheres' 'string' {'on' 'off'} 'off';\n 'links' 'real' [] [];\n 'image' { 'string' 'real' } [] 'mri';\n 'plot' 'string' { 'on' 'off' } 'on';\n 'meshdata' { 'string' 'cell' } [] '' }, 'dipplot');\n % 'std' 'cell' [] {}; \n % 'coreg' 'real' [] [];\n\n if isstr(g), error(g); end;\n if strcmpi(g.holdon, 'on'), g.gui = 'off'; end;\n if length(g.dipolesize) == 1, g.dipolesize = repmat(g.dipolesize, [1 length(sourcesori)]); end;\n \n g.zoom = 1500;\n\n if strcmpi(g.image, 'besa')\n error('BESA image not supported any more. Use EEGLAB version 4.512 or earlier. (BESA dipoles can still be plotted in MNI brain.)');\n end;\n \n % trying to determine coordformat\n % -------------------------------\n if ~isfield(sources, 'momxyz')\n g.coordformat = 'spherical';\n end;\n if strcmpi(g.coordformat, 'auto')\n if ~isempty(g.meshdata)\n g.coordformat = 'MNI';\n if strcmpi(g.verbose, 'on'), \n disp('Coordinate format unknown: using ''MNI'' since mesh data was provided as input');\n end\n else\n maxdiplen = 0;\n for ind = 1:length(sourcesori)\n maxdiplen = max(maxdiplen, max(abs(sourcesori(ind).momxyz(:))));\n end;\n if maxdiplen>2000\n if strcmpi(g.verbose, 'on'),\n disp('Coordinate format unknown: using ''MNI'' because of large dipole moments');\n end\n else\n g.coordformat = 'spherical';\n if strcmpi(g.verbose, 'on'),\n disp('Coordinate format unknown: using ''spherical'' since no mesh data was provided as input');\n end\n end;\n end;\n end;\n \n % axis image and limits\n % ---------------------\n dat.axistight = strcmpi(g.axistight, 'on');\n dat.drawedges = g.drawedges;\n dat.cornermri = strcmpi(g.cornermri, 'on');\n radius = 85;\n\n % look up an MRI file if necessary\n % --------------------------------\n if isempty(g.mri)\n if strcmpi(g.verbose, 'on'),\n disp('No MRI file given as input. Looking up one.');\n end\n dipfitdefs;\n g.mri = template_models(1).mrifile;\n end;\n \n % read anatomical MRI using Fieldtrip and SPM2 functons\n % -----------------------------------------------------\n if isstr(g.mri);\n try, \n g.mri = load('-mat', g.mri);\n g.mri = g.mri.mri;\n catch,\n disp('Failed to read Matlab file. Attempt to read MRI file using function read_fcdc_mri');\n try,\n warning off;\n g.mri = read_fcdc_mri(g.mri);\n %g.mri.anatomy(find(g.mri.anatomy > 255)) = 255;\n %g.mri.anatomy = uint8(g.mri.anatomy);\n g.mri.anatomy = round(gammacorrection( g.mri.anatomy, 0.8));\n g.mri.anatomy = uint8(round(g.mri.anatomy/max(reshape(g.mri.anatomy, prod(g.mri.dim),1))*255));\n % WARNING: if using double instead of int8, the scaling is different \n % [-128 to 128 and 0 is not good]\n % WARNING: the transform matrix is not 1, 1, 1 on the diagonal, some slices may be \n % misplaced\n warning on;\n catch,\n error('Cannot load file using read_fcdc_mri');\n end;\n end;\n end;\n \n if strcmpi(g.coordformat, 'spherical')\n dat.sph2spm = sph2spm;\n elseif strcmpi(g.coordformat, 'CTF')\n dat.sph2spm = traditionaldipfit([0 0 0 0 0 0 10 -10 10]);\n else\n dat.sph2spm = []; %traditional([0 0 0 0 0 pi 1 1 1]);\n end;\n \n if ~isempty(g.transform), dat.sph2spm = traditionaldipfit(g.transform);\n end;\n if isfield(g.mri, 'anatomycol')\n dat.imgs = g.mri.anatomycol;\n else\n dat.imgs = g.mri.anatomy;\n end;\n dat.transform = g.mri.transform; \n \n % MRI coordinates for slices\n % --------------------------\n if ~isfield(g.mri, 'xgrid')\n g.mri.xgrid = [1:size(dat.imgs,1)]; \n g.mri.ygrid = [1:size(dat.imgs,2)];\n g.mri.zgrid = [1:size(dat.imgs,3)];\n end;\n if strcmpi(g.coordformat, 'CTF')\n g.mri.zgrid = g.mri.zgrid(end:-1:1);\n end;\n\n dat.imgcoords = { g.mri.xgrid g.mri.ygrid g.mri.zgrid }; \n dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];\n COLORMESH = 'w';\n BACKCOLOR = 'k';\n \n % point 0\n % -------\n [xx yy zz] = transform(0, 0, 0, dat.sph2spm); % nothing happens for BEM since dat.sph2spm is empty\n dat.zeroloc = [ xx yy zz ];\n \n % conversion\n % ----------\n if strcmpi(g.normlen, 'on')\n if isfield(sources, 'besaextori')\n sources = rmfield(sources, 'besaextori'); \n end;\n end;\n if ~isfield(sources, 'besathloc') & strcmpi(g.image, 'besa') & ~is_sccn\n error(['For copyright reasons, it is not possible to use the BESA ' ...\n 'head model to plot non-BESA dipoles']);\n end;\n \n if isfield(sources, 'besathloc')\n sources = convertbesaoldformat(sources);\n end;\n if ~isfield(sources, 'posxyz')\n sources = computexyzforbesa(sources);\n end; \n if ~isfield(sources, 'component')\n if strcmpi(g.verbose, 'on'),\n disp('No component indices, making incremental ones...');\n end \n for index = 1:length(sources)\n sources(index).component = index;\n end;\n end; \n \n % find non-empty sources\n % ----------------------\n noempt = cellfun('isempty', { sources.posxyz } );\n sources = sources( find(~noempt) );\n \n % transform coordinates\n % ---------------------\n outsources = sources;\n for index = 1:length(sources)\n sources(index).momxyz = sources(index).momxyz/1000;\n end;\n \n % remove 0 second dipoles if any\n % ------------------------------\n for index = 1:length(sources)\n if size(sources(index).momxyz,1) == 2\n if all(sources(index).momxyz(2,:) == 0)\n sources(index).momxyz = sources(index).momxyz(1,:);\n sources(index).posxyz = sources(index).posxyz(1,:);\n end;\n end;\n end;\n\n % remove sources with out of bound Residual variance\n % --------------------------------------------------\n if isfield(sources, 'rv') & ~isempty(g.rvrange)\n if length(g.rvrange) == 1, g.rvrange = [ 0 g.rvrange ]; end;\n for index = length(sources):-1:1\n if sources(index).rv < g.rvrange(1)/100 | sources(index).rv > g.rvrange(2)/100\n sources(index) = [];\n end;\n end;\n end;\n \n % color array\n % -----------\n if isempty(g.color)\n g.color = { 'g' 'b' 'r' 'm' 'c' 'y' };\n if strcmp(BACKCOLOR, 'w'), g.color = { g.color{:} 'k' }; end;\n end;\n g.color = g.color(mod(0:length(sources)-1, length(g.color)) +1);\n if ~isempty(g.color)\n g.color = strcol2real( g.color, jet(64) );\n end;\n if ~isempty(g.projcol)\n g.projcol = strcol2real( g.projcol, jet(64) );\n g.projcol = g.projcol(mod(0:length(sources)-1, length(g.projcol)) +1); \n else\n g.projcol = g.color;\n for index = 1:length(g.color)\n g.projcol{index} = g.projcol{index}/2;\n end;\n end;\n \n % build summarized figure\n % -----------------------\n if strcmpi(g.summary, 'on') | strcmpi(g.summary, 'on2')\n figure;\n options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere ...\n 'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ...\n 'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight };\n pos1 = [0 0 0.5 0.5];\n pos2 = [0 0.5 0.5 .5];\n pos3 = [.5 .5 0.5 .5]; if strcmp(g.summary, 'on2'), tmp = pos1; pos1 =pos3; pos3 = tmp; end;\n axes('position', pos1); newsources = dipplot(sourcesori, 'view', [1 0 0] , options{:}); axis off; \n axes('position', pos2); newsources = dipplot(sourcesori, 'view', [0 0 1] , options{:}); axis off; \n axes('position', pos3); newsources = dipplot(sourcesori, 'view', [0 -1 0], options{:}); axis off; \n axes('position', [0.5 0 0.5 0.5]); \n colorcount = 1;\n if isfield(newsources, 'component')\n for index = 1:length(newsources)\n if isempty(g.dipnames), tmpname = sprintf( 'Comp. %d', newsources(index).component);\n else tmpname = char(g.dipnames{index});\n end;\n talpos = newsources(index).talcoord;\n if strcmpi(g.coordformat, 'CTF')\n textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%)' ], 100*newsources(index).rv) };\n elseif size(talpos,1) == 1\n textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d)' ], ...\n 100*newsources(index).rv, ...\n round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3))) };\n else\n textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d & %d,%d,%d)' ], ...\n 100*newsources(index).rv, ...\n round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3)), ...\n round(talpos(2,1)), round(talpos(2,2)), round(talpos(2,3))) };\n end;\n colorcount = colorcount+1;\n end;\n colorcount = colorcount-1;\n allstr = strvcat(textforgui{:});\n h = text(0,0.45, allstr);\n if colorcount >= 15, set(h, 'fontsize', 8);end;\n if colorcount >= 20, set(h, 'fontsize', 6);end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', 'w'); end;\n end;\n axis off;\n return;\n elseif strcmpi(g.summary, '3d')\n options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere, 'spheres', g.spheres ...\n 'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ...\n 'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight };\n figure('position', [ 100 600 600 200 ]); \n axes('position', [-0.1 -0.1 1.2 1.2], 'color', 'k'); axis off; blackimg = zeros(10,10,3); image(blackimg);\n axes('position', [0 0 1/3 1], 'tag', 'rear'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 -1 0]);\n axes('position', [1/3 0 1/3 1], 'tag', 'top' ); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 0 1]);\n axes('position', [2/3 0 1/3 1], 'tag', 'side'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([1 -0.01 0]);\n set(gcf, 'paperpositionmode', 'auto');\n return;\n end;\n \n % plot head graph in 3D\n % ---------------------\n if strcmp(g.gui, 'on')\n fig = figure('visible', g.plot); \n pos = get(gca, 'position');\n set(gca, 'position', [pos(1)+0.05 pos(2:end)]);\n end;\n indx = ceil(dat.imgcoords{1}(end)/2);\n indy = ceil(dat.imgcoords{2}(end)/2);\n indz = ceil(dat.imgcoords{3}(end)/2);\n if strcmpi(g.holdon, 'off')\n plotimgs( dat, [indx indy indz], dat.transform);\n \n set(gca, 'color', BACKCOLOR);\n %warning off; a = imread('besaside.pcx'); warning on;\n % BECAUSE OF A BUG IN THE WARP FUNCTION, THIS DOES NOT WORK (11/02)\n %hold on; warp([], wy, wz, a);\n % set camera target \n % -----------------\n \n % format axis (BESA or MRI)\n axis equal;\n set(gca, 'cameraviewanglemode', 'manual'); % disable change size\n camzoom(1.2^2);\n if strcmpi(g.coordformat, 'CTF'), g.view(2:3) = -g.view(2:3); end;\n view(g.view);\n %set(gca, 'cameratarget', dat.zeroloc); % disable change size\n %set(gca, 'cameraposition', dat.zeroloc+g.view*g.zoom); % disable change size\n axis off;\n end;\n \n % plot sphere mesh and nose\n % -------------------------\n if strcmpi(g.holdon, 'off')\n if isempty(g.meshdata)\n SPHEREGRAIN = 20; % 20 is also Matlab default\n [x y z] = sphere(SPHEREGRAIN);\n hold on; \n [xx yy zz] = transform(x*0.085, y*0.085, z*0.085, dat.sph2spm);\n [xx yy zz] = transform(x*85 , y*85 , z*85 , dat.sph2spm);\n %xx = x*100;\n %yy = y*100;\n %zz = z*100;\n if strcmpi(COLORMESH, 'w')\n hh = mesh(xx, yy, zz, 'cdata', ones(21,21,3), 'tag', 'mesh'); hidden off;\n else\n hh = mesh(xx, yy, zz, 'cdata', zeros(21,21,3), 'tag', 'mesh'); hidden off;\n end;\n else\n try, \n if isstr(g.meshdata)\n tmp = load('-mat', g.meshdata);\n g.meshdata = { 'vertices' tmp.vol.bnd(1).pnt 'faces' tmp.vol.bnd(1).tri };\n end;\n hh = patch(g.meshdata{:}, 'facecolor', 'none', 'edgecolor', COLORMESH, 'tag', 'mesh');\n catch, disp('Unrecognize model file (probably CTF)'); end;\n end;\n \n end;\n \n %x = x*100*scaling; y = y*100*scaling; z=z*100*scaling;\n %h = line(xx,yy,zz); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');\n %h = line(xx,zz,yy); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');\n %h = line([0 0;0 0],[-1 -1.2; -1.2 -1], [-0.3 -0.7; -0.7 -0.7]);\n %set(h, 'color', COLORMESH, 'linewidth', 3, 'tag', 'noze');\n \n % determine max length if besatextori exist\n % -----------------------------------------\n sizedip = [];\n for index = 1:length(sources)\n sizedip = [ sizedip sources(index).momxyz(3) ]; \n end;\n maxlength = max(sizedip);\n \n % diph = gca; % DEBUG\n % colormap('jet');\n % cbar\n % axes(diph);\n\n for index = 1:length(sources)\n nbdip = 1;\n if size(sources(index).posxyz, 1) > 1 & any(sources(index).posxyz(2,:)) nbdip = 2; end;\n \n % reorder dipoles for plotting\n if nbdip == 2\n if sources(index).posxyz(1,1) > sources(index).posxyz(2,1)\n tmp = sources(index).posxyz(2,:);\n sources(index).posxyz(2,:) = sources(index).posxyz(1,:);\n sources(index).posxyz(1,:) = tmp;\n tmp = sources(index).momxyz(2,:);\n sources(index).momxyz(2,:) = sources(index).momxyz(1,:);\n sources(index).momxyz(1,:) = tmp;\n end;\n if isfield(sources, 'active'),\n nbdip = length(sources(index).active);\n end;\n end;\n \n for dip = 1:nbdip\n \n multfactor = 1;\n x = sources(index).posxyz(dip,1);\n y = sources(index).posxyz(dip,2);\n z = sources(index).posxyz(dip,3);\n if strcmpi(g.normlen, 'on')\n len = sqrt(sum(sources(index).momxyz(dip,:).^2));\n if strcmpi(g.coordformat, 'CTF'), len = len*10; end;\n if len ~= 0, multfactor = 15/len; end;\n else\n if strcmpi(g.coordformat, 'spherical')\n multfactor = 100;\n else multfactor = 1.5;\n end; \n end;\n \n xo = sources(index).momxyz(dip,1)*g.dipolelength*multfactor;\n yo = sources(index).momxyz(dip,2)*g.dipolelength*multfactor;\n zo = sources(index).momxyz(dip,3)*g.dipolelength*multfactor;\n \n xc = 0;\n yc = 0;\n zc = 0;\n \n centvec = [xo-xc yo-yc zo-zc]; % vector pointing into center\n dipole_orient = [x+xo y+yo z+zo]/norm([x+xo y+yo z+zo]);\n c = dot(centvec, dipole_orient);\n \n if strcmpi(g.pointout,'on')\n if (c < 0) | (abs([x+xo,y+yo,z+zo]) < abs([x,y,z]))\n xo1 = x-xo; % make dipole point outward from head center\n yo1 = y-yo;\n zo1 = z-zo; \n %fprintf('invert because: %e \\n', c);\n else\n xo1 = x+xo;\n yo1 = y+yo;\n zo1 = z+zo;\n %fprintf('NO invert because: %e \\n', c);\n end\n else\n xo1 = x+xo;\n yo1 = y+yo;\n zo1 = z+zo;\n %fprintf('NO invert because: %e \\n', c);\n end\n \n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw dipole bar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n tag = [ 'dipole' num2str(index) ];\n \n % from spherical to electrode space\n % ---------------------------------\n [xx yy zz] = transform(x, y, z, dat.sph2spm); % nothing happens for BEM\n [xxo1 yyo1 zzo1] = transform(xo1, yo1, zo1, dat.sph2spm); % because dat.sph2spm = []\n\n if ~strcmpi(g.spheres,'on') % plot dipole direction lines\n h1 = line( [xx xxo1]', [yy yyo1]', [zz zzo1]');\n \n elseif g.dipolelength>0 % plot dipole direction cylinders with end cap patch\n \n [xc yc zc] = cylinder( 2, 10);\n [xs ys zs] = sphere(10);\n xc = [ xc; -xs(7:11,:)*2 ];\n yc = [ yc; -ys(7:11,:)*2 ];\n zc = [ zc; zs(7:11,:)/5+1 ];\n \n colorarray = repmat(reshape(g.color{index}, 1,1,3), [size(zc,1) size(zc,2) 1]);\n handles = surf(xc, yc, zc, colorarray, 'tag', tag, 'edgecolor', 'none', ...\n 'backfacelighting', 'lit', 'facecolor', 'interp', 'facelighting', ...\n 'phong', 'ambientstrength', 0.3);\n [xc yc zc] = adjustcylinder2( handles, [xx yy zz], [xxo1 yyo1 zzo1] );\n\n cx = mean(xc,2); %cx = [(3*cx(1)+cx(2))/4; (cx(1)+3*cx(2))/4];\n cy = mean(yc,2); %cy = [(3*cy(1)+cy(2))/4; (cy(1)+3*cy(2))/4];\n cz = mean(zc,2); %cz = [(3*cz(1)+cz(2))/4; (cz(1)+3*cz(2))/4];\n tmpx = xc - repmat(cx, [1 size(xc, 2)]);\n tmpy = yc - repmat(cy, [1 size(xc, 2)]);\n tmpz = zc - repmat(cz, [1 size(xc, 2)]);\n l=sqrt(tmpx.^2+tmpy.^2+tmpz.^2);\n warning('off', 'MATLAB:divideByZero'); % this is due to a Matlab 2008b (or later) \n normals = reshape([tmpx./l tmpy./l tmpz./l],[size(tmpx) 3]); % in the rotate function in adjustcylinder2\n warning('off', 'MATLAB:divideByZero'); % one of the z (the last row is not rotated)\n set( handles, 'vertexnormals', normals);\n \n end\n\n [xxmri yymri zzmri ] = transform(xx, yy, zz, pinv(dat.transform));\n [xxmrio1 yymrio1 zzmrio1] = transform(xxo1, yyo1, zzo1, pinv(dat.transform));\n dipstruct.mricoord = [xxmri yymri zzmri]; % Coordinates in MRI space\n dipstruct.eleccoord = [ xx yy zz ]; % Coordinates in elec space\n dipstruct.posxyz = sources(index).posxyz; % Coordinates in spherical space\n outsources(index).eleccoord(dip,:) = [xx yy zz];\n outsources(index).mnicoord(dip,:) = [xx yy zz];\n outsources(index).mricoord(dip,:) = [xxmri yymri zzmri];\n outsources(index).talcoord(dip,:) = mni2tal([xx yy zz]')';\n dipstruct.talcoord = mni2tal([xx yy zz]')';\n \n % copy for output\n % ---------------\n XX(index) = xxmri;\n YY(index) = yymri;\n ZZ(index) = zzmri;\n XO(index) = xxmrio1;\n YO(index) = yymrio1;\n ZO(index) = zzmrio1;\n\n if isempty(g.dipnames)\n dipstruct.rv = sprintf('%3.2f', sources(index).rv*100);\n dipstruct.name = sources(index).component;\n else\n dipstruct.rv = sprintf('%3.2f', sources(index).rv*100);\n dipstruct.name = g.dipnames{index};\n end;\n if ~strcmpi(g.spheres,'on') % plot disk markers\n set(h1,'userdata',dipstruct,'tag',tag,'color','k','linewidth',g.dipolesize(index)/7.5);\n if strcmp(BACKCOLOR, 'k'), set(h1, 'color', g.color{index}); end;\n end\n \n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw sphere or disk marker %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n hold on;\n if strcmpi(g.spheres,'on') % plot spheres\n if strcmpi(g.projimg, 'on')\n if strcmpi(g.verbose, 'on'),\n disp('Warning: projections cannot be plotted for 3-D sphere');\n end\n %tmpcolor = g.color{index} / 2;\n %h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}, 'proj', ...\n % [dat.imgcoords{1}(1) dat.imgcoords{2}(end) dat.imgcoords{3}(1)]*97/100, 'projcol', tmpcolor);\n \n %set(h(2:end), 'userdata', 'proj', 'tag', tag);\n else\n %h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index});\n end; \n h = plotsphere([xx yy zz], g.dipolesize(index)/6, 'color', g.color{index});\n set(h(1), 'userdata', dipstruct, 'tag', tag);\n % cko: try to plot dipnames\n if ~isempty(g.dipnames)\n try\n text(xx,yy,zz,g.dipnames{index},'color',[0.99 0.99 0.99]);\n catch\n end\n end\n \n else % plot dipole markers\n h = plot3(xx, yy, zz); \n set(h, 'userdata', dipstruct, 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize(index), 'color', g.color{index});\n end\n \n \n \n \n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto images %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n [tmp1xx tmp1yy tmp1zz ] = transform( xxmri , yymri , dat.imgcoords{3}(1), dat.transform);\n [tmp1xxo1 tmp1yyo1 tmp1zzo1] = transform( xxmrio1, yymrio1, dat.imgcoords{3}(1), dat.transform);\n [tmp2xx tmp2yy tmp2zz ] = transform( xxmri , dat.imgcoords{2}(end), zzmri , dat.transform);\n [tmp2xxo1 tmp2yyo1 tmp2zzo1] = transform( xxmrio1, dat.imgcoords{2}(end), zzmrio1, dat.transform);\n [tmp3xx tmp3yy tmp3zz ] = transform( dat.imgcoords{1}(1), yymri , zzmri , dat.transform);\n [tmp3xxo1 tmp3yyo1 tmp3zzo1] = transform( dat.imgcoords{1}(1), yymrio1, zzmrio1, dat.transform);\n \n if strcmpi(g.projimg, 'on') & strcmpi(g.spheres, 'off')\n tmpcolor = g.projcol{index};\n \n % project onto z axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [tmp1xx tmp1xxo1]', [tmp1yy tmp1yyo1]', [tmp1zz tmp1zzo1]');\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(tmp1xx, tmp1yy, tmp1zz); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);\n \n % project onto y axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [tmp2xx tmp2xxo1]', [tmp2yy tmp2yyo1]', [tmp2zz tmp2zzo1]');\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(tmp2xx, tmp2yy, tmp2zz); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);\n \n % project onto x axis\n tag = [ 'dipole' num2str(index) ];\n if ~strcmpi(g.image, 'besa')\n h = line( [tmp3xx tmp3xxo1]', [tmp3yy tmp3yyo1]', [tmp3zz tmp3zzo1]');\n set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);\n end;\n if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;\n h = plot3(tmp3xx, tmp3yy, tmp3zz); \n set(h, 'userdata', 'proj', 'tag', tag, ...\n 'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);\n end;\n\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto axes %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if ~strcmpi(g.projlines, 'off')\n clear h;\n % project onto z axis\n if any(strcmpi(g.projlines, {'on','z'}))\n tag = [ 'dipole' num2str(index) ];\n h(1) = line( [xx tmp1xx]', [yy tmp1yy]', [zz tmp1zz]);\n set(h(1), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', max(1,g.dipolesize(index)/7.5/5));\n end\n \n % project onto x axis\n if any(strcmpi(g.projlines, {'on','x'}))\n tag = [ 'dipole' num2str(index) ];\n h(2) = line( [xx tmp2xx]', [yy tmp2yy]', [zz tmp2zz]);\n set(h(2), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', max(1,g.dipolesize(index)/7.5/5));\n end\n \n % project onto y axis\n if any(strcmpi(g.projlines, {'on','y'}))\n tag = [ 'dipole' num2str(index) ];\n h(3) = line( [xx tmp3xx]', [yy tmp3yy]', [zz tmp3zz]);\n set(h(3), 'userdata', 'proj', 'linestyle', '--', ...\n 'tag', tag, 'color', g.color{index}, 'linewidth', max(1,g.dipolesize(index)/7.5/5));\n end\n \n if ~isempty(g.projcol)\n set(h, 'color', g.projcol{index});\n end;\n end;\n % \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw text %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if isfield(sources, 'component')\n if strcmp(g.num, 'on')\n h = text(xx, yy, zz, [ ' ' int2str(sources(index).component)]);\n set(h, 'userdata', dipstruct, 'tag', tag, 'fontsize', g.dipolesize(index)/2 );\n if ~strcmpi(g.image, 'besa'), set(h, 'color', 'w'); end;\n end;\n end;\n end;\n end;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3-D settings\n if strcmpi(g.spheres, 'on')\n lighting phong;\n material shiny;\n camlight left;\n camlight right;\n end;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw elipse for group of dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % does not work because of new scheme, have to be reprogrammed\n \n %if ~isempty(g.std)\n % for index = 1:length(g.std)\n % if ~iscell(g.std{index})\n % plotellipse(sources, g.std{index}, 1, dat.tcparams, dat.coreg);\n % else\n % sc = plotellipse(sources, g.std{index}{1}, g.std{index}{2}, dat.tcparams, dat.coreg);\n % if length( g.std{index} ) > 2\n % set(sc, g.std{index}{3:end});\n % end;\n % end;\n % end;\n % end;\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% buttons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n nbsrc = int2str(length(sources));\n cbmesh = [ 'if get(gcbo, ''userdata''), ' ...\n ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''off'');' ...\n ' set(gcbo, ''string'', ''Mesh on'');' ...\n ' set(gcbo, ''userdata'', 0);' ...\n 'else,' ...\n ' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''on'');' ...\n ' set(gcbo, ''string'', ''Mesh off'');' ...\n ' set(gcbo, ''userdata'', 1);' ...\n 'end;' ];\n cbplot = [ 'if strcmpi(get(gcbo, ''string''), ''plot one''),' ...\n ' for tmpi = 1:' nbsrc ',' ...\n ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''off'');' ...\n ' end; clear tmpi;' ...\n ' dipplot(gcbf);' ... \n ' set(gcbo, ''string'', ''Plot all'');' ...\n 'else,' ...\n ' for tmpi = 1:' nbsrc ',' ...\n ' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''on'');' ...\n ' end; clear tmpi;' ...\n ' set(gcbo, ''string'', ''Plot one'');' ...\n 'end;' ];\n cbview = [ 'tmpuserdat = get(gca, ''userdata'');' ...\n 'if tmpuserdat.axistight, ' ...\n ' set(gcbo, ''string'', ''Tight view'');' ...\n 'else,' ...\n ' set(gcbo, ''string'', ''Loose view'');' ...\n 'end;' ...\n 'tmpuserdat.axistight = ~tmpuserdat.axistight;' ...\n 'set(gca, ''userdata'', tmpuserdat);' ...\n 'clear tmpuserdat;' ...\n 'dipplot(gcbf);' ];\n viewstring = fastif(dat.axistight, 'Loose view', 'Tight view');\n enmesh = fastif(isempty(g.meshdata) & strcmpi(g.coordformat, 'MNI'), 'off', 'on');\n if strcmpi(g.coordformat, 'CTF'), viewcor = 'view([0 1 0]);'; viewtop = 'view([0 0 -1]);'; vis = 'off';\n else viewcor = 'view([0 -1 0]);'; viewtop = 'view([0 0 1]);'; vis = 'on';\n end;\n \n h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 1], 'tag', 'tmp', ...\n 'style', 'text', 'string',' ');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'fontweight', 'bold', 'string', 'No controls', 'callback', ...\n 'set(findobj(''parent'', gcbf, ''tag'', ''tmp''), ''visible'', ''off'');');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.05 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Top view', 'callback', viewtop);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.1 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Coronal view', 'callback', viewcor);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.15 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Sagittal view', 'callback', 'view([1 0 0]);');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.2 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', viewstring, 'callback', cbview);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.25 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Mesh on', 'userdata', 0, 'callback', ...\n cbmesh, 'enable', enmesh, 'visible', vis );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.3 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', 'Display:','fontweight', 'bold' );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.35 .15 .02], 'tag', 'tmp',...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.37 .15 .05], 'tag', 'tmp','userdata', 'z',...\n 'style', 'text', 'string', 'Z:', 'visible', vis );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.42 .15 .05], 'tag', 'tmp','userdata', 'y', ...\n 'style', 'text', 'string', 'Y:', 'visible', vis );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.47 .15 .05], 'tag', 'tmp', 'userdata', 'x',...\n 'style', 'text', 'string', 'X:', 'visible', vis );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.52 .15 .05], 'tag', 'tmp', 'userdata', 'rv',...\n 'style', 'text', 'string', 'RV:' );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.57 .15 .05], 'tag', 'tmp', 'userdata', 'comp', ...\n 'style', 'text', 'string', '');\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.62 .15 .05], 'tag', 'tmp', 'userdata', 'editor', ...\n 'style', 'edit', 'string', '1', 'callback', ...\n [ 'dipplot(gcbf);' ] );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.67 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Keep|Prev', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...\n 'tmpobj = get(gcf, ''userdata'');' ...\n 'eval(get(editobj, ''callback''));' ...\n 'set(tmpobj, ''visible'', ''on'');' ...\n 'clear editobj tmpobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.72 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Prev', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...\n 'eval(get(editobj, ''callback''));' ...\n 'clear editobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.77 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Next', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...\n 'dipplot(gcbf);' ...\n 'clear editobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.82 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Keep|Next', 'callback', ...\n [ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...\n 'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...\n 'tmpobj = get(gcf, ''userdata'');' ...\n 'dipplot(gcbf);' ...\n 'set(tmpobj, ''visible'', ''on'');' ...\n 'clear editobj tmpobj;' ]);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.87 .15 .05], 'tag', 'tmp', ...\n 'style', 'pushbutton', 'string', 'Plot one', 'callback', cbplot);\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.92 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', [num2str(length(sources)) ' dipoles:'], 'fontweight', 'bold' );\n h = uicontrol( 'unit', 'normalized', 'position', [0 0.97 .15 .05], 'tag', 'tmp', ...\n 'style', 'text', 'string', '');\n set(gcf, 'userdata', findobj('parent', gca, 'tag', 'dipole1'));\n \n dat.nbsources = length(sources);\n set(gca, 'userdata', dat ); % last param=1 for MRI view tight/loose\n set(gcf, 'color', BACKCOLOR);\n \n if strcmp(g.gui, 'off') | strcmpi(g.holdon, 'on')\n set(findobj('parent', gcf, 'tag', 'tmp'), 'visible', 'off');\n end;\n if strcmp(g.mesh, 'off')\n set(findobj('parent', gca, 'tag', 'mesh'), 'visible', 'off');\n end;\n \n updatedipplot(gcf);\n \n rotate3d on;\n \n % close figure if necessary\n if strcmpi(g.plot, 'off')\n try, close(fig); catch, end;\n end;\n \n if strcmpi(g.holdon, 'on')\n box off;\n axis equal;\n axis off;\n end;\n \nreturn;\n\n% electrode space to MRI space\n% ============================\nfunction [x,y,z] = transform(x, y, z, transmat);\n \n if isempty(transmat), return; end;\n for i = 1:size(x,1)\n for j = 1:size(x,2)\n tmparray = transmat * [ x(i,j) y(i,j) z(i,j) 1 ]';\n x(i,j) = tmparray(1);\n y(i,j) = tmparray(2);\n z(i,j) = tmparray(3);\n end;\n end;\n \n \n% does not work any more\n% ----------------------\nfunction sc = plotellipse(sources, ind, nstd, TCPARAMS, coreg);\n\n for i = 1:length(ind)\n tmpval(1,i) = -sources(ind(i)).posxyz(1); \n tmpval(2,i) = -sources(ind(i)).posxyz(2); \n tmpval(3,i) = sources(ind(i)).posxyz(3);\n [tmpval(1,i) tmpval(2,i) tmpval(3,i)] = transform(tmpval(1,i), tmpval(2,i), tmpval(3,i), TCPARAMS);\n end;\n \n % mean and covariance\n C = cov(tmpval');\n M = mean(tmpval,2);\n [U,L] = eig(C);\n \n % For N standard deviations spread of data, the radii of the eliipsoid will\n % be given by N*SQRT(eigenvalues).\n radii = nstd*sqrt(diag(L));\n \n % generate data for \"unrotated\" ellipsoid\n [xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3), 10);\n \n % rotate data with orientation matrix U and center M\n a = kron(U(:,1),xc); b = kron(U(:,2),yc); c = kron(U(:,3),zc);\n data = a+b+c; n = size(data,2);\n x = data(1:n,:)+M(1); y = data(n+1:2*n,:)+M(2); z = data(2*n+1:end,:)+M(3);\n \n % now plot the rotated ellipse\n c = ones(size(z));\n sc = mesh(x,y,z);\n alpha(0.5)\n \nfunction newsrc = convertbesaoldformat(src);\n newsrc = [];\n count = 1;\n countdip = 1;\n if ~isfield(src, 'besaextori'), src(1).besaextori = []; end;\n for index = 1:length(src)\n \n % convert format\n % --------------\n if isempty(src(index).besaextori), src(index).besaextori = 300; end; % 20 mm\n newsrc(count).possph(countdip,:) = [ src(index).besathloc src(index).besaphloc src(index).besaexent];\n newsrc(count).momsph(countdip,:) = [ src(index).besathori src(index).besaphori src(index).besaextori/300];\n \n % copy other fields\n % -----------------\n if isfield(src, 'stdX')\n newsrc(count).stdX = -src(index).stdY;\n newsrc(count).stdY = src(index).stdX;\n newsrc(count).stdZ = src(index).stdZ;\n end;\n if isfield(src, 'rv')\n newsrc(count).rv = src(index).rv;\n end;\n if isfield(src, 'elecrv')\n newsrc(count).rvelec = src(index).elecrv;\n end;\n if isfield(src, 'component')\n newsrc(count).component = src(index).component;\n if index ~= length(src) & src(index).component == src(index+1).component\n countdip = countdip + 1;\n else\n count = count + 1; countdip = 1;\n end;\n else\n count = count + 1; countdip = 1;\n end;\n end; \n\nfunction src = computexyzforbesa(src);\n \n for index = 1:length( src )\n for index2 = 1:size( src(index).possph, 1 )\n\n % compute coordinates\n % -------------------\n postmp = src(index).possph(index2,:);\n momtmp = src(index).momsph(index2,:);\n \n phi = postmp(1)+90; %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%\n theta = postmp(2); %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%\n phiori = momtmp(1)+90; %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%\n thetaori = momtmp(2); %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%\n % exentricities are in % of the radius of the head sphere\n [x y z] = sph2cart(theta/180*pi, phi/180*pi, postmp(3)/1.2); \n [xo yo zo] = sph2cart(thetaori/180*pi, phiori/180*pi, momtmp(3)*5); % exentricity scaled for compatibility with DIPFIT\n src(index).posxyz(index2,:) = [-y x z];\n src(index).momxyz(index2,:) = [-yo xo zo];\n \n end;\n end;\n \n% update dipplot (callback call)\n% ------------------------------\nfunction updatedipplot(fig)\n \n % find current dipole index and test for authorized range\n % -------------------------------------------------------\n dat = get(gca, 'userdata');\n editobj = findobj('parent', fig, 'userdata', 'editor');\n tmpnum = str2num(get(editobj(end), 'string'));\n if tmpnum < 1, tmpnum = 1; end;\n if tmpnum > dat.nbsources, tmpnum = dat.nbsources; end;\n set(editobj(end), 'string', num2str(tmpnum));\n \n % hide current dipole, find next dipole and show it\n % -------------------------------------------------\n set(get(gcf, 'userdata'), 'visible', 'off');\n newdip = findobj('parent', gca, 'tag', [ 'dipole' get(editobj(end), 'string')]);\n set(newdip, 'visible', 'on');\n set(gcf, 'userdata', newdip);\n \n % find all dipolar structures\n % ---------------------------\n index = 1;\n count = 1;\n for index = 1:length(newdip)\n if isstruct( get(newdip(index), 'userdata') )\n dip_mricoord(count,:) = getfield(get(newdip(index), 'userdata'), 'mricoord');\n count = count+1;\n foundind = index;\n end;\n end;\n \n % get residual variance\n % ---------------------\n if exist('foundind')\n tmp = get(newdip(foundind), 'userdata');\n tal = tmp.talcoord;\n if ~isstr( tmp.name )\n tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', [ 'Comp: ' int2str(tmp.name) ] );\n else tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', tmp.name );\n end;\n tmprvobj = findobj('parent', fig, 'userdata', 'rv'); set( tmprvobj(end), 'string', [ 'RV: ' tmp.rv '%' ] );\n tmprvobj = findobj('parent', fig, 'userdata', 'x'); set( tmprvobj(end), 'string', [ 'X tal: ' int2str(round(tal(1))) ]);\n tmprvobj = findobj('parent', fig, 'userdata', 'y'); set( tmprvobj(end), 'string', [ 'Y tal: ' int2str(round(tal(2))) ]);\n tmprvobj = findobj('parent', fig, 'userdata', 'z'); set( tmprvobj(end), 'string', [ 'Z tal: ' int2str(round(tal(3))) ]);\n end\n \n % adapt the MRI to the dipole depth\n % ---------------------------------\n delete(findobj('parent', gca, 'tag', 'img'));\n \n tmpdiv1 = dat.imgcoords{1}(2)-dat.imgcoords{1}(1);\n tmpdiv2 = dat.imgcoords{2}(2)-dat.imgcoords{2}(1);\n tmpdiv3 = dat.imgcoords{3}(2)-dat.imgcoords{3}(1);\n if ~dat.axistight\n [xx yy zz] = transform(0,0,0, pinv(dat.transform)); % elec -> MRI space\n indx = minpos(dat.imgcoords{1}-zz);\n indy = minpos(dat.imgcoords{2}-yy);\n indz = minpos(dat.imgcoords{3}-xx);\n else\n if ~dat.cornermri\n indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1))) - 3*tmpdiv1;\n indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2))) + 3*tmpdiv2;\n indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3))) - 3*tmpdiv3;\n else % no need to shift slice if not ploted close to the dipole\n indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1)));\n indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2)));\n indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3)));\n end;\n end;\n \n % middle of the brain\n % ------------------- \n plotimgs( dat, [indx indy indz], dat.transform);\n %end;\n \t\n% plot images (transmat is the uniform matrix MRI coords -> elec coords)\n% ----------------------------------------------------------------------\nfunction plotimgs(dat, mricoord, transmat);\n \n % loading images\n % --------------\n if ndims(dat.imgs) == 4 % true color data\n img1(:,:,3) = rot90(squeeze(dat.imgs(mricoord(1),:,:,3))); \n img2(:,:,3) = rot90(squeeze(dat.imgs(:,mricoord(2),:,3))); \n img3(:,:,3) = rot90(squeeze(dat.imgs(:,:,mricoord(3),3))); \n img1(:,:,2) = rot90(squeeze(dat.imgs(mricoord(1),:,:,2))); \n img2(:,:,2) = rot90(squeeze(dat.imgs(:,mricoord(2),:,2))); \n img3(:,:,2) = rot90(squeeze(dat.imgs(:,:,mricoord(3),2))); \n img1(:,:,1) = rot90(squeeze(dat.imgs(mricoord(1),:,:,1))); \n img2(:,:,1) = rot90(squeeze(dat.imgs(:,mricoord(2),:,1))); \n img3(:,:,1) = rot90(squeeze(dat.imgs(:,:,mricoord(3),1))); \n else\n img1 = rot90(squeeze(dat.imgs(mricoord(1),:,:))); \n img2 = rot90(squeeze(dat.imgs(:,mricoord(2),:))); \n img3 = rot90(squeeze(dat.imgs(:,:,mricoord(3)))); \n\n if ndims(img1) == 2, img1(:,:,3) = img1; img1(:,:,2) = img1(:,:,1); end;\n if ndims(img2) == 2, img2(:,:,3) = img2; img2(:,:,2) = img2(:,:,1); end;\n if ndims(img3) == 2, img3(:,:,3) = img3; img3(:,:,2) = img3(:,:,1); end;\n end;\n \n % computing coordinates for planes\n % -------------------------------- \n wy1 = [min(dat.imgcoords{2}) max(dat.imgcoords{2}); min(dat.imgcoords{2}) max(dat.imgcoords{2})];\n wz1 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})];\n wx2 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})];\n wz2 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})];\n wx3 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})];\n wy3 = [min(dat.imgcoords{2}) min(dat.imgcoords{2}); max(dat.imgcoords{2}) max(dat.imgcoords{2})];\n if dat.axistight & ~dat.cornermri\n wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(mricoord(1));\n wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(mricoord(2));\n wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(mricoord(3));\n else\n wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(1);\n wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(end);\n wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(1);\n end;\n \n % transform MRI coordinates to electrode space\n % --------------------------------------------\n [ elecwx1 elecwy1 elecwz1 ] = transform( wx1, wy1, wz1, transmat);\n [ elecwx2 elecwy2 elecwz2 ] = transform( wx2, wy2, wz2, transmat);\n [ elecwx3 elecwy3 elecwz3 ] = transform( wx3, wy3, wz3, transmat);\n \n % ploting surfaces\n % ----------------\n options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ...\n 'direct','tag','img', 'facelighting', 'none' };\n hold on;\n surface(elecwx1, elecwy1, elecwz1, img1(end:-1:1,:,:), options{:}); \n surface(elecwx2, elecwy2, elecwz2, img2(end:-1:1,:,:), options{:});\n surface(elecwx3, elecwy3, elecwz3, img3(end:-1:1,:,:), options{:}); \n %xlabel('x'); ylabel('y'); zlabel('z'); axis equal; dsaffd\n \n if strcmpi(dat.drawedges, 'on')\n % removing old edges if any\n delete(findobj( gcf, 'tag', 'edges'));\n if dat.axistight & ~dat.cornermri, col = 'k'; else col = [0.5 0.5 0.5]; end;\n h(1) = line([elecwx3(1) elecwx3(2)]', [elecwy3(1) elecwy2(1)]', [elecwz1(1) elecwz1(2)]'); % sagittal-transverse\n h(2) = line([elecwx3(1) elecwx2(3)]', [elecwy2(1) elecwy2(2)]', [elecwz1(1) elecwz1(2)]'); % coronal-tranverse\n h(3) = line([elecwx3(1) elecwx3(2)]', [elecwy2(1) elecwy2(2)]', [elecwz3(1) elecwz1(1)]'); % sagittal-coronal\n set(h, 'color', col, 'linewidth', 2, 'tag', 'edges');\n end;\n \n %%fill3([-2 -2 2 2], [-2 2 2 -2], wz(:)-1, BACKCOLOR);\n %%fill3([-2 -2 2 2], wy(:)-1, [-2 2 2 -2], BACKCOLOR);\n rotate3d on \n\nfunction index = minpos(vals);\n\tvals(find(vals < 0)) = inf;\n\t[tmp index] = min(vals);\n\nfunction scalegca(multfactor)\n xl = xlim; xf = ( xl(2) - xl(1) ) * multfactor;\n yl = ylim; yf = ( yl(2) - yl(1) ) * multfactor;\n zl = zlim; zf = ( zl(2) - zl(1) ) * multfactor;\n xlim( [ xl(1)-xf xl(2)+xf ]);\n ylim( [ yl(1)-yf yl(2)+yf ]);\n zlim( [ zl(1)-zf zl(2)+zf ]);\n \nfunction color = strcol2real(colorin, colmap)\n if ~iscell(colorin)\n for index = 1:length(colorin)\n color{index} = colmap(colorin(index),:);\n end;\n else\n color = colorin;\n for index = 1:length(colorin)\n if isstr(colorin{index})\n switch colorin{index}\n case 'r', color{index} = [1 0 0];\n case 'g', color{index} = [0 1 0];\n case 'b', color{index} = [0 0 1];\n case 'c', color{index} = [0 1 1];\n case 'm', color{index} = [1 0 1];\n case 'y', color{index} = [1 1 0];\n case 'k', color{index} = [0 0 0];\n case 'w', color{index} = [1 1 1];\n otherwise, error('Unknown color');\n end;\n end;\n end;\n end;\n\nfunction x = gammacorrection(x, gammaval);\n x = 255 * (double(x)/255).^ gammaval;\n % image is supposed to be scaled from 0 to 255\n % gammaval = 1 is identity of course\n \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/dipplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17513091711632015}} {"text": "clc;clear all;close all;\naddpath ../test\naddpath ..\naddpath CM_Curve\n%netStruct = load('../data/res52_drop0.75_batch16_psudo_label/net-epoch-25.mat');\n%netStruct.net.layers(end-3)=[];\n%netStruct.net.vars(178)=[];\n%net = dagnn.DagNN.loadobj(netStruct.net);\n%net.addLayer('feature',dagnn.Concat('dim',3),{'pool5','pool5_local'},{'pool5_fine'});\n%net.mode = 'test' ;\n%net.move('gpu') ;\nrank_size = 2000;\n%net.conserveMemory = false;\n%im_mean = net.meta.normalization.averageImage;\n%im_mean = imresize(im_mean,[224,224]);\n\n\n%% add necessary paths\nquery_dir = '/DATACENTER/1/qxl/PRID/Market-1501/query/';% query directory\ntest_dir = '/DATACENTER/1/qxl/PRID/Market-1501/bounding_box_test/';% database directory\nfeature_dir = '/home/qxl/Desktop/';\n\n%% calculate query features\nHist_query = importdata([feature_dir 'Hist_query.mat']);\nnQuery = size(Hist_query, 2);\n%nQuery = 100;\n%% calculate database features\nHist_test = importdata([feature_dir 'Hist_test.mat']);\nnTest = size(Hist_test, 2);\n%nTest = 19732;\n%% calculate the ID and camera for database images\nmkdir('./data')\ntest_files = dir([test_dir '*.jpg']);\ntestID = zeros(length(test_files), 1);\ntestCAM = zeros(length(test_files), 1);\nif ~exist('data/testID.mat')\n for n = 1:length(test_files)\n img_name = test_files(n).name;\n if strcmp(img_name(1), '-') % junk images\n testID(n) = -1;\n testCAM(n) = str2num(img_name(5));\n else\n %img_name\n testID(n) = str2num(img_name(1:4));\n testCAM(n) = str2num(img_name(7));\n end\n end\n save('data/testID.mat', 'testID');\n save('data/testCAM.mat', 'testCAM');\nelse\n testID = importdata('data/testID.mat');\n testCAM = importdata('data/testCAM.mat'); \nend\n\n%% calculate the ID and camera for query images\nquery_files = dir([query_dir '*.jpg']);\nqueryID = zeros(length(query_files), 1);\nqueryCAM = zeros(length(query_files), 1);\nif ~exist('data/queryID.mat')\n for n = 1:length(query_files)\n img_name = query_files(n).name;\n if strcmp(img_name(1), '-') % junk images\n queryID(n) = -1;\n queryCAM(n) = str2num(img_name(5));\n else\n queryID(n) = str2num(img_name(1:4));\n queryCAM(n) = str2num(img_name(7));\n end\n end\n save('data/queryID.mat', 'queryID');\n save('data/queryCAM.mat', 'queryCAM');\nelse\n queryID = importdata('data/queryID.mat');\n queryCAM = importdata('data/queryCAM.mat'); \nend\n\n%% search the database and calcuate re-id accuracy\nap = zeros(nQuery, 1); % average precision\nap_max_rerank = zeros(nQuery, 1); % average precision with MultiQ_max + re-ranking \nap_pairwise = zeros(nQuery, 6); % pairwise average precision with single query (see Fig. 7 in the paper)\n\nCMC = zeros(nQuery, rank_size);\nCMC_max_rerank = zeros(nQuery, rank_size);\n\nr1 = 0; % rank 1 precision with single query\nr1_max_rerank = 0; % rank 1 precision with MultiQ_max + re-ranking\nr1_pairwise = zeros(nQuery, 6);% pairwise rank 1 precision with single query (see Fig. 7 in the paper)\n\n%dist = importdata('/home/qxl/Desktop/score_distmat.mat');\ndist = sqdist(Hist_test, Hist_query); % distance calculate with single query. Note that Euclidean distance is equivalent to cosine distance if vectors are l2-normalized\n%dist_cos_max = (2-dist_max)./2; % cosine distance with MultiQ_max, used for re-ranking\n\nknn = 1; % number of expanded queries. knn = 1 yields best result\n%queryCam = importdata('data/queryCAM_duke.mat'); % camera ID for each query\n%testCam = importdata('data/testCAM_duke.mat'); % camera ID for each database image\n\nfor k = 1:nQuery\n % load ground truth for each query (good and junk)\n good_index = intersect(find(testID == queryID(k)), find(testCAM ~= queryCAM(k)))';% images with the same ID but different camera from the query\n junk_index1 = find(testID == -1);% images neither good nor bad in terms of bbox quality\n junk_index2 = intersect(find(testID == queryID(k)), find(testCAM == queryCAM(k))); % images with the same ID and the same camera as the query\n junk_index = [junk_index1; junk_index2]';\n score = dist(:, k);\n %score_avg = dist_avg(:, k); \n %score_max = dist_max(:, k);\n \n % sort database images according Euclidean distance\n [~, index] = sort(score, 'ascend'); % single query\n \n % re-rank select rank_size=1000 index\n index = index(1:rank_size); \n %for l=1:length(index)\n % fprintf('%d, %s\\n',index(l),test_files(index(l)).name)\n %end\n \n [ap(k), CMC(k, :)] = compute_AP_rerank(good_index, junk_index, index);% compute AP for single query\n %ap_pairwise(k, :) = compute_AP_multiCam(good_index, junk_index1,junk_index2, index, queryCAM(k), testCAM); % compute pairwise AP for single query\n fprintf('%d,%s::%f\\n',k,query_files(k).name,ap(k));\n %%%%%%%%%%% calculate pairwise r1 precision %%%%%%%%%%%%%%%%%%%%\n %r1_pairwise(k, :) = compute_r1_multiCam(good_index, junk_index1,junk_index2, index, queryCAM(k), testCAM); % pairwise rank 1 precision with single query\n %%%%%%%%%%%%%% calculate r1 precision %%%%%%%%%%%%%%%%%%%%\nend\nCMC = mean(CMC);\n%% print result\nfprintf('single query: mAP = %f, r1 precision = %f\\r\\n', mean(ap), CMC(1));\n%[ap_CM, r1_CM] = draw_confusion_matrix(ap_pairwise, r1_pairwise, queryCam);\n%fprintf('average of confusion matrix with single query: mAP = %f, r1 precision = %f\\r\\n', (sum(ap_CM(:))-sum(diag(ap_CM)))/30, (sum(r1_CM(:))-sum(diag(r1_CM)))/30);\n\n%% plot CMC curves\nfigure;\ns = 50;\nCMC_curve = CMC ;\nplot(1:s, CMC_curve(:, 1:s));\n", "meta": {"author": "naiq", "repo": "PN_GAN", "sha": "276dda6772709a527f99e0351342f1023e1bb423", "save_path": "github-repos/MATLAB/naiq-PN_GAN", "path": "github-repos/MATLAB/naiq-PN_GAN/PN_GAN-276dda6772709a527f99e0351342f1023e1bb423/script/Market-1501_baseline/quick_evaluate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1748659034787712}} {"text": "% PLOTTOPO - plot concatenated multichannel data epochs in a topographic\n% or\n% rectangular array. Uses a channel location file with the same \n% format as TOPOPLOT, or else plots data on a rectangular grid. \n% If data are all positive, they are assumed to be spectra.\n% Usage:\n% >> plottopo(data, 'key1', 'val1', 'key2', 'val2')\n% Or\n% >> plottopo(data,'chan_locs',frames,limits,title,channels,...\n% axsize,colors,ydir,vert) % old function call\n% Inputs:\n% data = data consisting of consecutive epochs of (chans,frames)\n% or (chans,frames,n)\n%\n% Optional inputs:\n% 'chanlocs' = [struct] channel structure or file plot ERPs at channel \n% locations. See help READLOCS for data channel format.\n% 'geom' = [rows cols] plot ERP in grid (overwrite previous option).\n% Grid size for rectangular matrix. Example: [6 4].\n% 'frames' = time frames (points) per epoch {def|0 -> data length}\n% 'limits' = [xmin xmax ymin ymax] (x's in ms or Hz) {def|0 \n% (or both y's 0) -> use data limits)\n% 'ylim' = [ymin ymax] y axis limits. Overwrite option above.\n% 'title' = [string] plot title {def|'' -> none}\n% 'chans' = vector of channel numbers to plot {def|0 -> all}\n% 'axsize' = [x y] axis size {default [.05 .08]}\n% 'legend' = [cell array] cell array of string for the legend. Note\n% the last element can be an integer to set legend \n% position.\n% 'showleg' = ['on'|'off'] show or hide legend.\n% 'colors' = [cell array] cell array of plot aspect. E.g. { 'k' 'k--' }\n% for plotting the first curve in black and the second one\n% in black dashed. Can also contain additional formatting.\n% { { 'k' 'linewidth' 2 } 'k--' } same as above but\n% the first line is bolded.\n% 'ydir' = [1|-1] y-axis polarity (pos-up = 1; neg-up = -1) {def -> -1}\n% 'vert' = [vector] of times (in ms or Hz) to plot vertical lines \n% {def none}\n% 'hori' = [vector] plot horizontal line at given ordinate values.\n% 'regions' = [cell array] cell array of size nchan. Each cell contains a\n% float array of size (2,n) each column defining a time region \n% [low high] to be highlighted.\n% 'plotfunc' = [cell] use different function for plotting data. The format\n% is { funcname arg2 arg3 arg2 ... }. arg1 is taken from the\n% data.\n%\n% Author: Scott Makeig and Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3-2-98 \n%\n% See also: PLOTDATA, TOPOPLOT\n\n% Copyright (C) 3-2-98 from PLOTDATA Scott Makeig, SCCN/INC/UCSD,\n% scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 5-11-98 added channels arg -sm\n% 7-15-98 added ydir arg, made pos-up the default -sm\n% 7-23-98 debugged ydir arg and pos-up default -sm\n% 12-22-99 added grid size option, changed to SBPLOT order -sm\n% 03-16-00 added AXCOPY feature -sm & tpj\n% 08-21-00 debugged axheight/axwidth setting -sm\n% 01-25-02 reformated help & license, added links -ad \n% 03-11-02 change the channel names plotting position and cutomize pop-up -ad \n% 03-15-02 added readlocs and the use of eloc input structure -ad \n% 03-15-02 debugging chanlocs structure -ad & sm \n\n% 'chan_locs' = file of channel locations as in >> topoplot example {grid}\n% ELSE: [rows cols] grid size for rectangular matrix. Example: [6 4]\n% frames = time frames (points) per epoch {def|0 -> data length}\n% [limits] = [xmin xmax ymin ymax] (x's in ms or Hz) {def|0 \n% (or both y's 0) -> use data limits)\n% 'title' = plot title {def|0 -> none}\n% channels = vector of channel numbers to plot & label {def|0 -> all}\n% else, filename of ascii channel-name file\n% axsize = [x y] axis size {default [.07 .07]}\n% 'colors' = file of color codes, 3 chars per line \n% ( '.' = space) {0 -> default color order}\n% ydir = y-axis polarity (pos-up = 1; neg-up = -1) {def -> pos-up}\n% vert = [vector] of times (in ms or Hz) to plot vertical lines {def none}\n% hori = [vector] of amplitudes (in uV or dB) to plot horizontal lines {def none}\n%\n\nfunction plottopo(data, varargin);\n \n%\n%%%%%%%%%%%%%%%%%%%%% Graphics Settings - can be customized %%%%%%%%%%%%%%%%%%\n%\nLINEWIDTH = 0.7; % data line widths (can be non-integer)\nFONTSIZE = 10; % font size to use for labels\nCHANFONTSIZE = 7; % font size to use for channel names\nTICKFONTSIZE = 8; % font size to use for axis labels\nTITLEFONTSIZE = 12; % font size to use for the plot title\nPLOT_WIDTH = 0.95; % 0.75, width and height of plot array on figure\nPLOT_HEIGHT = 0.88; % 0.88\ngcapos = get(gca,'Position'); axis off;\nPLOT_WIDTH = gcapos(3)*PLOT_WIDTH; % width and height of gca plot array on gca\nPLOT_HEIGHT = gcapos(4)*PLOT_HEIGHT;\ncurfig = gcf; % learn the current graphic figure number\n%\n%%%%%%%%%%%%%%%%%%%% Default settings - use commandline to override %%%%%%%%%%%\n%\nDEFAULT_AXWIDTH = 0.05; %\nDEFAULT_AXHEIGHT = 0.08; % \nDEFAULT_SIGN = -1; % Default - plot positive-up\nISRECT = 0; % default\n \nif nargin < 1\n help plottopo\n return\nend\n\nif length(varargin) > 0\n if length(varargin) == 1 || ~ischar(varargin{1}) || isempty(varargin{1}) || ...\n (length(varargin)>2 & ~ischar(varargin{3}))\n options = { 'chanlocs' varargin{1} };\n if nargin > 2, options = { options{:} 'frames' varargin{2} }; end\n if nargin > 3, options = { options{:} 'limits' varargin{3} }; end\n if nargin > 5, options = { options{:} 'chans' varargin{5} }; end\n if nargin > 6, options = { options{:} 'axsize' varargin{6} }; end\n if nargin > 7, options = { options{:} 'colors' varargin{7} }; end\n if nargin > 8, options = { options{:} 'ydir' varargin{8} }; end\n if nargin > 9, options = { options{:} 'vert' varargin{9} }; end\n if nargin > 10,options = { options{:} 'hori' varargin{10} }; end\n if nargin > 4 && ~isequal(varargin{4}, 0), options = {options{:} 'title' varargin{4} }; end\n % , chan_locs,frames,limits,plottitle,channels,axsize,colors,ydr,vert)\n else\n options = varargin;\n end\nelse\n options = varargin;\nend\ng = finputcheck(options, { 'chanlocs' '' [] '';\n 'frames' 'integer' [1 Inf] size(data,2);\n 'chans' { 'integer','string' } { [1 Inf] [] } 0;\n 'geom' 'integer' [1 Inf] [];\n 'channames' 'string' [] '';\n 'limits' 'float' [] 0;\n 'ylim' 'float' [] [];\n 'title' 'string' [] '';\n 'plotfunc' 'cell' [] {};\n 'axsize' 'float' [0 1] [nan nan];\n 'regions' 'cell' [] {};\n 'colors' { 'cell','string' } [] {};\n 'legend' 'cell' [] {};\n 'showleg' 'string' {'on','off'} 'on';\n 'ydir' 'integer' [-1 1] DEFAULT_SIGN;\n 'vert' 'float' [] [];\n 'hori' 'float' [] []});\nif ischar(g), error(g); end\ndata = reshape(data, size(data,1), size(data,2), size(data,3)); \n%if length(g.chans) == 1 & g.chans(1) ~= 0, error('can not plot a single ERP'); end\n\n[chans,framestotal]=size(data); % data size\n\n%\n%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%%%%%%%%%%%%%\n%\n \naxwidth = g.axsize(1);\nif length(g.axsize) < 2\n axheight = NaN;\nelse \n axheight = g.axsize(2);\nend\nif isempty(g.chans) || g.chans(1) == 0\n g.chans = 1:size(data,1);\nelseif ~ischar(g.chans)\n g.chans = g.chans;\nend\n\nnolegend = 0;\nif isempty(g.legend), nolegend = 1; end\n\nif ~isempty(g.ylim)\n g.limits(3:4) = g.ylim;\nend\nplotgrid = 0;\nif isempty(g.chanlocs) % plot in a rectangular grid\n plotgrid = 1;\nelseif ~isfield(g.chanlocs, 'theta')\n plotgrid = 1;\nend\nif length(g.chans) < 4 && ~plotgrid\n disp('Not enough channels, does not use channel coordinate to plot axis');\n plotgrid = 1;\nend\nif plotgrid && isempty(g.geom)\n n = ceil(sqrt(length(g.chans)));\n g.geom = [n ceil(length(g.chans)/n)];\nend\nif ~isempty(g.geom)\n plotgrid = 1;\nend\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n icadefs; % read BACKCOLOR, MAXPLOTDATACHANS constant from icadefs.m\n if g.frames <=0,\n g.frames = framestotal; % default\n datasets=1;\n elseif g.frames==1,\n fprintf('plottopo: cannot plot less than 2 frames per trace.\\n');\n return\n datasets=1;\n else\n datasets = fix(framestotal/g.frames); % number of traces to overplot\n end\n\n if max(g.chans) > chans\n fprintf('plottopo(): max channel index > %d channels in data.\\n',...\n chans);\n return\n end\n if min(g.chans) < 1\n fprintf('plottopo(): min channel index (%g) < 1.\\n',...\n min(g.chans));\n return\n end\n if length(g.chans)>MAXPLOTDATACHANS,\n fprintf('plottopo(): not set up to plot more than %d traces.\\n',...\n MAXPLOTDATACHANS);\n return\n end\n\n if datasets>MAXPLOTDATAEPOCHS \n fprintf('plottopo: not set up to plot more than %d epochs.\\n',...\n MAXPLOTDATAEPOCHS);\n return\n end\n if datasets<1\n fprintf('plottopo: cannot plot less than 1 epoch!\\n');\n return\n end\n\n if ~isempty(g.geom)\n if isnan(axheight) % if not specified\n axheight = gcapos(4)/(g.geom(1)+1);\n axwidth = gcapos(3)/(g.geom(2)+1);\n end\n % if chan_locs(2) > 5\n % axwidth = 0.66/(chan_locs(2)+1);\n % end\n elseif isnan(axwidth)\n axheight = DEFAULT_AXHEIGHT;\n axwidth = DEFAULT_AXWIDTH;\n end\n fprintf('Plotting data using axis size [%g,%g]\\n',axwidth,axheight);\n\n %\n %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%%\n %\n curfig = gcf;\n h=figure(curfig);\n set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference\n set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent\n orient portrait\n axis('normal');\n\n set(gca,'Color',BACKCOLOR); % set the background color\n \n axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is\n vertcolor = 'k';\n horicolor = vertcolor;\n \n% %\n% %%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% if isempty(g.channames)\n% if ~ischar(g.chans) \n% % g.channames = zeros(MAXPLOTDATACHANS,4);\n% % for c=1:length(g.chans),\n% % g.channames(c,:)= sprintf('%4d',g.chans(c));\n% % end\n% if length(g.chans) > 1 | g.chans(1) ~= 0\n% g.channames = num2str(g.chans(:)); %%CJH\n% end\n% else % ischar(g.chans)\n% chid = fopen(g.chans,'r');\n% if chid <3,\n% fprintf('PLOTTOPO: cannot open file %s.\\n',g.chans);\n% return\n% else\n% fprintf('PLOTTOPO: opened file %s.\\n',g.chans);\n% end\n% \n% %%%%%%%\n% % fid=fopen('fgetl.m');\n% % while 1\n% % line = fgetl(fid);\n% % if ~ischar(line), break, end\n% % disp(line)\n% % end\n% % end\n% % fclose(fid);\n% %%%%%%% \n% \n% g.channames = fscanf(chid,'%s',[4 MAXPLOTDATACHANS]);\n% g.channames = g.channames';\n% [r c] = size(g.channames);\n% for i=1:r\n% for j=1:c\n% if g.channames(i,j)=='.',\n% g.channames(i,j)=' ';\n% end\n% end\n% end\n% end; % setting g.channames\n% end\n% \n %\n %%%%%%%%%%%%%%%%%%%%%%%%% Plot and label specified channels %%%%%%%%%%%%%%%%%%\n %\n data = data(g.chans,:);\n chans = length(g.chans);\n \n %\n %%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if ischar(g.colors) % filename for backward compatibility but not documented\n cid = fopen(g.colors,'r');\n % fprintf('cid = %d\\n',cid);\n if cid <3,\n fprintf('plottopo: cannot open file %s.\\n',g.colors);\n return\n end\n g.colors = fscanf(cid,'%s',[3 MAXPLOTDATAEPOCHS]);\n g.colors = g.colors';\n [r c] = size(g.colors);\n for i=1:r\n for j=1:c\n if g.colors(i,j)=='.',\n g.colors(i,j)=' ';\n end\n end\n end\n g.colors = cellstr(g.colors);\n for c=1:length(g.colors) % make white traces black unless axis color is white\n if g.colors{c}(1)=='w' && axcolor~=[1 1 1]\n g.colors{c}(1)='k';\n end\n end\n else % use default color order (no yellow!)\n tmpcolors = { 'b' 'r' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ...\n 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm'};\n g.colors = {g.colors{:} tmpcolors{:}}; % make > 64 available\n end\n %\n %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if g.limits==0, % == 0 or [0 0 0 0]\n xmin=0;\n xmax=g.frames-1;\n % for abs max scaling:\n ymax=max(max(abs(data)));\n ymin=ymax*-1;\n % for data limits:\n %ymin=min(min(data));\n %ymax=max(max(data));\n else\n if length(g.limits)~=4,\n error('plottopo: limits should be 0 or an array [xmin xmax ymin ymax].\\n');\n end\n xmin = g.limits(1);\n xmax = g.limits(2);\n ymin = g.limits(3);\n ymax = g.limits(4);\n end\n\n if xmax == 0 && xmin == 0,\n x = (0:1:g.frames-1);\n xmin = 0;\n xmax = g.frames-1;\n else\n dx = (xmax-xmin)/(g.frames-1);\n x=xmin*ones(1,g.frames)+dx*(0:g.frames-1); % compute x-values\n end\n if xmax<=xmin,\n fprintf('plottopo() - xmax must be > xmin.\\n')\n return\n end\n\n if ymax == 0 && ymin == 0,\n % for abs max scaling:\n ymax=max(max(abs(data)));\n ymin=ymax*-1;\n % for data limits:\n %ymin=min(min(data));\n %ymax=max(max(data));\n end\n if ymax<=ymin,\n fprintf('plottopo() - ymax must be > ymin.\\n')\n return\n end\n\n xlabel = 'Time (ms)';\n %\n %%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % h = gcf;\n % set(h,'YLim',[ymin ymax]); % set default plotting parameters\n % set(h,'XLim',[xmin xmax]);\n % set(h,'FontSize',18);\n % set(h,'DefaultLineLineWidth',1); % for thinner postscript lines\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % clf; % clear the current figure\n\n % print plottitle over (left) subplot 1\n figure(curfig); h=gca;title(g.title,'FontSize',TITLEFONTSIZE); % title plot \n hold on\n msg = ['Plotting %d traces of %d frames with colors: '];\n\n for c=1:datasets\n cind = mod(c-1, length(g.colors))+1;\n if iscell(g.colors{cind})\n msg = [msg '''' g.colors{cind}{1} ''' ' ];\n else\n msg = [msg '''' g.colors{cind} ''' ' ];\n end\n end\n msg = [msg '\\n']; % print starting info on screen . . .\n fprintf('limits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\\n',...\n xmin,xmax,ymin,ymax);\n fprintf(msg,datasets,g.frames);\n\n set(h,'FontSize',FONTSIZE); % choose font size\n set(h,'YLim',[ymin ymax]); % set default plotting parameters\n set(h,'XLim',[xmin xmax]);\n\n axis('off')\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%% Read chan_locs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if plotgrid\n ISRECT = 1;\n ht = g.geom(1);\n wd = g.geom(2);\n if chans > ht*wd\n fprintf('plottopo(): (%d) channels to be plotted > grid size [%d %d]\\n',...\n chans,ht,wd);\n return\n end\n xvals = 0; yvals = 0;\n if isempty(g.channames)\n if isfield(g.chanlocs,'labels') && ~iscellstr({g.chanlocs.labels})\n g.channames = strvcat(g.chanlocs.labels);\n else\n g.channames = repmat(' ',ht*wd,4);\n for i=1:ht*wd\n channum = num2str(i);\n g.channames(i,1:length(channum)) = channum;\n end\n end\n end\n \n else % read chan_locs file\n % read the channel location file\n % ------------------------------\n if isstruct(g.chanlocs)\n nonemptychans = cellfun('isempty', { g.chanlocs.theta });\n nonemptychans = find(~nonemptychans);\n [tmp g.channames Th Rd] = readlocs(g.chanlocs(nonemptychans));\n g.channames = strvcat({ g.chanlocs.labels });\n else\n [tmp g.channames Th Rd] = readlocs(g.chanlocs);\n g.channames = strvcat(g.channames);\n nonemptychans = [1:length(g.channames)];\n end\n Th = pi/180*Th; % convert degrees to radians\n Rd = Rd; \n \n if length(g.chans) > length(g.chanlocs),\n error('plottopo(): data channels must be <= ''chanlocs'' channels')\n end\n \n [yvalstmp,xvalstmp] = pol2cart(Th,Rd); % translate from polar to cart. coordinates\n xvals(nonemptychans) = xvalstmp;\n yvals(nonemptychans) = yvalstmp;\n \n % find position for other channels\n % --------------------------------\n totalchans = length(g.chanlocs);\n emptychans = setdiff_bc(1:totalchans, nonemptychans);\n totalchans = floor(sqrt(totalchans))+1;\n for index = 1:length(emptychans)\n xvals(emptychans(index)) = 0.7+0.2*floor((index-1)/totalchans);\n yvals(emptychans(index)) = -0.4+mod(index-1,totalchans)/totalchans;\n end\n g.channames = g.channames(g.chans,:);\n xvals = xvals(g.chans);\n yvals = yvals(g.chans);\n end\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % xvals = 0.5+PLOT_WIDTH*xvals; % controls width of plot array on page!\n % yvals = 0.5+PLOT_HEIGHT*yvals; % controls height of plot array on page!\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if length(xvals) > 1\n if length(unique(xvals)) > 1\n xvals = (xvals-mean([max(xvals) min(xvals)]))/(max(xvals)-min(xvals)); % recenter\n xvals = gcapos(1)+gcapos(3)/2+PLOT_WIDTH*xvals; % controls width of plot \n % array on current axes\n end\n end\n yvals = gcapos(2)+gcapos(4)/2+PLOT_HEIGHT*yvals; % controls height of plot \n % array on current axes\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n\n xdiff=xmax-xmin;\n ydiff=ymax-ymin;\n\n Axes = [];\n for P=0:datasets-1, % for each data epoch\n fprintf('trace %d: ',P+1);\n\n for c=1:chans, %%%%%%%% for each data channel %%%%%%%%%%%%%%%%%%%%%%%%%%\n\n if P>0 % subsequent pages (Axes specified)\n axes(Axes(c))\n hold on; % plot down left side of page first\n axis('off')\n else % first page, specify axes\n if plotgrid\n Axes = [ Axes sbplot(g.geom(1), g.geom(2), c)];\n else\n xcenter = xvals(c);\n ycenter = yvals(c);\n Axes = [Axes axes('Units','Normal','Position', ...\n [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight])];\n end\n %axes(Axes(c))\n axis('off')\n \n hold on; % plot down left side of page first\n % set(h,'YLim',[ymin ymax]); % set default plotting parameters\n % set(h,'XLim',[xmin xmax]);\n \n axislcolor = get(gca,'Xcolor'); %%CJH\n \n axis('off');\n\n % secondx = 200; % draw second vert axis \n % axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor); \n %\n %%%%%%%%%%%%%%%%%%%%%%% Print channel names %%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n NAME_OFFSET = -.25;\n NAME_OFFSETY = .2;\n if ymin <= 0 && ymax >= 0,\n yht = 0;\n else\n yht = mean(data(c,1+P*g.frames:1+P*g.frames+g.frames-1));\n end\n if ~ISRECT % print before traces\n xt = double(xmin-NAME_OFFSET*xdiff);\n yt = double(yht-NAME_OFFSETY*ydiff); \n str = [g.channames(c,:)];\n h=text(xt,yt,str);\n set(h,'HorizontalAlignment','right'); \n %set(h,'FontSize',CHANFONTSIZE); % choose font size\n else % ISRECT\n xmn = xdiff/2+xmin;\n h=text(double(xmn),double(ymax+0.05*ymax),[g.channames(c,:)]); \n set(h,'HorizontalAlignment','right'); \n %set(h,'FontSize',CHANFONTSIZE); % choose font size\n end % ISRECT\n \n \n %\n %%%%%%%%%%%%%%%%%%%%%%% Highlight regions %%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n if ~isempty(g.regions)\n for index=1:size(g.regions{c},2)\n tmpreg = g.regions{c}(:,index);\n if tmpreg(1) ~= tmpreg(2)\n tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ...\n [-100 -100 100 100], [0.9 0.9 0.9]); hold on;\n set(tmph, 'edgecolor', [0.9 0.9 0.9]); %,'facealpha',0.5,'edgealpha',0.5);\n end\n end\n end\n \n end; % P=0 \n \n %\n %%%%%%%%%%%%%%%%%%%%%%% Plot data traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n Pind = mod(P+1-1, length(g.colors))+1;\n if ~iscell( g.colors{Pind} ), tmpcolor = { g.colors{Pind} 'linewidth' LINEWIDTH };\n else tmpcolor = g.colors{Pind};\n end\n ymn = min([ymax ymin]);\n ymx = max([ymax ymin]);\n if isempty(g.plotfunc)\n if ischar(tmpcolor{1}) && length(tmpcolor) > 1\n plot(x,data(c,1+P*g.frames:1+P*g.frames+g.frames-1), tmpcolor{1}, tmpcolor{2:end}); \n else\n plot(x,data(c,1+P*g.frames:1+P*g.frames+g.frames-1), 'color', tmpcolor{:}); \n end; \n if g.ydir == -1\n set(gca, 'ydir', 'reverse');\n end\n axis([xmin xmax ymn ymx]); % set axis bounds\n elseif P == 1\n func = eval( [ '@' g.plotfunc{1} ] );\n feval(func, data(c,:), g.plotfunc{2:end});\n end\n \n if P == datasets-1 % last pass\n %\n %%%%%%%%%%%%%%%%%%%%%%% Plot lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n plot([0 0],[ymin ymax],'color',axislcolor); % draw vert axis at time 0 \n axis('off');\n plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis \n\n %\n %%%%%%%%%%%%%%%%%%%% plot vertical lines (optional) %%%%%%%%%%%%%%%%%\n %\n \n if isempty(g.vert)\n g.vert = [xmin xmax];\n ymean = (ymin+ymax)/2; \n vmin = ymean-0.1*(ymean-ymin);\n vmax = vmin*-1; %ymean+0.2*(ymax-ymean);\n elseif ~isnan(g.vert)\n ymean = (ymin+ymax)/2; \n vmin = ymean-0.1*(ymean-ymin);\n vmax = vmin*-1; %ymean+0.2*(ymax-ymean);\n for v = g.vert\n plot([v v],[vmin vmax],'color',vertcolor); % draw vertical lines \n end\n end\n \n %\n %%%%%%%%%%%%%%%%%%%% plot horizontal lines (optional) %%%%%%%%%%%%%%%\n %\n if isempty(g.hori)\n g.hori = [ymin ymax]; \n end\n if ~isnan(g.hori)\n xmean = 0; \n hmin = xmean-0.2*(xmean-xmin);\n hmax = hmin*-1; %xmean+0.3*(xmax-xmean);\n for v = g.hori\n plot([hmin hmax],[v v], 'color',horicolor); % draw horizontal lines \n end\n end\n\n end\n \n fprintf(' %d',c); % finished with channel plot\n end; % c, chans / subplot\n % handle legend\n if nolegend, g.legend{P+1} = ['Data ' int2str(P) ]; end\n \n fprintf('\\n');\n end; % P / epoch\n\n %\n %%%%%%%%%%%%%%%%%%%%% Make time and amp cal bar %%%%%%%%%%%%%%%%%%%%%%%%%\n %\n ax = axes('Units','Normal','Position', ...\n [0.85 0.1 axwidth axheight]); % FIX!!!!\n axes(ax)\n axis('off');\n if xmin <=0\n figure(curfig);p=plot([0 0],[ymn ymx],'color','k'); % draw vert axis at zero\n else\n figure(curfig);p=plot([xmin xmin],[ymn ymx],'color','k'); % draw vert axis at zero\n end\n if g.ydir == -1\n set(gca, 'ydir', 'reverse');\n end\n axis([xmin xmax ymn ymx]); % set axis values\n hold on\n %set(p, 'Clipping','off'); % center text\n figure(curfig);p=plot([xmin xmax],[0 0],'color',axislcolor); % draw horizontal axis \n axis([xmin xmax ymin ymax]); % set axis values\n %\n %%%%%%%%%%%%%%%%%%%% plot vertical lines (optional) %%%%%%%%%%%%%%%%%\n %\n if ~isnan(g.vert)\n for v = g.vert\n figure(curfig);plot([v v],[vmin vmax],'color',vertcolor); % draw vertical lines \n end\n end\n %\n %%%%%%%%%%%%%%%%%%%% plot horizontal lines (optional) %%%%%%%%%%%%%%%%%\n %\n if ~isnan(g.hori)\n xmean = 0; \n hmin = xmean-0.2*(xmean-xmin);\n hmax = hmin*-1; %xmean+0.3*(xmax-xmean);\n for v = g.hori\n figure(curfig);plot([hmin hmax],[v v], 'color',horicolor); % draw horizontal lines \n end\n end\n \n % secondx = 200; % draw second vert axis \n % axis('off');plot([secondx secondx],[ylo ymax],'color',axislcolor); \n %\n %%%%%%%%%%%%%%%%%%%%% Plot negative-up %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n signx = xmin-0.15*xdiff;\n figure(curfig);axis('off');h=text(double(signx),double(ymin),num2str(ymin,3)); % text ymin\n set(h,'FontSize',TICKFONTSIZE); % choose font size\n set(h,'HorizontalAlignment','right','Clipping','off');\n\n figure(curfig);axis('off');h=text(double(signx), double(ymax),['+' num2str(ymax,3)]); % text +ymax\n set(h,'FontSize',TICKFONTSIZE); % choose font size\n set(h,'HorizontalAlignment','right','Clipping','off');\n\n ytick = g.ydir*(-ymax-0.3*ydiff);\n figure(curfig);tick = [int2str(xmin)]; h=text(double(xmin),double(ytick),tick);\n set(h,'FontSize',TICKFONTSIZE); % choose font size\n set(h,'HorizontalAlignment','center',...\n 'Clipping','off'); % center text\n\n tick = [xlabel]; figure(curfig);h=text(double(xmin+xdiff/2),double(ytick-0.5*g.ydir*ydiff),tick);\n set(h,'FontSize',TICKFONTSIZE); % choose font size\n set(h,'HorizontalAlignment','center',...\n 'Clipping','off'); % center text\n\n tick = [int2str(xmax)]; figure(curfig);h=text(double(xmax),double(ytick),tick);\n set(h,'FontSize',TICKFONTSIZE); % choose font size\n set(h,'HorizontalAlignment','center',...\n 'Clipping','off'); % center text\n\n if length(g.legend) > 1 && strcmpi(g.showleg, 'on')\n tmpleg = vararg2str(g.legend);\n quotes = find(tmpleg == '''');\n for index = length(quotes):-1:1\n tmpleg(quotes(index)+1:end+1) = tmpleg(quotes(index):end);\n tmpleg(quotes(index)) = '''';\n end\n tmpleg = [ 'legend(' tmpleg ');' ];\n else tmpleg = '';\n end\n com = [ 'axis on;' ...\n 'clear xlabel ylabel;' tmpleg ...\n 'xlabel(''''Time (ms)'''');' ...\n 'ylabel(''''Potential (\\muV)'''');' ];\n axcopy(gcf, com); % turn on popup feature\n %\n %%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n orient tall\n % curfig = gcf;\n % h=figure(curfig);\n % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/plottopo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17477724340228773}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright 2014 National Renewable Energy Laboratory and National \n% Technology & Engineering Solutions of Sandia, LLC (NTESS). \n% Under the terms of Contract DE-NA0003525 with NTESS, \n% the U.S. Government retains certain rights in this software.\n% \n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n% \n% http://www.apache.org/licenses/LICENSE-2.0\n% \n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef cableClass0.001\n error('The Y and Z vectors defining the constraint''s orientation must be orthogonal.')\n end\n x = cross(y,z)/norm(cross(y,z));\n x = x(:)';\n obj.orientation.x = x;\n obj.orientation.rotationMatrix = [x',y',z'];\n \n end\n\n function setInitDisp(obj, relCoord, axisAngleList, addLinDisp)\n % Function to set a body's initial displacement\n % \n % This function assumes that all rotations are about the same relative coordinate. \n % If not, the user should input a relative coordinate of 0,0,0 and \n % use the additional linear displacement parameter to set the cg or location\n % correctly.\n %\n % Parameters\n % ------------\n % relCoord : [1 3] float vector\n % Distance from x_rot to the body center of gravity or the constraint\n % or pto location as defined by: relCoord = cg - x_rot. [m]\n %\n % axisAngleList : [nAngle 4] float vector\n % List of axes and angles of the rotations with the \n % format: [n_x n_y n_z angle] (angle in rad)\n % Rotations applied consecutively in order of dimension 1\n %\n % addLinDisp : [1 3] float vector\n % Initial linear displacement (in addition to the \n % displacement caused by rotation) [m]\n % \n \n % initialize quantities before for loop\n axisList = axisAngleList(:,1:3);\n angleList = axisAngleList(:,4);\n nAngle = size(axisList,1);\n rotMat = eye(3);\n \n % Loop through all axes and angles.\n for i=1:nAngle\n rotMat = axisAngle2RotMat(axisList(i,:),angleList(i))*rotMat;\n end\n % calculate net axis-angle rotation\n [netAxis, netAngle] = rotMat2AxisAngle(rotMat);\n % calculate net displacement due to rotation\n rotatedRelCoord = relCoord*(rotMat');\n linDisp = rotatedRelCoord - relCoord;\n % apply rotation and displacement to object\n obj.initial.displacement = linDisp + addLinDisp;\n obj.initial.axis = netAxis;\n obj.initial.angle = netAngle; \n end \n \n function setVolume(obj, rho)\n % This method mades the mass of the cable drag bodies neutrally bouyant\n obj.volume = obj.mass/rho;\n end\n \n function dragForcePre(obj,rho)\n % This method performs Drag Body pre-processing calculations,\n % similar to hydroForcePre, but only loads in the necessary\n % values to calculate linear damping and viscous drag. Note\n % that body DOF is inherited from the length of the drag\n % coefficients.\n if any(any(obj.quadDrag.drag)) ~= 1 %check if obj.quadDrag.drag is not defined\n obj.quadDrag.drag = diag(0.5*rho.*obj.quadDrag.cd.*obj.quadDrag.area);\n end\n \n end\n \n function linearDampingMatrix(obj)\n % This method makes the linear damping vector (as specified)\n % into a 6 x 6 matrix with this damping along the diagonal (as\n % required for calculation). Operates on the drag bodies\n % representing the cable dynamics.\n obj.linearDamping = diag(obj.linearDamping);\n end\n \n function setCb(obj)\n % This method sets the buoyancy center to equal the center of\n % gravity, if the center of buoyancy is not defined\n obj.base.centerBuoyancy = obj.base.centerGravity;\n obj.follower.centerBuoyancy = obj.follower.centerGravity;\n end\n \n function setCg(obj)\n % This method specifies the Cg of the drag bodies as coincident\n % with the fixed ends of the cable, if not otherwise specied.\n obj.base.centerGravity = obj.base.location;\n obj.follower.centerGravity = obj.follower.location;\n end\n \n function setLength(obj)\n % This method specifies length as the distance between cable fixed\n % ends (i.e. pretension = 0), if not otherwise specified.\n if ~any(obj.length) && ~any(obj.preTension)\n obj.length = sqrt((obj.base.location(1)-obj.follower.location(1)).^2 ...\n + (obj.base.location(2)-obj.follower.location(2)).^2 ...\n + (obj.base.location(3)-obj.follower.location(3)).^2);\n fprintf('\\n\\t cable(i).length undefined and cable(i).preTension undefined. \\n \\r',...\n 'cable(i).length set equal to distance between follower.location and base.location \\n and cable(i).preTension set equal to zero \\n'); \n elseif ~any(obj.length) && any(obj.preTension)\n obj.length = sqrt((obj.base.location(1)-obj.follower.location(1)).^2 ...\n + (obj.base.location(2)-obj.follower.location(2)).^2 ...\n + (obj.base.location(3)-obj.follower.location(3)).^2) + obj.preTension/obj.stiffness; \n elseif ~any(obj.preTension) && any(obj.length)\n obj.preTension = obj.stiffness * (sqrt((obj.base.location(1)-obj.follower.location(1)).^2 ...\n + (obj.base.location(2)-obj.follower.location(2)).^2 ...\n + (obj.base.location(3)-obj.follower.location(3)).^2) - obj.length); \n elseif any(obj.preTension) && any(obj.length)\n error('System overdefined. Please define cable(i).preTension OR cable(i).length, not both.')\n end\n end\n \n function listInfo(obj)\n % This method prints cable information to the MATLAB Command Window.\n fprintf('\\n\\t***** Cable Name: %s *****\\n',obj.name)\n fprintf('\\tCable Stiffness (N/m;Nm/rad) = %G\\n',obj.stiffness)\n fprintf('\\tCable Damping (Ns/m;Nsm/rad) = %G\\n',obj.damping) \n end\n\n function setNumber(obj,number)\n % Method to set the private number property\n obj.number = number;\n end\n end\n \nend", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/cableClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17475743960370999}} {"text": "function nlp = ZMPCost(nlp, varargin)\n \n \n w = varargin{1};\n \n \n plant = nlp.Plant;\n force = plant.Inputs.ConstraintWrench.ffoot;\n \n ws = SymVariable('w');\n \n zmp = -force(3)./force(2);\n constr = ws*(zmp+0.1).^2;\n m_fun = SymFunction(['zmp_cost_' plant.Name],tovector(constr),{force},{ws});\n addRunningCost(nlp,m_fun,{'ffoot'},{w});\nend", "meta": {"author": "ayonga", "repo": "frost-dev", "sha": "e5dc0624d834520872bfa588dd3eda5643da71de", "save_path": "github-repos/MATLAB/ayonga-frost-dev", "path": "github-repos/MATLAB/ayonga-frost-dev/frost-dev-e5dc0624d834520872bfa588dd3eda5643da71de/example/acrobot/+CostFcns/ZMPCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.174757436084208}} {"text": "function [hCBodySurf, hCBodySurfXForm] = ma_initOrbPlot(hFig, orbitDispAxes, bodyInfo)\n %ma_initOrbPlot Summary of this function goes here\n % Detailed explanation goes here\n \n hold(orbitDispAxes,'on');\n set(orbitDispAxes,'XTickLabel',[]);\n set(orbitDispAxes,'YTickLabel',[]);\n set(orbitDispAxes,'ZTickLabel',[]);\n grid(orbitDispAxes,'on');\n\n axis(orbitDispAxes, 'equal');\n \n axis(orbitDispAxes, 'tight');\n \n if(~isempty(bodyInfo))\n dRad = bodyInfo.radius;\n [X,Y,Z] = sphere(50);\n \n if(not(isempty(bodyInfo.surftexturefile)))\n try\n I = bodyInfo.getSurfaceTexture();\n if(not(isempty(I)) && not(any(any(any(isnan(I))))))\n hCBodySurf = surf(orbitDispAxes, dRad*X,dRad*Y,dRad*Z, 'CData',I, 'FaceColor','texturemap', 'BackFaceLighting','lit', 'FaceLighting','gouraud', 'EdgeLighting','gouraud', 'LineStyle','none');\n else\n hCBodySurf = createUntexturedSphere(bodyInfo, orbitDispAxes, dRad, X, Y, Z);\n end\n \n catch ME\n if(exist('hCBodySurf','var'))\n delete(hCBodySurf); %#ok\n warning('Could not create textured celestial body \"%s\". Error message: \\n\\n%s', bodyInfo.name, ME.message);\n end\n \n hCBodySurf = createUntexturedSphere(bodyInfo, orbitDispAxes, dRad, X, Y, Z);\n end\n \n else\n hCBodySurf = createUntexturedSphere(bodyInfo, orbitDispAxes, dRad, X, Y, Z);\n end\n \n hCBodySurfXForm = hgtransform('Parent', orbitDispAxes);\n set(hCBodySurf,'Parent',hCBodySurfXForm); \n material(hCBodySurf,'dull');\n else\n hCBodySurf = [];\n end\n \n mColor = colorFromColorMap(bodyInfo.bodycolor);\n plot3(orbitDispAxes, 0, 0, 0,'Marker','o','MarkerEdgeColor',mColor,'MarkerFaceColor',mColor,'MarkerSize',3);\n \n hold(orbitDispAxes, 'off');\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/plotting/ma_initOrbPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1746049134041139}} {"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": "%% THE AGENT BASE CLASS (agent.m) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This class is designed to define a generic agent and import this variables\n% into the simulation space for the purpose of multi-vehicle control simulation.\n% The agent object is a child of the objectDefintion; the prinicple\n% distinctions being:\n% sensorRange - The agent is assumed capable of observing its\n% surroundings.\n% controlFrequency - The frequency at which the control cycle is computed.\n\n% Author: James A. Douthwaite\n\nclassdef agent < objectDefinition & agent_tools\n %% AGENT BASE CLASS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % This class contains the basic properties of a generic agent, neither\n % aerial or ground based.\n properties\n % DEFAULT BEHAVIOUR\n v_nominal = 2; % Default nominal linear speed (m/s)\n v_max = 4; % Default maximal linear speed (m/s)\n w_max = 0.5; % Default maximal angular speed (rad/s)\n detectionRadius = inf;\n % WAYPOINTS\n targetWaypoint; % The current waypoint target\n achievedWaypoints; % The agents list of locally achieved waypoints\n % DYNAMIC PARAMETERS\n DYNAMICS;\n % SENSOR MEASUREMENT PARAMETERS\n SENSORS = struct('range',inf); % Only generic parameter is a visual horizon\n % AGENT-SIDE OUTPUT DATA\n DATA; % The output container for agent-side data.\n end\n \n %% ///////////////////////// MAIN METHODS /////////////////////////////\n methods\n % Constructor\n function [this] = agent(varargin)\n % This function is to construct the agent object using the\n % object defintions held in the 'objectDefinition' base class.\n % INPUTS:\n % namestr - Assigned name string\n % OUTPUTS:\n % this - The constructed object\n \n % Call the super class\n this@objectDefinition(varargin);\n \n % //////////////////// SENSOR PARAMETERS //////////////////////\n [this.SENSORS] = this.GetDefaultSensorParameters(); % Default sensing\n % /////////////////////////////////////////////////////////////\n this.SetGLOBAL(this.CreateGLOBAL()); % Assign (agent) GLOBAL structure\n this.DYNAMICS = this.CreateDYNAMICS(); % Assign (agent) DYNAMICS structure\n this.SetBufferSize(1); % Assign default buffer size \n \n % Assign defaults\n this.radius = 0.5; % Default radius (m)\n this.localState = zeros(12,1); % Assign state\n\n % //////////////// Check for user overrides ///////////////////\n % - It is assumed that overrides to the properties are provided\n % via the varargin structure.\n this = this.ApplyUserOverrides(varargin); % Recursive overrides\n % /////////////////////////////////////////////////////////////\n end\n % Setup (agent default)\n function [this] = setup(this,localXYZvelocity,localXYZrotations) % [x y z phi theta psi]\n % This function is called in order to build the initial state\n % vector for the generic agent class 'objectDefinition'.\n % INPUTS:\n \n % ASSUMPTIONS:\n % - The designed state is described in the ENU axes.\n % - The state is of the form:\n % - [x y z phi theta psi dx dy dz dphi dtheta dpsi]\n \n switch this.Is3D()\n case false \n % Initialises the state vector [x y psi ; dx dy dpsi]\n this.setup_2DVelocities(localXYZvelocity,localXYZrotations);\n case true\n % Initialises the state vector [x y z phi theta psi ; dx dy dz dphi dtheta dpsi]\n this.setup_3DVelocities(localXYZvelocity,localXYZrotations)\n otherwise\n error('Object dimensionality unknown');\n end\n end\n % Main\n function [this] = main(this,ENV,varargin)\n % This function is designed to house a generic agent process\n % cycle that results in an acceleration vector in the global axis.\n % INPUTS:\n % ENV - The TIME simulations structure\n % varargin - Cell array of inputs\n % OUTPUTS:\n % this - The updated project\n \n % PLOT AGENT FIGURE\n visualiseProblem = 0;\n visualiseAgent = 1;\n if this.objectID == visualiseAgent && visualiseProblem == 1\n %overHandle = figure('name','testFigure');\n overHandle = gcf;\n ax = gca;\n hold on; grid on;\n axis equal;\n xlabel('x_{m}'); ylabel('y_{m}'); zlabel('z_{m}');\n end\n \n % //////////// CHECK FOR NEW INFORMATION UPDATE ///////////////\n % UPDATE THE AGENT WITH THE NEW ENVIRONMENTAL INFORMATION\n [this,obstacleSet,agentSet] = this.GetAgentUpdate(ENV,varargin{1});\n \n % /////////////////// WAYPOINT TRACKING ///////////////////////\n % Design the current desired trajectory from the waypoint.\n [headingVector] = this.GetTargetHeading();\n desiredVelocity = headingVector*this.v_nominal;\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % %\n % DO NOTHING %\n % %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n % PASS THE DESIRED VELOCITY TO THE DEFAULT CONTROLLER\n [this] = this.Controller(ENV.dt,desiredVelocity);\n end\n end\n \n %% ////////////////////// BASIC UPDATE FUNCTIONS //////////////////////\n methods\n % AGENT UPDATE (IDEAL) - Update from perfect environmental knowledge\n function [this,obstacleSet,agentSet,waypointSet] = GetAgentUpdate(this,ENV,observedobjects)\n % This function computes the agents process for updating its\n % knowledge of the environment.\n % INPUTS:\n % ENV.dt - The unit timstep\n % observedobjects - The full observed object structure\n % OUTPUTS:\n % this - The updated object\n % obstacleSet - The list of obstacle structures\n % waypointSet - The list of waypoint structures\n \n agentSet = []; obstacleSet = []; waypointSet = []; % No observed objects\n \n % Check #1 - Nothing is observed..\n if isempty(observedobjects)\n return\n end\n \n % Input sanity check\n assert(isstruct(ENV),'Expecting environment update structure.');\n assert(isnumeric(ENV.dt),'The time-step must be a numeric timestep.');\n assert(isstruct(observedobjects),'Second parameter is a vector of observation structures.');\n \n % Update agent memory structure\n for entry = 1:numel(observedobjects)\n % Apply sensor model if there is one\n sensedobject = this.SensorModel(ENV.dt,observedobjects(entry));\n % Update memory structure from measurements\n this = this.UpdateMemoryFromObject(ENV.currentTime,sensedobject);\n end\n \n % SORT object SET BY PRIORITY\n [this] = this.UpdateMemoryOrderByField('priority');\n \n % DECERN object TYPES\n % this.MEMORY now contains an updated understanding of all the\n % objects in its visual horizon. From this, the waypoints and\n % obstacles must be parsed.\n \n % PULL MEMORY ITEMS FOR LATER MANIPULATION\n agentSet = this.MEMORY([this.MEMORY.type] == OMAS_objectType.agent);\n waypointSet = this.MEMORY([this.MEMORY.type] == OMAS_objectType.waypoint);\n obstacleSet = this.MEMORY([this.MEMORY.type] == OMAS_objectType.obstacle); % Differenciate between the different object types\n \n % UPDATE THE TARGET WAYPOINT, PRIORTIES\n [this] = this.UpdateTargetWaypoint(waypointSet); % Update the target waypoint and heading vector\n end\n end\n \n %% //////////////////////// SENSING FUNCTIONS /////////////////////////\n methods\n % SENSOR MODEL - TOP LEVEL (Default)\n function [observedobject] = SensorModel(this,dt,observedobject)\n % This function provides an overridable method resembling the\n % sensor model through which all objects are processed.\n \n % Input sanity check\n assert(isnumeric(dt) && numel(dt) == 1,'The time step value is invalid.');\n assert(numel(observedobject.position) <= 3,'Expecting a position value to be [2x1].');\n assert(numel(observedobject.velocity) <= 3,'Expecting a velocity value to be [2x1].');\n \n % Get measurements from a camera\n [psi_j,theta_j,alpha_j] = this.GetCameraMeasurements(observedobject);\n % Override ideal parameters with camera model\n observedobject.heading = psi_j;\n observedobject.elevation = theta_j;\n observedobject.width = alpha_j;\n % Get the range estimate\n [observedobject.range] = this.GetRangeFinderMeasurements(observedobject);\n end\n % SENSOR MODEL - CAMERA & RANGE FINDER\n function [psi_j,theta_j,alpha_j] = GetCameraMeasurements(this,observedobject)\n % This function takes the simulation data and calculates the\n % spherical position and radius that would otherwise be sensed\n % by the system.\n % INPUTS:\n % obstacleData - The object observation structure\n % OUTPUTS:\n % range - The obstacles apparent range\n % azimuth - The obstacles angular position in the XY plane\n % elevation - The obstacles angular position in the XZ plane\n % angularWidth - The obstacles angular width in the azimuth\n \n % Observed pixel coordinates\n psi_j = observedobject.heading + this.SENSORS.sigma_camera*randn(1);\n theta_j = observedobject.elevation + this.SENSORS.sigma_camera*randn(1);\n % Observed width\n alpha_j = observedobject.width + this.SENSORS.sigma_camera*randn(1); % Uncertainty in the angular measurement\n end\n % SENSOR MODEL - RANGE FINDER\n function [d_j] = GetRangeFinderMeasurements(this,observedobject)\n % This function takes a simulation data resembling an object\n % and calculates the apparent range to the agent.\n \n % EMULATE MEASURED POSITIONAL VARIABLES (measured = range(true) + distortion)\n d_j = observedobject.range + this.SENSORS.sigma_rangeFinder*randn(1);\n end\n % SENSOR MODEL - LOCAL GPS & PITOT TUBE\n function [p_i,v_i,r_i] = GetAgentMeasurements(this)\n % This function makes estimates of the agent's current position\n % and velocity states (defined in this.localState).\n \n if this.Is3D\n positionIndices = 1:3;\n velocityIndices = 7:9;\n else\n positionIndices = 1:2;\n velocityIndices = 4:5;\n end\n % GET THE LOCAL ABSOLUTE VARIABLES\n p_i = this.localState(positionIndices,1) + this.SENSORS.sigma_position*rand(numel(positionIndices),1); % Get the absolute position measurement\n v_i = this.localState(velocityIndices,1) + this.SENSORS.sigma_velocity*rand(numel(velocityIndices),1); % Get the absolute velocity measurement\n % RADIUS IS ASSUMED KNOWN\n r_i = this.radius();\n end\n % CALCULATE THE NEW STATE ESTIMATE\n function [position,velocity] = linearStateEstimation(this,dt,p0,v0,p1)\n % This function takes the previous known state of the obstacle\n % and estimates its new state.\n \n % GET THE POSITION\n dX = (p1 - p0);\n velocity = dX/dt; % Defines the average velocity\n position = p1;\n % NO PREVIOUS VELOCITY RECORDED\n if any(isnan(v0))\n return\n end\n end\n end\n methods (Static)\n % SENSOR MODEL - REPRESENTATIVE SENSING\n function [SENSORS] = GetCustomSensorParameters()\n % This function is designed to populate the SENSOR structure\n % with representative sensing parameters for the assembly of\n % the sensing intervals.\n % BUILD THE SENSOR FACTOR\n SENSORS = struct(...\n 'range',inf,... % Assume the agent has perfect environmental knowledge (m)\n 'sigma_position',0.5,... % Accurate to within 0.5m\n 'sigma_velocity',0.1,... % Accurate to within 0.1m/s\n 'sigma_rangeFinder',0.1,... % Accurate to within 0.1m\n 'sigma_camera',5.208E-5,... % One pixel in a 1080p image\n 'sampleFrequency',inf); % object has perfect precision\n end\n % SENSOR MODEL - PERFECT SENSING\n function [SENSORS] = GetDefaultSensorParameters()\n % This function is designed to populate the SENSOR field with\n % perfect sensor capabilities.\n % BUILD THE SENSOR FACTOR\n SENSORS = struct(...\n 'range',inf,... % Assume the agent has perfect environmental knowledge (m)\n 'sigma_position',0.0,... % Perfect position measurement\n 'sigma_velocity',0.0,... % Perfect velocity measurement\n 'sigma_rangeFinder',0.0,... % Perfect range acquistion\n 'sigma_camera',0.0,... % Infinte resolution\n 'sampleFrequency',inf); % object has perfect precision\n end\n end\n \n %% //////////////////////// DYNAMICS & CONTROL ////////////////////////\n methods\n % Simple controller\n function [this] = Controller(this,dt,desiredVelocity)\n % This function computes the agents change in state as a result\n % of the desired velocity vector\n \n % Input sanity check #1 - Is feasible\n assert(isnumeric(dt) && numel(dt) == 1,'The time step must be a numeric scalar.');\n assert(isnumeric(desiredVelocity) && numel(desiredVelocity) == 3,'Requested velocity vector is not a 2D numeric vector');\n assert(~any(isnan(desiredVelocity)),'The desired velocity vector contains NaNs.');\n \n % ///////////// UPDATE object GLOBAL PROPERTIES ///////////////\n % Input sanity check #2 - Zero vector\n [heading,speed] = this.nullVelocityCheck(desiredVelocity);\n \n % Get the relative heading\n [dPsi,dTheta] = this.GetVectorHeadingAngles([1;0;0],heading); % Relative heading angles\n % The desired heading rate\n omega = ([0;dTheta;-dPsi] - zeros(3,1))/dt;\n \n % Apply kinematic constraints to state changess\n [omega_actual,speed_actual] = this.ApplyKinematicContraints(dt,omega,speed);\n \n % OMIT TRAJECTORY CHANGES IF IDLE\n if this.IsIdle()\n omega_actual = zeros(3,1);\n speed_actual = 0;\n this.v_nominal = 0;\n end\n \n dX = [speed_actual;0;0;omega_actual];\n \n % /////////// SIMPLE DYNAMICS + PURE TRANSLATION //////////////\n [dX] = this.SimpleDynamics(this.localState(1:6),[speed_actual;0;0],omega_actual);\n this.localState(1:6) = this.localState(1:6) + dt*dX;\n this.localState(7:12) = dX;\n \n % ////// GLOBAL UPDATE FOR STATE WITH RETAINED VELOCITES //////\n [this] = this.GlobalUpdate_3DVelocities(dt,this.localState);\n end\n % SPEED AND HEADING (4D) PID CONTROLLER\n function [this] = Controller_PID(this,dt,desiredVelocity)\n % This function is desiged to generate feedack from a desired\n % local velocity vector.\n % INPUTS:\n % targetHeading - The unit heading vector\n % targetSpeed - The target speed in that direction\n % OUTPUTS:\n % heading_fb - The feedback on the agent heading\n % speed_fb - The feedback on the agent speed\n % this - The error-updated agent object\n \n % Input sanity check\n assert(isnumeric(dt) && numel(dt) == 1,'The time step must be a numeric scalar.');\n assert(isnumeric(desiredVelocity) && numel(desiredVelocity) == 3,'Requested velocity vector must be a 3D local vector.');\n assert(~any(isnan(desiredVelocity)),'The requested velocity contains NaNs.');\n \n % NUMERICAL SANITY CHECK TWO\n [unitDirection,desiredSpeed] = this.nullVelocityCheck(desiredVelocity);\n \n % APPLY SPEED CONSTRAINT\n if abs(desiredSpeed) > this.v_max\n desiredSpeed = sign(desiredSpeed)*this.v_max;\n end\n \n % GET THE EQUIVALENT HEADING ANGLE\n [dPsi,dTheta] = this.GetVectorHeadingAngles([1;0;0],unitDirection); % Relative heading angles\n dHeading = [0;dTheta;-dPsi];\n \n % RELATIVE SPEED\n e_speed = desiredSpeed - norm(this.localState(7:9)); % The speed error\n controlError = [e_speed;dHeading]; % -ve in the NED control frame of reference\n \n % TUNING PARAMETERS\n Kp_linear = 0.8;\n Kd_linear = 0;\n Kp_angular = 1;\n Kd_angular = 0;\n \n % CALCULATE THE CONTROL FEEDBACK\n control_fb = diag([Kp_linear Kp_angular Kp_angular Kp_angular])*controlError + ...\n diag([Kd_linear Kd_angular Kd_angular Kd_angular])*(controlError - this.priorError);\n % REMEMBER PREVIOUS ERROR\n this.priorError = controlError;\n \n % PARSE THE CONTROL FEEDBACK FOR EXTERNAL USE\n speedFeedback = control_fb(1); % Absolute speed input\n headingFeedback = control_fb(2:4);\n omega = headingFeedback/dt;\n \n % /////////// SIMPLE DYNAMICS + PURE TRANSLATION //////////////\n [dX] = this.SimpleDynamics(this.localState(1:6),[speedFeedback;0;0],omega);\n this.localState(1:6) = this.localState(1:6) + dt*dX;\n this.localState(7:12) = dX;\n \n % ///////////// UPDATE object GLOBAL PROPERTIES ///////////////\n if this.GLOBAL.idleStatus\n this.localState(7:12) = zeros(6,1);\n end\n \n % ////// GLOBAL UPDATE FOR STATE WITH RETAINED VELOCITES //////\n [this] = this.GlobalUpdate_3DVelocities(dt,this.localState);\n end\n % Apply the DYNAMICS constraints\n function [omega_actual,speed_actual] = ApplyKinematicContraints(this,dt,omega,speed)\n % This function is designed to take a desired heading and\n % velocity and compare them to the kinematic contraints of the\n % agent.\n \n % Determine agent dimension\n if this.Is3D\n currentVelocity = this.localState(7:9);\n currentOmega = this.localState(10:12);\n else\n currentVelocity = this.localState(4:5);\n currentOmega = this.localState(6);\n end\n \n % For clarity\n v_lim = this.DYNAMICS.maxLinearVelocity;\n dv_lim = this.DYNAMICS.maxLinearAcceleration;\n omega_lim = this.DYNAMICS.maxAngularVelocity;\n dOmega_lim = this.DYNAMICS.maxAngularAcceleration;\n \n % /////////////// Constrained heading change //////////////////\n % The implied angular acceleration\n omega_dot = (omega - currentOmega)/dt;\n % Constrain against heading acceleration limits\n bounded_omega_dot = boundValue(omega_dot,-dOmega_lim,dOmega_lim);\n % Calculate actual heading velocity limits\n omega = currentOmega + bounded_omega_dot*dt;\n % Constrain against heading rate limits\n omega_actual = boundValue(omega,-omega_lim,omega_lim);\n \n % ///////////////// Constrained speed change //////////////////\n % The current speed\n currentSpeed = norm(currentVelocity);\n % The proposed acceleration\n s_dot = (speed - currentSpeed)/dt;\n % Constrain against linear acceleration limits\n bounded_s_dot = boundValue(s_dot,-dv_lim(1),dv_lim(1));\n % Calcullate the actual speed\n speed = currentSpeed + bounded_s_dot*dt;\n % Interesect the velocity with permissible velocities\n speed_actual = boundValue(speed,-v_lim(1),v_lim(1));\n end\n % Create the DYNAMICS structure\n function [DYNAMICS] = CreateDYNAMICS(this)\n % Define basic DYNAMIC container\n [DYNAMICS] = this.CreateDYNAMICS_default();\n end\n % Create the default DYNAMICS constraint structure\n function [DYNAMICS] = CreateDYNAMICS_default(this)\n % Define an infinite \"throw\" range by default\n DYNAMICS = struct();\n % Define kinematic constraints\n if this.Is3D\n % States defined as [x,y,z,phi,theta,psi,dx,dy,dz,dphi,dtheta,dpsi]^T\n DYNAMICS.maxLinearVelocity = ones(3,1)*this.v_max; % Limits on the agents linear velocity\n DYNAMICS.maxLinearAcceleration = inf(3,1); % Limits on the agents linear acceleration\n DYNAMICS.maxAngularVelocity = ones(3,1)*this.w_max; % Limits on the agents angular velocity\n DYNAMICS.maxAngularAcceleration = inf(3,1); % Limits on the agents angular acceleration\n else\n % States defined as [x,y,psi,dx,dy,dpsi]^T\n DYNAMICS.maxLinearVelocity = ones(2,1)*this.v_max; % Limits on the agents linear velocity\n DYNAMICS.maxLinearAcceleration = inf(2,1); % Limits on the agents linear acceleration\n DYNAMICS.maxAngularVelocity = this.w_max; % Limits on the agents angular velocity\n DYNAMICS.maxAngularAcceleration = inf(1,1); % Limits on the agents angular acceleration\n end\n end\n end\n \n %% ////////////////////// GENERAL STATIC METHODS //////////////////////\n methods (Static)\n % DEFINE THE PITCH AND YAW TO MEET TARGET HEADING (2D & 3D)\n function [lambda,theta] = GetVectorHeadingAngles(V,U)\n % This function calculates the Line Of Sight (LOS) [horezontal]\n % angle which aids in defining the bank angle as a control input to the\n % dynamics.\n % INPUTS:\n % V - The current unity velocity vector\n % U - The unit correction vector\n % OUTPUTS:\n % lambda - The azimuth angle (2D)\n % theta - The pitch angle (3D)\n \n % NORMALISE THE ELEMENTS\n V = V/norm(V);\n U = U/norm(U);\n % GET THE HORIZONTAL ELEMENTS\n Vh = [V(1);V(2);0];\n Uh = [U(1);U(2);0]; % Reject the vertical elements\n % GET THE LINE OF SIGHT ANGLE\n rotationAxis = cross(Vh,Uh);\n \n % HANDLE 3D CASE (ELEVATION & LOS)\n if numel(V) == 3 && numel(U) == 3\n % GET THE LINE OF SIGHT ANGLE\n lambda = sign(rotationAxis(3))*acos(dot(Vh,Uh)/norm(Vh)); % Get the angle, signed by the direction of its cross product\n % GET THE ELEVATION ANGLE\n theta = atan2(U(3),norm(Uh));\n else\n % HANDLE 2D CASE (LOS)\n % GET THE LINE OF SIGHT ANGLE\n lambda = sign(rotationAxis(3))*acos(dot(Vh,Uh)/norm(Vh));\n % GET THE SUDO ELEVATION ANGLE\n theta = 0;\n end\n end\n % CALCULATE THE RADIUS\n function [r] = GetRadiusFromAngularWidth(d,alpha)\n % Calculate the radius of the object\n r = (sin(alpha/2)/(1-sin(alpha/2)))*d;\n end\n % VALIDATE THE OBSTACLE\n function [tau] = validateCollision(p,v)\n % CONFIRM WE KNOW THE HEADING OF THE OBSTACLE\n if any(isnan(v))\n tau = -inf;\n return\n end\n % Define the time to closest approach (+ve converging)\n tau = -(dot(p,v)/dot(v,v));\n end\n % BASIC VELOCITY VECTOR CHECK (2D & 3D)\n function [v_unit,v_mag] = nullVelocityCheck(v)\n v_mag = norm(v);\n if v_mag == 0\n v_unit = zeros(numel(v),1);\n v_unit(1) = 1; % [1 0 0] % Default to current local forward direction\n else\n v_unit = v/v_mag;\n end\n end\n end\n \n %% ///////////////// VISUALISATION AND GENERAL TOOLS //////////////////\n methods\n % PLOT ALL THE OBSERVABLE OBSTACLES IN THE LOCAL FRAME\n function [figureHandle] = GetobjectScene(this,figureHandle)\n % FIGURE PREPERATION\n if ~exist('figureHandle','var')\n figureHandle = figure();\n else\n cla reset\n end\n \n ax = get(figureHandle,'CurrentAxes');\n set(ax,'NextPlot','replacechildren')\n hold on; grid on;\n axis equal;\n xlabel('X (m)'); ylabel('Y (m)'); zlabel('Z (m)');\n view([-120 35]);\n title(ax,'The agents perspective of its neighbourhood');\n \n % PLOT THE AGENT FOR PERSPECTIVE\n if size(this.GEOMETRY.vertices,1) < 1\n geometry = OMAS_geometry.defineSphere(zeros(3,1),this.radius);\n % REPRESENT GEOMETRY AS A PATCH\n entityHandle = patch(ax,...\n 'Vertices',geometry.vertices,...\n 'Faces',geometry.faces,...\n 'FaceColor',[0.4940, 0.1840, 0.5560]);\n else\n % PLOT THE AGENTS VERTEX DATA\n entityHandle = patch(ax,...\n 'Vertices',this.GEOMETRY.vertices,...\n 'Faces',this.GEOMETRY.faces,...\n 'FaceColor',this.GLOBAL.colour);\n end\n % ADD ANNOTATION\n annotationText = sprintf(' \\t%s [ID-%d]',this.name,this.objectID);\n text(0,0,0,char(annotationText));\n \n % SET THE ENTITY DATA\n set(entityHandle,...\n 'EdgeColor','k',...\n 'EdgeAlpha',0.3,...\n 'FaceLighting','gouraud',...\n 'FaceAlpha',0.8,...\n 'LineWidth',0.1,...\n 'EdgeAlpha',0.7);\n \n % PLOT AGENT VELOCITY\n q = quiver3(0,0,0,1,0,0,'b');\n q.AutoScaleFactor = 1;\n % MOVE THROUGH THE OBSTACLE SET AND PLOT THE OBSTACLE POSITIONS\n for item = 1:numel(this.MEMORY)\n % Get the second objects data\n [p_j] = this.GetLastMeasurementByobjectID(this.MEMORY(item).objectID,'position');\n [v_j] = this.GetLastMeasurementByobjectID(this.MEMORY(item).objectID,'velocity');\n [r_j] = this.GetLastMeasurementByobjectID(this.MEMORY(item).objectID,'radius');\n \n if numel(this.MEMORY(item).geometry.vertices) < 1\n % DEFINE GEOMETRY AS A SPHERE\n if this.Is3D\n [geometry] = OMAS_graphics.defineSphere(p_j,r_j);\n else\n [geometry] = OMAS_graphics.defineSphere([p_j;0],r_j);\n end\n else\n % DEFINE FROM OWN GEOMETRY\n geometry = this.MEMORY(item).geometry; % Should be in the current frame\n end\n % REPRESENT GEOMETRY AS A PATCH\n entityHandle = patch(ax,...\n 'Vertices',geometry.vertices,...\n 'Faces',geometry.faces,...\n 'EdgeColor','k',...\n 'EdgeAlpha',0.2,...\n 'FaceLighting','gouraud',...\n 'FaceAlpha',0.2,...\n 'LineWidth',1);\n % PLOT REPRESENTATION\n switch this.MEMORY(item).type\n case OMAS_objectType.agent\n set(entityHandle,'FaceColor','b');\n case OMAS_objectType.obstacle\n set(entityHandle,'FaceColor','r');\n case OMAS_objectType.waypoint\n set(entityHandle,'FaceColor','g');\n otherwise\n set(entityHandle,'FaceColor','m');\n end\n % ADD ANNOTATION\n annotationText = sprintf(' \\t%s [ID-%d]',this.MEMORY(item).name,this.MEMORY(item).objectID);\n if this.Is3D\n text(p_j(1),p_j(2),p_j(3),char(annotationText)); % PLOT AGENT VELOCITY\n q = quiver3(ax,p_j(1),p_j(2),p_j(3),...\n v_j(1),v_j(2),v_j(3),'k'); % The velocity vector\n else\n text(p_j(1),p_j(2),0,char(annotationText));\n q = quiver3(ax,p_j(1),p_j(2),0,...\n v_j(1),v_j(2),0,'k'); % The velocity vector\n end\n q.AutoScaleFactor = 1;\n end\n drawnow;\n hold off;\n end\n % APPEND AN FIGURE FRAME TO ANIMATION\n function [figureHandle] = GetAnimationFrame(this,ENV,figureHandle,fileName)\n % INPUT HANDLING\n if nargin < 4\n fileName = sprintf('bodyAxes - %s [ID-%.0f].gif',this.name,this.objectID);\n end\n \n % FIGURE PREPERATION\n filePath = strcat(ENV.outputPath,fileName);\n drawnow; % Ensure all items are plotted before taking the image\n % CAPTURE FIGURE AS FRAME\n frame = getframe(figureHandle);\n im = frame2im(frame); % Capture the figure as an image\n [imind,cm] = rgb2ind(im,256);\n % Write to the GIF File\n if ENV.currentStep == 1\n imwrite(imind,cm,filePath,'gif',...\n 'Loopcount',inf,...\n 'DelayTime',ENV.dt,...\n 'Location',[0 0],...\n 'Comment',sprintf('%s[ID-%.0f]',this.name,this.objectID));\n else\n imwrite(imind,cm,filePath,'gif',...\n 'WriteMode','append',...\n 'DelayTime',ENV.dt,...\n 'Location',[0 0]);\n end\n pause(0.1); % Pause for stability\n end\n % AGENT DATA STORAGE\n function [this] = writeAgentData(this,TIME,loopIndicator,loopDuration)\n % This function writes a regular DATA structure to the agent\n % .DATA structure to allow it to be easily interpretted.\n \n % THE AGENT COMPUTATION TIMES\n this.DATA.indicator(TIME.currentStep) = loopIndicator;\n this.DATA.dt(TIME.currentStep) = loopDuration;\n this.DATA.steps(TIME.currentStep) = TIME.currentStep;\n this.DATA.time(TIME.currentStep) = TIME.currentTime;\n end\n end\n %% ///////////////////////// GET/SET METHODS //////////////////////////\n methods\n % Set the maximum linear speed\n function set.v_max(this,v)\n assert(numel(v) == 1,'Expecting a scalar linear rate.');\n this.v_max = v;\n this.DYNAMICS.maxLinearVelocity(:) = v;\n end\n % Set the maximum angular speed\n function set.w_max(this,w)\n assert(numel(w) == 1,'Expecting a scalar angular rate.');\n this.w_max = w;\n this.DYNAMICS.maxAngularVelocity(:) = w;\n end\n % Set the detection radius\n function set.detectionRadius(this,r)\n assert(isnumeric(r) && numel(r) == 1,'Detection radius must be a scalar value.');\n % Override the SENSORS parameter to reflect the change\n if isstruct(this.SENSORS) && isfield(this.SENSORS,'range')\n this.SENSORS.range = r; % Set the sensor range value\n end \n % Assign the value to the GLOBAL structure\n this.SetGLOBAL('detectionRadius',r); % Set the detection radius\n end\n % User update (Override)\n function [this] = ApplyUserOverrides(this,pairArray)\n % This function is designed to parse a generic set of user\n % inputs and allow them to be compared to a default input\n % structure. This should be called in the class constructor\n \n % Input sanity check #1\n if nargin < 2 || numel(pairArray) == 0\n return\n end\n \n % Call the all parameter overrider\n [this] = GetParameterOverrides_recursive(this,pairArray);\n \n % Preform dependant value checks\n this.MEMORY = this.CreateMEMORY(this.maxSamples); % Initialise memory structure (with 2D varient)\n \n if this.detectionRadius ~= this.SENSORS.range\n % The detection radius is determined by SENSORS.range\n this.SENSORS.range = this.detectionRadius;\n end\n end\n end\nend\n\n", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/objects/agent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17416210467732013}} {"text": "function [tParam, regParam] = histology_blockface_reg(pathstrh, fileh, pathstrbf, filebf, regParam, polymask, ellipmask, opts)\n% HISTOLOGY_BLOCKFACE_REG Register deformed histology volume to blockface.\n%\n% Correct a histology volume obtained by intraslice registration with\n% histology_blockface_reg(). The steps in this function are:\n%\n% 1) Each \"valid\" histology slice is registered to the corresponding\n% blockface slice (typically with a B-spline, but the user can provide\n% any registration parameters). \"Valid\" slices are pre-selected by the\n% user, and are those where the registration will give a good result,\n% because there are no artifacts in the wax, the tissue has no tears,\n% etc.\n%\n% 2) B-spline transforms for \"invalid\" slices are interpolated and\n% extrapolated from the valid ones.\n%\n% 3) Each B-spline coefficient is smoothed so that it changes slowly\n% between each slice and its neighbours. This preserves the structural\n% integrity of the histology reconstruction.\n%\n% [TPARAM, REGPARAM] = histology_blockface_reg(PATHSTRH, FILEH, PATHSTRBF, FILEBF, REGPARAM, POLYMASK, ELLIPMASK)\n%\n% PATHSTRH and PATHSTRBF are strings with the paths to the histology and\n% blockface images, respectively.\n%\n% FILEH, FILEBF are the lists of histology and blockface files, obtained\n% with dir(). Each file contains a slice. FILEH(i) corresponds to\n% FILEBF(i).\n%\n% REGPARAM is a struct (or a string with the full path to a file) with\n% the registration parameters for elastix. Typically, you want this\n% registration to use a multi-level B-spline.\n%\n% POLYMASK, ELLIPMASK are two binary masks with the polygon highlighting\n% the wax blockface (POLYMASK) and an ellipse around the heart at it's\n% biggest (ELLIPMASK). The masks can be produced with\n% blockface_create_masks().\n%\n% ... = histology_blockface_reg(..., OPTS)\n%\n% OPTS is a struct with parameters for the algorithm.\n%\n% 'verbose': (def 0) Verbose output of the registration algorithm.\n%\n% 't0': (def []) Initial transform to apply to histology slices\n% before registration.\n%\n% 'IdxIgnore': (def []) Indices of slices where instead from a\n% registration, the transform is obtained by\n% interpolation/extrapolation from the other slices.\n% This parameter can be provided as a vector of indices or\n% as a boolean vector.\n\n% Author: Ramon Casero \n% Copyright \u00a9 2014 University of Oxford\n% Version: 0.1.0\n%\n% University of Oxford means the Chancellor, Masters and Scholars of\n% the University of Oxford, having an administrative office at\n% Wellington Square, Oxford OX1 2JD, UK. \n%\n% This file is part of Gerardus.\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details. The offer of this\n% program under the terms of the License is subject to the License\n% being interpreted in accordance with English Law and subject to any\n% action against the University of Oxford being under the jurisdiction\n% of the English Courts.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see\n% .\n\nDEBUG = 0;\n\n% check arguments\nnarginchk(7, 8);\nnargoutchk(0, 2);\n\n% defaults\nif (nargin < 8 || isempty(opts) || ~isfield(opts, 'verbose'))\n opts.verbose = 0;\nend\nif (isempty(opts) || ~isfield(opts, 't0'))\n error('OPTS.t0 expected');\nend\nif (~isfield(opts, 'IdxIgnore'))\n opts.IdxValid = true(1, length(fileh));\nelseif (~islogical(opts.IdxValid))\n % if user provides indices as integers, convert to logical vector so\n % that it's easier to get a list of invalid slices\n aux = false(1, length(fileh));\n aux(opts.IdxValid) = true;\n opts.IdxValid = aux;\nend\nif (isempty(pathstrh))\n pathstrh = '.';\nend\nif (isempty(pathstrbf))\n pathstrbf = '.';\nend\n\nif (~isempty(opts.t0))\n if (ischar(opts.t0))\n opts.t0 = elastix_read_file2param(opts.t0);\n end\n if ((length(opts.t0) == 1))\n opts.t0 = opts.t0(ones(1, length(fileh)));\n end\nend\n\nszMask = size(ellipmask);\nif (any(szMask ~= size(polymask)))\n error('ELLIPMASK and POLYMASK must be the same size')\nend\n\n% if registration parameters are provided as a filename, convert to struct\nif (ischar(regParam))\n regParam = elastix_read_file2param(regParam);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Initial alignment of histology to blockface\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% we use 10% of the voxels in the slice\nregParam.NumberOfSpatialSamples = round(numel(ellipmask) / 10);\n\n% iterate blockface images\nfor I = find(opts.IdxValid)\n\n if (opts.verbose)\n disp(['I = ' num2str(I)])\n end\n \n % load blockface and histology\n imbf = imread([pathstrbf filesep filebf(I).name]);\n imh = imread([pathstrh filesep fileh(I).name]);\n \n if (any(szMask ~= size(imbf)))\n error(['Blockface image is not the same size as masks: ' ...\n pathstrbf filesep filebf(I).name])\n end\n \n % plot slices\n if (DEBUG)\n subplot(2, 1, 1)\n imagesc(imbf)\n subplot(2, 1, 2)\n imagesc(imh)\n end\n \n % preprocessing of blockface and histology to prepare them for\n % registration\n [imh, imbf] = histology_blockface_preprocessing(imh, imbf, ...\n polymask, ellipmask);\n \n % plot slices\n if (DEBUG)\n subplot(2, 1, 1)\n imagesc(imbf)\n axis([1 size(imbf, 2) 1 size(imbf, 1)])\n subplot(2, 1, 2)\n imagesc(imh)\n end\n \n % we are going to use the user-provided initial transform for the\n % registration\n optsI.t0 = opts.t0(I);\n \n % plot initial alignment\n if (DEBUG)\n imh0 = transformix(optsI.t0, imh);\n subplot(2, 1, 2)\n imagesc(imh0)\n axis([1 size(imbf, 2) 1 size(imbf, 1)])\n imshowpair(imbf, imh0)\n end\n \n % registration of histology on blockface: Similarity\n optsI.verbose = 0;\n optsI.fMask = ellipmask;\n tic\n [tParam(I), imhreg, iterinfo] = elastix(...\n regParam, imbf, imh, optsI);\n toc\n \n % plot result of initial registration\n if (DEBUG)\n subplot(2, 1, 1)\n imagesc(imhreg)\n axis([1 size(imbf, 2) 1 size(imbf, 1)])\n subplot(1, 1, 1)\n imshowpair(imbf, imhreg)\n end\n \n \nend\n\n% DEBUG: check result\nif (DEBUG)\n for I = 1:length(filebf)\n \n disp(['I = ' num2str(I)])\n \n % load blockface and histology\n imbf = imread([pathstrbf filesep filebf(I).name]);\n imh = imread([pathstrh filesep fileh(I).name]);\n \n imh0 = transformix(tParam(I), imh);\n imshowpair(imbf, imh0)\n title(['I = ' num2str(I)])\n pause\n end\nend\n\n% extract transform parameters to matrix\ntParamMat = cat(1, tParam(:).TransformParameters);\n\n% smooth out parameters so that we can fit the histology to the\n% blockface without breaking the slice correspondence we already have\nfor I = 1:tParam(1).NumberOfParameters\n \n % interpolate/extrapolate values of the sections where the user has\n % signaled that the registration fails\n tParamMat(:, I) = interp1(find(opts.IdxValid), tParamMat(opts.IdxValid, I), ...\n 1:length(fileh), 'linear', 'extrap');\n \n % smooth the values of the B-spline coefficients\n tParamMat(:, I) = smooth(tParamMat(:, I), 'rlowess');\n \nend\n\n% overwrite transform parameters with the smoothed values\nfor I = 1:length(filebf)\n tParam(I).TransformParameters = tParamMat(I, :);\nend\n\nend\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/CardiacToolbox/histology_blockface_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.17406047624107265}} {"text": "function ExtractVideoCNNFeature_ucf(layer,scale,gpu_id, tag, ind)\naddpath /home/lmwang/code/caffe_data_parallel/caffe/matlab\nsizes =[480,640; 340,454; 240,320; 170,227; 120,160];\npath_org = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/';\nfolderlist = dir(path_org);\nfoldername = {folderlist(:).name};\nfoldername = setdiff(foldername,{'.','..'});\n\n% FLOW\nif strcmp(tag,'flow') \n path2 = ['/media/RAID0/lmwang/data/UCF/ucf101_tvl1_flow_conv5_scale_',num2str(scale),'/'];\n path3 = ['/media/RAID0/lmwang/data/UCF/ucf101_tvl1_flow_conv4_scale_',num2str(scale),'/'];\n path4 = ['/media/RAID0/lmwang/data/UCF/ucf101_tvl1_flow_conv3_scale_',num2str(scale),'/'];\n path5 = ['/media/RAID0/lmwang/data/UCF/ucf101_tvl1_flow_pool2_scale_',num2str(scale),'/'];\n path_flow = '/media/RAID0/lmwang/data/UCF/ucf101_flow_img_tvl1_gpu/';\n \n model_def_file = [ 'models/flow_',layer,'_scale_',num2str(scale),'_new.prototxt'];\n model_file = '10_flow_iter_90000_new.caffemodel';\n caffe.reset_all();\n caffe.set_mode_gpu();\n caffe.set_device(gpu_id);\n net = caffe.Net(model_def_file, model_file, 'test');\n\n for i = ind\n if ~exist([path2,foldername{i}],'dir')\n mkdir([path2,foldername{i}]);\n end\n if ~exist([path3,foldername{i}],'dir')\n mkdir([path3,foldername{i}]);\n end\n if ~exist([path4,foldername{i}],'dir')\n mkdir([path4,foldername{i}]);\n end\n if ~exist([path5,foldername{i}],'dir')\n mkdir([path5,foldername{i}]);\n end\n filelist = dir([path_org,foldername{i},'/*.avi']);\n for j = 1:length(filelist)\n filename = [path_flow,foldername{i},'/',filelist(j).name(1:end-4),'/'];\n if ~exist([path5,foldername{i},'/',filelist(j).name(1:end-4),'.mat'],'file')\n tic;\n [feature_c5, feature_c4, feature_c3, feature_p2] = TemporalCNNFeature(filename, net, sizes(scale,1), sizes(scale,2));\n toc;\n tic;\n feature = feature_c5;\n save([path2,foldername{i},'/',filelist(j).name(1:end-4),'.mat'],'feature','-v7.3');\n feature = feature_c4;\n save([path3,foldername{i},'/',filelist(j).name(1:end-4),'.mat'],'feature','-v7.3');\n feature = feature_c3;\n save([path4,foldername{i},'/',filelist(j).name(1:end-4),'.mat'],'feature','-v7.3');\n feature = feature_p2;\n save([path5,foldername{i},'/',filelist(j).name(1:end-4),'.mat'],'feature','-v7.3');\n toc;\n end\n end\n i\n end\n caffe.reset_all();\nend\n\n", "meta": {"author": "wanglimin", "repo": "TDD", "sha": "ac9a1dd76ca60a5c5ae9062b3915ea9f539260ed", "save_path": "github-repos/MATLAB/wanglimin-TDD", "path": "github-repos/MATLAB/wanglimin-TDD/TDD-ac9a1dd76ca60a5c5ae9062b3915ea9f539260ed/ExtractVideoCNNFeature_ucf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.1740604762410726}} {"text": "imOut = '/biac3/wandell4/data/reading_longitude/betCheck';\nbaseDir = {'/biac3/wandell4/data/reading_longitude/dti_y1',...\n\t\t '/biac3/wandell4/data/reading_longitude/dti_y2',...\n\t\t '/biac3/wandell4/data/reading_longitude/dti_y3',...\n\t\t '/biac3/wandell4/data/reading_longitude/dti_y4'};\nbet = 'bet2';\n% fractional intensity threshold (0->1); default=0.5; \n% smaller values give larger brain outline estimates\nbetF = {'0.35','0.40','0.45','0.55','0.60','0.65'};\n\nfor(jj=1:length(baseDir))\n d = dir(fullfile(baseDir{jj},'*0*'));\n for(ii=1:length(d))\n subCodes{ii} = d(ii).name;\n files{ii} = fullfile(baseDir{jj},d(ii).name,'t1','t1');\n end\n \n if(~exist(imOut,'dir')), mkdir(imOut); end\n N = length(files);\n doThese = [1:N];\n for(ii=doThese)\n\tif(~exist([files{ii} '.nii.gz'],'file'))\n\t disp(['Skipping ' subCodes{ii} '...']);\n\telse\n\t fprintf('Processing %s (%d of %d)...\\n', files{ii}, ii, length(doThese));\n\t t1 = niftiRead([files{ii} '.nii.gz']);\n\t slices = [1:3:t1.dim(3)-6];\n\t im = double(makeMontage(t1.data, slices));\n\t clear t1;\n\t im = mrAnatHistogramClip(im, 0.4, 0.99);\n\t im = uint8(im./max(im(:)).*255+0.5);\n\t for(jj=1:length(betF))\n\t\toutName = [files{ii} '_' betF{jj}];\n\t\tbetCmd = [bet ' ' files{ii} ' ' outName ' -mnf ' betF{jj}];\n\t\tdisp([' running BET: ' betCmd '...']);\n\t\tunix(['export FSLOUTPUTTYPE=NIFTI_GZ ; ' betCmd]);\n\t\tmask = niftiRead([outName '_mask.nii.gz']);\n\t\tmask = logical(makeMontage(mask.data, slices));\n\t\tskull = im; skull(mask) = 0;\n\t\tbrain = im; brain(~mask) = 0;\n\t\trgb(:,:,1) = brain;\n\t\trgb(:,:,2) = skull+brain;\n\t\trgb(:,:,3) = brain;\n\t\timwrite(rgb, fullfile(imOut, [subCodes{ii} '_betF' betF{jj}(end-2:end) '.png']));\n\t end\n\tend\n end\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrScripts/diffusion/dtiExtractBrains.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.17406046926575722}} {"text": "function spm_run_bms_vis(varargin)\n% Show results for Bayesian Model Selection Maps\n% SPM job execution function\n% takes a harvested job data structure (or no input) and calls SPM \n% functions to show results from Bayesian Model Selection of \n% Log. Evidence Maps \n%\n% Input:\n% Varargin - can be harvested job data structure (see matlabbatch help).\n% Output:\n% No output.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Maria Joao Rosa\n% $Id: spm_run_bms_vis.m 7577 2019-04-24 08:59:56Z guillaume $\n\n% Input\n% -------------------------------------------------------------------------\nif isempty(varargin)\n job.file{1}=''; job.img{1}=''; job.thres = []; job.scale = []; job.k=[];\nelse\n job = varargin{1};\nend\nfile_str = length(job.file{1});\nimage = length(job.img{1});\nthres_b = length(job.thres);\nodds_b = length(job.scale);\next_thre = length(job.k);\n\n% Initialise SPM Interactive window\n% -------------------------------------------------------------------------\n[Finter,F,CmdLine] = spm('FnUIsetup','SPM BMC Toolbox: Visualise options',0);\nF = spm_figure('FindWin','Graphics');\nspm('Clear',Finter);\nWS = spm('WinScale');\nFS = spm('FontSizes');\n\n% Select results image from BMS Maps\n% -------------------------------------------------------------------------\nif file_str\n file_fname = job.file{1};\nelse\n file_fname = spm_select(1,'mat','Load BMS file (.mat)');\nend\n\n% Load BMS\nload(file_fname);\nwd = fileparts(file_fname);\n\n% Select results image from BMS Maps\n% -------------------------------------------------------------------------\nif image\n post = job.img{1};\nelse\n post = spm_select(1,'image','Select BMS Maps results (ex: ppm, alpha or epm image)',[],wd);\nend\n\n% Select threshold to apply to image\n% -------------------------------------------------------------------------\nif thres_b\n threshold = job.thres;\nelse\n threshold = spm_input('Probability Threshold:', '+1', 'r', '0.5', [1, inf]);\nend\n\n% Extent threshold\n% -------------------------------------------------------------------------\nif ext_thre\n k = job.k;\nelse\n k = spm_input('& extent threshold {voxels}','+1','r',0,1,[0,Inf]);\nend\n\n% Select scale\n% -------------------------------------------------------------------------\nif odds_b\n odds = job.scale;\nelse\n odds = spm_input('Change scale to Log-Odds?', '+1', 'y/n', [1,0], 2);\nend\n\n% Image dimensions\n% -------------------------------------------------------------------------\nV = spm_vol(post);\nM = V.mat;\niM = inv(M);\nvox = sqrt(sum(M(1:3,1:3).^2));\nDIM = V.dim(1:3)'; \nxdim = DIM(1); ydim = DIM(2); zdim = DIM(3);\n[xords,yords] = ndgrid(1:xdim,1:ydim);\nxords = xords(:)'; yords = yords(:)';\nI = 1:xdim*ydim;\nzords_init = ones(1,xdim*ydim);\nsvol = xdim*ydim*zdim;\n\n% Legend of results being plotted\n% -------------------------------------------------------------------------\n[pathstr,name_image] = fileparts(V.fname);\nundersc = find(name_image=='_');\n\nif ~isempty(undersc) && length(undersc)>1\n res_name = name_image(undersc(end)+1);\n subset_model = name_image(1:undersc(end-1)-1);\nelse\n res_name = '';\nend\n\n% Show results being displayed on graphics window\nswitch res_name\n case 'a' \n xSPM.str = sprintf('Alphas: %s',subset_model);\n case 'p'\n xSPM.str = sprintf('PPM: %s',subset_model);\n case 'x'\n xSPM.str = sprintf('PPM: %s',subset_model);\n case 'e'\n xSPM.str = sprintf('EPM: %s',subset_model);\n otherwise\n xSPM.str = '';\nend\n\n% Loop over slices (get voxels above threshold)\n% -------------------------------------------------------------------------\nxyz_above = [];\nz_above = [];\nxyz_total = [];\n\nfor z = 1:zdim,\n \n zords = z*zords_init;\n xyz = [xords(I); yords(I); zords(I)];\n zvals = spm_get_data(V,xyz);\n above = find(zvals>threshold);\n if ~isempty(above)\n xyz_above = [xyz_above,xyz(:,above)];\n z_above = [z_above,zvals(above)];\n end\n xyz_total = [xyz_total,xyz];\nend\n\n% SPM figure: SPM, MIP and GUI\n% -------------------------------------------------------------------------\nif ~isempty(z_above)\n \n z_orig = z_above;\n % Log odds transform\n if odds\n z_odds = log(z_above./(ones(1,length(z_above))-z_above));\n if isempty(find(z_odds == Inf)) % Data don't contain Infs\n z_above = z_odds;\n else\n odds = 0; % Don't plot odds\n end\n end\n \n % Calculate extent threshold filtering\n % ---------------------------------------------------------------------\n A = spm_clusters(xyz_above);\n Q = [];\n for i = 1:max(A)\n j = find(A == i);\n if length(j) >= k; Q = [Q j]; end\n end\n\n % ...eliminate voxels\n %----------------------------------------------------------------------\n Z = z_above(:,Q);\n XYZ = xyz_above(:,Q);\n z_ps = z_orig(:,Q);\n if isempty(Q)\n warning(sprintf('No voxels survive extent threshold k=%0.2g',k))\n end\n\n % Save data in xSPM structure\n voxels_mm = M*[XYZ;ones(1,size(XYZ,2))];\n voxels_mm = voxels_mm(1:3,:);\n xSPM.swd = file_fname;\n xSPM.STAT = '';\n xSPM.Z = Z;\n xSPM.XYZ = XYZ;\n xSPM.XYZmm = voxels_mm;\n xSPM.xVol.M = M;\n xSPM.xVol.DIM = DIM;\n xSPM.SPM.xVol.XYZ = xyz_total;\n xSPM.SPM.xVol.S = svol;\n xSPM.SPM.xVol.M = M;\n xSPM.SPM.xVol.DIM = DIM;\n xSPM.DIM = DIM;\n xSPM.M = M;\n xSPM.iM = iM;\n xSPM.n = 1;\n xSPM.k = k;\n xSPM.df = [];\n xSPM.u = threshold;\n xSPM.FWHM = 10; % arbritary value\n xSPM.STAT = '';\n xSPM.VOX = vox; \n xSPM.thres = threshold;\n xSPM.vols = post;\n xSPM.scale = odds;\n xSPM.units = {'mm' 'mm' 'mm'};\n xSPM.Ps = [];\n xSPM.S = 0;\n xSPM.z_ps = z_ps;\n xSPM.VRpv = [];\n xSPM.Vspm = [];\n BMS.xSPM = xSPM;\n \n % Display on workspace\n assignin('base','BMS',BMS);\n assignin('base','xSPM',xSPM);\n \n % Display results\n hReg = spm_bms_display(BMS,'Init');\n \n assignin('base','hReg',hReg);\n \nelse\n \n % No voxels for selected threshold\n disp('No voxels above threshold!');\n uicontrol(Finter,'Style','Text','String','No voxels above threshold!',...\n 'Position',[020 010 200 020].*WS,...\n 'FontAngle','Italic',...\n 'FontSize',FS(12),...\n 'HorizontalAlignment','Left',...\n 'ForegroundColor','w')\n do_results = spm_input('Return to Results?', '+1', 'y/n', [1,0], 2);\n \n % Go back to BMS Maps (Results)\n if do_results \n \n % Return to display routine \n spm_run_bms_vis;\n \n else\n \n spm('Clear',Finter); % Clear Finter window\n return % Finish \n \n end\n \n \nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/config/spm_run_bms_vis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17345965093365545}} {"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 rez = fullMPMU(rez, DATA)\n\nops = rez.ops;\n\nNfilt = ops.Nfilt;\nlam = ones(Nfilt, 1, 'single');\nlam(:) = ops.lam(3);\n\n[W, U, mu, UtU, nu] = decompose_dWU(ops, rez.dWU, ops.Nrank,rez.ops.kcoords);\n\n\npm = exp(-ops.momentum(2));\nParams = double([ops.NT ops.Nfilt ops.Th(3) ops.maxFR 10 ops.Nchan ops.Nrank pm ops.epu ops.nt0]);\n\nParams(3) = ops.Th(3);\nParams(4) = 50000;\nParams(5) = 50; \n\nif ops.GPU\n U0 = gpuArray(U);\nelse\n U0 = U;\nend\n%%\nnt0 = rez.ops.nt0;\nNrank = ops.Nrank;\nWtW = zeros(Nfilt,Nfilt,2*nt0-1, 'single');\nfor i = 1:Nrank\n for j = 1:Nrank\n utu0 = U0(:,:,i)' * U0(:,:,j);\n if ops.GPU\n wtw0 = gather_try(mexWtW2(Params, W(:,:,i), W(:,:,j), utu0));\n else\n wtw0 = getWtW2(Params, W(:,:,i), W(:,:,j), utu0);\n wtw0 = permute(wtw0, [2 3 1]);\n end\n WtW = WtW + wtw0;\n clear wtw0 utu0\n% wtw0 = squeeze(wtw(:,i,:,j,:));\n \n end\nend\n\nmWtW = max(WtW, [], 3);\nWtW = permute(WtW, [3 1 2]);\n\nif ops.GPU\n WtW = gpuArray(WtW);\nend\n%%\nNbatch_buff = rez.temp.Nbatch_buff;\nNbatch = rez.temp.Nbatch;\nNchan = ops.Nchan;\nif ~ops.GPU\n fW = rez.fW; % load fft-ed templates \nend\n% mWtW = mWtW - diag(diag(mWtW));\n\n% rez.WtW = gather_try(WtW);\n%\nclear wtw0 utu0 U0\n%\nclear nspikes2\nst3 = [];\nrez.st3 = [];\n\nif ops.verbose\n fprintf('Time %3.0fs. Running the final template matching pass...\\n', toc) \nend\n\nif Nbatch_buff100);\n cr = mWtW .* (vld * vld');\n cr(isnan(cr)) = 0;\n [~, iNgsort] = sort(cr, 1, 'descend');\n \n % save full similarity score\n rez.simScore = cr;\n maskTT = zeros(Nfilt, 'single');\n rez.iNeigh = iNgsort(1:nNeigh, :);\n for i = 1:Nfilt\n maskTT(rez.iNeigh(:,i),i) = 1;\n end\nend\nif ~isempty(ops.nNeighPC)\n nNeighPC = ops.nNeighPC;\n load PCspikes\n ixt = round(linspace(1, size(Wi,1), ops.nt0));\n Wi = Wi(ixt, 1:3);\n rez.cProjPC = zeros(5e6, 3*nNeighPC, 'single');\n \n % sort best channels\n [~, iNch] = sort(abs(U(:,:,1)), 1, 'descend');\n maskPC = zeros(Nchan, Nfilt, 'single');\n rez.iNeighPC = iNch(1:nNeighPC, :);\n for i = 1:Nfilt\n maskPC(rez.iNeighPC(:,i),i) = 1;\n end\n maskPC = repmat(maskPC, 3, 1);\nend\n\nirun = 0;\ni1nt0 = int32([1:nt0])';\n%%\nLAM = lam .* (20./mu).^2;\n\nNT = ops.NT;\nbatchstart = 0:NT:NT*(Nbatch-Nbatch_buff);\n\nfor ibatch = 1:Nbatch \n if ibatch>Nbatch_buff\n offset = 2 * ops.Nchan*batchstart(ibatch-Nbatch_buff); % - ioffset;\n fseek(fid, offset, 'bof');\n dat = fread(fid, [NT ops.Nchan], '*int16');\n else\n dat = DATA(:,:,ibatch); \n end\n if ops.GPU\n dataRAW = gpuArray(dat);\n else\n dataRAW = dat;\n end\n dataRAW = single(dataRAW);\n dataRAW = dataRAW / ops.scaleproc;\n \n % project data in low-dim space\n if ops.GPU\n data = gpuArray.zeros(NT, Nfilt, Nrank, 'single');\n else\n data = zeros(NT, Nfilt, Nrank, 'single');\n end\n for irank = 1:Nrank\n data(:,:,irank) = dataRAW * U(:,:,irank);\n end\n data = reshape(data, NT, Nfilt*Nrank);\n\n if ops.GPU\n [st, id, x, errC, PCproj] ...\n = mexMPmuFEAT(Params,data,W,WtW, mu, lam .* (20./mu).^2, nu);\n else\n [st, id, x, errC, PCproj]= cpuMPmuFEAT(Params,data,fW,WtW, mu, lam .* (20./mu).^2, nu, ops);\n end\n \n if ~isempty(st)\n if ~isempty(ops.nNeighPC)\n % PCA coefficients\n inds = repmat(st', nt0, 1) + repmat(i1nt0, 1, numel(st));\n try datSp = dataRAW(inds(:), :);\n catch\n datSp = dataRAW(inds(:), :);\n end\n datSp = reshape(datSp, [size(inds) Nchan]);\n coefs = reshape(Wi' * reshape(datSp, nt0, []), size(Wi,2), numel(st), Nchan);\n coefs = reshape(permute(coefs, [3 1 2]), [], numel(st));\n coefs = coefs .* maskPC(:, id+1);\n iCoefs = reshape(find(maskPC(:, id+1)>0), 3*nNeighPC, []);\n rez.cProjPC(irun + (1:numel(st)), :) = gather_try(coefs(iCoefs)');\n end\n if ~isempty(ops.nNeigh)\n % template coefficients\n % transform coefficients\n PCproj = bsxfun(@rdivide, ...\n bsxfun(@plus, PCproj, LAM.*mu), sqrt(1+LAM));\n \n PCproj = maskTT(:, id+1) .* PCproj;\n iPP = reshape(find(maskTT(:, id+1)>0), nNeigh, []);\n rez.cProj(irun + (1:numel(st)), :) = PCproj(iPP)';\n end\n % increment number of spikes\n irun = irun + numel(st);\n \n if ibatch==1;\n ioffset = 0;\n else\n ioffset = ops.ntbuff;\n end\n st = st - ioffset;\n \n % nspikes2(1:size(W,2)+1, ibatch) = histc(id, 0:1:size(W,2));\n STT = cat(2, ops.nt0min + double(st) +(NT-ops.ntbuff)*(ibatch-1), ...\n double(id)+1, double(x), ibatch*ones(numel(x),1));\n st3 = cat(1, st3, STT);\n end\n if rem(ibatch,100)==1\n% nsort = sort(sum(nspikes2,2), 'descend');\n fprintf(repmat('\\b', 1, numel(msg)));\n msg = sprintf('Time %2.2f, batch %d/%d, NTOT %d\\n', ...\n toc, ibatch,Nbatch, size(st3,1)); \n fprintf(msg);\n \n end\nend\n%%\n[~, isort] = sort(st3(:,1), 'ascend');\nst3 = st3(isort,:);\n\nrez.st3 = st3;\nif ~isempty(ops.nNeighPC)\n % re-sort coefficients for projections\n rez.cProjPC(irun+1:end, :) = [];\n rez.cProjPC = reshape(rez.cProjPC, size(rez.cProjPC,1), [], 3);\n rez.cProjPC = rez.cProjPC(isort, :,:);\n for ik = 1:Nfilt\n iSp = rez.st3(:,2)==ik;\n OneToN = 1:nNeighPC;\n [~, isortNeigh] = sort(rez.iNeighPC(:,ik), 'ascend');\n OneToN(isortNeigh) = OneToN;\n rez.cProjPC(iSp, :,:) = rez.cProjPC(iSp, OneToN, :);\n end\n \n rez.cProjPC = permute(rez.cProjPC, [1 3 2]);\nend\nif ~isempty(ops.nNeigh)\n rez.cProj(irun+1:end, :) = [];\n rez.cProj = rez.cProj(isort, :);\n\n % re-index the template coefficients\n for ik = 1:Nfilt\n iSp = rez.st3(:,2)==ik;\n OneToN = 1:nNeigh;\n [~, isortNeigh] = sort(rez.iNeigh(:,ik), 'ascend');\n OneToN(isortNeigh) = OneToN;\n rez.cProj(iSp, :) = rez.cProj(iSp, OneToN);\n end\nend\n\n\n%%\n% rez.ops = ops;\nrez.W = W;\nrez.U = U;\nrez.mu = mu;\n\nrez.t2p = [];\nfor i = 1:Nfilt\n wav0 = W(:,i,1);\n wav0 = my_conv(wav0', .5)';\n [~, itrough] = min(wav0);\n [~, t2p] = max(wav0(itrough:end));\n rez.t2p(i,1) = t2p;\n rez.t2p(i,2) = itrough; \nend\n\nrez.nbins = histc(rez.st3(:,2), .5:1:Nfilt+1);\n\n[~, rez.ypos] = max(rez.U(:,:,1), [], 1);\nif Nbatch_buff.\n%\n% $Id$\n\n% this persistent variable is used for caching the 600 packets\n% which inproves the throughput when reading overlapping data segments\npersistent ctf_shm\n\n% read the data from shared memory, first the meta information only\n[msgType msgId sampleNumber numSamples numChannels] = read_ctf_shm;\n\nif isempty(ctf_shm)\n ctf_shm.msgType = nan(size(msgType));\n ctf_shm.msgId = nan(size(msgId));\n ctf_shm.sampleNumber = nan(size(sampleNumber));\n ctf_shm.numSamples = nan(size(numSamples));\n ctf_shm.numChannels = nan(size(numChannels));\n ctf_shm.data = {};\n ctf_shm.hit = 0;\n ctf_shm.mis = 0;\nend\n\n% there seems to be a bug in Acq, causing the messageId to wrap around\n% hence it cannot be used as index into the packets, so construct a new trial numbering vector \ntrlNum = nan(size(msgId));\ntrlNum(msgType==1) = sampleNumber(msgType==1)./numSamples(msgType==1) + 1;\n\n% allocate memory for the data, fill with NaNs\ndat = nan(length(chanindx), hdr.nSamples, endtrial-begtrial+1);\n\n% determine which trials/packets to read \nsel = find((trlNum>=begtrial) & (trlNum<=endtrial));\n\n% this is for calibrating the integer values to physical values\nif isfield(hdr, 'orig') && isfield(hdr.orig, 'gainV')\n gain = diag(hdr.orig.gainV(chanindx));\nelseif isfield(hdr, 'orig') && isfield(hdr.orig, 'res4')\n gain = diag([hdr.orig.res4.senres(chanindx).gain]);\nend\n\nif length(chanindx)>1\n % this speeds up the multiplication, but would result in a sparse matrix when nchans=1\n gain = sparse(gain);\nend\n\nfor i=1:length(sel)\n % nchan = numChannels(i);\n % nsmp = numSamples(i);\n nchan = hdr.nChans;\n nsmp = hdr.nSamples;\n % buf = read_ctf_shm(sel(i));\n % buf = buf(1:nchan*nsmp);\n if all([msgType(sel(i)) msgId(sel(i)) sampleNumber(sel(i)) numSamples(sel(i)) numChannels(sel(i))] == [ctf_shm.msgType(sel(i)) ctf_shm.msgId(sel(i)) ctf_shm.sampleNumber(sel(i)) ctf_shm.numSamples(sel(i)) ctf_shm.numChannels(sel(i))])\n % get the data from the cache\n buf = ctf_shm.data{sel(i)};\n ctf_shm.hit = ctf_shm.hit+1;\n else\n % read the data from shared memory, update the cache\n buf = read_ctf_shm(sel(i),nchan*nsmp);\n ctf_shm.data{sel(i)} = buf;\n ctf_shm.msgType(sel(i)) = msgType(sel(i));\n ctf_shm.msgId(sel(i)) = msgId(sel(i));\n ctf_shm.sampleNumber(sel(i)) = sampleNumber(sel(i));\n ctf_shm.numSamples(sel(i)) = numSamples(sel(i));\n ctf_shm.numChannels(sel(i)) = numChannels(sel(i));\n ctf_shm.mis = ctf_shm.mis+1;\n end\n buf = reshape(buf, nchan, nsmp);\n thistrial = trlNum(sel(i));\n % apply calibration to the selected channels\n dat(:,:,thistrial-begtrial+1) = gain * double(buf(chanindx,:));\nend\n\n% if any(isnan(dat(:)))\n% ft_warning('data has been padded with NaNs');\n% fprintf('trials present = %d - %d\\n', min(trlNum), max(trlNum));\n% fprintf('trials requested = %d - %d\\n', begtrial, endtrial);\n% end\n\ndimord = 'chans_samples_trials';\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/fileio/private/read_shm_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17299967127271607}} {"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": "% EEGTHRESH - reject trials with out-of-bounds channel values within a\n% specified epoch time range.\n%\n% Usage:\n% >> [Iin, Iout, newsignal, elec] = eegthresh( signal, frames, ...\n% elecs, negthresh, posthresh, timerange, starttime,endtime);\n%\n% Required inputs:\n% signal - 2-D data matrix [channels, frames*sweeps], \n% or 3-D data matrix [channels, frames, sweeps]\n% frames - number of points per epoch\n% elecs - [int vector] electrode indices to reject on\n% negthresh - minimum rejection threshold(s) in uV. This can be an array \n% of values for individual electrodes. If fewer values than \n% electrodes, the last value is used for the remaining \n% electrodes.\n% posthresh - maximum rejection threshold(s) in uV (same syntax as for\n% negthresh)\n% timerange - [mintime maxtime] time range limits of the signal\n% starttime - Starting limit (in seconds or Hz) of range to perform \n% rejection (same syntax as negthresh)\n% endtime - Ending limit (in seconds or Hz) of range to perform \n% rejection (same syntax as negthresh)\n%\n% Outputs:\n% Iin - Indexes of epochs accepted\n% Iout - Indexes of epochs rejected\n% newsignal - input data after epoch rejection\n% elec - electrode that triggered the rejections (array of 0s \n% and 1s with the same number of columns as Iout\n% and number of rows = number of electrodes).\n%\n% Author: Arnaud Delorme, CNL / Salk Institute, 2001\n%\n% See also: POP_EEGTHRESH, EEGLAB\n\n% Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction [Iin, Iout, newsignal, elec] = eegthresh( signal, pnts, electrodes, negthresh, posthresh, timerange, starttime, endtime)\n\nif nargin < 7\n\thelp eegthresh;\n\treturn;\nend\n\nif starttime < timerange(1)\n\tdisp('eegthresh: starting point out of range, adjusted');\n starttime = timerange(1);\nend\nif endtime > timerange(2)\n\tdisp('eegthresh: ending point out of range, adjusted');\n endtime = timerange(2);\nend\nif isempty(electrodes)\n electrodes = 1:size(signal,1);\nend\n\n% complete thresholds values if necessary\n%----------------------------------------\nif size(posthresh,2) < size(electrodes,2)\n\tposthresh = [ posthresh posthresh(end)*ones(1,size(electrodes,2)-size(posthresh,2))];\nend\nif size(negthresh,2) < size(electrodes,2)\n\tnegthresh = [ negthresh negthresh(end)*ones(1,size(electrodes,2)-size(negthresh,2))];\nend\n\t\n% complete timeselect values if necessary\n%----------------------------------------\nif size(starttime,2) < size(electrodes,2)\n\tstarttime = [ starttime starttime(end)*ones(1,size(electrodes,2)-size(starttime,2))];\nend\nif size(endtime,2) < size(electrodes,2)\n\tendtime = [ endtime endtime(end)*ones(1,size(electrodes,2)-size(endtime,2))];\nend\n\n% find the maximum for each trial\n%--------------------------------\nsweeps = size(signal(1,:),2)/pnts;\nsignal = reshape(signal(electrodes,:), size(electrodes(:),1), pnts, sweeps);\n\n% reject the selected trials\n%---------------------------\nelec = zeros(size(electrodes(:),1), sweeps);\nallelec = zeros(1, sweeps);\nfor indexe = 1:size(electrodes(:),1)\n\t% transform the time range\n\t% ------------------------\n\tframelowlimit = max(1,floor((starttime(indexe)-timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1);\t\n\tframehighlimit = floor((endtime(indexe) -timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1;\n\n\t% remove outliers\n\t% ---------------\n\tsigtmp = squeeze(signal(indexe,framelowlimit:framehighlimit,:));\n if size(signal,3) == 1, sigtmp = sigtmp'; end\n\tsigmax = max(sigtmp, [], 1);\n\tsigmin = min(sigtmp, [], 1);\n\telec(indexe,:) = ( sigmin < negthresh(indexe) ) | ( sigmax > posthresh(indexe) );\n\tallelec = allelec | elec(indexe,:);\nend\nIout = find( allelec == 1 );\nIin = find( allelec == 0 );\nelec = elec(:,Iout);\n\n% reject the selected trials\n%---------------------------\nnewsignal = reshape(signal, size(signal,1), pnts, sweeps);\nif ~isempty(Iin)\n\tnewsignal = newsignal(:,:,Iin);\n\tif ndims(signal) == 2\n\t\tnewsignal = newsignal(:,:);\n\tend\nelse\n\tnewsignal = [];\nend\nreturn;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/eegthresh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17291729798365907}} {"text": "% eeg_getica() - get ICA component activation. Recompute if necessary.\n%\n% >> mergelocs = eeg_getica(EEG, comp);\n%\n% Inputs: \n% EEG - EEGLAB dataset structure\n% comp - component index\n%\n% Output: \n% icaact - ICA component activity\n%\n% Author: Arnaud Delorme, 2006\n\n% Copyright (C) Arnaud Delorme, CERCO, 2006, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction icaact = eeg_getica(EEG, comp)\n\n if nargin < 1\n help eeg_getica;\n return;\n end;\n if nargin < 2\n comp = 1:size(EEG.icaweights,1);\n end;\n \n if ~isempty(EEG.icaact)\n icaact = EEG.icaact(comp,:,:);\n else\n disp('Recomputing ICA activations');\n if isempty(EEG.icachansind)\n EEG.icachansind = 1:EEG.nbchan;\n disp('Channels indices are assumed to be in regular order and arranged accordingly');\n end\n icaact = (EEG.icaweights(comp,:)*EEG.icasphere)*reshape(EEG.data(EEG.icachansind,:,:), length(EEG.icachansind), EEG.trials*EEG.pnts);\n icaact = reshape( icaact, size(icaact,1), EEG.pnts, EEG.trials);\n end;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/eeg_getica.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1727894544405122}} {"text": "function [image_data,vlat,vlon] = mygrid_sand2(region,ssfname)\n% MYGRID_SAND2 Read bathymetry data from Sandwell Database\n% [Z,LAT,LON] = MYGRID_SAND2(REGION) extracts data from\n% the Sandwell and Smith bathymetry, which is now at 1-minute\n% resolution.\n%\n%\n% WARNING: change ssfname and ssversion to the correct one for \n% your machine\n%\n% Catherine de Groot-Hedlin\n% modified Rich Pawlowicz\n%\n% latitudes must be between -80.738 and 80.738;\n% input:\n% REGION =[west east south north];\n% output:\n% Z - matrix of sandwell bathymetry/topography\n% LAT - vector of latitudes associated with image_data\n% LON - vector of longitudes\n%\n% An odd Z value of say -2001m signifies that this pixel was constrained\n% by a real depth sounding while an even depth of say -2000m is\n% a predicted depth. Plot rem(Z,2) to see this.\n%\n% Changes Jan/18 - modified to work with post v9 database versions\n% also order of arguments, and various other\n% things that bothered me.\n\nif nargin<1\n region=[-140 -121 46 52];\nend\n\nif nargin<2\n %ssfname='/ocean/rich/more/mmapbase/s_and_s/topo_8.2.img';\n %ssversion=8.2;\n ssfname='/ocean/rich/more/mmapbase/s_and_s/topo_18.1.img';\n ssversion=18.1;\nend\n\n\n%------no changes below here-------------\n\n% determine the requested region\nwlon = region(1);\nelon = region(2);\nblat = region(3);\ntlat = region(4);\n\n% Setup the parameters for reading Sandwell data version \nif ssversion<9\n db_res = 2/60; % 2 minute resolution\n db_loc = [-72.006 72.006 0.0 360-db_res];\n db_size = [6336 10800];\nelse\n db_res = 1/60; % 1 minute resolution\n db_loc = [-80.738 80.738 0.0 360-db_res];\n db_size = [17280 21600]; \nend \nnbytes_per_lat = db_size(2)*2; % 2-byte integers\n\n% Check ranges\n\nif blatdb_loc(2)\n tlat=db_loc(2);\nend\n\n\n% Determine if the database needs to be read twice (overlapping prime meridian)\nif ((wlon<0)&&(elon>=0))\n wlon = [wlon 0];\n elon = [360-db_res elon];\nend\n\n% Calculate number of \"records\" down to start (latitude) (0 to db_size(1)-1)\n% (mercator projection)\nrad=pi/180;\n\narg1=log(tand(45+db_loc(1)/2));\narg2=log(tand(45+blat/2));\niblat = fix(db_size(1) +1 - (arg2-arg1)/(db_res*rad));\n\narg2=log(tand(45+tlat/2));\nitlat = fix(db_size(1) +1 - (arg2-arg1)/(db_res*rad));\n\nif (iblat < 0 ) || (itlat > db_size(1)-1)\n errordlg([' Requested latitude is out of file coverage ']);\nend\n\n% Go ahead and read the database\n% Open the data file\nfid = fopen( ssfname, 'r','b');\nif (fid < 0)\n error(['Could not open database: ' ssfname],'Error');\nend\n\nimage_data = [];\nfor i = 1:length(wlon)\n\n\n % Make sure the longitude data goes from 0 to 360\n if wlon(i) < 0\n wlon(i) = 360 + wlon(i);\n end\n\n if elon(i) < 0\n elon(i) = 360 + elon(i);\n end\n\n % Calculate the longitude indices into the matrix (0 to db_size(1)-1)\n iwlon(i) = fix((wlon(i)-db_loc(3))/db_res);\n ielon(i) = fix((elon(i)-db_loc(3))/db_res);\n if (iwlon(i) < 0 ) || (ielon(i) > db_size(2)-1)\n error([' Requested longitude is out of file coverage ']);\n end\n\n % allocate memory for the data\n data = zeros(iblat-itlat+1,ielon(i)-iwlon(i)+1);\n\n % Skip into the appropriate spot in the file, and read in the data\n disp('Reading in bathymetry data');\n for ilat = itlat:iblat\n offset = ilat*nbytes_per_lat + iwlon(i)*2;\n status = fseek(fid, offset, 'bof');\n data(iblat-ilat+1,:)=fread(fid,[1,ielon(i)-iwlon(i)+1],'integer*2');\n end\n\n\n % put the two files together if necessary\n if (i>1)\n image_data = [image_data data];\n else\n image_data = data;\n end\nend\n% close the file\nfclose(fid);\n\n\n% Determine the coordinates of the image_data\nvlat=zeros(1,iblat-itlat+1);\narg2 = log(tand(45+db_loc(1)/2.));\nfor ilat=itlat+1:iblat+1\n arg1 = rad*db_res*(db_size(1)-ilat+0.5);\n term=exp(arg1+arg2);\n vlat(iblat-ilat+2)=2*atand(term)-90;\nend\nvlon=db_res*((iwlon+1:ielon+1)-0.5);\n\n% to plot it up\n\nif nargout==0\n [xx,yy]=meshgrid(vlon,vlat);\n pcolor(xx,yy,image_data),shading flat,colormap(jet),colorbar('vert')\n xlabel('longitude'),ylabel('latitude'),title('Smith and Sandwell bathymetry Example')\n clear image_data vlon vlat\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/thirdParty/m_map/mygrid_sand2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.17267628580070687}} {"text": "function rgb = brain\n\n% returns a predefined color as [red green blue] values\n%\n% skin_surface = [255 213 119]/255;\n% outer_skull_surface = [140 85 85]/255;\n% inner_skull_surface = [202 100 100]/255;\n% cortex = [255 213 119]/255;\n% black = [0 0 0 ]/255;\n% white = [255 255 255]/255;\n% red = [255 0 0 ]/255;\n% green = [0 192 0 ]/255;\n% blue = [0 0 255]/255;\n% yellow = [255 255 0 ]/255;\n% cortex_light = [199 194 169]/255;\n% cortex_dark = [100 97 85]/255;\n\nrgb = [202 100 100]/255;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/brain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.1725209829220042}} {"text": "% COVAREP parallel feature formant extraction function\n%\n% Description\n% This function performs COVAREP_feature_formant_extraction\n% on all .wav files in the specified folder in parallel\n%\n% Input\n% in_dir [directory path] : Path to directory containing wav files to be analysed\n% options: Struct with optional arguments (applied to all files in folder).\n%\n% Output\n% None\n%\n% 'options' can have the following fields:\n% feature_fs: Sampling rate of the returned features (default: 0.01ms)\n% gender: Used for vowelSpace (0: female (default); 1: male; 2: child)\n% features: The list of features to be extracted (default: all).\n% Possible features are: 'f0', 'F', 'VUV', 'NAQ', 'QOQ',\n% 'H1H2', 'PSP', 'MDQ', 'HRF', 'peakSlope', 'Rd', 'Rd_conf',\n% 'MCEP', 'HMPDM', 'HMPDD', 'vowelSpace', 'VAD'\n% mcep_order: Order of the MCEPs (default: 24)\n% hmpdm_order:\tOrder of the HMPDMs (default: 24)\n% hmpdd_order:\tOrder of the HMPDDs (default: 12)\n% channel: If the audio file has multiple channels (default: 1)\n% save_mat: Save the results as a MAT file (default: false)\n% save_csv: Save the results as a CSV file (default: true)\n% If 'save_mat' or 'save_csv' are strings, they are\n% interpreted as paths to the file to be created.\n% Author\n% Florian Helmhold based on\n% COVAREP_feature_formant_extraction_perfile (Torsten W\u00f6rtwein )\n% COVAREP_feature_extraction.m (John Kane )\n% COVAREP_formant_extraction.m (Stefan Scherer )\n\nfunction COVAREP_feature_formant_extraction(in_dir, options)\n\n%% Default settings\nif nargin < 2\n options = struct; % Default empty options struct\nend\n\n%% Sanity check options\nif isfield(options, 'save_mat') && ~islogical(options.save_mat)\n warning('Non boolean save_mat options will overwrite the output file.')\nend\n\nif isfield(options, 'save_csv') && ~islogical(options.save_csv)\n warning('Non boolean save_csv options will overwrite the output file.')\nend\n\n% Analysis settings\nfileList=dir([in_dir filesep '*.wav']);\nN=length(fileList);\n\nif N==0\n disp('No wav files in inputted directory!!!')\nend\n\nif(hasParallelComputing)\n parfor n=1:N\n basename=regexp(fileList(n).name,'\\.wav','split');\n basename=char(basename(1));\n disp(['Analysing file: ' basename])\n try\n COVAREP_feature_formant_extraction_perfile([in_dir filesep basename '.wav'], options)\n disp([basename ' successfully analysed'])\n catch err\n warning(['An error occurred while analysing ' basename ': ' getReport(err)])\n end\n end\nelse\n for n=1:N\n basename=regexp(fileList(n).name,'\\.wav','split');\n basename=char(basename(1));\n disp(['Analysing file: ' basename])\n try\n COVAREP_feature_formant_extraction_perfile([in_dir filesep basename '.wav'], options)\n disp([basename ' successfully analysed'])\n catch err\n warning(['An error occurred while analysing ' basename ': ' getReport(err)])\n end\n end\nend\n\n%% Helper functions\n\nfunction has_parallel = hasParallelComputing\n% get all installed toolbox names\nv = ver;\n% collect the names in a cell array\n[installedToolboxes{1:length(v)}] = deal(v.Name);\n\n% check\nhas_parallel = all(ismember({'Parallel Computing Toolbox'},installedToolboxes));\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/feature_extraction/COVAREP_feature_formant_extraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.17231907171283956}} {"text": "function [ obj ] = estimate( obj, varargin )\n% Estimate parameters of the HUGE model.\n% \n% INPUTS:\n% obj - A tapas_Huge object containing fMRI time series.\n% \n% OPTIONAL INPUTS:\n% This function accepts optional name-value pair arguments. For a list of\n% valid name-value pairs, see the user manual or type 'help\n% tapas_huge_property_names'.\n% \n% OUTPUTS:\n% obj - A tapas_Huge object containing the estimation result in the\n% 'posterior' property. \n%\n% EXAMPLES:\n% [obj] = ESTIMATE(obj) Invert the HUGE model stored in obj. \n% \n% [obj] = ESTIMATE(obj, 'K', 2) Set the number of clusters to 2 and\n% invert the HUGE model stored in obj.\n% \n% [obj] = ESTIMATE(obj, 'Verbose', true) Print progress of estimation\n% to command line. \n% \n% [obj] = ESTIMATE(obj, 'Dcm', dcms, 'OmitFromClustering', 1) Import\n% data stored in 'dcms' and omit self-connections from clustering.\n% \n% See also TAPAS_HUGE_DEMO\n% \n\n% Author: Yu Yao (yao@biomed.ee.ethz.ch)\n% Copyright (C) 2019 Translational Neuromodeling Unit\n% Institute for Biomedical Engineering,\n% University of Zurich and ETH Zurich.\n% \n% This file is part of TAPAS, which is released under the terms of the GNU\n% General Public Licence (GPL), version 3. For further details, see\n% .\n% \n% This software is provided \"as is\", without warranty of any kind, express\n% or implied, including, but not limited to the warranties of\n% merchantability, fitness for a particular purpose and non-infringement.\n% \n% This software is intended for research only. Do not use for clinical\n% purpose. Please note that this toolbox is under active development.\n% Considerable changes may occur in future releases. For support please\n% refer to:\n% https://github.com/translationalneuromodeling/tapas/issues\n% \n\n\n%% process and check input\nobj = obj.optional_inputs(varargin{:});\nassert(obj.N > 0, 'TAPAS:HUGE:NoData', 'Cannot estimate without data.')\n\ntapas_huge_compile( );\n\n% save random number generator seed\nseed = rng();\n\n% check if filename for storing result is valid\nfilename = obj.options.nvp.saveto;\nif ~isempty(filename)\n [pathStr, fileStr, extStr] = fileparts(filename);\n if ~strcmpi(extStr,'.mat')\n filename = [filename '.mat'];\n [pathStr, fileStr, extStr] = fileparts(filename);\n end\n if isempty(fileStr)\n fileStr = ['huge' datestr(now,'-yyyymmdd-HHMMSS')];\n end\n filename = fullfile(pathStr, [fileStr, extStr]);\n save(filename, obj);\nend\n\n% decide how to treat confounds\nswitch lower(obj.options.nvp.confoundsvariant)\n case 'default'\n obj.options.confVar = double(obj.M > 0);\n case 'none'\n obj.options.confVar = 0;\n case 'global'\n obj.options.confVar = 1;\n case 'cluster'\n obj.options.confVar = 2;\nend\nif obj.options.confVar && ~obj.M\n obj.options.confVar = 0;\n warning('TAPAS:HUGE:MissingConfounds',...\n ['HUGE is configured to use group-level confounds, but no values ' ...\n 'for confounds were supplied. Proceeding without confounds.']);\nend\n\nif obj.K > obj.N\n warning('TAPAS:HUGE:LargeK',...\n 'Number of clusters K exceeds number of subjects N.');\nend\n\n% check priors\nobj.prior = build_prior(obj);\n\n% starting values\nobj = prepare_starting_values(obj);\n\n\n%% model inversion\nobj.aux = struct();\nfprintf('Inverting HUGE with %u cluster', obj.K);\nif obj.K > 1\n fprintf('s');\nend\nfprintf(' using %s.\\n', obj.options.nvp.method);\n\nswitch obj.options.nvp.method\n case 'VB'\n obj = obj.vb_invert( );\n case 'MH'\n obj = obj.mh_invert( );\nend\n\n%% post processing\nobj.aux = [];\nobj.options.start = rmfield(obj.options.start, {'subjects', 'clusters'});\n\n% if working with simulated data, calculate balanced purity\nobj.posterior.bPurity = [];\nif ~isempty(obj.model)\n model = obj.model;\n [~, labels] = max(model.d, [], 2);\n obj.posterior.bPurity = tapas_huge_bpurity(labels, obj.posterior.q_nk);\nend\n% save additional information\nobj.posterior.method = obj.options.nvp.method;\nobj.posterior.version = obj.version;\nobj.posterior.seed = seed;\n\n% save result\nif ~isempty(filename)\n save(filename, obj);\n fprintf('Saved result to \"%s\".\\n', filename);\nend\n\nend\n\n\nfunction [ prior ] = build_prior( obj )\n\nprior = struct();\n\n% alpha_0\nprior.alpha_0 = obj.options.prior.alpha_0;\nif isscalar(prior.alpha_0)\n prior.alpha_0 = repmat(prior.alpha_0, obj.K, 1);\nend\nassert(size(prior.alpha_0, 1) == obj.K && size(prior.alpha_0, 2) == 1 && ...\n all(prior.alpha_0 > 0), 'TAPAS:HUGE:Prior', ...\n 'Prior alpha0 must be positive column vector of length %u.', obj.K);\n\n% S_0\nprior.S_0 = obj.options.nvp.priorclustervariance;\nif isscalar(prior.S_0)\n prior.S_0 = eye(obj.idx.P_c)*prior.S_0;\nend\nassert(size(prior.S_0, 1) == obj.idx.P_c, 'TAPAS:HUGE:Prior',...\n 'PriorClusterVariance must be of size %ux%u.', obj.idx.P_c, obj.idx.P_c);\n\n% m_0\nprior.m_0 = obj.options.nvp.priorclustermean;\nif isscalar(prior.m_0)\n prior.m_0 = repmat(prior.m_0, 1, obj.idx.P_c);\nend\nassert(numel(prior.m_0) == obj.idx.P_c, 'TAPAS:HUGE:Prior', ...\n 'PriorClusterMean must be row vector of length %u.', obj.idx.P_c);\nprior.m_0 = prior.m_0(:)';\n\n% nu_0\nprior.nu_0 = obj.options.nvp.priordegree;\nassert(all(prior.nu_0(:) > 0), 'TAPAS:HUGE:Prior', ...\n 'PriorDegree must be positive scalar.');\n\n% tau_0\nprior.tau_0 = obj.options.nvp.priorvarianceratio;\nassert(all(prior.tau_0(:) > 0), 'TAPAS:HUGE:Prior', ...\n 'PriorCovarianceRatio must be positive scalar.');\n\n\n% mu_h\nprior.mu_h = obj.options.prior.mu_h;\nif isscalar(prior.mu_h)\n prior.mu_h = repmat(prior.mu_h, 1, obj.idx.P_h);\nend\nassert(size(prior.mu_h, 2) == obj.idx.P_h && ...\n size(prior.mu_h, 1) == 1, 'TAPAS:HUGE:Prior', ...\n 'Prior homogenous mean must be row vector of length %u.', obj.idx.P_h);\n\n% Sigma_h\nprior.Sigma_h = obj.options.prior.Sigma_h;\nif isscalar(prior.Sigma_h)\n prior.Sigma_h = eye(obj.idx.P_h)*prior.Sigma_h;\nelseif isvector(prior.Sigma_h)\n assert(length(prior.Sigma_h)>=4, 'TAPAS:HUGE:Prior', ...\n 'Prior homogenous covariance must be a vector of length 4.')\n A = double(obj.dcm.a - diag(diag(obj.dcm.a)))*prior.Sigma_h(2) + ...\n eye(obj.R)*prior.Sigma_h(1);\n tmp = double([obj.dcm.b(:);obj.dcm.c(:);obj.dcm.d(:)])*prior.Sigma_h(3);\n tmp = [A(:); tmp; ones(2*obj.R+1,1)*prior.Sigma_h(4)];\n prior.Sigma_h = diag(tmp(obj.idx.homogenous));\nend\ntry \n assert(size(prior.Sigma_h, 1) == obj.idx.P_h && ...\n issymmetric(prior.Sigma_h), '', '');\n chol(prior.Sigma_h);\ncatch\n error('TAPAS:HUGE:Prior', ['Prior hemodynamic covariance must ' ...\n 'be symmetric, positive definite matrix of size %u.'], obj.idx.P_h);\nend\n\n% mean and variance of lambda\nprior.mu_lambda = obj.options.prior.mu_lambda;\nassert(prior.mu_lambda > 0, 'TAPAS:HUGE:Prior', ...\n 'Prior mean of noise precision must be positive scalar.'); \nprior.s2_lambda = obj.options.prior.s2_lambda;\nassert(prior.s2_lambda > 0, 'TAPAS:HUGE:Prior', ...\n 'Prior variance of noise precision must be positive scalar.'); \n\n% m_beta_0\nprior.m_beta_0 = obj.options.prior.m_beta_0;\nif isscalar(prior.m_beta_0)\n prior.m_beta_0 = repmat(prior.m_beta_0, obj.M, 1);\nend\nassert(size(prior.m_beta_0, 1) == obj.M && ...\n size(prior.m_beta_0, 2) == 1, 'TAPAS:HUGE:Prior', ...\n 'Prior confound mean must be column vector of length %u.', obj.M);\n\n% S_beta_0\nprior.S_beta_0 = obj.options.prior.S_beta_0;\nif isscalar(prior.S_beta_0)\n prior.S_beta_0 = eye(obj.M)*prior.S_beta_0;\nend\ntry \n assert(size(prior.S_beta_0, 1) == obj.M && ...\n issymmetric(prior.S_beta_0), '', '');\n chol(prior.S_beta_0);\ncatch\n error('TAPAS:HUGE:Prior', ['Prior confound covariance must ' ...\n 'be symmetric, positive definite matrix of size %u.'], obj.M);\nend\n\nend\n\n\nfunction [ obj ] = prepare_starting_values( obj )\n% subject-level\n% initialize starting values to prior mean\nstVal1 = repmat([obj.prior.m_0, obj.prior.mu_h], obj.N, 1);\n\nif ~isempty(obj.options.nvp.startingvaluedcm) && ...\n isnumeric(obj.options.nvp.startingvaluedcm) % custom starting values\n stVal1 = obj.options.nvp.startingvaluedcm; \n [stN, stP] = size(stVal1);\n assert(stN == obj.N && stP == obj.idx.P_c + obj.idx.P_h,...\n 'TAPAS:HUGE:StartingValues',...\n 'Size of subject-level starting values does not agree with model.')\nelseif strcmpi(obj.options.nvp.startingvaluedcm, 'spm') % use SPM estimates\n for n = 1:obj.N\n try\n tmp = [obj.data(n).spm.A(:); obj.data(n).spm.B(:); ...\n obj.data(n).spm.C(:); obj.data(n).spm.D(:); ...\n obj.data(n).spm.transit(:); obj.data(n).spm.decay(:);...\n obj.data(n).spm.epsilon(:)];\n stVal1(n,:) = full(tmp([obj.idx.clustering; obj.idx.homogenous]));\n catch\n fprintf('Missing or invalid SPM estimate for subject %u.' , n);\n fprintf(' Using prior as starting value instead.\\n');\n end\n end\nend\n\n% randomize starting values\nif obj.options.nvp.randomize && ~(strcmpi(obj.options.nvp.method, 'MH') && ...\n ~obj.options.mh.nSteps.dcm) %%% TODO remove exception and introduce new method for clustering only\n stVal1 = stVal1 + randn(size(stVal1)).*obj.options.start.dcm;\nend\n\nobj.options.start.subjects = stVal1;\n\n% cluster-level\nif ~isempty(obj.options.nvp.startingvaluegmm) && ...\n isnumeric(obj.options.nvp.startingvaluegmm) % custom starting values\n stVal2 = obj.options.nvp.startingvaluegmm; \n [stN, stP] = size(stVal2);\n assert(stN == obj.K && stP == obj.idx.P_c,...\n 'TAPAS:HUGE:StartingValues',...\n 'Size of cluster-level starting values does not agree with model.')\nelse\n stVal2 = repmat(obj.prior.m_0, obj.K, 1);\nend\n\n% randomize starting values\nif obj.options.nvp.randomize && ~(strcmpi(obj.options.nvp.method, 'MH') && ...\n ~obj.options.mh.nSteps.clusters)\n stVal2 = stVal2 + randn(size(stVal2)).*obj.options.start.gmm;\nend\n\nobj.options.start.clusters = stVal2;\n\nend\n\n\n\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/huge/@tapas_Huge/estimate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1723190647021133}} {"text": "function output = callecos(yalmipmodel)\noriginalModel = yalmipmodel;\n% Fix ECOS options\noptions = yalmipmodel.options;\noptions.ecos.verbose = options.verbose~=0;\nif ~isempty(yalmipmodel.binary_variables)\n options.ecos.bool_vars_idx = yalmipmodel.binary_variables;\nend\nif ~isempty(yalmipmodel.integer_variables)\n options.ecos.int_vars_idx = yalmipmodel.integer_variables;\nend\nmodel.opts = options.ecos;\n\nif ~isempty(yalmipmodel.ub)\n [yalmipmodel.F_struc,yalmipmodel.K] = addStructureBounds(yalmipmodel.F_struc,yalmipmodel.K,yalmipmodel.ub,yalmipmodel.lb);\nend\n\n% Write nonlinear functions using exponential cone operators, if possible\n[yalmipmodel,output] = normalizeExponentialCone(yalmipmodel);\nif output.problem\n return\nend\n\n% Map to ECOS syntax\ncones = [];\ncones.f = yalmipmodel.K.f;\ncones.l = yalmipmodel.K.l;\ncones.q = yalmipmodel.K.q;\ncones.s = yalmipmodel.K.s;\ncones.ep = yalmipmodel.K.e;\nmodel.c = full(yalmipmodel.c);\nmodel.A = -yalmipmodel.F_struc(1:cones.f,2:end);if isempty(model.A);model.A = [];end\nmodel.b = full(yalmipmodel.F_struc(1:cones.f,1));if isempty(model.b);model.b = [];end\nmodel.G = -yalmipmodel.F_struc(1+cones.f:end,2:end);if isempty(model.G);model.G = [];end\nmodel.h = full(yalmipmodel.F_struc(1+cones.f:end,1));if isempty(model.h);model.h = [];end\nif nnz(cones.l) > 0\n model.dims.l = cones.l;\nend\nif nnz(cones.q) > 0\n model.dims.q = cones.q;\nend\nif nnz(cones.ep) > 0\n model.dims.e = cones.ep;\n tempG = model.G(1:model.dims.l+sum(cones.q),:);\n temph = model.h(1:model.dims.l+sum(cones.q));\n top = 1+model.dims.l+sum(cones.q);\n for i = 1:model.dims.e\n tempG = [tempG;model.G(top + [0;2;1],:)];\n temph = [temph;model.h(top + [0;2;1],:)];\n top = top + 3;\n end\n model.G = tempG;\n model.h = temph;\nend\n\nif options.savedebug\n save ecosdebug model\nend\n\n\nif options.showprogress;showprogress(['Calling ' yalmipmodel.solver.tag],options.showprogress);end\nif isempty(model.A) \n solvertime = tic;\n [x,y,info,s,z] = ecos(model.c,model.G,model.h,model.dims,model.opts); \n solvertime = toc(solvertime);\nelse \n solvertime = tic;\n [x,y,info,s,z] = ecos(model.c,model.G,model.h,model.dims,model.A,model.b,model.opts);\n solvertime = toc(solvertime);\nend\n\n% Internal format, only keep original variablesop\nif ~isempty(x)\n Primal = x(1:length(originalModel.c));\nelse\n Primal = nan(length(originalModel.c),1);\nend\nif ~isempty(yalmipmodel.evalMap)\n % No support for duals when exponential cones yet\n Dual = [];\nelse\n Dual = [y;z];\nend\n\nswitch info.exitflag\n case 0\n problem = 0;\n case 1\n problem = 1;\n case 2\n problem = 2;\n case -1\n problem = 3;\n case {-2,-3}\n problem = 4;\n case -7\n problem = 9;\n case {10,11}\n problem = 4;\n otherwise\n problem = 9;\nend\n\n% Save ALL data sent to solver\nif options.savesolverinput\n solverinput.model = model;\nelse\n solverinput = [];\nend\n\n% Save ALL data from the solution?\nif options.savesolveroutput\n solveroutput.x = x;\n solveroutput.y = y;\n solveroutput.info = info;\n solveroutput.s = s;\n solveroutput.z = z;\nelse\n solveroutput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(Primal,Dual,[],problem,yalmipmodel.solver.tag,solverinput,solveroutput,solvertime);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callecos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.2658804847339313, "lm_q1q2_score": 0.17223690058313834}} {"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": "function fgOut=dtiGetFibersConnectingGM(fg, dt, minDist, showFig)\n%Select fibers with both endpoints located near grey matter.\n%\n% fg=dtiFibersConnectingGM(fg, dt, [minDist=1.74])\n%\n% Returns a fibers structure which is a subset of fibers from the original\n% fiber group, keeping only the fibers whose both endpoints terminate near\n% grey matter or the most inferior axial plane (the latter to trap\n% cortico-spinal fibers). Relies on spm to perform tissue segmentation of b0.\n% Grey matter mask is rather generous: anything with probability(gm)>0. \n%\n% Input parameters:\n% minDist - maximum distance from a fiber endpoint to Gm mask.\n% showFig - 'true', will show Gm mask; 'false', will save the mask.\n%\n% HISTORY:\n% 07/31/2009 ER wrote it\n\nif ~exist('showFig', 'var') || isempty(showFig)\nshowFig=false; \nend\n\nif ~exist('minDist','var') || isempty(minDist)\n minDist=1.74;\nend\n\n[wm, gm, csf] = mrAnatSpmSegment(dt.b0, dt.xformToAcpc, 'mniepi'); gm=gm>=127;\n\n% Only fibers whose both endpoints are within the gray matter (roi prepared) will be considered.\n[x1,y1,z1] = ind2sub(size(gm), find(gm));\n\n%fill up the most inferior nonzero slice & below with \"gray matter\" voxels -- to make\n%sure corticospinal fibers will not be eliminated when retaining only\n%\"gray matter connecting\" voxels.\ngm_withcst=gm; \ngm_withcst(:, :, min(z1))=1;\n\n\n[x1_withcst,y1_withcst,z1_withcst] = ind2sub(size(gm_withcst), find(gm_withcst));\nroi4cst= dtiNewRoi('mrAnatSpmSegment_gm');\nroi4cst.coords = mrAnatXformCoords(dt.xformToAcpc, [x1_withcst,y1_withcst,z1_withcst]);\n\n\n[fgOut] = dtiIntersectFibersWithRoi([], {'and', 'both_endpoints'}, minDist, roi4cst, fg);\n\nif showFig\n showMontage(gm_withcst); \nelse\n imwrite(makeMontage(gm_withcst), fullfile(fileparts(dt.dataFile), 'bin', 'gmMask.png')); \nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/fiber/dtiGetFibersConnectingGM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1715082494779129}} {"text": "function [net, stats] = cnn_train_modified(net, imdb, getBatch, varargin)\n%CNN_TRAIN An example implementation of SGD for training CNNs\n% CNN_TRAIN() is an example learner implementing stochastic\n% gradient descent with momentum to train a CNN. It can be used\n% with different datasets and tasks by providing a suitable\n% getBatch function.\n%\n% The function automatically restarts after each training epoch by\n% checkpointing.\n%\n% The function supports training on CPU or on one or more GPUs\n% (specify the list of GPU IDs in the `gpus` option).\n\n% Copyright (C) 2014-16 Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nopts.expDir = fullfile('data','exp') ;\nopts.continue = true ;\nopts.batchSize = 256 ;\nopts.numSubBatches = 1 ;\nopts.train = [] ;\nopts.val = [] ;\nopts.gpus = [] ;\nopts.prefetch = false ;\nopts.numEpochs = 300 ;\nopts.learningRate = 0.001 ;\nopts.weightDecay = 0.0005;\nopts.momentum = 0.9 ;\nopts.saveMomentum = true ;\nopts.nesterovUpdate = false ;\nopts.randomSeed = 0 ;\nopts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;\nopts.profile = false ;\nopts.parameterServer.method = 'mmap' ;\nopts.parameterServer.prefix = 'mcn' ;\n\nopts.conserveMemory = true ;\nopts.backPropDepth = +Inf ; %+Inf \nopts.sync = false ;\nopts.cudnn = true ;\nopts.errorFunction = 'softmax_regression' ;\nopts.errorLabels = {} ;\nopts.plotDiagnostics = false ;\nopts.plotStatistics = true;\nopts = vl_argparse(opts, varargin) ;\n\nif ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end\nif isempty(opts.train), opts.train = find(imdb.images.set==1) ; end\nif isempty(opts.val), opts.val = find(imdb.images.set==2) ; end\nif isnan(opts.train), opts.train = [] ; end\nif isnan(opts.val), opts.val = [] ; end\n\n% -------------------------------------------------------------------------\n% Initialization\n% -------------------------------------------------------------------------\n\nnet = vl_simplenn_tidy(net); % fill in some eventually missing values\nnet.layers{end-1}.precious = 1; % do not remove predictions, used for error\nvl_simplenn_display(net, 'batchSize', opts.batchSize) ;\n\nevaluateMode = isempty(opts.train) ;\nif ~evaluateMode\n for i=1:numel(net.layers)\n J = numel(net.layers{i}.weights) ;\n if ~isfield(net.layers{i}, 'learningRate')\n net.layers{i}.learningRate = ones(1, J) ;\n end\n if ~isfield(net.layers{i}, 'weightDecay')\n net.layers{i}.weightDecay = ones(1, J) ;\n end\n end\nend\n\n% setup error calculation function\nhasError = true ;\nif isstr(opts.errorFunction)\n switch opts.errorFunction\n case 'none'\n opts.errorFunction = @error_none ;\n hasError = false ;\n case 'multiclass'\n opts.errorFunction = @error_multiclass ;\n if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end\n case 'binary'\n opts.errorFunction = @error_binary ;\n if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end\n case 'softmax_regression'\n opts.errorFunction = @error_crossentropy_or_l2norm ;\n if isempty(opts.errorLabels), opts.errorLabels = {'crossentropy_or_l2norm'} ; end\n otherwise\n error('Unknown error function ''%s''.', opts.errorFunction) ;\n end\nend\n\nstate.getBatch = getBatch ;\nstats = [] ;\n\n% -------------------------------------------------------------------------\n% Train and validate\n% -------------------------------------------------------------------------\n\nmodelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));\nmodelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;\n\nstart = opts.continue * findLastCheckpoint(opts.expDir) ;\nif start >= 1\n fprintf('%s: resuming by loading epoch %d\\n', mfilename, start) ;\n [net, state, stats] = loadState(modelPath(start)) ;\nelse\n state = [] ;\nend\n\nfor epoch=start+1:opts.numEpochs\n\n % Set the random seed based on the epoch and opts.randomSeed.\n % This is important for reproducibility, including when training\n % is restarted from a checkpoint.\n\n rng(epoch + opts.randomSeed) ;\n% prepareGPUs(opts, epoch == start+1) ;\n\n % Train for one epoch.\n params = opts ;\n params.epoch = epoch ;\n params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;\n params.train = opts.train(randperm(numel(opts.train))) ; % shuffle\n params.val = opts.val(randperm(numel(opts.val))) ;\n params.imdb = imdb ;\n params.getBatch = getBatch ;\n\n if numel(params.gpus) <= 1\n [net, state] = processEpoch(net, state, params, 'train') ;\n [net, state] = processEpoch(net, state, params, 'val') ;\n \n if size(imdb.images.labels,1) > 1\n [net.meta.svm_model1,net.meta.svm_err1] = training_SVR(net,params);\n end\n \n if ~evaluateMode\n saveState(modelPath(epoch), net, state) ;\n end\n lastStats = state.stats ;\n else\n spmd\n [net, state] = processEpoch(net, state, params, 'train') ;\n [net, state] = processEpoch(net, state, params, 'val') ;\n if labindex == 1 && ~evaluateMode\n saveState(modelPath(epoch), net, state) ;\n end\n lastStats = state.stats ;\n end\n lastStats = accumulateStats(lastStats) ;\n end\n \n \n \n stats.train(epoch) = lastStats.train ;\n stats.val(epoch) = lastStats.val ;\n clear lastStats ;\n saveStats(modelPath(epoch), stats) ;\n\n% if params.plotStatistics\n% switchFigure(1) ; clf ;\n% plots = setdiff(...\n% cat(2,...\n% fieldnames(stats.train)', ...\n% fieldnames(stats.val)'), {'num', 'time'}) ;\n% for p = plots\n% p = char(p) ;\n% values = zeros(0, epoch) ;\n% leg = {} ;\n% for f = {'train', 'val'}\n% f = char(f) ;\n% if isfield(stats.(f), p)\n% tmp = [stats.(f).(p)] ;\n% values(end+1,:) = tmp(1,:)' ;\n% leg{end+1} = f ;\n% end\n% end\n% subplot(1,numel(plots),find(strcmp(p,plots))) ;\n% plot(1:epoch, values','o-') ;\n% xlabel('epoch') ;\n% title(p) ;\n% legend(leg{:}) ;\n% grid on ;\n% end\n% drawnow ;\n% print(1, modelFigPath, '-dpdf') ;\n% end\nend\n\n% With multiple GPUs, return one copy\nif isa(net, 'Composite'), net = net{1} ; end\n\n% -------------------------------------------------------------------------\nfunction err = error_multiclass(params, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\n[~,predictions] = sort(predictions, 3, 'descend') ;\n\n% be resilient to badly formatted labels\nif numel(labels) == size(predictions, 4)\n labels = reshape(labels,1,1,1,[]) ;\nend\n\n% skip null labels\nmass = single(labels(:,:,1,:) > 0) ;\nif size(labels,3) == 2\n % if there is a second channel in labels, used it as weights\n mass = mass .* labels(:,:,2,:) ;\n labels(:,:,2,:) = [] ;\nend\n\nm = min(5, size(predictions,3)) ;\n\nerror = ~bsxfun(@eq, predictions, labels) ;\nerr(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;\nerr(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_crossentropy_or_l2norm(opts, labels, res)\n% -------------------------------------------------------------------------\npredictions = gather(res(end-1).x) ;\nif size(predictions,3) > 1\n error = sum( - labels(:) .* log(predictions(:)+eps(1)));\nelse\n error = sum((predictions(:) - labels(:)).^2);\nend\nerr = error;\n\n% -------------------------------------------------------------------------\nfunction err = error_binary(params, labels, res)\n% -------------------------------------------------------------------------\n% predictions = gather(res(end-1).x) ;\npredictions = squeeze(gather(res(end-1).x))' ;\nerror = bsxfun(@times, predictions, labels) < 0 ;\nerr = sum(error(:)) ;\n\n% -------------------------------------------------------------------------\nfunction err = error_none(params, labels, res)\n% -------------------------------------------------------------------------\nerr = zeros(0,1) ;\n\n% -------------------------------------------------------------------------\nfunction [net, state] = processEpoch(net, state, params, mode)\n% -------------------------------------------------------------------------\n% Note that net is not strictly needed as an output argument as net\n% is a handle class. However, this fixes some aliasing issue in the\n% spmd caller.\n\n% initialize with momentum 0\nif isempty(state) || isempty(state.momentum)\n for i = 1:numel(net.layers)\n for j = 1:numel(net.layers{i}.weights)\n state.momentum{i}{j} = 0 ;\n end\n end\nend\n\n% move CNN to GPU as needed\nnumGpus = numel(params.gpus) ;\nif numGpus >= 1\n net = vl_simplenn_move(net, 'gpu') ;\n for i = 1:numel(state.momentum)\n for j = 1:numel(state.momentum{i})\n state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;\n end\n end\nend\nif numGpus > 1\n parserv = ParameterServer(params.parameterServer) ;\n vl_simplenn_start_parserv(net, parserv) ;\nelse\n parserv = [] ;\nend\n\n% profile\nif params.profile\n if numGpus <= 1\n profile clear ;\n profile on ;\n else\n mpiprofile reset ;\n mpiprofile on ;\n end\nend\n\nsubset = params.(mode) ;\nnum = 0 ;\nstats.num = 0 ; % return something even if subset = []\nstats.time = 0 ;\nadjustTime = 0 ;\nres = [] ;\nerror = 0 ;\n\nstart = tic ;\nfor t=1:params.batchSize:numel(subset)\n fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...\n fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;\n batchSize = min(params.batchSize, numel(subset) - t + 1) ;\n\n for s=1:params.numSubBatches\n % get this image batch and prefetch the next\n batchStart = t + (labindex-1) + (s-1) * numlabs ;\n batchEnd = min(t+params.batchSize-1, numel(subset)) ;\n batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n num = num + numel(batch) ;\n if numel(batch) == 0, continue ; end\n\n [im, labels] = params.getBatch(params.imdb, batch) ;\n \n if params.prefetch\n if s == params.numSubBatches\n batchStart = t + (labindex-1) + params.batchSize ;\n batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;\n else\n batchStart = batchStart + numlabs ;\n end\n nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;\n params.getBatch(params.imdb, nextBatch) ;\n end\n\n if numGpus >= 1\n im = gpuArray(im) ;\n \n end\n\n if strcmp(mode, 'train')\n dzdy = 1 ;\n evalMode = 'normal' ;\n else\n dzdy = [] ;\n evalMode = 'test' ;\n end\n net.layers{end}.class = labels ;\n res = vl_simplenn_modified(net, im, dzdy, res, ...\n 'accumulate', s ~= 1, ...\n 'mode', evalMode, ...\n 'conserveMemory', params.conserveMemory, ...\n 'backPropDepth', params.backPropDepth, ...\n 'sync', params.sync, ...\n 'cudnn', params.cudnn, ...\n 'parameterServer', parserv, ...\n 'holdOn', s < params.numSubBatches) ;\n\n % accumulate errors\n error = error + sum(double(gather(res(end).x))) ;\n end\n\n % accumulate gradient\n if strcmp(mode, 'train')\n if ~isempty(parserv), parserv.sync() ; end\n [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;\n end\n\n % get statistics\n time = toc(start) + adjustTime ;\n batchTime = time - stats.time ;\n% stats = extractStats(net, params, error / num) ;\n stats.objective = error / num;\n stats.num = num ;\n stats.time = time ;\n currentSpeed = batchSize / batchTime ;\n averageSpeed = (t + batchSize - 1) / time ;\n if t == 3*params.batchSize + 1\n % compensate for the first three iterations, which are outliers\n adjustTime = 4*batchTime - time ;\n stats.time = time + adjustTime ;\n end\n\n fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;\n for f = setdiff(fieldnames(stats)', {'num', 'time'})\n f = char(f) ;\n fprintf(' %s: %.6f', f, stats.(f)) ;\n end\n fprintf('\\n') ;\n\n % collect diagnostic statistics\n if strcmp(mode, 'train') && params.plotDiagnostics\n switchFigure(2) ; clf ;\n diagn = [res.stats] ;\n diagnvar = horzcat(diagn.variation) ;\n diagnpow = horzcat(diagn.power) ;\n subplot(2,2,1) ; barh(diagnvar) ;\n set(gca,'TickLabelInterpreter', 'none', ...\n 'YTick', 1:numel(diagnvar), ...\n 'YTickLabel',horzcat(diagn.label), ...\n 'YDir', 'reverse', ...\n 'XScale', 'log', ...\n 'XLim', [1e-5 1], ...\n 'XTick', 10.^(-5:1)) ;\n grid on ;\n subplot(2,2,2) ; barh(sqrt(diagnpow)) ;\n set(gca,'TickLabelInterpreter', 'none', ...\n 'YTick', 1:numel(diagnpow), ...\n 'YTickLabel',{diagn.powerLabel}, ...\n 'YDir', 'reverse', ...\n 'XScale', 'log', ...\n 'XLim', [1e-5 1e5], ...\n 'XTick', 10.^(-5:5)) ;\n grid on ;\n subplot(2,2,3); plot(squeeze(res(end-1).x)) ;\n drawnow ;\n end\nend\n\n% Save back to state.\nstate.stats.(mode) = stats ;\nif params.profile\n if numGpus <= 1\n state.prof.(mode) = profile('info') ;\n profile off ;\n else\n state.prof.(mode) = mpiprofile('info');\n mpiprofile off ;\n end\nend\nif ~params.saveMomentum\n state.momentum = [] ;\nelse\n for i = 1:numel(state.momentum)\n for j = 1:numel(state.momentum{i})\n state.momentum{i}{j} = gather(state.momentum{i}{j}) ;\n end\n end\nend\n\nnet = vl_simplenn_move(net, 'cpu') ;\n\n% -------------------------------------------------------------------------\nfunction [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)\n% -------------------------------------------------------------------------\nnumGpus = numel(params.gpus) ;\notherGpus = setdiff(1:numGpus, labindex) ;\n\nfor l=numel(net.layers):-1:1\n for j=numel(res(l).dzdw):-1:1\n\n if ~isempty(parserv)\n tag = sprintf('l%d_%d',l,j) ;\n parDer = parserv.pull(tag) ;\n else\n parDer = res(l).dzdw{j} ;\n end\n\n if j == 3 && strcmp(net.layers{l}.type, 'bnorm')\n % special case for learning bnorm moments\n thisLR = net.layers{l}.learningRate(j) ;\n net.layers{l}.weights{j} = vl_taccum(...\n 1 - thisLR, ...\n net.layers{l}.weights{j}, ...\n thisLR / batchSize, ...\n parDer) ;\n else\n % Standard gradient training.\n thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;\n thisLR = params.learningRate * net.layers{l}.learningRate(j) ;\n\n if thisLR>0 || thisDecay>0\n % Normalize gradient and incorporate weight decay.\n parDer = vl_taccum(1/batchSize, parDer, ...\n thisDecay, net.layers{l}.weights{j}) ;\n\n % Update momentum.\n state.momentum{l}{j} = vl_taccum(...\n params.momentum, state.momentum{l}{j}, ...\n -1, parDer) ;\n\n % Nesterov update (aka one step ahead).\n if params.nesterovUpdate\n delta = vl_taccum(...\n params.momentum, state.momentum{l}{j}, ...\n -1, parDer) ;\n else\n delta = state.momentum{l}{j} ;\n end\n\n % Update parameters.\n net.layers{l}.weights{j} = vl_taccum(...\n 1, net.layers{l}.weights{j}, ...\n thisLR, delta) ;\n end\n end\n\n % if requested, collect some useful stats for debugging\n if params.plotDiagnostics\n variation = [] ;\n label = '' ;\n switch net.layers{l}.type\n case {'conv','convt'}\n variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;\n power = mean(res(l+1).x(:).^2) ;\n if j == 1 % fiters\n base = mean(net.layers{l}.weights{j}(:).^2) ;\n label = 'filters' ;\n else % biases\n base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;\n label = 'biases' ;\n end\n variation = variation / base ;\n label = sprintf('%s_%s', net.layers{l}.name, label) ;\n end\n res(l).stats.variation(j) = variation ;\n res(l).stats.power = power ;\n res(l).stats.powerLabel = net.layers{l}.name ;\n res(l).stats.label{j} = label ;\n end\n end\nend\n\n% -------------------------------------------------------------------------\nfunction stats = accumulateStats(stats_)\n% -------------------------------------------------------------------------\n\nfor s = {'train', 'val'}\n s = char(s) ;\n total = 0 ;\n\n % initialize stats stucture with same fields and same order as\n % stats_{1}\n stats__ = stats_{1} ;\n names = fieldnames(stats__.(s))' ;\n values = zeros(1, numel(names)) ;\n fields = cat(1, names, num2cell(values)) ;\n stats.(s) = struct(fields{:}) ;\n\n for g = 1:numel(stats_)\n stats__ = stats_{g} ;\n num__ = stats__.(s).num ;\n total = total + num__ ;\n\n for f = setdiff(fieldnames(stats__.(s))', 'num')\n f = char(f) ;\n stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;\n\n if g == numel(stats_)\n stats.(s).(f) = stats.(s).(f) / total ;\n end\n end\n end\n stats.(s).num = total ;\nend\n\n% -------------------------------------------------------------------------\nfunction stats = extractStats(net, params, errors)\n% -------------------------------------------------------------------------\nstats.objective = errors(1) ;\nfor i = 1:numel(params.errorLabels)\n stats.(params.errorLabels{i}) = errors(i+1) ;\nend\n\n% -------------------------------------------------------------------------\nfunction saveState(fileName, net, state)\n% -------------------------------------------------------------------------\n% save(fileName, 'net', 'state') ;\nsave(fileName, 'net') ;\n\n% -------------------------------------------------------------------------\nfunction saveStats(fileName, stats)\n% -------------------------------------------------------------------------\nif exist(fileName)\n save(fileName, 'stats', '-append') ;\nelse\n save(fileName, 'stats') ;\nend\n\n% -------------------------------------------------------------------------\nfunction [net, state, stats] = loadState(fileName)\n% -------------------------------------------------------------------------\nload(fileName, 'net', 'state', 'stats') ;\nnet = vl_simplenn_tidy(net) ;\nif isempty(whos('stats'))\n error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...\n fileName) ;\nend\n\n% -------------------------------------------------------------------------\nfunction epoch = findLastCheckpoint(modelDir)\n% -------------------------------------------------------------------------\nlist = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;\ntokens = regexp({list.name}, 'net-epoch-([\\d]+).mat', 'tokens') ;\nepoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;\nepoch = max([epoch 0]) ;\n\n% -------------------------------------------------------------------------\nfunction switchFigure(n)\n% -------------------------------------------------------------------------\nif get(0,'CurrentFigure') ~= n\n try\n set(0,'CurrentFigure',n) ;\n catch\n figure(n) ;\n end\nend\n\n% -------------------------------------------------------------------------\nfunction clearMex()\n% -------------------------------------------------------------------------\n%clear vl_tmove vl_imreadjpeg ;\ndisp('Clearing mex files') ;\nclear mex ;\nclear vl_tmove vl_imreadjpeg ;\n\n% -------------------------------------------------------------------------\nfunction prepareGPUs(params, cold)\n% -------------------------------------------------------------------------\nnumGpus = numel(params.gpus) ;\nif numGpus > 1\n % check parallel pool integrity as it could have timed out\n pool = gcp('nocreate') ;\n if ~isempty(pool) && pool.NumWorkers ~= numGpus\n delete(pool) ;\n end\n pool = gcp('nocreate') ;\n if isempty(pool)\n parpool('local', numGpus) ;\n cold = true ;\n end\nend\nif numGpus >= 1 && cold\n fprintf('%s: resetting GPU\\n', mfilename) ;\n clearMex() ;\n if numGpus == 1\n disp(gpuDevice(params.gpus)) ;\n else\n spmd\n clearMex() ;\n disp(gpuDevice(params.gpus(labindex))) ;\n end\n end\nend\n\nfunction [svm_model,svm_err] = training_SVR(net,params)\n\nnet = vl_simplenn_move(net, 'gpu') ;\nnet.layers = net.layers(1:end-1);\nbatch = 256;\nsampling = (length(params.imdb.images.score) / 10000);\nscores_train = params.imdb.images.score(1:sampling:end);\ndata = params.imdb.images.data(:,:,:,1:sampling:end);\nnum_batch = floor(length(scores_train) / batch);\nfor i = 1:num_batch\n images = gpuArray(data(:,:,:,(i-1)*batch+1:i*batch));\n res = vl_simplenn(net, images, [],[],'Mode','test','ConserveMemory',true);\n feats(:,(i-1)*batch+1:i*batch) = squeeze(gather(res(end).x));\nend\nimages = gpuArray(data(:,:,:,num_batch*batch+1:length(scores_train)));\nres = vl_simplenn(net, images, [],[],'Mode','test','ConserveMemory',true);\nfeats(:,num_batch*batch+1:length(scores_train)) = squeeze(gather(res(end).x));\n\nsvm_model = svmtrain(scores_train', double(feats'), '-s 4 -t 0');\n[scores_pred, ~,~] = svmpredict(scores_train', double(feats'), svm_model,'-q');\nsvm_err = (sum(abs(scores_pred - scores_train'))) / length(scores_train);\n\n\n", "meta": {"author": "HuiZeng", "repo": "BIQA_Toolbox", "sha": "39d606574f0cbfde82ecbc3c208b353d9fa9a450", "save_path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox", "path": "github-repos/MATLAB/HuiZeng-BIQA_Toolbox/BIQA_Toolbox-39d606574f0cbfde82ecbc3c208b353d9fa9a450/tools/src/cnn_train_modified.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.17121498122630413}} {"text": "function DVH_out = dvh_Rectum_shift_1cm(planC,structNum,doseNum)\n%function DVH_out = dvh_Rectum_shift_1cm(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\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\n%Histogram for the expectation of dose over all trials\n[doseBinsV, volsHistV] = doseHist(meanDoseV, volsV, binWidth);\n\nDVH_out = [doseBinsV(:)'; volsHistV(:)'];\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/dvh_Rectum_shift_1cm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33458944125318607, "lm_q1q2_score": 0.17121497284794418}} {"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": "function output = callpensdpm(interfacedata);\n\n% Retrieve needed data\noptions = interfacedata.options;\nF_struc = interfacedata.F_struc;\nc = interfacedata.c;\nK = interfacedata.K;\nx0 = interfacedata.x0;\nub = interfacedata.ub;\nlb = interfacedata.lb;\n\n% Bounded variables converted to constraints\nif ~isempty(ub)\n [F_struc,K] = addStructureBounds(F_struc,K,ub,lb);\nend\n\nif K.f>0\n F_struc = [-F_struc(1:K.f,:);F_struc];\n F_struc(1:K.f,1) = F_struc(1:K.f,1)+sqrt(eps);\n K.l = K.l + 2*K.f;\n K.f = 0;\nend\n\n% *******************************\n% CONVERT FROM INTERNAL FORMAT\n% *******************************\npen = sedumi2pen(F_struc,K,c,x0);\n\n% **************************\n% COPY OPTIONS\n% **************************\nops = struct2cell(options.pensdp);ops = [ops{1:end}];\npen.ioptions = ops(1:8);\npen.foptions = ops(9:end);\npen.ioptions(4) = max(0,min(3,options.verbose+1));\nif pen.ioptions(4)==1\n pen.ioptions(4)=0;\nend\n\nif ~isempty(x0) \n x0(isnan(x0)) = 0;\n pen.x0 = x0(:)'; \nend\n\n%**************************\n% CALL PENSDP\n%**************************\nif options.savedebug\n save pensdpmdebug pen\nend\nif options.showprogress;showprogress('Calling PENSDP',options.showprogress);end\nsolvertime = tic;\n[f,x,u,iflag,niter,feas] = pensdpm(pen);\nsolvertime = toc(solvertime);\n\n% Get dual variable (this must be possible to do easier...)\nif options.saveduals | options.dimacs\n u = u(:);\n D_struc = u(1:1:K.l);\n if length(K.s)>0\n if any(K.s)\n pos = K.l+1;\n for i = 1:length(K.s)\n temp = zeros(K.s(i),K.s(i));\n vecZ = u(pos:pos+0.5*K.s(i)*(K.s(i)+1)-1);\n top = 1;\n for j = 1:K.s(i)\n len = K.s(i)-j+1;\n temp(j:end,j)=vecZ(top:top+len-1);top=top+len;\n end\n temp = (temp+temp');j = find(speye(K.s(i)));temp(j)=temp(j)/2;\n D_struc = [D_struc;temp(:)];\n pos = pos + (K.s(i)+1)*K.s(i)/2;\n end\n end\n end\nelse\n D_struc = [];\nend\n\nswitch iflag \ncase 0\n problem = 0;\ncase 1\n problem = 4;\ncase 2\n problem = 1;\ncase 3\n problem = 4;\ncase 4\n problem = 3;\ncase 5\n problem = 7;\ncase 6\n problem = 11;\ncase 7\n problem = 9;\notherwise\n problem = -1;\nend \n\nif options.savesolveroutput\n solveroutput.f = f;\n solveroutput.x = x;\n solveroutput.u = u;\n solveroutput.iflag = iflag;\n solveroutput.niter = niter;\n solveroutput.feas = feas;\nelse\n solveroutput = [];\nend\nif options.savesolverinput\n solverinput.pen = pen;\nelse\n solverinput = [];\nend\n\n% Standard interface \noutput = createOutputStructure(x(:),D_struc,[],problem,interfacedata.solver.tag,solverinput,solveroutput,solvertime);\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callpensdpm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.17107061582836194}} {"text": "function cnn_resnet_finetune(varargin)\n\nif ~isempty(gcp('nocreate')),\n delete(gcp)\nend\naddpath('resnet');\nopts = cnn_setup_environment();\nopts.train.gpus = [1] ;\n% opts.train.gpus = [ 1 : 3 ]\nopts.dataSet = 'Remat'; \n% opts.dataSet = 'hmdb51'; \nopts.aug = 'stretch'; \nopts.border = 0; \nopts.pad = 0; \nopts.train.memoryMapFile = fullfile(tempdir, 'ramdisk', ['matconvnet' num2str(feature('getpid')) '.bin']) ;\naddpath('network_surgery');\nopts.dataDir = fullfile(opts.dataPath, opts.dataSet) ;\nopts.splitDir = [opts.dataSet '_splits']; \nopts.nSplit = 1 ;\nopts.dropOutRatio = 0.5 ;\nopts.train.cheapResize = 0 ; \nopts.inputdim = [ 224, 224, 3] ;\n\nopts.train.batchSize = 196 ;\nopts.train.numSubBatches = ceil(8 / max(numel(opts.train.gpus),1));\n\nopts.train.epochFactor = 10 ;\nopts.train.augmentation = 'borders25';\n\nopts.train.backpropDepth = cell(1, 2);\nopts.train.backpropDepth(:) = {'pool5'};\nopts.train.learningRate = [1e-2*ones(1, 2) 1e-2*ones(1, 3) 1e-3*ones(1, 3) 1e-4*ones(1, 3)] ;\nif strcmp(opts.dataSet, 'hmdb51')\n opts.train.learningRate = [1e-2*ones(1, 2) 1e-2*ones(1, 1) 1e-3*ones(1, 1) 1e-4*ones(1, 1)] ;\nend\n\nmodel = ['img-res50-' opts.train.augmentation '-bs=' num2str(opts.train.batchSize) ...\n '-split' num2str(opts.nSplit) '-dr' num2str(opts.dropOutRatio)];\n\nif strfind(model, 'vgg16');\n baseModel = 'imagenet-vgg-verydeep-16.mat' ;\n opts.train.learningRate = [1e-3*ones(1, 3) 5e-4*ones(1, 5) 5e-5*ones(1,2) 5e-6*ones(1,2)] ;\n opts.train.backpropDepth = cell(1, 3);\n opts.train.backpropDepth(:) = {'layer37'};\n opts.train.batchSize = 128 ;\n opts.train.numSubBatches = ceil(16 / max(numel(opts.train.gpus),1));\nelseif strfind(model, 'vgg-m');\n baseModel = 'imagenet-vgg-m-2048.mat' ;\nelseif strfind(model, 'res152');\n baseModel = 'imagenet-resnet-152-dag.mat' ;\nelseif strfind(model, 'res101');\n baseModel = 'imagenet-resnet-101-dag.mat' ;\nelseif strfind(model, 'res50');\n baseModel = 'imagenet-resnet-50-dag.mat' ;\n opts.train.numSubBatches = ceil(32 / max(numel(opts.train.gpus),1));\nelse\n error('Unknown model %s', model) ; \nend\nopts.model = fullfile(opts.modelPath,baseModel) ;\nopts.expDir = fullfile(opts.dataDir, [opts.dataSet '-' model]) ;\nopts.imdbPath = fullfile(opts.dataDir, [opts.dataSet '_resnet_split' num2str(opts.nSplit) 'imdb.mat']);\n\nopts.train.plotDiagnostics = 0 ;\nopts.train.continue = 1 ;\nopts.train.prefetch = 1 ;\nopts.train.expDir = opts.expDir ;\nopts.train.numAugments = 1;\nopts.train.frameSample = 'random';\nopts.train.nFramesPerVid = 1;\nopts.train.uniformAugments = false;\n\n[opts, varargin] = vl_argparse(opts, varargin) ;\n\n\n% -------------------------------------------------------------------------\n% Database initialization\n% -------------------------------------------------------------------------\nif exist(opts.imdbPath)\n imdb = load(opts.imdbPath) ;\nelse\n imdb = cnn_Remat_resnet_setup_data('dataPath', opts.dataPath, 'flowDir',opts.flowDir, ...\n 'dataSet', opts.dataSet, 'nSplit', opts.nSplit) ;\n save(opts.imdbPath, '-struct', 'imdb', '-v6') ;\nend\nnClasses = length(imdb.classes.name);\nif ~exist(opts.model)\n fprintf('Downloading base model file: %s ...\\n', baseModel);\n mkdir(fileparts(opts.model)) ;\n urlwrite(...\n ['http://www.vlfeat.org/matconvnet/models/' baseModel], ...\n opts.model) ;\nend\n\nnet = load(opts.model);\nif isfield(net, 'net'), net=net.net;end\n\nif isstruct(net.layers)\n % replace 1000-way imagenet classifiers\n for p = 1 : numel(net.params)\n sz = size(net.params(p).value);\n if any(sz == 1000)\n sz(sz == 1000) = nClasses;\n fprintf('replace classifier layer of %s\\n', net.params(p).name);\n if numel(sz) > 2\n net.params(p).value = 0.01 * randn(sz, class(net.params(p).value));\n else\n net.params(p).value = zeros(sz, class(net.params(p).value));\n end\n end\n end\n\n net.meta.normalization.border = [256 256] - net.meta.normalization.imageSize(1:2);\n net = dagnn.DagNN.loadobj(net);\n if strfind(model, 'bnorm')\n net = insert_bnorm_layers(net) ;\n end\nelse\n% net=vl_simplenn_tidy(net);\n if isfield(net, 'meta'),\n netNorm = net.meta.normalization;\n else\n netNorm = net.normalization;\n end\n if(netNorm.imageSize(3) == 3) && ~isempty(strfind(opts.model, 'imagenet'))\n netNorm.border = [240 240] - netNorm.imageSize(1:2);\n net = replace_last_layer(net, [1 2], [1 2], nClasses, opts.dropOutRatio);\n end\n if strfind(model, 'bnorm')\n net = insert_bnorm_layers(net) ;\n end\n\n net = dagnn.DagNN.fromSimpleNN(net) ;\n\nend\n\nnet = dagnn.DagNN.setLrWd(net);\n\nnet.renameVar(net.vars(1).name, 'input');\n\nif ~isnan(opts.dropOutRatio)\n dr_layers = find(arrayfun(@(x) isa(x.block,'dagnn.DropOut'), net.layers)) ;\n if ~isempty(dr_layers)\n if opts.dropOutRatio > 0\n for i=dr_layers, net.layers(i).block.rate = opts.dropOutRatio; end\n else\n net.removeLayer({net.layers(dr_layers).name});\n end\n else\n if opts.dropOutRatio > 0\n pool5_layer = find(arrayfun(@(x) isa(x.block,'dagnn.Pooling'), net.layers)) ;\n conv_layers = pool5_layer(end);\n for i=conv_layers\n block = dagnn.DropOut() ; block.rate = opts.dropOutRatio ;\n newName = ['drop_' net.layers(i).name];\n\n net.addLayer(newName, ...\n block, ...\n net.layers(i).outputs, ...\n {newName}) ;\n\n for l = 1:numel(net.layers)-1\n for f = net.layers(i).outputs\n sel = find(strcmp(f, net.layers(l).inputs )) ;\n if ~isempty(sel)\n [net.layers(l).inputs{sel}] = deal(newName) ;\n end\n end\n end\n end\n end\n end\nend \nnet.layers(~cellfun('isempty', strfind({net.layers(:).name}, 'err'))) = [] ;\n\nopts.train.derOutputs = {} ;\nfor l=numel(net.layers):-1:1\n if isa(net.layers(l).block, 'dagnn.Loss') && isempty(strfind(net.layers(l).name, 'err'))\n opts.train.derOutputs = {opts.train.derOutputs{:}, net.layers(l).outputs{:}, 1} ;\n end\n if isa(net.layers(l).block, 'dagnn.SoftMax') \n net.removeLayer(net.layers(l).name)\n l = l - 1;\n end\nend\n\nif isempty(opts.train.derOutputs)\n net = dagnn.DagNN.insertLossLayers(net, 'numClasses', nClasses) ;\n fprintf('setting derivative for layer %s \\n', net.layers(end).name);\n opts.train.derOutputs = {opts.train.derOutputs{:}, net.layers(end).outputs{:}, 1} ;\nend\n\nlossLayers = find(arrayfun(@(x) isa(x.block,'dagnn.Loss') && strcmp(x.block.loss,'softmaxlog'),net.layers));\n\n\nnet.addLayer('top1error', ...\n dagnn.Loss('loss', 'classerror'), ...\n net.layers(lossLayers(end)).inputs, ...\n 'top1error') ;\n\nnet.addLayer('top5error', ...\n dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...\n net.layers(lossLayers(end)).inputs, ...\n 'top5error') ;\n \nnet.print() ; \nnet.rebuild() ;\n\nnet.meta.normalization.rgbVariance = [];\nnet.meta.normalization.averageImage = mean(mean(net.meta.normalization.averageImage, 1), 2);\nopts.train.train = find(ismember(imdb.images.set, [1])) ;\nopts.train.train = repmat(opts.train.train,1,opts.train.epochFactor);\n% opts.train.valmode = '250samples';\n\nopts.train.valmode = '30samples'\n\nopts.train.denseEval = 1;\nnet.conserveMemory = 1 ;\n fn = getBatchFn(opts, net.meta);\n%fn = getBatchWrapper_ucf101_rgbflow(net.meta.normalization, opts.numFetchThreads, opts.train) ;\n[info] = cnn_resnet_train_dag(net, imdb, fn, opts.train) ;\n\nend\n\n\n\n% -------------------------------------------------------------------------\nfunction fn = getBatchFn(opts, meta)\n% -------------------------------------------------------------------------\nbopts.numThreads = opts.numFetchThreads ;\nbopts.pad = opts.pad ;\nbopts.border = opts.border ;\nbopts.transformation = opts.aug ;\nbopts.imageSize = meta.normalization.imageSize ;\nbopts.averageImage = meta.normalization.averageImage ;\nbopts.rgbVariance = meta.normalization.rgbVariance ;\n% bopts.transformation = meta.augmentation.transformation ;\n\nfn = @(x,y) getSimpleNNBatch(bopts,x,y) ;\nend\n\n% -------------------------------------------------------------------------\nfunction [im,labels] = getSimpleNNBatch(opts, imdb, batch)\n% -------------------------------------------------------------------------\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nisVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ;\n\nif ~isVal\n % training\n im = cnn_resnet_get_batch(images, opts, ...\n 'prefetch', nargout == 0) ;\nelse\n % validation: disable data augmentation\n% opts.border=0;\n im = cnn_resnet_get_batch(images, opts, ...\n 'prefetch', nargout == 0, ...\n 'transformation', 'none') ;\nend\n\nif nargout > 0\n labels = imdb.images.class(batch) ;\nend\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/DAIN-master/cnn_resnet_finetune.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17107061231407403}} {"text": "% im2imstat computes image statistics from several images\n% and finds the projections of laser points\n%\n% The computation core is taken from im2points.m\n% computes average image and image of standard deviations\n% requires configdata.m\n% The name of the experiment has to be specified\n% it determines the location of files etc ...\n%\n% the scripts serves as a template for a multiprocessing\n% it assumes a vector of camera IDs CamIds to be known\n% indexes in the CamIds are supposed to be correct\n%\n% It is used by im2pmultiproc.pl\n\n% $Author: svoboda $\n% $Revision: 2.0 $\n% $Id: im2imstat.m,v 2.0 2003/06/19 12:06:51 svoboda Exp $\n% $State: Exp $\n\n% Read configuration from whatever is specified on command-line (via --config=FILENAME)\nconfig = read_configuration();\n\nSTEP4STAT = 5; % step for computing average and std images, if 1 then all images taken\n\nim.dir = config.paths.img;\nim.ext = config.files.imgext;\n\n% NoCams = size(config.files.idxcams,2);\t% number of cameras\n% Use concrete CameraIds instead of all cameras\nNoCams = size(CamsIds,2);\nCamsIds\n\n% load image names\nfor i=1:NoCams,\n seq(i).camId = CamsIds(i);\n if seq(i).camId > -1\n\tseq(i).data = dir([sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]);\n\t[sprintf(im.dir,seq(i).camId),sprintf(config.files.imnames,seq(i).camId),im.ext]\n else\n\tseq(i).data = dir([im.dir,sprintf(config.files.imnames),im.ext]);\n end\n seq(i).size = size(seq(i).data,1);\n if seq(i).size<4\n\terror('Not enough images found. Wrong image path or name pattern?');\n end\nend\n\n% Expected number of 3D points is equal to the number of frames.\n% In fact, some frames might be without any calibration point\n\n% Because of non-consistent stopping of capturing, the sequences might\n% have different number of images, select the minimal value as the right one\nNoPoints = min([seq.size]);\n\n% compute the average images that will be used for finding LEDs\n% if not already computed\n\npointsIdx = [1:STEP4STAT:NoPoints];\n\nt = cputime;\nfor i=1:NoCams,\n if ~exist(sprintf(config.files.avIM,seq(i).camId)),\n\tdisp(sprintf('The average image of the camera %d is being computed',seq(i).camId));\n\tavIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tfor j=pointsIdx,\n\t IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t avIM = avIM + double(IM);\n\tend\n\tavIM = uint8(round(avIM./size(pointsIdx,2)));\n\timwrite(avIM,sprintf(config.files.avIM,seq(i).camId));\n else\tdisp('Average files already exist');\n end\nend\ndisp(sprintf('Elapsed time for average images: %d [sec]',cputime-t))\n% compute the standard deviations images that will be used for finding LEDs\n% if not already computed\nt = cputime;\nfor i=1:NoCams,\n if ~exist(sprintf(config.files.stdIM,seq(i).camId)),\n\tavIM = double(imread(sprintf(config.files.avIM,seq(i).camId)));\n\tdisp(sprintf('The image of standard deviations of the camera %d is being computed',seq(i).camId));\n\tstdIM = zeros(size(imread([sprintf(im.dir,seq(i).camId),seq(i).data(1).name])));\n\tfor j=pointsIdx,\n\t IM = imread([sprintf(im.dir,seq(i).camId),seq(i).data(j).name]);\n\t stdIM = stdIM + (double(IM)-avIM).^2;\n\tend\n\tstdIM = uint8(round(sqrt(stdIM./(size(pointsIdx,2)-1))));\n\timwrite(stdIM,sprintf(config.files.stdIM,seq(i).camId));\n else\n\tdisp('Image of standard deviations already exist')\n end\nend\ndisp(sprintf('Elapsed time for computation of images [sec]: %d',cputime-t))\n\n% find points in the images\nWs = [];\nIdWs = [];\nRes\t = [];\n\nIdMat = ones(NoCams,NoPoints);\n% IdMat is very important for Martinec&Pajdla filling [ECCV2002]\n% it is a NoCams x NoPoints matrix,\n% IdMat(i,j) = 0 -> no j-th point in i-th\n% IdMat(i,j) = 1 -> point successfully detected\n\nfor i=1:NoCams,\n Points = [];\n avIM = imread(sprintf(config.files.avIM,seq(i).camId));\n stdIM\t= imread(sprintf(config.files.stdIM,seq(i).camId));\n for j=1:NoPoints,\n\t[pos,err] = getpoint([sprintf(im.dir,seq(i).camId),seq(i).data(j).name], 0, config.imgs, avIM, stdIM);\n\tif err\n\t IdMat(i,j) = 0;\n\t Points = [Points, [NaN; NaN; NaN]];\n\telse\n\t Points = [Points, [pos; 1]];\n\tend\n end\n Ws = [Ws; Points];\n Res= [Res; size(avIM,2), size(avIM,1)];\nend\n\nidx = '.';\nfor i=CamsIds,\n idx = sprintf('%s%02d',idx,i);\nend\n\nsave([config.files.points,idx], 'Ws','-ASCII')\n% save(config.files.IdPoints,'IdWs','-ASCII')\nsave([config.files.Res,idx], 'Res', '-ASCII')\nsave([config.files.IdMat,idx], 'IdMat', '-ASCII')\n\n% write auxiliary file that is done\ndone=1;\nsave(donefile,'done','-ascii');\n\n% exit the Matlab\n% this script is to be used in the batch mode\n% hence exit at the end is necessary\nexit;\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/FindingPoints/im2imstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.17107060879978614}} {"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 [P] = spm_dcm_fit(P,use_parfor)\n% Bayesian inversion of DCMs using Variational Laplace\n% FORMAT [DCM] = spm_dcm_fit(P)\n%\n% P - {N x M} DCM structure array (or filenames) from N subjects\n% use_parfor - if true, will attempt to run in parallel (default: false)\n% NB: all DCMs are loaded into memory\n%\n% DCM - Inverted (1st level) DCM structures with posterior densities\n%__________________________________________________________________________\n%\n% This routine is just a wrapper that calls the appropriate dcm inversion\n% routine for a set a pre-specifed DCMs.\n%\n% If called with a cell array, each column is assumed to contain 1st level\n% DCMs inverted under the same model. Each row contains a different data\n% set (or subject).\n%__________________________________________________________________________\n% Copyright (C) 2015 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_dcm_fit.m 7755 2019-12-16 13:19:28Z spm $\n\nif nargin < 2, use_parfor = false; end\n\n% get filenames and set up\n%--------------------------------------------------------------------------\nif ~nargin\n [P, sts] = spm_select([1 Inf],'^DCM.*\\.mat$','Select DCM*.mat files');\n if ~sts, return; end\nend\nif ischar(P), P = cellstr(P); end\nif isstruct(P), P = {P}; end\n\n% Number of subjects (data) and models (of those data)\n%--------------------------------------------------------------------------\n[Ns,Nm] = size(P);\n\n% Find model class and modality\n%--------------------------------------------------------------------------\ntry, load(P{1}); catch, DCM = P{1}; end\n\nmodel = spm_dcm_identify(DCM);\n\nif isempty(model) \n warning('unknown inversion scheme');\n return \nend\n\n% Get data structure for each subject (column)\n%--------------------------------------------------------------------------\nfor i = 1:Ns\n for j = 2:Nm\n switch model \n case{'DEM'}\n P{i, j}.xY = P{i, 1}.Y;\n otherwise\n P{i, j}.xY = P{i, 1}.xY;\n end\n end\nend\n\n% Estimate\n%--------------------------------------------------------------------------\nif use_parfor\n % Estimate DCMs in parallel using parfor\n P = spm_dcm_load(P);\n \n parfor i = 1:numel(P)\n P{i} = fit_dcm(P{i}, model);\n end\nelse\n % Estimate DCMs without parfor\n for i = 1:numel(P)\n try\n DCM = load(P{i});\n DCM = DCM.DCM;\n catch\n DCM = P{i}; \n end\n P{i} = fit_dcm(DCM, model);\n end\nend\n \n% -------------------------------------------------------------------------\nfunction DCM = fit_dcm(DCM, model)\n% Inverts a DCM. \n% DCM - the DCM structure\n% model - a string identifying the model type (see spm_dcm_identify)\n \nswitch model\n\n % fMRI model\n %----------------------------------------------------------------------\n case{'fMRI'}\n DCM = spm_dcm_estimate(DCM);\n\n % conventional neural-mass and mean-field models\n %----------------------------------------------------------------------\n case{'fMRI_CSD'}\n DCM = spm_dcm_fmri_csd(DCM);\n\n % conventional neural-mass and mean-field models\n %----------------------------------------------------------------------\n case{'ERP'}\n DCM = spm_dcm_erp(DCM);\n\n % cross-spectral density model (complex)\n %----------------------------------------------------------------------\n case{'CSD'}\n DCM = spm_dcm_csd(DCM);\n\n % cross-spectral density model (steady-state responses)\n %----------------------------------------------------------------------\n case{'TFM'}\n DCM = spm_dcm_tfm(DCM);\n\n % induced responses\n %----------------------------------------------------------------------\n case{'IND'}\n DCM = spm_dcm_ind(DCM);\n\n % phase coupling\n %----------------------------------------------------------------------\n case{'PHA'}\n DCM = spm_dcm_phase(DCM);\n\n % cross-spectral density model (steady-state responses)\n %----------------------------------------------------------------------\n case{'NFM'}\n DCM = spm_dcm_nfm(DCM);\n\n % behavioural Markov decision process model\n %----------------------------------------------------------------------\n case{'MDP'}\n DCM = spm_dcm_mdp(DCM);\n\n % generic nonlinear system identification\n %----------------------------------------------------------------------\n case{'NLSI'}\n [Ep,Cp,Eh,F] = spm_nlsi_GN(DCM.M,DCM.xU,DCM.xY);\n DCM.Ep = Ep;\n DCM.Eh = Eh;\n DCM.Cp = Cp;\n DCM.F = F;\n\n % hierarchical dynamic mmodel\n %----------------------------------------------------------------------\n case{'DEM'}\n DCM = spm_DEM(DCM);\n\n % default\n %----------------------------------------------------------------------\n otherwise\n try\n DCM = feval(model, DCM);\n catch\n error('unknown DCM');\n end\nend ", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dcm_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1709746833472227}} {"text": "function [D,L] = spm_opm_create(S)\n% Read or simulate magnetometer data and optionally set up forward model\n% FORMAT D = spm_opm_create(S)\n% S - input structure\n% Optional fields of S:\n% SENSOR LEVEL INFO\n% S.data - filepath to .bin file - Default: Simulates data \n% S.channels - channels.tsv file - Default: REQUIRED \n% S.fs - Sampling frequency (Hz) - Default: REQUIRED if S.meg is empty\n% S.meg - meg.json file - Default: REQUIRED if S.fs is empty\n% S.precision - 'single' or 'double' - Default: 'single'\n% SIMULATION\n% S.wholehead - whole head coverage flag - Deafult: 0\n% S.space - space between sensors(mm) - Default: 25\n% S.offset - scalp to sensor distance(mm) - Default: 6.5\n% S.nSamples - number of samples - Default: 1000\n% S.Dens - number of density checks - Default: 40\n\n% SOURCE LEVEL INFO\n% S.coordsystem - coordsystem.json file - Default: \n% S.positions - positions.tsv file - Default:\n% S.sMRI - Filepath to MRI file - Default: uses template\n% S.cortex - Custom cortical mesh - Default: Use inverse normalised cortical mesh\n% S.scalp - Custom scalp mesh - Default: Use inverse normalised scalp mesh\n% S.oskull - Custom outer skull mesh - Default: Use inverse normalised outer skull mesh\n% S.iskull - Custom inner skull mesh - Default: Use inverse normalised inner skull mesh\n% S.voltype - Volume conducter Model type - Default: 'Single Shell'\n% S.meshres - mesh resolution(1,2,3) - Default: 1\n% S.lead - flag to compute lead field - Default: 0\n% Output:\n% D - MEEG object (also written to disk)\n% L - Lead field (also written on disk)\n%__________________________________________________________________________\n% Copyright (C) 2018 Wellcome Trust Centre for Neuroimaging\n\n% Tim Tierney\n% $Id: spm_opm_create.m 7645 2019-07-25 13:58:25Z tim $\nspm('FnBanner', mfilename);\n\n%-Set default values\n%--------------------------------------------------------------------------\nif ~isfield(S, 'voltype'), S.voltype = 'Single Shell'; end\nif ~isfield(S, 'meshres'), S.meshres = 1; end\nif ~isfield(S, 'scalp'), S.scalp = []; end\nif ~isfield(S, 'cortex'), S.cortex = []; end\nif ~isfield(S, 'iskull'), S.iskull = []; end\nif ~isfield(S, 'oskull'), S.oskull = []; end\nif ~isfield(S, 'lead'), S.lead = 0; end\nif ~isfield(S, 'fs'), S.fs = 1000; end\nif ~isfield(S, 'nSamples'), S.nSamples = 1000; end\nif ~isfield(S, 'nDens'), S.nDens = 40; end\nif ~isfield(S, 'space'), S.space = 30; end\nif ~isfield(S, 'offset'), S.offset = 6.5; end\nif ~isfield(S, 'data'), S.data = zeros(1,S.nSamples); end\nif ~isfield(S, 'wholehead'), S.wholehead = 1; end\nif ~isfield(S, 'fname'), S.fname = 'sim_opm'; end\nif ~isfield(S, 'precision'), S.precision = 'single'; end\n \n\n%- Read Binary File\n%----------------------------------------------------------------------\ntry % to read data \n [direc, dataFile] = fileparts(S.data);\n dat = fopen(S.data);\n S.data = fread(dat,Inf,S.precision,0,'b');\n fclose(dat);\n binData=1;\ncatch % if not readable check if it is numeric \n if ~isa(S.data,'numeric') % if not numeric throw error\n error('A valid dataest or file was not supplied')\n end\n binData=0;\n direc = pwd();\n dataFile=S.fname;\nend\n%- identify potential BIDS Files\n%----------------------------------------------------------------------\nbase = strsplit(dataFile,'meg');\nchanFile= fullfile(direc,[base{1},'channels.tsv']);\nmegFile= fullfile(direc,[base{1},'meg.json']);\nposFile= spm_select('FPList',direc,[base{1},'positions.tsv']);\ncoordFile= fullfile(direc,[base{1},'coordsystem.json']);\n\n%- Check for channel Info\n%--------------------------------------------------------------------------\ntry % to load a channels file\n channels = spm_load(S.channels);\ncatch \n try % to load a BIDS channel file \n channels = spm_load(chanFile);\n catch\n try % use channel struct if supplied\n channels = S.channels;\n catch % create channel struct \n args=[];\n args.base='Chan';\n args.n= size(S.data,1);\n labs= spm_create_labels(args);\n channels = [];\n channels.name=labs;\n channels.type=repmat({'MEG'},size(S.data,1),1);\n channels.units= repmat({'fT'},size(S.data,1),1);\n end\n end \nend\n\n%- reformat data according to channel info\n%--------------------------------------------------------------------------\nnc = size(channels.name,1);\n\nif binData\n S.data = reshape(S.data,nc,numel(S.data)/nc);\nelseif nc~=size(S.data,1)\n error('numer of channels in S.data different to S.channels')\nelse\n S.data =S.data;\nend\n\n%- Check for MEG Info\n%--------------------------------------------------------------------------\ntry % to load a meg file\n meg = spm_load(S.meg);\ncatch \n try % to load a BIDS meg file \n meg = spm_load(megFile);\n catch\n try % to use meg struct \n meg = S.meg;\n catch \n try % to use S.fs argument to get sampling frequency\n meg =[];\n meg.SamplingFrequency=S.fs;\n catch\n ('A valid meg.json file is required if S.fs is empty');\n end\n end\n end \nend\n\n%- Position File check \n%----------------------------------------------------------------------\ntry % to load a channels file\n posOri = spm_load(S.positions);\n positions =1;\ncatch \n try % to load a BIDS channel file \n posOri = spm_load(posFile);\n positions =1;\n catch\n positions =0;\n end \nend\n\n%- Forward model Check\n%----------------------------------------------------------------------\nsubjectSource = (positions|isfield(S,'space')) & isfield(S,'sMRI');\nsubjectSensor = ~subjectSource;\n\nif subjectSource\n forward =1;\n template =0;\nelseif subjectSensor\n forward =0;\n template =0;\nelse\n forward =1;\n template =1;\nend\n \n\n%- Create SPM object of simulated or real data\n%--------------------------------------------------------------------------\nDtemp = meeg(size(S.data,1),size(S.data,2),size(S.data,3));\nDtemp = fsample(Dtemp,meg.SamplingFrequency);\nDtemp = fname(Dtemp,[dataFile,'.mat']);\nDtemp = path(Dtemp,direc);\nDtemp = chanlabels(Dtemp,1:size(Dtemp,1),channels.name);\nDtemp = units(Dtemp,1:size(Dtemp,1),channels.units);\nDtemp = chantype(Dtemp,1:size(Dtemp,1),channels.type);\n\n%- Overwrite and Save\n%--------------------------------------------------------------------------\nma = fullfile(direc,[dataFile,'.mat']);\nda = fullfile(direc,[dataFile,'.dat']);\n\nae = exist(fname(Dtemp),'file')==2;\nif(ae)\n delete(ma);\n delete(da);\nend\nDtemp.save();\n% create data file and insert data\nD= blank(Dtemp,[dataFile,'.dat']);\ndim=size(D);\nD(1:dim(1),1:dim(2),1:dim(3)) = S.data;\nD.save();\n\n%- Create Meshes\n%--------------------------------------------------------------------------\nif forward\n %initially used inverse normalised meshes\n D = spm_eeg_inv_mesh_ui(D,1,S.sMRI,S.meshres);\n save(D);\n % then fill in custom meshes(if they exist)\n args = [];\n args.D = D;\n args.scalp = S.scalp;\n args.cortex = S.cortex;\n args.iskull = S.iskull;\n args.oskull = S.oskull;\n args.template = template;\n D = opm_customMeshes(args);\n save(D);\nend\n\n%- Create the Sensor Array\n%--------------------------------------------------------------------------\nif forward\n try % create positions and orientations\n pos = [posOri.Px,posOri.Py,posOri.Pz];\n ori = [posOri.Ox,posOri.Oy,posOri.Oz];\n cl = posOri.name;\n catch % if no postions and orientations provided then create them\n args = [];\n args.D =D;\n args.offset = S.offset;\n args.space = S.space;\n args.wholehead = S.wholehead;\n args.nDens = S.nDens;\n [pos,ori] = opm_createSensorArray(args);\n end\n \n nSensors=size(pos,1);\n if nSensors>size(S.data,1) % \n args=[];\n args.base='Chan';\n args.n= nSensors;\n labs= spm_create_labels(args);\n channels = [];\n channels.name=labs;\n channels.type=repmat({'MEG'},nSensors,1);\n channels.units= repmat({'fT'},nSensors,1);\n D = clone(D,fnamedat(D),[nSensors,S.nSamples,1],1);\n D = chanlabels(D,1:size(D,1),channels.name);\n D = units(D,1:size(D,1),channels.units);\n D = chantype(D,1:size(D,1),channels.type); \n cl=chanlabels(D)';\n end\nend\n \n\n\n%-Place Sensors in object\n%--------------------------------------------------------------------------\nif forward\n grad= [];\n grad.label = cl;\n grad.coilpos = pos;\n grad.coilori = ori;\n grad.tra = eye(numel(grad.label));\n grad.chanunit = repmat({'T'}, numel(grad.label), 1);\n grad.chantype= 'MEG';\n grad = ft_datatype_sens(grad, 'amplitude', 'T', 'distance', 'mm');\n D = sensors(D, 'MEG', grad);\n save(D);\nend\n\n\n%- fiducial settings\n%--------------------------------------------------------------------------\nif subjectSource\n miMat = zeros(3,3);\n fiMat = zeros(3,3);\n fid=[];\n try % to read the coordsystem.json\n coord = spm_load(S.coordsystem);\n fiMat(1,:) = coord.HeadCoilCoordinates.coil1;\n fiMat(2,:) = coord.HeadCoilCoordinates.coil2;\n fiMat(3,:) = coord.HeadCoilCoordinates.coil3;\n miMat(1,:) = coord.AnatomicalLandmarkCoordinates.coil1;\n miMat(2,:) = coord.AnatomicalLandmarkCoordinates.coil2;\n miMat(3,:) = coord.AnatomicalLandmarkCoordinates.coil3;\n fid.fid.label = fieldnames(coord.HeadCoilCoordinates);\n fid.fid.pnt =fiMat;\n fid.pos= []; % headshape field that is left blank (GRB)\n M = fid;\n M.fid.pnt=miMat;\n M.pnt = D.inv{1}.mesh.fid.pnt;\n catch\n try % to find the BIDS coordsystem.json\n coord = spm_load(coordFile);\n fiMat(1,:) = coord.HeadCoilCoordinates.coil1;\n fiMat(2,:) = coord.HeadCoilCoordinates.coil2;\n fiMat(3,:) = coord.HeadCoilCoordinates.coil3;\n miMat(1,:) = coord.AnatomicalLandmarkCoordinates.coil1;\n miMat(2,:) = coord.AnatomicalLandmarkCoordinates.coil2;\n miMat(3,:) = coord.AnatomicalLandmarkCoordinates.coil3;\n fid.fid.label = fieldnames(coord.HeadCoilCoordinates);\n fid.fid.pnt =fiMat;\n fid.pos= []; % headshape field that is left blank (GRB)\n M = fid;\n M.fid.pnt=miMat;\n M.pnt = D.inv{1}.mesh.fid.pnt;\n catch % DEFAULT: transform between fiducials and anatomy is identity\n fid.fid.label = {'nas', 'lpa', 'rpa'}';\n fid.fid.pnt = [0 0 0; -1 0 0; 1 0 0];\n fid.pos= [];\n M = fid;\n M.pnt = D.inv{1}.mesh.fid.pnt;\n end\n end\nend\n\nif(template) %make \n fid.fid.label = {'nas', 'lpa', 'rpa'}';\n fid.fid.pnt = D.inv{1}.mesh.fid.fid.pnt(1:3,:);\n fid.pos= []; % headshape field that is left blank (GRB)\n M = fid;\n M.pnt = D.inv{1}.mesh.fid.pnt;\nend\n\n%- Coregistration\n%--------------------------------------------------------------------------\nif(subjectSource)\n D = fiducials(D, fid);\n save(D);\n f=fiducials(D);\n f.pnt =zeros(0,3);\n D = spm_eeg_inv_datareg_ui(D,1,f,M,0);\nend\n%- 2D view based on mean orientation of sensors \n%--------------------------------------------------------------------------\nif(forward)\n n1=mean(grad.coilori); n1= n1./sqrt(dot(n1,n1));\n t1=cross(n1,[0 0 1]);\n t2=cross(t1,n1);\n pos2d =zeros(size(grad.coilpos,1),2);\n for i=1:size(grad.coilpos,1)\n pos2d(i,1)=dot(grad.coilpos(i,:),t1);\n pos2d(i,2)=dot(grad.coilpos(i,:),t2);\n end\n \n nMEG = length(indchantype(D,'MEG'));\n if nMEG~=size(pos2d,1)\n m1 = '2D positions could not be set as there are ';\n m2 =num2str(nMEG);\n m3 = ' channels but only ';\n m4 = num2str(size(pos2d,1));\n m5 = ' channels with position information.';\n message = [m1,m2,m3,m4,m5];\n warning(message);\n else\n args=[];\n args.D=D;\n args.xy= pos2d';\n args.label=grad.label;\n args.task='setcoor2d';\n D=spm_eeg_prep(args);\n D.save;\n end\nend\n%- Foward model specification\n%--------------------------------------------------------------------------\nif forward\n D.inv{1}.forward.voltype = S.voltype;\n D = spm_eeg_inv_forward(D);\n nverts = length(D.inv{1}.forward.mesh.vert);\n if(S.lead)\n [L,D] = spm_eeg_lgainmat(D,1:nverts);\n end\n spm_eeg_inv_checkforward(D,1,1);\nend\nsave(D);\nfprintf('%-40s: %30s\\n','Completed',spm('time')); \n\n\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Create Sensor Array % \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [pos,ori] = opm_createSensorArray(S)\n% Given a scalp surface even samples the surface with sensors \n% \n% FORMAT [pos,ori] = spm_opm_createSensorArray(S)\n% S - input structure\n% Fields of S:\n% S.D - SPM M/EEG object with surface meshes \n% S.offset - distance to place sensors(mm) from scalp surface\n% S.space - distance between sensors(mm) \n% S.wholehead - boolean: Should whole scalp surface should be covered?\n% S.nDens - number of density optimisations\n% _________________________________________________________________________\n\n% Args\n%--------------------------------------------------------------------------\nD = S.D;\nwholehead = S.wholehead;\n\n% Meshes\n%--------------------------------------------------------------------------\nscalp = gifti(D.inv{1}.mesh.tess_scalp);\ncortex = gifti(D.inv{1}.mesh.tess_ctx);\nlp = min(cortex.vertices(:,3));\n\n% create convex hull of mesh\n%--------------------------------------------------------------------------\n[~,V1] = convhull(double(scalp.vertices));\n\n% outward facing vertx normals of convex hull\n%--------------------------------------------------------------------------\n[Nv,~] = spm_mesh_normals(scalp,true);\nns = Nv;\nvs = scalp.vertices;\ncog1=mean(vs);\n\nfor i = 1:length(ns)\n ad = vs(i,:) + 5*ns(i,:);\n subtrac = vs(i,:) - 5*ns(i,:);\n \n d1 = sum((cog1 - ad).^2);\n d2 = sum((cog1 - subtrac).^2);\n \n if(d2>d1)\n ns(i,:) = -ns(i,:);\n else\n ns(i,:) =ns(i,:);\n end\nend\n\n% add an offset to the convex hull\n%--------------------------------------------------------------------------\noffVertices=vs+ns*S.offset;\n[~,V2] = convhull(double(offVertices));\n\n\n% Expand solution space by ratio of Volumes\n%--------------------------------------------------------------------------\nT= eye(4)*(V2/V1)^(1/3);\nT(4,4)=1;\nscalp = spm_mesh_transform(scalp,T);\n\n% Translate solution space so centre of gravities overlap\n%--------------------------------------------------------------------------\n\ncog2 = mean(scalp.vertices);\nT= eye(4);\nT(1:3,4)=cog1-cog2+0;\nscalp = spm_mesh_transform(scalp,T);\n\n% Create the sensor array \n%--------------------------------------------------------------------------\nargs= [];\nargs.space=S.space;\nargs.g=scalp;\nargs.nDens=S.nDens;\n[pos, ~, ~] = spm_mesh_pack_points(args);\n\n\n% get orientation of scalp\n%--------------------------------------------------------------------------\n[~,Nf] = spm_mesh_normals(scalp,true);\ncog=mean(scalp.vertices);\n\nv=scalp.vertices;\nf=scalp.faces;\nfaceP=zeros(size(f,1),3);\nfor i =1:length(faceP)\n whichVerts= f(i,:);\n verts= v(whichVerts,:);\n faceP(i,:)=mean(verts);\nend\n\n% make all normals point outwards\n%--------------------------------------------------------------------------\nfor i = 1:length(Nf)\n ad = faceP(i,:) + 5*Nf(i,:);\n subtrac = faceP(i,:) - 5*Nf(i,:);\n \n d1 = sum((cog - ad).^2);\n d2 = sum((cog - subtrac).^2);\n \n if(d2>d1)\n Nf(i,:) = -Nf(i,:);\n else\n Nf(i,:) =Nf(i,:);\n end\nend\n\n% assign orientatation to sensors of closest face normal\n%--------------------------------------------------------------------------\n ori=zeros(size(pos));\nfor i =1:length(ori)\n tmp=pos(i,:);\n di=sqrt(sum(bsxfun(@minus,faceP,tmp).^2,2));\n [~,indmin]=min(di);\n ori(i,:)=-Nf(indmin,:);\nend\n\n% Check if wholehead is requested\n%--------------------------------------------------------------------------\nif(~wholehead)\n C= pos(:,3)>(lp);\n pos= pos(C,:);\n ori = ori(C,:);\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Custom Meshes % \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function D = opm_customMeshes(S)\n% wrapper for adding custom meshes to MEG object\n% FORMAT D = spm_opm_customMeshes(S)\n% S - input structure\n% Fields of S:\n% S.D - Valid MEG object - Default: \n% S.cortex - Cortical mesh file - Default: Use inverse normalised cortical mesh\n% S.scalp - Scalp mesh file - Default: Use inverse normalised scalp mesh\n% S.oskull - Outer skull mesh file - Default: Use inverse normalised outer skull mesh\n% S.iskull - Inner skull mesh file - Default: Use inverse normalised inner skull mesh\n% S.template - is mesh in MNI space? - Default: 0\n% Output:\n% D - MEEG object \n%--------------------------------------------------------------------------\n\n%- Default values & argument check\n%--------------------------------------------------------------------------\nif ~isfield(S, 'D'), error('MEG object needs to be supplied'); end\nif ~isfield(S, 'cortex'), S.cortex = []; end\nif ~isfield(S, 'scalp'), S.scalp = []; end\nif ~isfield(S, 'oskull'), S.oskull = []; end\nif ~isfield(S, 'iskull'), S.iskull = []; end\nif ~isfield(S, 'template'), S.template = 0; end\n\nD = S.D;\nif ~isfield(D.inv{1}.mesh,'sMRI')\n error('MEG object needs to be contain inverse normalised meshes already') \nend\n\n%- add custom scalp and skull meshes if supplied\n%--------------------------------------------------------------------------\nif ~isempty(S.scalp)\n D.inv{1}.mesh.tess_scalp = S.scalp;\nend\n\nif ~isempty(S.oskull)\n D.inv{1}.mesh.tess_oskull = S.oskull;\nend\n\nif ~isempty(S.iskull)\n D.inv{1}.mesh.tess_iskull = S.iskull;\nend\n\n%- add custom cortex and replace MNI cortex with warped cortex\n%--------------------------------------------------------------------------\nif ~isempty(S.cortex)\n D.inv{1}.mesh.tess_ctx = S.cortex;\n if(S.template)\n D.inv{1}.mesh.tess_mni = S.cortex;\n else\n defs.comp{1}.inv.comp{1}.def = {D.inv{1}.mesh.def};\n defs.comp{1}.inv.space = {D.inv{1}.mesh.sMRI};\n defs.out{1}.surf.surface = {D.inv{1}.mesh.tess_ctx};\n defs.out{1}.surf.savedir.savesrc = 1;\n out = spm_deformations(defs);\n D.inv{1}.mesh.tess_mni = export(gifti(out.surf{1}), 'spm');\n end\nend\nsave(D);\n \n end\n ", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/MEEGtools/spm_opm_create.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17073193224172747}} {"text": "function [success,msg,fps] = ...\n ReadFPS_Ctrax(varargin)\n\nsuccess = false;\nmsg = ''; %#ok\n\n[fps,intrxfile,annfile] = myparse(varargin,...\n 'fps',1,'intrxfile','','annfile','');\n\n% try to read from the trx file first\nif isempty(intrxfile),\n msg = 'Input trxfile not yet set';\n return;\nend\n\ntry\n [trx,~,success1,timestamps] = load_tracks(intrxfile,'',...\n 'dosave',false,'annname',annfile,'verbose',false);\n if ~success1,\n msg = sprintf('Could not load tracks from trxfile %s',intrxfile);\n return;\n end\n readfps = false;\n if isfield(trx,'fps'),\n fps = [trx.fps];\n if nnz(~isnan(fps)) > 0,\n fps = nanmedian(fps);\n readfps = true;\n end\n end\n if ~readfps,\n if nnz(~isnan(timestamps)) == 0,\n msg = sprintf('No timestamps read in from trxfile %s',intrxfile);\n return;\n end\n fps = 1/nanmedian(diff(timestamps));\n end\ncatch ME,\n msg = sprintf('Could not load from trxfile %s: %s',intrxfile,getReport(ME));\n return;\nend\n\nsuccess = true;\nmsg = 'Read fps from trxfile';\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/perframe/ReadFPS_Ctrax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.17073192883832553}} {"text": "function Process_ConvertOptitrack2Pos(fbasename,varargin)\n\n% USAGE\n%\n% Process_ConvertOptitrack2Pos(fbasename,varargin)\n% \n% \n% \n% fbasename basename of the video file (should be filebasenmae.avi)\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'syncDatFile' name of binary file where sync signal is stored\n% (default = filebasename_digitalin.dat)\n% 'syncSampFq' sampling freqeuncy of the sync signal (default= 20kHz)\n% 'syncChan' sync channel to read (default = 1)\n% 'syncNbCh' number of channels in the sync file (default = 1)\n% 'posSampFq' sampling frequency of the final pos file (after\n% interpolation)\n% =========================================================================\n%\n% \n% This function assumes that a Motive (Optitrack) behavioral session \n% has been exported to a .CSV file with default settings.\n% (http://wiki.optitrack.com/index.php?title=Data_Export:_CSV)\n%\n% \n%\n\nif strcmp(fbasename,'')\n d = dir('*sessionInfo.mat');\n load(d.name);\n fbasename = sessionInfo.FileName;\nend\n\nwarning('this functions is now deprecated and has been replaced by processConvertOptitrack2Behav.m')\n\nsyncDatFile = ['digitalin.dat']; % defaults if args aren't given... assuming a single digitalin channel on Intan\nsyncSampFq = 20000;\nsyncChan = 1;\nsyncNbCh = 1;\nposSampFq = 120; %in Hz\n\n% Parse options\nfor i = 1:2:length(varargin)\n if ~isa(varargin{i},'char')\n error(['Parameter ' num2str(i+3) ' is not a property .']);\n end\n switch(lower(varargin{i}))\n case 'syncdatfile'\n syncDatFile = varargin{i+1};\n if ~isa(duration,'char')\n error('Incorrect value for property ''syncDatFile'' .');\n end\n case 'syncsampfq'\n syncSampFq = varargin{i+1};\n if ~isa(frequency,'numeric')\n error('Incorrect value for property ''syncsampfq'' .');\n end\n case 'syncchan'\n syncChan = varargin{i+1};\n if ~isa(start,'numeric')pw\n error('Incorrect value for property ''syncChan'' .');\n end\n if start < 0, start = 0; end\n case 'syncnbch'\n syncNbCh = varargin{i+1};\n if ~isa(syncNbCh,'numeric')\n error('Incorrect value for property ''syncNbCh'' .');\n end\n case 'possampfq'\n posSampFq = varargin{i+1};\n if ~isa(posSampFq,'numeric')\n error('Incorrect value for property ''posSampFq'' .');\n end\n otherwise\n error(['Unknown property ''' num2str(varargin{i}) ''' .']);\n end\nend\n\n\nif exist([fbasename '.csv'],'file') % assumes csv naming matches basename\n dat = importdata([fbasename '.csv']);\n dat = scrubTracking(dat); \nelseif ~isempty(dir('*.csv')) % looks for any csv file in the current recording folder\n csv = dir('*.csv');\n if length(csv) > 1\n dat=[];\n for i=1:length(csv)\n dat = [dat; importdata(csv(i).name)];\n end\n else\n dat = importdata(csv.name);\n end\n \n if isstruct(dat)\n d=[];\n for i=1:length(csv)\n d = [d;dat(i).data]; \n end\n clear dat; dat.data = d;\n end\n dat = scrubTracking(dat);\nelseif ~isempty(dir('Session*')) % Looks for a /Session*/ folder that Motive/Optitrack has created\n d = dir('Session*');\n cd(d.name)\n csv = dir('*.csv');\n if length(csv) > 1\n dat=[];\n for i=1:length(csv)\n dat = [dat; importdata(csv(i).name)];\n end\n else\n dat = importdata(csv.name);\n end\n if isstruct(dat)\n d=[];\n for i=1:length(csv)\n d = [d;dat(i).data]; \n end\n clear dat; dat.data = d;\n else\n d.data = dat;\n dat = d;\n end\n dat = scrubTracking(dat);\n cd ..\nend\n\npos = dat.data; \n\nfid = fopen(syncDatFile); \ndig = fread(fid,[syncNbCh inf],'int16=>int16'); % default type for Intan digitalin\ndig = dig(syncChan,:);\n\nt = (0:length(dig)-1)'/syncSampFq;\n\ndPos = find(diff(dig)==1);\ndNeg = find(diff(dig)==-1);\n\nif length(dPos) == length(dNeg)+1\n dPos = dPos(1:end-1);\nelseif length(dPos) > length(dNeg)+1 || length(dPos) < length(dNeg)\n keyboard\nend\n\n% Frame timing is the middle of shuter opening\nframeT = (t(dPos)+t(dNeg))/2;\n\n% The system sometimes (rarely) keeps on recording a few frames after software stopped\n% recording. So we skip the last frames of the TTL\n\nif length(frameT)size(pos,1)\n frameT = frameT(1:size(pos,1));\nend\n\n% We now interpolate the data at 120 Hz (or sampling fqcy specified in\n% arguments)\n% recDuration = length(dig)/syncSampFq;\n% \n% timestamps = (0:1/posSampFq:recDuration-1/posSampFq)';\n% pos(pos==-1) = NaN;\n% newPos = interp1(frameT,pos,timestamps,'linear');\n\n% timestamps(isnan(newPos(:,2))) = [];\n% newPos(isnan(newPos(:,2)),:)=[];\n\ndlmwrite([fbasename '.pos'],[frameT pos],'delimiter','\\t', 'precision', 32);\n\nend\n\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/preprocessing/positionTracking/optitrack/Process_ConvertOptitrack2Pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.17065208293850812}} {"text": "% This script train an LSTM or DNN based clean speech log spectrogram \n% predictor, using simulated data of Reverb challenge. \n% \n% Xiong Xiao, Nanyang Technological University, Singapore\n% Last modified: 08 Feb 2016. \n%\n%clear\nfunction TrainEnhanceNet_Regression(modelType, hiddenLayerSize, hiddenLayerSizeFF, DeltaGenerationType, learning_rate, useGPU)\nnUtt4Iteration = 10000;\nnSequencePerMinibatch = 40;\nuseFileName = 1;\n\naddpath('local', '../beamforming/lib', '../dereverb/local'); % remember to run addMyPath.m in SignalGraph root directory first. \n% define SignalGraph settings. Type ParseOptions2() in command line to see the options. \npara.IO.nStream = 2; % two data streams, one is input signal, one is clean target log spectrogram\npara.IO.mode = 'dynamicDistortion'; % distorted speech is generated dynamically during training. So each iteration uses different data. \npara.NET.sequential = 1; % do not randomize at frame level, randomize at sentence level\npara.NET.variableLengthMinibatch = 1; % a minibatch may contain multiple sentences of different lengths\npara.NET.nSequencePerMinibatch = nSequencePerMinibatch; % number of sentences per minibatch\npara.NET.nSequencePerMinibatchCV = nSequencePerMinibatch; % number of sentences per minibatch for CV\npara.NET.maxNumSentInBlock = 100; % maximum number of sentences in a block\npara.NET.L2weight = 3e-4;\npara.NET.learning_rate = learning_rate;\npara.NET.momentum = [0.9];\npara.NET.learning_rate_decay_rate = 0.999;\npara.NET.reduceLearnRateSpeed = 0.9;\npara.NET.gradientClipThreshold = 1;\npara.NET.weight_clip = 3;\npara.useGPU = useGPU; % don't use GPU for single sentence minibatch for LSTM. It's even slower than CPU. \npara.minItr = 100;\npara.displayGPUstatus = 1;\npara.displayInterval = ceil(para.NET.maxNumSentInBlock / para.NET.nSequencePerMinibatch / 10);\npara.skipInitialEval = 1;\n\npara.local.clean_wav_root = ChoosePath4OS({'E:\\Data\\LibriSpeech\\train-clean-100', '/media/xiaoxiong/OS/data1/G/Libri/LibriSpeech/train-clean-100'}); \npara.local.clean_wav_ext = 'flac';\npara.local.rir_wav_root = ChoosePath4OS({'E:\\Data\\ReverbEstimation\\RIR_T60_1ch', '/media/xiaoxiong/DATA1/data1/ReverbEstimation/RIR_T60_1ch'}); \npara.local.rir_wav_ext = 'wav';\npara.local.noise_wav_root = ChoosePath4OS({'E:\\Data\\musan\\noise', '/media/xiaoxiong/DATA1/data1/musan/noise'}); \npara.local.noise_wav_ext = 'wav';\npara.local.useFileName = useFileName; % if set to 0, load all training data to memory. otherwise, only load file names.\npara.local.seglen = 100;\npara.local.segshift = 100;\n\npara.topology.useChannel = 1;\npara.topology.useWav = 1;\npara.topology.RegressionNetType = modelType;\npara.topology.useCMN = 0;\npara.topology.DeltaGenerationType = DeltaGenerationType; % Choose 'DeltaByEqn' or 'DeltaByAffine'\npara.topology.MSECostWeightSDA = [1 4.5 10];\npara.topology.hiddenLayerSize = hiddenLayerSize;\npara.topology.hiddenLayerSizeFF = hiddenLayerSizeFF;\npara = ConfigDereverbNet_Regression(para);\n\npara.IO.DynamicDistortion.fs = para.topology.fs;\npara.IO.DynamicDistortion.nUtt4Iteration = nUtt4Iteration; % dynamically generate 10000 distorted sentences for each training iteration\npara.IO.DynamicDistortion.nHours4Iteration = 10; % dynamically generate 10 hours of distorted speech for each training iteration\npara.IO.DynamicDistortion.SNR_PDF = 'uniform'; % distribution of SNR, choose [uniform|normal]\npara.IO.DynamicDistortion.SNR_para = [-20 30]; % parameters of SNR PDF. If use uniform, it is the lowest and highest SNR allowed. \n % if use normal, it is the mean and variance of SNR. \npara.IO.DynamicDistortion.seglen = 100; % cut distorted sentences into equal length segments. \npara.IO.DynamicDistortion.segshift = 100;\npara.IO.DynamicDistortion.frame_len = para.topology.frame_len;\npara.IO.DynamicDistortion.frame_shift = para.topology.frame_shift;\n\n[Data_tr, para] = LoadWavRIRNoise_Libri(para, 1);\n\n[layer, para] = Build_EnhanceNet_Regression(Data_tr, para);\n\n% load the cv data\npara.local.cv_wav_root = ChoosePath4OS({'D:\\Data\\NoiseData\\Libri\\LibriSpeech\\dev-parallel', '/media/xiaoxiong/DATA1/data1/Libri/LibriSpeech/dev-parallel'}); \npara.local.useFileName = 0;\n[Data_cv, para] = LoadParallelWav_Libri(para, 2);\n\n% generate directory and file names to store the networks. \nif para.topology.useCMN; para.output = 'nnet/EnhanceRegression.CMN';\nelse; para.output = 'nnet/EnhanceRegression.noCMN'; end\npara.output = sprintf('%s.%s.MbSize%d.U%d.%d-%s', para.output, para.topology.DeltaGenerationType, ...\n para.NET.nSequencePerMinibatch, length(Data_tr(1).data), 3*(para.topology.fft_len/2+1), para.topology.RegressionNetType);\nfor i=1:length(para.topology.hiddenLayerSize)\n para.output = sprintf('%s-%d', para.output, para.topology.hiddenLayerSize(i));\nend\nif ~isempty(para.topology.hiddenLayerSizeFF)\n para.output = [para.output '-DNN'];\n for i=1:length(para.topology.hiddenLayerSizeFF)\n para.output = sprintf('%s-%d', para.output, para.topology.hiddenLayerSizeFF(i));\n end\nend\npara.output = sprintf('%s-%d.L2_%s.LR_%s/nnet', para.output, 3*(para.topology.fft_len/2+1), FormatFloat4Name(para.NET.L2weight),FormatFloat4Name(para.NET.learning_rate));\nLOG = [];\npara.displayTag = para.output(1:min(90, length(para.output)));\n\n% show the configurations\npara\npara.NET\npara.IO\npara.topology\n\ndnn = load('nnet/EnhanceRegression.noCMN.DeltaByEqn.MbSize20.U28539.771-LSTM-2048-771.L2_3E-4.LR_1E-4/nnet.itr62.LR4.97E-8.CV2439.245.mat');\nlayer = dnn.layer;\n\n% train the network using SGD\ntrainGraph_SGD(layer, Data_tr, Data_cv, para, LOG);\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/examples/enhancement/TrainEnhanceNet_Regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.17042094603848473}} {"text": "% dipfit_gridsearch() - do initial batch-like dipole scan and fit to all \n% data components and return a dipole model with a \n% single dipole for each component.\n% \n% Usage: \n% >> EEGOUT = dipfit_gridsearch( EEGIN, varargin)\n%\n% Inputs:\n% ...\n%\n% Optional inputs:\n% 'component' - vector with integers, ICA components to scan\n% 'xgrid' - vector with floats, grid positions along x-axis\n% 'ygrid' - vector with floats, grid positions along y-axis\n% 'zgrid' - vector with floats, grid positions along z-axis\n%\n% Output:\n% ...\n%\n% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003, load/save by\n% Arnaud Delorme\n% Thanks to Nicolas Robitaille for his help on the CTF MEG\n% implementation\n\n% SMI, University Aalborg, Denmark http://www.smi.auc.dk/\n% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl\n\n% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC roberto@smi.auc.dk\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [EEGOUT] = dipfit_gridsearch(EEG, varargin)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% convert the optional arguments into a configuration structure that can be\n% understood by FIELDTRIPs dipolefitting function \nif nargin>2\n cfg = struct(varargin{:});\nelse\n help dipfit_gridsearch\n return\nend\n\n% specify the FieldTrip DIPOLEFITTING configuration\ncfg.model = 'moving';\ncfg.gridsearch = 'yes';\ncfg.nonlinear = 'no';\n% add some additional settings from EEGLAB to the configuration\ntmpchanlocs = EEG.chanlocs;\ncfg.channel = { tmpchanlocs(EEG.dipfit.chansel).labels };\nif isfield(EEG.dipfit, 'vol')\n cfg.vol = EEG.dipfit.vol;\nelseif isfield(EEG.dipfit, 'hdmfile')\n cfg.hdmfile = EEG.dipfit.hdmfile;\nelse\n error('no head model in EEG.dipfit')\nend\nif isfield(EEG.dipfit, 'elecfile') & ~isempty(EEG.dipfit.elecfile)\n cfg.elecfile = EEG.dipfit.elecfile;\nend\nif isfield(EEG.dipfit, 'gradfile') & ~isempty(EEG.dipfit.gradfile)\n cfg.gradfile = EEG.dipfit.gradfile;\nend\n\n% convert the EEGLAB data structure into a structure that looks as if it\n% was computed using FIELDTRIPs componentanalysis function\ncomp = eeglab2fieldtrip(EEG, 'componentanalysis', 'dipfit');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Added code to handle CTF data with multipleSphere head model %\n% This code is copy-pasted in dipfit_gridSearch, dipfit_nonlinear %\n% The flag .isMultiSphere is used by dipplot %\n% Nicolas Robitaille, January 2007. %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Do some trick to force fieldtrip to use the multiple sphere model\nif strcmpi(EEG.dipfit.coordformat, 'CTF')\n cfg = rmfield(cfg, 'channel');\n comp = rmfield(comp, 'elec');\n cfg.gradfile = EEG.dipfit.chanfile;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% END %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(cfg, 'component')\n % default is to scan all components\n cfg.component = 1:size(comp.topo,2);\nend\n\n% for each component scan the whole brain with dipoles using FIELDTRIPs\n% dipolefitting function\nsource = ft_dipolefitting(cfg, comp);\n\n% reformat the output dipole sources into EEGLABs data structure\nfor i=1:length(cfg.component)\n EEG.dipfit.model(cfg.component(i)).posxyz = source.dip(i).pos;\n EEG.dipfit.model(cfg.component(i)).momxyz = reshape(source.dip(i).mom, 3, length(source.dip(i).mom)/3)';\n EEG.dipfit.model(cfg.component(i)).rv = source.dip(i).rv;\nend\n\nEEGOUT = EEG;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/dipfit_gridsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17035914897391397}} {"text": "function [rxnList, rxnFormulaList] = findRxnsFromMets(model, metList, varargin)\n% Returns a list of reactions in which at least one\n% metabolite listed in metList participates.\n%\n% USAGE:\n%\n% [rxnList, rxnFormulaList] = findRxnsFromMets(model, metList, printFlag)\n%\n% INPUTS:\n% model: COBRA model structure\n% metList: Metabolite list\n%\n% OPTIONAL INPUTS:\n% printFlag: Print reaction formulas to screen (Default = false)\n% Property/Value: Allowed Properties are:\n% * `containsAll` - If true only reactions containing all metabolites in metList are returned (Default: false)\n% * `printFlag` - as above, will overwrite a `printFlag` set individually (Default: false)\n% * `producersOnly` - Only return reactions which produce any of the given metabolites. (Default: false)\n% * `consumersOnly` - Only return reactions which consume any of the given metabolites. (Default: false)\n% * `exclusive` - Only return those reactions, which do not contain any metabolites but those given (Default: false)\n%\n% OUTPUTS:\n% rxnList: List of reactions\n% rxnFormulaList: Reaction formulas coresponding to `rxnList`\n%\n% .. Authors:\n% - Richard Que (08/12/2010)\n% - Almut Heinken (09/25/2015)- made change so formulas are not printed if reaction list is empty.\n% - Thomas Pfau (21/1/2016) - Additional Options, and minimal speedup of the indexing, also updated behaviour of verbFlag to accurately reflect the description.\n\nverbFlag = false;\ncontainsAll = false;\nif isa(metList,'char')\n metList = {metList};\nend\n\n\nif mod(numel(varargin), 2) == 1 % the first argument has to be verbFlag, the remaining are property/value pairs\n verbFlag = varargin{1};\n if numel(varargin) > 1\n varargin = varargin(2:end);\n end\nend\n\nparser = inputParser();\nparser.addParameter('containsAll',false,@(x) (isnumeric(x) && (x==1 || x ==0)) || islogical(x));\nparser.addParameter('producersOnly',false,@(x) (isnumeric(x) && (x==1 || x ==0)) || islogical(x));\nparser.addParameter('consumersOnly',false,@(x) (isnumeric(x) && (x==1 || x ==0)) || islogical(x));\nparser.addParameter('printFlag',verbFlag,@(x) isnumeric(x) );\nparser.addParameter('verbFlag',verbFlag,@(x) isnumeric || islogical(x) ); % backward compatability\nparser.addParameter('exclusive',false,@(x) (isnumeric(x) && (x==1 || x ==0)) || islogical(x));\n\nparser.parse(varargin{:});\n%Verbosity flag backward compatability\nif ismember('verbFlag',parser.UsingDefaults)\n verbFlag = parser.Results.printFlag;\nelseif ismember('printFlag',parser.UsingDefaults)\n verbFlag = parser.Results.verbFag;\nelse\n verbFlag = max([parser.Results.printFlag,parser.Results.verbFlag]);\nend\n\ncontainsAll = parser.Results.containsAll;\nproducersOnly = parser.Results.producersOnly;\nconsumersOnly = parser.Results.consumersOnly;\nexclusive = parser.Results.exclusive;\n\n%Find met indicies\nindex = ismember(model.mets,metList);\nif producersOnly && consumersOnly \n producers = sum(model.S(index,:) > 0,1)';\n consumers = sum(model.S(index,:) < 0,1)';\n rels = producers > 0 & model.ub > 0 | consumers > 0 & model.lb < 0 | producers > 0 & model.lb < 0 | consumers > 0 & model.ub > 0; \n totals = producers + consumers;\nelseif producersOnly\n producers = sum(model.S(index,:) > 0,1)';\n consumers = sum(model.S(index,:) < 0,1)';\n rels = producers > 0 & model.ub > 0 | consumers > 0 & model.lb < 0; \n totals = producers + consumers;\nelseif consumersOnly\n producers = sum(model.S(index,:) > 0,1)';\n consumers = sum(model.S(index,:) < 0,1)';\n rels = producers > 0 & model.lb < 0 | consumers > 0 & model.ub > 0; \n totals = producers + consumers;\nelse\n totals = sum(model.S(index,:) ~= 0,1);\n rels = totals > 0;\nend\n\nif exclusive\n others = sum(model.S(~index,:) ~= 0);\n %exclude anything that has other reactants.\n rels = rels & others == 0;\nend\n \n\nif containsAll\n rxnList = model.rxns(totals == numel(metList) & rels);\nelse\n %rxns = repmat(model.rxns,1,length(index));\n %find reactions i.e. all columns with at least one non zero value\n rxnList = model.rxns(totals > 0 & rels);\nend\n\n\nif (nargout > 1) || verbFlag\n if ~isempty(rxnList)\n rxnFormulaList = printRxnFormula(model,rxnList,verbFlag);\n else\n rxnFormulaList={};\n end\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/exploration/findRxnsFromMets.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17035914897391394}} {"text": "function [balanced_ds,idxs,classes]=cosmo_balance_dataset(ds,varargin)\n% sub-sample a dataset to have an equal number of samples for each target\n%\n% [balanced_ds,idxs,classes]=cosmo_balance_dataset(ds)\n%\n% Inputs:\n% ds dataset struct with fields .samples,\n% .sa.targets and .sa.chunks. All values in\n% .sa.chunks must be different from each other.\n% 'sample_balancer', f (optional)\n% function handle with signature\n% [idxs,classes]=f(targets,seed)\n% where idxs is a SxC vector with indices for C\n% classes and S targets per class. If omitted a\n% builtin function is used.\n% 'seed', s (optional, default=1)\n% Seed to use for pseudo-random number generation\n%\n% Output:\n% balanced_ds dataset with a subset of the samples from ds\n% so that each target occurs equally often.\n% Selection is (by default) done in a\n% pseudo-determistic manner.\n% idxs SxC vector indicating which\n% classes Cx1 vector containing unique class labels\n%\n% Notes:\n% - this function is to be used with MEEG datasets. it is not intended\n% for fMRI data.\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n\n defaults=struct();\n defaults.seed=1;\n defaults.sample_balancer=[];\n\n opt=cosmo_structjoin(defaults,varargin{:});\n\n check_inputs(ds,opt)\n\n [idxs,classes]=select_subset(ds.sa.targets,opt);\n balanced_ds=cosmo_slice(ds,idxs(:),1);\n\n\nfunction [idxs,classes]=select_subset(targets,opt)\n sample_balancer=opt.sample_balancer;\n if isempty(sample_balancer)\n sample_balancer=@default_sample_balancer;\n end\n\n [idxs,classes]=sample_balancer(targets,opt.seed);\n\n\nfunction [idxs,classes]=default_sample_balancer(targets,seed)\n [all_idxs,classes]=cosmo_index_unique(targets);\n class_counts=cellfun(@numel,all_idxs);\n\n min_count=min(class_counts);\n max_count=max(class_counts);\n\n nclasses=numel(class_counts);\n % invoke PRNG only once\n rand_vals=cosmo_rand(max_count,nclasses,'seed',seed);\n\n idxs=zeros(min_count,nclasses);\n for k=1:nclasses\n % set class_idxs to have values in the range 1:class_counts in\n % random order\n [unused,class_idxs]=sort(rand_vals(1:class_counts(k),k));\n\n % select min_count values from the indices in class_idxs\n idxs(:,k)=all_idxs{k}(class_idxs(1:min_count));\n end\n\n\nfunction check_inputs(ds,opt)\n cosmo_check_dataset(ds);\n\n % chunks and targets must be present\n raise_exception=true;\n cosmo_isfield(ds,{'sa.targets','sa.chunks'},raise_exception);\n\n chunks=ds.sa.chunks;\n if numel(sort(chunks)) ~= numel(unique(chunks))\n error(['All values in .sa.chunks must be unique. If '...\n '*and only if* all '...\n 'observations in .samples can be assumed to be '...\n 'independent, for a dataset ds you can set '...\n ' ds.sa.chunks(:)=1:numel(ds.sa.chunks,1)'...\n 'to indicate independence. This assumption typically '...\n 'only applies to M/EEG datasets; this function should '...\n 'not be used for typical fMRI datasets']);\n end\n\n\n\n\n\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_balance_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17035914897391394}} {"text": "function mtPaths_ = dtiLoadMetrotracPathsFromStrVer3(str,i, numstats, mtPaths,xform)\n% Loads version 3 pdb file\n%\n% mtPaths_ = dtiLoadMetrotracPathsFromStrVer3(str,i, numstats,mtPaths,xform)\n%\n% str is the string buffer\n% i is the current position in the string buffer\n% numstats is the number of statistics in the pdb\n% It appears that xform is never used.\n%\n% HISTORY:\n% 2010.08.01 \n%\n% Stanford VISTA\n%\n%% \n\n% profile on\n\n% Boolean. Only Matlab transform what? Appears to always be false and\n% thus the code below is not used.\n\n% How many bytes for int32 and double\nint32size = size(typecast(int32(0),'uint8'),2);\ndoublesize = size(typecast(double(0.0),'uint8'),2);\n\n\nnumpaths = typecast( uint8(str(i:i+int32size-1)),'uint32'); \ni = i + int32size;\npoints_per_fiber = typecast( uint8(str(i:i+int32size*numpaths-1)),'int32'); i = i + int32size*numpaths;\n\n% compute the total number of points\ntotal_pts = 0;\nfor k = 1:numpaths\n total_pts = total_pts + points_per_fiber(k);\nend\ntotal_pts = uint32(total_pts);\n\n% read all the fiber points\nfiber_points = typecast( uint8(str(i:i+doublesize*total_pts*3-1)),'double'); \ni = i + doublesize*total_pts*3;\npoints_read = 0;\n\n%% Reading each pathway\nfor p = 1:numpaths \n numnodes = points_per_fiber(p);\n mtPaths.pathwayInfo(p).algo_type = 0; % algo type\n mtPaths.pathwayInfo(p).seed_point_index = 1; % seedpointindex ???\n \n % Reading path positions\n mtPaths.pathways{p,1} = fiber_points( 1+points_read*3 : (points_read+numnodes)*3);\n mtPaths.pathways{p,1} = reshape(mtPaths.pathways{p,1},3,numnodes);\n points_read = points_read + numnodes;\n\n if mod(p,10000)==0\n disp(['Loaded ' num2str(p) ' of ' num2str(numpaths)]);\n end\nend\n\n% Transform all fiber coords in one go (much faster!)\n% I don't know why this offset is still necessary, isn't ACPC space all\n% ACPC space??\nbOnlyMatlabXForm=0; % It appears that this is always false and could be deleted. \nif( ~bOnlyMatlabXForm )\n xformToMatlab = eye(4);\n xformToAcpc = xformToMatlab*mtPaths.xform;\n if isfield(mtPaths,'pathways')\n mtPaths.pathways = dtiXformFiberCoords(mtPaths.pathways, xformToAcpc);\n else\n mtPaths.pathways = [];\n mtPaths.pathwayInfo = [];\n end\nend\n\n%% Read per fiber stats\nfor as = 1:numstats\n per_fiber_stat = typecast( uint8(str(i:i+doublesize*numpaths-1)),'double'); \n i = i + doublesize*numpaths;\n for p = 1:numpaths\n mtPaths.pathwayInfo(p).pathStat(as) = per_fiber_stat(p);\n\n end\nend\n%% Read per point stats\nfor as = 1:numstats\n if(mtPaths.statHeader(as).is_computed_per_point)\n per_point_stat = typecast( uint8(str(i:i+doublesize*total_pts-1)),'double'); \n i = i + doublesize*total_pts; \n end\n \n points_read = 0;\n % Assign per point stats value\n for p = 1:numpaths\n if(mtPaths.statHeader(as).is_computed_per_point)\n mtPaths.pathwayInfo(p).point_stat_array(as,:) = ...\n per_point_stat(points_read+1 : points_read+points_per_fiber(p));\n points_read = points_read + points_per_fiber(p);\n end\n end\nend\nmtPaths_ = mtPaths;\n\n% profile off\n\nend\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/quench/dtiLoadMetrotracPathsFromStrVer3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.17025323707587603}} {"text": "function decision = cutBlocks(structIn,cnst,currImName)\n blockIn = structIn.data;\n\n currSize = size(blockIn);\n if (currSize(1) == currSize(2)) % discard non-square blocks \n \n % keep only non-background blocks, according to Coudray et al., Nat Med 2018\n % criterion\n bwIm = mean(blockIn,3); % black and white image\n if sum(sum(bwIm>=220))<(0.5*numel(bwIm))\n \n % resize block to 512x512\n blockIn = imresize(blockIn,[cnst.finalBlockSize,cnst.finalBlockSize]);\n \n if cnst.verbose\n imshow(blockIn);\n drawnow\n end\n \n % clean up file name\n currDot = strfind(currImName,'.');\n currImName = currImName(1:(currDot(1)-1));\n \n % identify failed (black) images\n if sum(sum(bwIm<=1))<(numel(bwIm))\n % save image\n imwrite(blockIn,[cnst.outDir,currImName,'-blk-',randseq(12,'alphabet','amino'),'.png']);\n decision = 4; % code for success\n else\n warning('moving block to failures');\n imwrite(blockIn,[cnst.failDir,currImName,'-blk-',randseq(12,'alphabet','amino'),'.png']);\n decision = 1; % code for fail\n end\n else\n if cnst.verbose\n disp('discarding background block');\n end\n decision = 2; % code for background\n end\n else\n if cnst.verbose\n disp('discarding edge');\n end\n decision = 3; % code for edge\n end\n \nend", "meta": {"author": "jnkather", "repo": "MSIfromHE", "sha": "27b351b9220583271cd2bcedbc9e75459916e06c", "save_path": "github-repos/MATLAB/jnkather-MSIfromHE", "path": "github-repos/MATLAB/jnkather-MSIfromHE/MSIfromHE-27b351b9220583271cd2bcedbc9e75459916e06c/subroutines/cutBlocks.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.32766828768970446, "lm_q1q2_score": 0.17023066198233394}} {"text": "function [ni,canXform] = niftiApplyCannonicalXform(ni, canXform, phaseDir)\n% Reorient NIFTI data and metadata fields into RAS space \n%\n% [ni,canXform] = ...\n% niftiApplyCannonicalXform(ni, ...\n% [canXform=mrAnatComputeCannonicalXformFromDicomXform], phaseDir=[])\n%\n% Inputs:\n% ni: Nifti-1 data structure. (Should allow a filename in future).\n% canXform: Canonical transform from current form to RAS (Right-left,\n% Anterior-posterior, Superior-inferior). If not passed in,\n% then the transform is estimated\n% phaseDir: ???? Phase encode direction. (Columns, rows ... ???)\n%\n% ** PLEASE EXPLAIN WHY WE NEED TO KNOW PHASE ENCODE DIRECTION ***\n%\n% Returns:\n% ni: New nifti data set\n% canXform: Canonical transform\n%\n% Given a NIFTI-1 file ni- reorients the data and adjusts relevant metadata\n% fields (like quaternion, pixfdim, freq/phase/slice dims, etc.) to be\n% consistent. \n%\n% The transformation is specified by canXform (canonical transform). If the\n% canXform isn't provided, it is estimated using\n%\n% mrAnatComputeCannonicalXformFromDicomXform\n%\n% You can also pass the phase dir to overwrite a bad phase_dir field in\n% your nifti header. Note that you should specify the phase_dir of the\n% input data *before* the cannonical xform is applied. The value should be\n% 1, 2, or 3 to specify phase-encoding along the first, second or third\n% image dimension. ** PLEASE EXPLAIN WHICH FUNCTION USES THIS INFORMATION\n%\n% See also: mrAnatComputeCannonicalXformFromDicomXform, applyCannonicalXform\n%\n% HISTORY:\n% 2007.05.17 RFD: wrote it.\n% 2008.08.15 RFD: fixed dim order bug.\n%\n% (c) Stanford VISTALAB\n\nif(nargin<1), help(mfile); end\n\n% Do a sanity-check on the nifti transform\n% ni = niftiCheckQto(ni);\nni = niftiSet(ni,'Check Qto',''); %The final value is not necessary here\n\nif(~exist('canXform','var') || isempty(canXform))\n canXform = mrAnatComputeCannonicalXformFromDicomXform(ni.qto_xyz, ni.dim(1:3));\nend\n%canXform(:,4) = [0 0 0 1]';\nif(exist('phaseDir','var') && ~isempty(phaseDir))\n ni.phase_dim = phaseDir;\nend\n\nif(all(all(canXform == eye(4))))\n fprintf('[%s]: Data are already in canonical orientation.\\n', mfilename)\nelse\n \n % Apply the transform\n [ni.data,newPixdim,dimOrder] = ...\n applyCannonicalXform(ni.data, canXform, ni.pixdim(1:3), false);\n \n % Fill the NIFTI image slots\n ni = niftiSet(ni,'dim',size(niftiGet(ni,'data')));\n ni.pixdim(1:3) = newPixdim;\n\n % Fill the transform slots\n ni = niftiSet(ni, 'qto', inv(canXform * niftiGet(ni,'qto_ijk')));\n if(any(ni.sto_xyz(:)>0))\n ni.sto_ijk = canXform*ni.sto_ijk;\n ni.sto_xyz = inv(ni.sto_ijk);\n end\n \n if(ni.freq_dim>0 && ni.freq_dim<4)\n ni.freq_dim = dimOrder(ni.freq_dim);\n else\n disp('freq_dim not set correctly in NIFTI header.');\n end\n \n if(ni.phase_dim>0 && ni.phase_dim<4)\n ni.phase_dim = dimOrder(ni.phase_dim);\n else\n disp('phase_dim not set correctly in NIFTI header.');\n end\n \n if(ni.slice_dim>0 && ni.slice_dim<4)\n ni.slice_dim = dimOrder(ni.slice_dim);\n end\nend\n\nend", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/fileFilters/nifti/niftiApplyCannonicalXform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1701211839570354}} {"text": "function outW = extract(w, method, startV, endV)\n %EXTRACT creates a waveform with a subset of another's data.\n % waveform = extract(waveform, 'TIME', startTime, endTime)\n % returns a waveform with the subset of data from startTime to\n % endTime. Both times are matlab formatted (string or datenum)\n %\n % waveform = extract(waveform, 'INDEX', startIndex, endIndex)\n % returns a waveform with the subset of data from StartIndex to\n % EndIndex. this is roughly equivelent to grabbing the waveform's\n % data into an array, as in D = get(W,'data'), then returning a\n % waveform with the subset of data,\n % ie. waveform = set(waveform,'data', D(startIndex:endIndex));\n %\n % waveform = extract(waveform, 'INDEX&DURATION', startIndex, duration)\n % a hybrid method that starts from data index startIndex, and then\n % returns a specified length of data as indicated by duration.\n % Duration is a matlab formatted time (string or datenum).\n %\n % waveform = extract(waveform, 'TIME&SAMPLES', startTime, Samples)\n % a hybrid method that starts from data index startIndex, and then\n % returns a specified length of data as indicated by duration.\n % Duration is a matlab formatted time (string or datenum).\n %\n % Input Arguments:\n % WAVEFORM: waveform object N-DIMENSIONAL\n % METHOD: 'TIME', or 'INDEX', or 'INDEX&DURATION'\n % TIME: starttime and endtime are absolute times\n % (include the date)\n % INDEX: startt and endt are the offset (index) within the data\n % INDEX&DURATION: first value is an offset (index), the next says\n % how much data to retrieve...\n % TIME&SAMPLES: grab first value at time startTime, and grab\n % Samplength data points\n % STARTTIME: Start time (matlab or text format)\n % ENDTIME: End time (matlab or text format)\n % STARTINDEX: position within data array to begin extraction\n % ENDINDEX: final grabbed position within data array\n % DURATION: matlab format time indicating duration of data to grab\n % SAMPLES: the number of data points to grab.\n %\n % the output waveform will have the new, appropriate start time.\n % if the times are outside the range of the waveform object, then the\n % output waveform will contain only the portion of the data that is\n % appropriate.\n %\n % *MULTIPLE EXTRACTIONS* can be received if the time values are vectors.\n % Both starttime/startindex and endtime/endindex/endduration/samples must\n % have the same number of elements. In this case the output waveforms\n % will be reshaped with each waveform represented by row, and each\n % extracted time represented by column. that is...\n %\n % The output of this function, for multiple waveforms and times will be:\n % t1 t2 t3 ... tn\n % -----------------------\n % w1 |\n % w2 |\n % w3 |\n % . |\n % . |\n % wn |\n %\n %\n %% examples:\n % % say that Win is a waveform that starts 1/5/2007 04:00, and\n % % contains 1 hour of data at 100 Hz (360000 samples)\n %\n % % grab samples between 4:15 and 4:20\n % Wout = extract(Win, 'TIME', '1/5/2007 4:15:00','1/5/2007 4:20:00');\n %\n % % grab 3 minutes, starting at the 10000th sample\n % Wout = extract(Win, 'INDEX&DURATION', 10000 , '0/0/0 00:03:00');\n %\n %\n %% example of multiple extract:\n % % declare the times we're interested in\n % firstsnippet = datenum('6/20/2003 00:00:00');\n % lastsnippet = datenum('6/20/2003 24:00:00');\n %\n % % divide the day into 1-hour segments.\n % % note, 25 peices. equivelent to 0:1:24, including both midnights\n % alltimes = linspace(firstsnippet, lastsnippet, 25);\n % starttimes = alltimes(1:end-1);\n % endtimes = alltimes(2:end);\n %\n % % grab each hour of time, and shove it into wHours\n % wHours = extract(wDay, 'time',starttimes, endtimes);\n %\n % scaleFactor = 4 * std(double(wDay));\n % wHours = wHours ./ scaleFactor;\n % %\n % for n = 1:length(wHours)\n % wHours(n) = -wHours(n) + n; %add offset for plotting\n % end\n % plot(wHours,'xunit','m','b'); %plot it in blue with at nm scaling\n % axis ([0 60 1 25])\n % set(gca,'ytick',[0:2:24],'xgrid', 'on','ydir','reverse');\n % ylabel('Hour');\n %\n % See also WAVEFORM/SET -- Sample_Length\n \n % AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks\n % $Date$\n % $Revision$\n \n %% Set up condition variables, and ensure validity of input\n MULTIPLE_WAVES = ~isscalar(w);\n \n %if either of our times are strings, it's 'cause they're actually dates\n if ischar(startV)\n startV = datenum(startV);\n end\n if ischar(endV)\n endV = datenum(endV);\n end\n \n if numel(startV) ~= numel(endV)\n error('Waveform:extract:indexMismatch',...\n 'Number of start times (or indexes) must equal number of end times')\n end\n \n % are we getting a series of extractions from each waveform?\n MULTIPLE_EXTRACTION = numel(endV) > 1;\n \n if MULTIPLE_WAVES && MULTIPLE_EXTRACTION\n w = w(:);\n end\n \n %%\n if numel(w)==0 || numel(startV) ==0\n warning('Waveform:extract:emptyWaveform','no waveforms to extract');\n return\n end\n \n % changed by glenn thompson 20161006 as it was losing calibration\n % information\n %outW(numel(w),numel(startV)) = waveform; % removed\n outW = w; % added\n \n for m = 1: numel(startV) %loop through the number of extractions\n for n=1:numel(w); %loop through the waveforms\n inW = w(n);\n myData = inW.data;\n \n switch lower(method)\n case 'time'\n \n % startV and endV are both matlab formated dates\n %sampleTimes = get(inW,'timevector');\n \n % ensure the format of our times\n if startV(m) > endV(m)\n warning('Waveform:extract:reversedValues',...\n 'Start time prior to end time. Flipping.');\n [startV(m), endV(m)] = swap(startV(m), endV(m));\n end\n \n \n %if requested data is outside the existing waveform, change the\n %start time, and clear out the data.\n startsAfterWave = startV(m) > get(inW,'end') ;\n endsBeforeWave = endV(m) < get(inW,'start');\n if startsAfterWave || endsBeforeWave\n myStart = startV(m);\n myData = [];\n else\n %some aspect of this data must be represented by the waveform\n [myStartI myStartTime] = time2offset(inW,startV(m));\n [myEndI] = time2offset(inW,endV(m)) - 1;\n if isempty(myStartTime)\n %waveform starts sometime after requested start\n myStartTime = get(inW,'start');\n myStartI = 1;\n end\n \n if myEndI > numel(myData)\n myEndI = numel(myData);\n end\n myData = myData(myStartI:myEndI);\n myStart = myStartTime;\n end\n case 'index'\n %startV and endV are both indexes into the data\n \n \n if startV(m) > numel(myData)\n warning('Waveform:extract:noDataFound',...\n 'no data after start index');\n return\n end;\n if endV(m) > numel(myData)\n endV(m) = length(myData);\n warning('Waveform:extract:truncatingData',...\n 'end index too long, truncating to match data');\n end\n \n if startV(m) > endV(m)\n warning('Waveform:extract:reversedValues',...\n 'Start time prior to end time. Flipping.');\n [startV(m), endV(m)] = swap(startV(m), endV(m));\n end\n \n myData = myData(startV(m):endV(m));\n sampTimes = get(inW,'timevector'); % grab individual sample times\n myStart = sampTimes(startV(m));\n \n case 'index&duration'\n % startV is an index into the data, endV is a matlab date\n myData = myData(startV(m):end); %grab the data starting at our index\n \n sampTimes = get(inW,'timevector'); % grab individual sample times\n sampTimes = sampTimes(startV(m):end); % truncate to match data\n \n myStart = sampTimes(1); %grab our starting date before hacking it\n \n sampTimes = sampTimes - sampTimes(1); %set first time to zero\n count = sum(sampTimes <= endV(m)) -1;\n myData = myData(1:count);\n \n \n case 'time&samples'\n % startV is a matlab date, while endV is an index into the data\n sampTimes = get(inW,'timevector'); % grab individual sample times\n \n index_to_times = sampTimes >= startV(m); %mask of valid times\n goodTimes = find(index_to_times,endV(m));%first howevermany of these good times\n \n myData = myData(goodTimes); % keep matching samples\n \n try\n myStart = sampTimes(goodTimes(1)); %first sample time is new waveform start\n catch\n warning('Waveform:extract:NoDataFound',...\n 'no data');\n myStart = startV(1);\n end\n \n otherwise\n error('Waveform:extract:unknownMethod','unknown method: %s', method);\n end\n \n if MULTIPLE_EXTRACTION\n outW(n,m) = set(inW,'start',myStart, 'data', myData);\n else\n outW(n) = set(inW,'start',myStart, 'data', myData);\n end\n end % n-loop (looping through waveforms)\n end % m-loop (looping through extractions)\nend\n\nfunction [B,A] = swap(A,B)\n %do nothing, just flip inputs & outputs\nend", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@waveform/extract.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.1699084913003356}} {"text": "function [vardistx, model] = vargplvmPartExpand(model, x, update)\n% VARGPLVMPARTEXPAND\n% This function is used when the model is using jointly the test and\n% training data (possibly with missing values from the first) to optimise\n% and in that case only part of the parameters are being optimised. This\n% function, thus, expands the model by taking into account only the\n% optimised parameters (the old ones are being kept fixed).\n\n% In this version of the function the params that are considered to be\n% optimised again are the var. distribution, dyn. kernel hyperparams and\n% inducing points. The rest (base kernel and beta) are being kept fixed.\n\n% x = [mu_bar lambda theta_t X_u] where mu_bar and lambda are augmented to\n% include the vardist. of the test points.\n\n% Note on the order of the parameters:\n% [(N*Q*2) |theta_t| Q*k |theta_f| 1] -> vargplvmExtractParam(model)\n% [(N*Q*2)+(Nstar*Q*2) |theta_t| Q*k] -> x\n%\n% COPYRIGHT: Andreas C. Damianou, Michalis K. Titsias 2011\n% VARGPLVM\n\n% The model params before optimisation\nparamsOrig = vargplvmExtractParam(model);\n\n% The optimised parameters x here are not only the vardist. but also\n% gDynKern and inducing points.\nparamsNew = x;\n\n% x will now hold only the vardist. params.\nvardistxNparams=length(model.dynamics.t_star) * model.q * 2;\nx = paramsNew(1:(model.dynamics.vardist.nParams + vardistxNparams));\n\n% now separate the variational disribution into the training part and the\n% testing part and update the original training model (only with the new training\n% variational distribution) and the test variational distribution\n% this is doing the expand\nvardistNumData = size(x,2)/(model.q*2);\nx = reshape(x, vardistNumData, model.dynamics.q*2);\nxtrain = x(1:model.N,:);\nxtest = x(model.N+1:end,:);\n%model.dynamics.vardist = vardistExpandParam(model.dynamics.vardist, xtrain);\nvardistx = vardistExpandParam(model.vardistx, xtest(:)');\n\n% The model will be expanded with the origParams vector where all the\n% new values (optimised) will overwrite the old ones.\nparams = paramsOrig;\n\nstartVal = 1;\nendVal = model.dynamics.vardist.nParams;\n\n% This will overwrite the vardist original params with the newly optimised\n% ones\nparams(startVal:endVal) = xtrain(:)';\n\n% This will overwrite the dyn.kern params and the inducing points.\nstartVal = endVal+1;\nendVal = endVal + model.dynamics.kern.nParams + model.q * model.k;\nparams(startVal:endVal) = paramsNew((startVal+vardistxNparams):(endVal+vardistxNparams));\n\n% Update the model\nif exist('update') && update\n model = vargplvmExpandParam(model, params);\nelse\n % Update the model withoug calling update stats (this is used in the\n % optimisation likelihood and wrapper functions which do all the\n % precomputations themselves)\n model = vargplvmExpandParamNoUpdate(model, params);\nend\n\n\n%-----------\n\n\n% This is copy-paste of vargplvmExpandParam without the last call to\n% vargplvmUpdateStats (because this is done inside the objective and gradient functions)\nfunction model = vargplvmExpandParamNoUpdate(model,params)\nstartVal = 1;\nif isfield(model, 'dynamics') & ~isempty(model.dynamics)\n % variational parameters (reparametrized) AND dyn.kernel's parameters\n endVal = model.dynamics.nParams;\n model.dynamics = modelExpandParam(model.dynamics, params(startVal:endVal));\nelse\n % variational parameters (means and covariances), original ones\n endVal = model.vardist.nParams;\n model.vardist = modelExpandParam(model.vardist, params(startVal:endVal));\nend\n\n% inducing inputs\nstartVal = endVal+1;\nif model.fixInducing\n if isfield(model, 'dynamics') & ~isempty(model.dynamics)\n Kt = kernCompute(model.dynamics.kern, model.dynamics.t);%%%%%%%%%%%%5\n model.X_u = Kt*model.dynamics.vardist.means; %dynamics\n model.X_u = model.X_u(model.inducingIndices,:);\n else\n model.X_u = model.vardist.means(model.inducingIndices, :); % static\n end\n % X_u values are taken from X values.\n % model.X_u = model.X(model.inducingIndices, :);\nelse\n % Parameters include inducing variables.\n endVal = endVal + model.q*model.k;\n model.X_u = reshape(params(startVal:endVal),model.k,model.q);\nend\n\n% kernel hyperparameters\nstartVal = endVal+1;\nendVal = endVal + model.kern.nParams;\nmodel.kern = kernExpandParam(model.kern, params(startVal:endVal));\n\n% likelihood beta parameters\nif model.optimiseBeta\n startVal = endVal + 1;\n endVal = endVal + prod(size(model.beta));\n fhandle = str2func([model.betaTransform 'Transform']);\n model.beta = fhandle(params(startVal:endVal), 'atox');\nend\n\nmodel.nParams = endVal;\n", "meta": {"author": "SheffieldML", "repo": "vargplvm", "sha": "480201fde5ac84ff36e4a9f06d3fafeafa8ef06d", "save_path": "github-repos/MATLAB/SheffieldML-vargplvm", "path": "github-repos/MATLAB/SheffieldML-vargplvm/vargplvm-480201fde5ac84ff36e4a9f06d3fafeafa8ef06d/vargplvm/matlab/vargplvmPartExpand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.16990848793091773}} {"text": "function [varargout] = read_plexon_nex(filename, varargin)\n\n% READ_PLEXON_NEX reads header or data from a Plexon *.nex file, which\n% is a file containing action-potential (spike) timestamps and waveforms\n% (spike channels), event timestamps (event channels), and continuous\n% variable data (continuous A/D channels).\n%\n% LFP and spike waveform data that is returned by this function is \n% expressed in microVolt.\n%\n% Use as\n% [hdr] = read_plexon_nex(filename)\n% [dat] = read_plexon_nex(filename, ...)\n% [dat1, dat2, dat3, hdr] = read_plexon_nex(filename, ...)\n%\n% Optional arguments should be specified in key-value pairs and can be\n% header structure with header information\n% feedback 0 or 1\n% tsonly 0 or 1, read only the timestamps and not the waveforms\n% channel number, or list of numbers (that will result in multiple outputs)\n% begsample number (for continuous only)\n% endsample number (for continuous only)\n%\n% See also READ_PLEXON_PLX, READ_PLEXON_DDT\n\n% Copyright (C) 2007, 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% parse the optional input arguments\nhdr = ft_getopt(varargin, 'header');\nchannel = ft_getopt(varargin, 'channel');\nfeedback = ft_getopt(varargin, 'feedback', false);\ntsonly = ft_getopt(varargin, 'tsonly', false);\nbegsample = ft_getopt(varargin, 'begsample', 1);\nendsample = ft_getopt(varargin, 'endsample', inf);\n\n% start with empty return values and empty data\nvarargout = {};\n\n% read header info from file, use Matlabs for automatic byte-ordering\nfid = fopen_or_error(filename, 'r', 'ieee-le');\nfseek(fid, 0, 'eof');\nsiz = ftell(fid);\nfseek(fid, 0, 'bof');\n\nif isempty(hdr)\n if feedback, fprintf('reading header from %s\\n', filename); end\n % a NEX file consists of a file header, followed by a number of variable headers\n % sizeof(NexFileHeader) = 544\n % sizeof(NexVarHeader) = 208\n hdr.FileHeader = NexFileHeader(fid);\n if hdr.FileHeader.NumVars<1\n ft_error('no channels present in file');\n end\n hdr.VarHeader = NexVarHeader(fid, hdr.FileHeader.NumVars);\nend\n\nfor i=1:length(channel)\n chan = channel(i);\n vh = hdr.VarHeader(chan);\n clear buf\n fseek(fid, vh.DataOffset, 'bof');\n switch vh.Type\n case 0\n % Neurons, only timestamps\n buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');\n\n case 1\n % Events, only timestamps\n buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');\n\n case 2\n % Interval variables\n buf.begs = fread(fid, [1 vh.Count], 'int32=>int32');\n buf.ends = fread(fid, [1 vh.Count], 'int32=>int32');\n\n case 3\n % Waveform variables\n buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');\n if ~tsonly\n buf.dat = fread(fid, [vh.NPointsWave vh.Count], 'int16');\n % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt\n buf.dat = buf.dat * (vh.ADtoMV * 1000);\n end\n\n case 4\n % Population vector\n ft_error('population vectors are not supported');\n\n case 5\n % Continuously recorded variables\n buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');\n buf.indx = fread(fid, [1 vh.Count], 'int32=>int32');\n if vh.Count>1 && (begsample~=1 || endsample~=inf)\n ft_error('reading selected samples from multiple AD segments is not supported');\n end\n if ~tsonly\n numsample = min(endsample - begsample + 1, vh.NPointsWave);\n fseek(fid, (begsample-1)*2, 'cof');\n buf.dat = fread(fid, [1 numsample], 'int16');\n % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt\n buf.dat = buf.dat * (vh.ADtoMV * 1000);\n end\n\n case 6\n % Markers\n buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');\n for j=1:vh.NMarkers\n buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char');\n for k=1:vh.Count\n buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char');\n end\n end\n\n otherwise\n ft_error('incorrect channel type');\n end % switch channel type\n\n % return the data of this channel\n varargout{i} = buf;\nend % for channel\n\n% always return the header as last\nvarargout{end+1} = hdr;\n\nfclose(fid);\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction hdr = NexFileHeader(fid)\nhdr.NexFileHeader = fread(fid,4,'uint8=>char')'; % string NEX1\nhdr.Version = fread(fid,1,'int32');\nhdr.Comment = fread(fid,256,'uint8=>char')';\nhdr.Frequency = fread(fid,1,'double'); % timestamped freq. - tics per second\nhdr.Beg = fread(fid,1,'int32'); % usually 0\nhdr.End = fread(fid,1,'int32'); % maximum timestamp + 1\nhdr.NumVars = fread(fid,1,'int32'); % number of variables in the first batch\nhdr.NextFileHeader = fread(fid,1,'int32'); % position of the next file header in the file, not implemented yet\nPadding = fread(fid,256,'uint8=>char')'; % future expansion\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction hdr = NexVarHeader(fid, numvar)\nfor varlop=1:numvar\n hdr(varlop).Type = fread(fid,1,'int32'); % 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded\n hdr(varlop).Version = fread(fid,1,'int32'); % 100\n hdr(varlop).Name = fread(fid,64,'uint8=>char')'; % variable name\n hdr(varlop).DataOffset = fread(fid,1,'int32'); % where the data array for this variable is located in the file\n hdr(varlop).Count = fread(fid,1,'int32'); % number of events, intervals, waveforms or weights\n hdr(varlop).WireNumber = fread(fid,1,'int32'); % neuron only, not used now\n hdr(varlop).UnitNumber = fread(fid,1,'int32'); % neuron only, not used now\n hdr(varlop).Gain = fread(fid,1,'int32'); % neuron only, not used now\n hdr(varlop).Filter = fread(fid,1,'int32'); % neuron only, not used now\n hdr(varlop).XPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D\n hdr(varlop).YPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D\n hdr(varlop).WFrequency = fread(fid,1,'double'); % waveform and continuous vars only, w/f sampling frequency\n hdr(varlop).ADtoMV = fread(fid,1,'double'); % waveform continuous vars only, coeff. to convert from A/D values to Millivolts\n hdr(varlop).NPointsWave = fread(fid,1,'int32'); % waveform only, number of points in each wave\n hdr(varlop).NMarkers = fread(fid,1,'int32'); % how many values are associated with each marker\n hdr(varlop).MarkerLength = fread(fid,1,'int32'); % how many characters are in each marker value\n Padding = fread(fid,68,'uint8=>char')';\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_plexon_nex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1699084845614999}} {"text": "function ctf_plot(ctf,CHAN,TIME,TRIALS,Xhair)\n\n% ctf_plot - plot ctf.data\n%\n% ctf_plot(ctf,CHAN,TIME,TRIALS,Xhair)\n%\n% CHAN - see ctf_channel_select for options\n% TIME - see ctf_read for options (given in msec)\n% TRIALS - select 1 trial to plot (the default is trial = 1)\n%\n% Xhair - 1 to use the crosshair GUI features (default), 0 otherwise\n%\n% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n% < >\n% < DISCLAIMER: >\n% < >\n% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. >\n% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR >\n% < OFFICIAL USE. >\n% < >\n% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>\n%\n\n% $Revision: 1.1 $ $Date: 2009-01-30 03:49:27 $\n\n% Copyright (C) 2004 Darren L. Weber\n% \n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% Modified: 02/2004, Darren.Weber_at_radiology.ucsf.edu\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\nif ~exist('CHAN','var'), CHAN = 'all'; end\nif ~exist('TIME','var'), TIME = 'all'; end\nif ~exist('TRIALS','var'), TRIALS = 1; end\nif ~exist('Xhair','var'), Xhair = 1; end\n\n\nif isempty(CHAN), CHAN = 'all'; end\nif isempty(TIME), TIME = 'all'; end\nif isempty(TRIALS), TRIALS = 1; end\nif isempty(Xhair), Xhair = 1; end\n\n\n% This function calls ctf_channel_select\n[CHAN,type] = ctf_channel_select(ctf,CHAN);\n\nswitch num2str(TIME),\n case 'all',\n TIME = ctf.setup.time_msec;\n TIME_index = 1:ctf.setup.number_samples;\notherwise\n fprintf('...sorry, time restrictions not implemented correctly (03/2004)\\n');\n TIME = ctf.setup.time_msec;\n TIME_index = 1:ctf.setup.number_samples;\n \n \n % % assume the input is a range of times in sec\n % % check the range\n % if TIME(1) > ctf.setup.time_msec(1),\n % fprintf('...setting TIME(1) = ctf.setup.time_msec(1)\\n');\n % TIME(1) = ctf.setup.time_msec(1);\n % end\n % if TIME(end) > ctf.setup.time_msec(end),\n % fprintf('...setting TIME(end) = ctf.setup.time_msec(end)\\n');\n % TIME(end) = ctf.setup.time_msec(end);\n % end\n % % now find the nearest indices into the samples matrix\n % TIME_index = interp1(ctf.setup.time_msec,1:ctf.setup.number_samples,TIME,'nearest');\n % % now ensure that the TIME array is consistent with ctf.setup.time_sec\n % TIME = ctf.setup.time_msec(TIME_index);\nend\nTIME = sort(TIME);\n\n\nswitch num2str(TRIALS),\n case 'all',\n TRIALS = 1:ctf.setup.number_trials;\n otherwise\n % assume the input is an array of trials\nend\nTRIALS = unique(sort(TRIALS));\n\n% check the input data for more than 1 trial\ntrials = size(ctf.data,3);\nif trials > 1,\n fprintf('...plotting trial %d of %d trials in ctf.data\\n',TRIALS,trials);\n data = ctf.data(:,:,TRIALS);\nelse\n data = ctf.data;\nend\n\n\n% now plot the data\nswitch type,\n \n case 'all',\n \n if isempty(ctf.sensor.index.meg_sens),\n fprintf('...no meg sensors\\n');\n else\n figure('Name','MEG sensors');\n MEGCHAN = ctf_channel_select(ctf,'meg');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,MEGCHAN))\n axis tight\n if exist('crosshair') & Xhair,\n crosshair;\n end\n end\n \n if isempty(ctf.sensor.index.eeg_sens),\n fprintf('...no eeg sensors\\n');\n else\n figure('Name','EEG sensors');\n EEGCHAN = ctf_channel_select(ctf,'eeg');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,EEGCHAN))\n axis tight\n end\n \n \n case 'meg',\n \n if isempty(CHAN),\n fprintf('...no meg sensors\\n');\n else\n figure('Name','MEG sensors');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,CHAN))\n axis tight\n end\n \n case 'eeg',\n \n if isempty(CHAN),\n fprintf('...no eeg sensors\\n');\n else\n figure('Name','EEG sensors');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,CHAN))\n axis tight\n end\n \n case 'ref',\n \n if isempty(CHAN),\n fprintf('...no ref sensors\\n');\n else\n figure('Name','MEG REF sensors');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,CHAN))\n axis tight\n end\n \n case 'others',\n \n if isempty(CHAN),\n fprintf('...no other sensors\\n');\n else\n figure('Name','Other sensors');\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,CHAN))\n axis tight\n end\n \n otherwise\n \n figure;\n plot(ctf.setup.time_msec(TIME_index),data(TIME_index,CHAN))\n axis tight\n \nend\n\nif exist('crosshair') & Xhair,\n crosshair;\nend\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ctfimport1.03/ctf_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.1699084811920821}} {"text": "% COMPDSP - Display standard info figures for a data decomposition\n% Creates four figure windows showing: Component amplitudes,\n% scalp maps, activations and activation spectra.\n% Usage:\n% >> compdsp(data,weights,locfile,[srate],[title],[compnums],[amps],[act]);\n%\n% Inputs:\n% data = data matrix used to train the decomposition\n% weights = the unmixing matrix (e.g., weights*sphere from RUNICA)\n%\n% Optional:\n% locfile = 2-d electrode locations file (as in >> topoplot example)\n% {default|[]: default locations file given in icadefs.m\n% srate = sampling rate in Hz {default|[]: as in icadefs.m}\n% title = optional figure title text \n% {default|'': none}\n% compnums = optional vector of component numbers to display \n% {default|[] -> all}\n% amps = all component amplitudes (from RUNICA) \n% {default|[]->recompute}\n% act = activations matrix (from RUNICA)\n% {default|[]->recompute}\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 \n\n% Copyright (C) 12/16/00 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 02-01-01 replaced STD with RMS -sm\n% 02-10-01 made srate optional -sm\n% 01-25-02 reformated help & license -ad \n\nfunction compdsp(data,unmix,locfile,srate,titl,compnums,amps,act)\n\nminHz = 2; % frequency display limits\nmaxHz = 40;\nACTS_PER_EEGPLOT = 32;\n\n%\n%%%%%%%%%%%%%%%%%%%%%% Read and test arguments %%%%%%%%%%%%%%%%%%%%%%%%\n%\nicadefs % read BACKCOLOR, DEFAULT_SRATE\n\nif nargin<2\n help compdsp\n return\nend\n\nchans = size(data,1);\nframes = size(data,2);\nncomps = size(unmix,1);\n\nif ncomps < 1\n error('Unmixing matrix must have at least one component');\nend\nif chans < 2\n error('Data must have at least two channels');\nend\nif frames < 2\n error('Data must have at least two frames');\nend\nif size(unmix,2) ~= chans\n error('Sizes of unmix and data do not match');\nend\nif nargin<3\n locfile=[];\nend\nif isempty(locfile)\n locfile = DEFAULT_ELOC; % from icsdefs.m\nend\nif ~exist(locfile)\n error('Cannot find electrode locations file');\nend\n\nif nargin<4\n srate = 0; % from icadefs\nend\nif isempty(srate) || srate==0\n srate = DEFAULT_SRATE; % from icadefs\nend\nif nargin<5\n titl = ''; % default - no title text\nend\nif isempty(titl)\n titl = '';\nend\nif nargin<6\n compnums = 0; % default - all components\nend\nif isempty(compnums)\n compnums = 0;\nend\nif nargin<7\n amps = NaN; % default - recompute amps\nend\nif isempty(amps)\n amps = NaN;\nend\nif ~isnan(amps) && length(amps) ~= ncomps\n error('Supplied amps does not match the number of unmixed components');\nend\n\nif compnums(1) == 0\n compnums = 1:ncomps;\nend\nif min(compnums) < 1\n error('Compnums must be positive');\nend\nif min(compnums) > ncomps\n error('Some compnum > number of components in unmix');\nend\n\nif nargin<8\n act = NaN; % default - recompute act\nend\n\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%% Create plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n\nif chans == ncomps \n winv = inv(unmix);\nelseif chans < ncomps \n error('More components than channels?');\nelse\n winv = pinv(unmix);\nend\n\nif isnan(act)\n fprintf('Computing activations ...')\n act = unmix(compnums,:)*data;\n fprintf('\\n');\nelseif size(act,2) ~= frames\n error('Supplied activations do not match data length');\nelseif size(act,1) ~= ncomps && size(act,1) ~= length(compnums)\n error('Number of supplied activations matrix does not match data or weights');\nelseif size(act,1) == ncomps \n act = act(compnums,:); % cut down matrix to desired components\nend\n\n%\n%%%%%%%%%%%%%%%%%%%%% I. Plot component amps %%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\npos = [40,520,550,400]; figure('Position',pos);\nif isnan(amps)\n fprintf('Computing component rms amplitudes ');\n amps = zeros(1,length(compnums));\n for j=1:length(compnums)\n amps(j) = rms(winv(:,compnums(j)))*rms(act(j,:)');\n fprintf('.')\n end\n fprintf('\\n');\nelse\n amps = amps(compnums); % truncate passed amps to desired compnums\nend\nplot(compnums,amps,'k');\nhold on\nplot(compnums,amps,'r^');\nxl=xlabel('Component numbers');\nyl=ylabel('RMS Amplitudes');\ntl=title([titl ' Amplitudes']);\nax = axis;\naxis([min(compnums)-1 max(compnums)+1 0 ax(4)]);\n\n%\n%%%%%%%%%%%%%%%%%%%%%%%%% II. Plot component maps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\npos = [40,40,550,400]; figure('Position',pos);\n\nfprintf('Plotting component scalp maps ...') % compmaps() may make multiple figures\ncompmap(winv,locfile,compnums,[titl ' Scalp Maps'],0,compnums); \nfprintf('\\n');\n\n%\n%%%%%%%%%%%%%%%%%%%%%% III. EEGPLOT activations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nif frames/srate < 10\n dispsecs = ceil(frames/srate);\nelse\n dispsecs = 10; % defaults - display 10s data per screen\nend\nrange = 0.8*max(max(act')-min(act'));\n\nstact=1;\nlact=ACTS_PER_EEGPLOT;\nif lact>size(act,1)\n lact = size(act,1);\nend\n\npos = [620,520,550,400]; figure('Position',pos);\nwhile stact <= size(act,1)\n % eegplot(data,srate,spacing,eloc_file,windowlength,title,posn)\n eegplot(act(stact:lact,:),srate,range,compnums(stact:lact),...\n dispsecs,[titl ' Activations'],pos);\n pos = pos + [.02 .02 0 0];\n stact = stact+ACTS_PER_EEGPLOT;\n lact = lact +ACTS_PER_EEGPLOT;\n if lact>size(act,1)\n lact = size(act,1);\n end\nend\n\n%\n%%%%%%%%%%%%%%%%%%%%%%% IV. PLOTDATA spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\npos = [620,40,550,400]; figure('Position',pos);\n\nif frames > 2048\n windw = 512;\nelseif frames > 1024\n windw = 256;\nelse\n windw = 128;\nend\nfprintf('Computing component spectra ')\nfor j = 1:length(compnums)\n % [Pxx,F] = PSD(X,NFFT,Fs,WINDOW,NOVERLAP)\n [spec,freqs] = psd(act(j,:),1024,srate,windw,ceil(windw*0.5));\n if ~exist('specs')\n specs = zeros(length(compnums),length(freqs));\n end\n specs(j,:) = spec';\n fprintf('.')\nend\nfprintf('\\n');\nspecs = 10*log10(specs);\n\ntmp = ceil(sqrt(length(compnums)));\ntmp2 = ceil(length(compnums)/tmp);\nfor j=1:length(compnums)\n sbplot(tmp2,tmp,j)\n plot(freqs,specs(j,:))\n set(gca,'box','off')\n set(gca,'color',BACKCOLOR);\n ax=axis;\n axis([minHz,maxHz,ax(3),ax(4)]);\n tl = title(int2str(compnums(j)));\nend\nxl=xlabel('Frequency (Hz)');\nyl=ylabel('Power (dB)');\nset(gca,'YAxisLocation','right');\ntxl=textsc([titl ' Activation Spectra'],'title');\naxcopy % pop-up axes on mouse click\n\n% plottopo(specs,[tmp2 tmp],0,[2,70 min(min(specs)) max(max(specs))],...\n% [titl ' Activation Power Spectra']);\n\nfunction rmsval = rms(column)\n rmsval = sqrt(mean(column.*column)); % don't remove mean\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/compdsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16985429246555472}} {"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 [TruePositives, FalseNegatives] = testPutrefactionPathways(model, microbeID, biomassReaction, database)\n% Performs an FVA and reports those putrefaction pathway end reactions (exchange reactions)\n% that can carry flux in the model and should carry flux according to\n% data (true positives) and those putrefaction pathway end reactions that\n% cannot carry flux in the model but should be secreted according to in\n% vitro data (false negatives).\n%\n% INPUT\n% model COBRA model structure\n% microbeID Microbe ID in carbon source data file\n% biomassReaction Biomass objective functions (low flux through BOF\n% required in analysis)\n% database Structure containing rBioNet reaction and metabolite\n% database\n%\n% OUTPUT\n% TruePositives Cell array of strings listing all putrefaction reactions\n% that can carry flux in the model and in in vitro data.\n% FalseNegatives Cell array of strings listing all putrefaction reactions\n% that cannot carry flux in the model but should carry flux according to in\n% vitro data.\n%\n% .. Author:\n% Almut Heinken, Dec 2017\n% March 2022 - changed code to string-matching to make\n% it more robust\n\nglobal CBT_LP_SOLVER\nif isempty(CBT_LP_SOLVER)\n initCobraToolbox\nend\n\n% read putrefaction product tables\ndataTable = readInputTableForPipeline('PutrefactionTable.txt');\n\ncorrRxns = {'Histidine degradation (histidine -> glutamate)','GLUFORT';'THF production (histidine -> tetrahydrofolate)','FTCD';'Glutamate production (glutamate -> acetate + pyruvate)','CITMALL';'Putrescine_1','EX_ptrc(e)';'Putrescine_2','EX_ptrc(e)';'Putrescine_3','EX_ptrc(e)';'Spermidine/ Spermine production (methionine -> spermidine)','EX_spmd(e)';'Cadaverine production (lysine -> cadaverine)','EX_15dap(e)';'Cresol production (tyrosine -> cresol)','EX_pcresol(e)';'Indole production (tryptophan -> indole)','EX_indole(e)';'Phenol production (tyrosine -> phenol)','EX_phenol(e)';'H2S_1','EX_h2s(e)';'H2S_2','EX_h2s(e)';'H2S_3','EX_h2s(e)';'H2S_4','EX_h2s(e)';'H2S_5','EX_h2s(e)'};\n\nTruePositives = {}; % true positives (uptake in vitro and in silico)\nFalseNegatives = {}; % false negatives (uptake in vitro not in silico)\n\n% find microbe index in putrefaction table\nmInd = find(strcmp(dataTable(:,1), microbeID));\nif isempty(mInd)\n warning(['Microbe \"', microbeID, '\" not found in putrefaction product data file.'])\nelse\n % perform FVA to identify uptake metabolites\n % set BOF\n if ~any(ismember(model.rxns, biomassReaction)) || nargin < 3\n error(['Biomass reaction \"', biomassReaction, '\" not found in model.'])\n end\n model = changeObjective(model, biomassReaction);\n % set a low lower bound for biomass\n % model = changeRxnBounds(model, biomassReaction, 1e-3, 'l');\n % list exchange reactions\n exchanges = model.rxns(strncmp('EX_', model.rxns, 3));\n % open all exchanges\n model = changeRxnBounds(model, exchanges, -1000, 'l');\n model = changeRxnBounds(model, exchanges, 1000, 'u');\n\n % get the reactions to test\n rxns = {};\n for i=2:size(dataTable,2)\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n end\n end\n\n % flux variability analysis on reactions of interest\n rxns = unique(rxns);\n rxns = rxns(~cellfun('isempty', rxns));\n rxnsInModel=intersect(rxns,model.rxns);\n if ~isempty(rxnsInModel)\n currentDir=pwd;\n try\n [minFlux, maxFlux, ~, ~] = fastFVA(model, 0, 'max', 'ibm_cplex', ...\n rxnsInModel, 'S');\n catch\n warning('fastFVA could not run, so fluxVariability is instead used. Consider installing fastFVA for shorter computation times.');\n cd(currentDir)\n [minFlux, maxFlux] = fluxVariability(model, 0, 'max', rxnsInModel);\n end\n\n % active flux\n flux = rxnsInModel(maxFlux > 1e-6);\n else\n flux = {};\n end\n\n % which reaction should carry flux according to in vitro data\n for i=2:size(dataTable,2)\n rxn={};\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n end\n end\n if ~isempty(rxn)\n % add any that are not in model/not carrying flux to the false negatives\n if ~isempty(intersect(rxn,flux))\n TruePositives = union(TruePositives,rxn);\n else\n FalseNegatives=union(FalseNegatives,rxn);\n end\n end\n end\nend\n\n% replace reaction IDs with metabolite names\nif ~isempty(TruePositives)\n TruePositives = TruePositives(~cellfun(@isempty, TruePositives));\n TruePositives=strrep(TruePositives,'EX_','');\n TruePositives=strrep(TruePositives,'(e)','');\n\n for i=1:length(TruePositives)\n if ~isempty(find(strcmp(database.metabolites(:,1),TruePositives{i})))\n TruePositives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),TruePositives{i})),2};\n end\n end\nend\n\n% warn about false negatives\nif ~isempty(FalseNegatives)\n FalseNegatives = FalseNegatives(~cellfun(@isempty, FalseNegatives));\n FalseNegatives=strrep(FalseNegatives,'EX_','');\n FalseNegatives=strrep(FalseNegatives,'(e)','');\n for i = 1:length(FalseNegatives)\n if ~isempty(find(strcmp(database.metabolites(:,1),FalseNegatives{i})))\n FalseNegatives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),FalseNegatives{i})),2};\n end\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/reconstruction/demeter/suite/tests/testPutrefactionPathways.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16951403196023943}} {"text": "function models=train_svms_box(imnames, feat_dir, region_meta_info, cachedir, run_name, varargin)\n%random seed\nrng(3);\n\n\n%input parser to allow additional inputs\np = inputParser;\naddOptional(p, 'to_train', [1:20], @isnumeric);\naddOptional(p, 'svm_C', 10^-3, @isscalar);\naddOptional(p,'bias_mult',10,@isscalar);\naddOptional(p, 'pos_loss_weight', 2, @isscalar);\naddOptional(p, 'do_latent', 0, @isscalar);\naddOptional(p, 'pos_ov_thresh', 0.5, @isscalar);\naddOptional(p, 'neg_ov_thresh', 0.3, @isscalar);\naddOptional(p, 'hard_neg_thresh', -1.0001, @isscalar);\naddOptional(p, 'evict_thresh', -1.2, @isscalar);\naddOptional(p, 'retrain_limit', 2000, @isscalar);\nparse(p, varargin{:});\nopts=p.Results;\n\nto_train=opts.to_train;\n\n%if cachedir does not exist, create it\nif(~exist(cachedir, 'file')) mkdir(cachedir); end\ncachedir=fullfile(cachedir, run_name);\nif(~exist(cachedir, 'file')) mkdir(cachedir); end\n\n\n%collect feature stats\nfprintf('Collecting feature stats...\\n');\nstats=collect_feature_stats(imnames, feat_dir, cachedir, region_meta_info);\n\n%initialize caches\nfor i=1:numel(to_train)\n caches(i) = init_cache;\n models(i).categid=to_train(i);\n models(i).w=[];\n models(i).b=[];\n models(i).meannrm=stats.meannrm;\nend\n\n%load GT positives\npos_file=fullfile(cachedir, 'pos.mat');\nif(exist(pos_file, 'file'))\n tmp=load(pos_file);\n X_pos=tmp.X_pos;\nelse\n X_pos=get_positives(imnames, feat_dir, to_train, region_meta_info, false, models, opts.pos_ov_thresh);\n save(pos_file, 'X_pos');\nend\nfor i=1:numel(to_train)\n caches(i).X_pos=X_pos{i};\n fprintf('Category %d has %d positives\\n', to_train(i), size(X_pos{i},1));\nend \n\n%train\nfirst_time=true;\nforce_update=false;\nmax_outer_iter=opts.do_latent+1;\nfor iter=1:max_outer_iter\n if(iter~=max_outer_iter)\n %subsample negatives\n negidx=randperm(numel(imnames));\n negidx=negidx(1:min(1000, numel(negidx)));\n else\n negidx=1:numel(imnames);\n end\n if(iter>1)\n %latent update\n X_pos=get_positives(imnames, feat_dir, to_train, region_meta_info, true, models, opts.pos_ov_thresh);\n for i=1:numel(to_train)\n caches(i).X_pos=X_pos{i};\n fprintf('Latent update: Category %d has %d positives\\n', to_train(i), size(X_pos{i},1));\n\n end\n force_update=true;\n end\n %for every negative\n for i=1:numel(negidx)\n fprintf('Hard negatives iter: %d, image number: %d/%d\\n',iter, i, numel(negidx));\n [X_neg, curr_keys]=get_hard_negatives(negidx(i), imnames, feat_dir, to_train,...\n region_meta_info, models, {caches.keys}, opts.neg_ov_thresh, opts.hard_neg_thresh, first_time);\n very_last_iter=(iter==max_outer_iter) && (i==numel(negidx));\n for j=1:numel(to_train)\n caches(j).X_neg=cat(1, caches(j).X_neg,X_neg{j});\n caches(j).keys=cat(1, caches(j).keys, curr_keys{j});\n caches(j).num_added=caches(j).num_added+size(X_neg{j},1);\n if(caches(j).num_added>opts.retrain_limit || first_time ||very_last_iter || force_update)\n %time to retrain\n fprintf('Retraining category %d with %d positives and %d negatives\\n', to_train(j), size(caches(j).X_pos,1), size(caches(j).X_neg,1));\n models(j)=update_model(models(j), caches(j), opts.svm_C, opts.bias_mult, opts.pos_loss_weight);\n [reg, posloss, negloss, neg_scores]=compute_obj_val(models(j),...\n caches(j), opts.svm_C, opts.pos_loss_weight);\n caches(j).pos_loss(end+1)=posloss;\n caches(j).neg_loss(end+1)=negloss;\n caches(j).reg_loss(end+1)=reg;\n caches(j).tot_loss(end+1)=posloss+negloss+reg;\n for t=1:numel(caches(j).tot_loss)\n fprintf('%d: %f = %f + %f + %f\\n',t,caches(j).tot_loss(t),...\n caches(j).reg_loss(t),caches(j).pos_loss(t), caches(j).neg_loss(t));\n end\n\n %evict\n keep=neg_scores>opts.evict_thresh;\n caches(j).X_neg=caches(j).X_neg(keep,:);\n caches(j).keys=caches(j).keys(keep,:);\n fprintf('Kept: %d negatives \\n', sum(keep));\n caches(j).num_added=0;\n end\n \n end\n first_time=false;\n force_update=false;\n end \nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n%--------------------------------\n% Feature stats\n%--------------------------------\nfunction stats = collect_feature_stats(imnames, feat_dir, cachedir, region_meta_info)\nstat_file=fullfile(cachedir, 'stats.mat');\nif(exist(stat_file, 'file'))\n tmp=load(stat_file);\n stats=tmp.stats; clear tmp;\nelse\n\n num_images=100;\n regs_per_img=100;\n ri=randperm(numel(imnames));\n ri=ri(1:num_images);\n totalnrm=0;\n totalcnt=0;\n for i=1:num_images\n fprintf('%d/%d\\n', i, num_images);\n\n %load random image\n tmp=load(fullfile(feat_dir, [imnames{ri(i)} '.mat']));\n\n %pick random regions\n num=min(regs_per_img, region_meta_info.num_regs(ri(i)));\n ri2=randperm(region_meta_info.num_regs(ri(i)));\n ri2=ri2(1:num); \n \n %get norm\n nrm=sqrt(sum(tmp.feats(ri2,:).^2,2));\n totalnrm=totalnrm+sum(nrm);\n totalcnt=totalcnt+num;\n end\n stats.meannrm=totalnrm./totalcnt;\n save(stat_file, 'stats');\nend\nfprintf('\\n\\nMean norm=%f\\n\\n',stats.meannrm);\n\n%------------------------------\n% Init cache\n%------------------------------\nfunction cache=init_cache\ncache.X_pos = single([]);\ncache.X_neg = single([]);\ncache.keys = [];\ncache.num_added = 0;\ncache.retrain_limit = 2000;\ncache.evict_thresh = -1.2;\ncache.hard_thresh = -1.0001;\ncache.pos_loss = [];\ncache.neg_loss = [];\ncache.reg_loss = [];\ncache.tot_loss = [];\n\n\n\n%------------------------------\n% Get positives from image\n%------------------------------\n\nfunction X_pos=get_positives(imnames, featdir, to_train, region_meta_info, islatent, models, pos_ov_thresh)\nfor k=1:numel(to_train)\n X_pos{k}=single([]);\nend\n\nfor i=1:numel(imnames)\n fprintf('Positives: %d/%d\\n',i, numel(imnames));\n tmp=load(fullfile(featdir, [imnames{i} '.mat']));\n feats=xform_feat(tmp.feats, models(1).meannrm);\n \n %for every category\n for j=1:numel(to_train)\n sel=[];\n if(islatent)\n %latent update: consider all features greater than thresh\n %find gt for this category and get corresponding overlaps\n gtidx=find(region_meta_info.gt{i}==to_train(j));\n nongt=find(region_meta_info.gt{i}==0);\n \n ovs=region_meta_info.box_overlaps{i}(gtidx,:);\n overlapping=find(max(ovs,[],1)>=pos_ov_thresh);\n ovs=ovs(:,overlapping);\n \n scores=feats*models(j).w+models(j).b;\n\n %for every gt, find the highest scoring gt that overlaps by >70\n for k=1:numel(gtidx)\n ovs_this=ovs(k,:);\n idx=find(ovs_this>pos_ov_thresh);\n if(isempty(idx)) continue; end\n [m, argmax]=max(scores(nongt(overlapping(idx))));\n sel=[sel nongt(overlapping(idx(argmax)))];\n end\n else\n sel=find(region_meta_info.gt{i}==to_train(j));\n end\n X_pos{j}=cat(1, X_pos{j},feats(sel,:));\n end\nend\n\n%------------------------------\n% Hard negatives\n%------------------------------\n\nfunction [X_neg, curr_keys]=get_hard_negatives(i, imnames, featdir, to_train, region_meta_info, models, keys, neg_ov_thresh, score_thresh, first_time)\ntmp=load(fullfile(featdir, [imnames{i} '.mat']));\nfeats=xform_feat(tmp.feats, models(1).meannrm);\n\nif(~first_time)\n %concatenate all models\n w=cat(2,models(:).w);\n b=cat(2,models(:).b);\n\n %compute all scores\n scores=bsxfun(@plus,feats*w, b);\nelse\n scores=(score_thresh+1)*ones(size(feats,1), numel(models));\nend\n\n\n%for every category\nfor j=1:numel(to_train)\n %get the groundtruths that don't belong to this category\n wronggtidx=find(region_meta_info.gt{i}~=to_train(j) & region_meta_info.gt{i}~=0);\n %get the non-groundtruths that overlap by less than threshold\n \n nongt=find(region_meta_info.gt{i}==0);\n gtidx=find(region_meta_info.gt{i}==to_train(j));\n if(~isempty(gtidx))\n idx=find(max(region_meta_info.box_overlaps{i}(gtidx,:),[],1)=score_thresh);\n\n %get the keys for each of these\n tmp_keys=[i*ones(numel(allidx),1) allidx];\n \n %check that duplicate keys are not added\n keep=~ismember(tmp_keys, keys{j}, 'rows');\n \n %add these feats\n X_neg{j}=feats(allidx(keep),:);\n curr_keys{j}=tmp_keys(keep,:);\nend\n\n\n%------------------------------\n% Update model\n%------------------------------\nfunction model=update_model(model, cache, svm_c, bias_mult, pos_weight)\nopts = sprintf('-w1 %.10f -c %.10f -s 3 -B %.10f', ...\n pos_weight, svm_c, bias_mult);\n\nX=cat(2, cache.X_pos', cache.X_neg');\ny=[ones(size(cache.X_pos,1),1); zeros(size(cache.X_neg,1),1)];\nfprintf('calling liblinear with:%s\\n',opts);\nllm = liblinear_train(y, sparse(double(X)), opts, 'col');\nmodel.w = single(llm.w(1:end-1)');\nmodel.b = single(llm.w(end)*bias_mult);\n\n\n\n%---------------------------\n% Compute objective value\n%---------------------------\nfunction [reg, posloss, negloss, neg_scores]=compute_obj_val(model,cache, svm_c, pos_weight)\npos_scores=cache.X_pos*model.w+model.b;\nneg_scores=cache.X_neg*model.w+model.b;\nposloss=sum(max(1-pos_scores,0))*svm_c*pos_weight;\nnegloss=sum(max(1+neg_scores,0))*svm_c;\nreg=0.5*model.w'*model.w;\n\n\n%---------------------------\n% xform_feat\n%---------------------------\nfunction feats=xform_feat(feats, nrm)\nfeats=feats*20./nrm;\n\n\n\n\n\n \n", "meta": {"author": "bharath272", "repo": "sds_eccv2014", "sha": "3804648e3451040263ceeff938aab5873476cfc1", "save_path": "github-repos/MATLAB/bharath272-sds_eccv2014", "path": "github-repos/MATLAB/bharath272-sds_eccv2014/sds_eccv2014-3804648e3451040263ceeff938aab5873476cfc1/region_classification/train_svms_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.16946333528942603}} {"text": "function bbox_reg = trans_bbox_reg(bbox_reg, use_gpu)\n% translate bbox_reg model for fast compute\n%\n% AUTORIGHTS\n% ---------------------------------------------------------\n% Copyright (c) 2014, Shaoqing Ren\n% \n% This file is part of the SPP code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% ---------------------------------------------------------\n\n for i = 1:length(bbox_reg.models)\n bbox_reg.models{i}.Beta = bbox_reg.models{i}.Beta';\n if use_gpu\n bbox_reg.models{i}.Beta_gpu = gpuArray(bbox_reg.models{i}.Beta);\n end\n end\n \n bbox_reg.combined_Beta = cell2mat(cellfun(@(x) x.Beta', bbox_reg.models', 'UniformOutput', false))';\n if use_gpu\n bbox_reg.combined_Beta_gpu = gpuArray(bbox_reg.combined_Beta);\n end\n bbox_reg.combined_T_inv = cell2mat(cellfun(@(x) x.T_inv, bbox_reg.models, 'UniformOutput', false));\nend", "meta": {"author": "ShaoqingRen", "repo": "SPP_net", "sha": "ca9675907f8af6c02773571bc91147b3a2ddfcc1", "save_path": "github-repos/MATLAB/ShaoqingRen-SPP_net", "path": "github-repos/MATLAB/ShaoqingRen-SPP_net/SPP_net-ca9675907f8af6c02773571bc91147b3a2ddfcc1/bbox_regression/trans_bbox_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1692679776587329}} {"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\ufffdnez Cort\ufffds\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 script_faster_rcnn_demo()\nclose all;\nclc;\nclear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));\n%% -------------------- CONFIG --------------------\nopts.caffe_version = 'caffe_faster_rcnn';\nopts.gpu_id = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\n\nopts.per_nms_topN = 6000;\nopts.nms_overlap_thres = 0.7;\nopts.after_nms_topN = 300;\nopts.use_gpu = true;\n\nopts.test_scales = 600;\n\n%% -------------------- INIT_MODEL --------------------\nmodel_dir = fullfile(pwd, 'output', 'faster_rcnn_final', 'faster_rcnn_VOC0712_vgg_16layers'); %% VGG-16\n%model_dir = fullfile(pwd, 'output', 'faster_rcnn_final', 'faster_rcnn_VOC0712_ZF'); %% ZF\nproposal_detection_model = load_proposal_detection_model(model_dir);\n\nproposal_detection_model.conf_proposal.test_scales = opts.test_scales;\nproposal_detection_model.conf_detection.test_scales = opts.test_scales;\nif opts.use_gpu\n proposal_detection_model.conf_proposal.image_means = gpuArray(proposal_detection_model.conf_proposal.image_means);\n proposal_detection_model.conf_detection.image_means = gpuArray(proposal_detection_model.conf_detection.image_means);\nend\n\n% caffe.init_log(fullfile(pwd, 'caffe_log'));\n% proposal net\nrpn_net = caffe.Net(proposal_detection_model.proposal_net_def, 'test');\nrpn_net.copy_from(proposal_detection_model.proposal_net);\n% fast rcnn net\nfast_rcnn_net = caffe.Net(proposal_detection_model.detection_net_def, 'test');\nfast_rcnn_net.copy_from(proposal_detection_model.detection_net);\n\n% set gpu/cpu\nif opts.use_gpu\n caffe.set_mode_gpu();\nelse\n caffe.set_mode_cpu();\nend \n\n%% -------------------- WARM UP --------------------\n% the first run will be slower; use an empty image to warm up\n\nfor j = 1:2 % we warm up 2 times\n im = uint8(ones(375, 500, 3)*128);\n if opts.use_gpu\n im = gpuArray(im);\n end\n [boxes, scores] = proposal_im_detect(proposal_detection_model.conf_proposal, rpn_net, im);\n aboxes = boxes_filter([boxes, scores], opts.per_nms_topN, opts.nms_overlap_thres, opts.after_nms_topN, opts.use_gpu);\n if proposal_detection_model.is_share_feature\n [boxes, scores] = fast_rcnn_conv_feat_detect(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...\n rpn_net.blobs(proposal_detection_model.last_shared_output_blob_name), ...\n aboxes(:, 1:4), opts.after_nms_topN);\n else\n [boxes, scores] = fast_rcnn_im_detect(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...\n aboxes(:, 1:4), opts.after_nms_topN);\n end\nend\n\n%% -------------------- TESTING --------------------\nim_names = {'001763.jpg', '004545.jpg', '000542.jpg', '000456.jpg', '001150.jpg'};\n% these images can be downloaded with fetch_faster_rcnn_final_model.m\n\nrunning_time = [];\nfor j = 1:length(im_names)\n \n im = imread(fullfile(pwd, im_names{j}));\n \n if opts.use_gpu\n im = gpuArray(im);\n end\n \n % test proposal\n th = tic();\n [boxes, scores] = proposal_im_detect(proposal_detection_model.conf_proposal, rpn_net, im);\n t_proposal = toc(th);\n th = tic();\n aboxes = boxes_filter([boxes, scores], opts.per_nms_topN, opts.nms_overlap_thres, opts.after_nms_topN, opts.use_gpu);\n t_nms = toc(th);\n \n % test detection\n th = tic();\n if proposal_detection_model.is_share_feature\n [boxes, scores] = fast_rcnn_conv_feat_detect(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...\n rpn_net.blobs(proposal_detection_model.last_shared_output_blob_name), ...\n aboxes(:, 1:4), opts.after_nms_topN);\n else\n [boxes, scores] = fast_rcnn_im_detect(proposal_detection_model.conf_detection, fast_rcnn_net, im, ...\n aboxes(:, 1:4), opts.after_nms_topN);\n end\n t_detection = toc(th);\n \n fprintf('%s (%dx%d): time %.3fs (resize+conv+proposal: %.3fs, nms+regionwise: %.3fs)\\n', im_names{j}, ...\n size(im, 2), size(im, 1), t_proposal + t_nms + t_detection, t_proposal, t_nms+t_detection);\n running_time(end+1) = t_proposal + t_nms + t_detection;\n \n % visualize\n classes = proposal_detection_model.classes;\n boxes_cell = cell(length(classes), 1);\n thres = 0.6;\n for i = 1:length(boxes_cell)\n boxes_cell{i} = [boxes(:, (1+(i-1)*4):(i*4)), scores(:, i)];\n boxes_cell{i} = boxes_cell{i}(nms(boxes_cell{i}, 0.3), :);\n \n I = boxes_cell{i}(:, 5) >= thres;\n boxes_cell{i} = boxes_cell{i}(I, :);\n end\n figure(j);\n showboxes(im, boxes_cell, classes, 'voc');\n pause(0.1);\nend\nfprintf('mean time: %.3fs\\n', mean(running_time));\n\ncaffe.reset_all(); \nclear mex;\n\nend\n\nfunction proposal_detection_model = load_proposal_detection_model(model_dir)\n ld = load(fullfile(model_dir, 'model'));\n proposal_detection_model = ld.proposal_detection_model;\n clear ld;\n \n proposal_detection_model.proposal_net_def ...\n = fullfile(model_dir, proposal_detection_model.proposal_net_def);\n proposal_detection_model.proposal_net ...\n = fullfile(model_dir, proposal_detection_model.proposal_net);\n proposal_detection_model.detection_net_def ...\n = fullfile(model_dir, proposal_detection_model.detection_net_def);\n proposal_detection_model.detection_net ...\n = fullfile(model_dir, proposal_detection_model.detection_net);\n \nend\n\nfunction aboxes = boxes_filter(aboxes, per_nms_topN, nms_overlap_thres, after_nms_topN, use_gpu)\n % to speed up nms\n if per_nms_topN > 0\n aboxes = aboxes(1:min(length(aboxes), per_nms_topN), :);\n end\n % do nms\n if nms_overlap_thres > 0 && nms_overlap_thres < 1\n aboxes = aboxes(nms(aboxes, nms_overlap_thres, use_gpu), :); \n end\n if after_nms_topN > 0\n aboxes = aboxes(1:min(length(aboxes), after_nms_topN), :);\n end\nend\n", "meta": {"author": "ShaoqingRen", "repo": "faster_rcnn", "sha": "49ad0990512a5d6e34f56e3c6596eb5fbf22f651", "save_path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn", "path": "github-repos/MATLAB/ShaoqingRen-faster_rcnn/faster_rcnn-49ad0990512a5d6e34f56e3c6596eb5fbf22f651/experiments/script_faster_rcnn_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1690720937026987}} {"text": "function varargout= bbci_acquire_cognionics(varargin)\n%BBCI_ACQUIRE_cognionics - Online data acquisition from Cognionics headset\n%\n%Synopsis:\n% STATE= bbci_acquire_cognionics('init', )\n% [CNTX, MRKTIME, MRKDESC, STATE]= bbci_acquire_cognionics(STATE)\n% bbci_acquire_cognionics('close')\n% bbci_acquire_cognionics('close', STATE)\n% \n%Arguments:\n% PARAM - Optional arguments\n% 'clab', 'fs', 'filtHd', 'blocksize', 'port', 'timeout', 'verbose'\n% \n%Output:\n% STATE - Structure characterizing the incoming signals; fields:\n% 'fs', 'clab', and intern stuff\n% CNTX - 'acquired' signals [Time x Channels]\n% The following variables hold the markers that have been 'acquired' within\n% the current block (if any).\n% MRKTIME - DOUBLE: [1 nMarkers] position [msec] within data block.\n% A marker occurrence within the first sample would give\n% MRKTIME= 1/STATE.fs.\n% MRKDESC - DOUBLE [1 nMarkers] values of markers\n\n% benjamin.blankertz\n\n\nif isequal(varargin{1}, 'init'),\n state= opt_proplistToStruct(varargin{2:end});\n default_clab= ...\n {'AF5' 'AF3' 'AF1' 'AFz' 'AF2' 'AF4' 'AF6' ...\n 'F5' 'F3', 'F1' 'Fz' 'F2' 'F4' 'F6' ...\n 'FC7' 'FC5' 'FC3' 'FC1' 'FCz' 'FC2' 'FC4' 'FC6' 'FC8' ...\n 'T7' 'C5' 'C3' 'C1' 'Cz' 'C2' 'C4' 'C6' 'T8' ...\n 'CP7' 'CP5' 'CP3' 'CP1' 'CPz' 'CP2' 'CP4' 'CP6' 'CP8' ...\n 'P7' 'P5' 'P3' 'P1' 'Pz' 'P2' 'P4' 'P6' 'P8' ...\n 'PO5' 'PO3' 'PO1' 'POz' 'PO2' 'PO4' 'PO6' ...\n 'O5' 'O3' 'O1' 'Oz' 'O2' 'O4' 'O6' ...\n };\n props= {'fs' 250 '!DOUBLE[1]'\n 'clab' default_clab 'CELL{CHAR}'\n 'blocksize' 40 '!DOUBLE[1]'\n 'port' 'COM11' '!CHAR'\n 'timeout' 3 '!DOUBLE[1]'\n 'filtHd' [] 'STRUCT'\n 'verbose' true '!BOOL'\n };\n [state, isdefault]= opt_setDefaults(state, props, 1);\n if state.fs~=250,\n error('Only fs=250 allowed');\n end\n if isdefault.filtHd,\n % Fs/4\n filt1.b= [0.85 0 0.85]\n filt1.a= [1 0 0.7]\n %Fs/2\n filt2.b= [0.8 0.8]\n filt2.a= [1 0.6]\n state.filtHd= procutil_catFilters(filt1, filt2);\n state.filtHd.PersistentMemory= true;\n end\n state.nChans= length(state.clab);\n state.nBytesPerPacket= 2+3*state.nChans+4;\n nPacketsPerPoll= ceil(state.blocksize/1000*state.fs);\n state.nBytesPerPoll= nPacketsPerPoll*state.nBytesPerPacket;\n \n % try to find connected cognionics port\n cog_ports= instrfind('Tag', 'Cognionics');\n if isempty(cog_ports),\n state.sp= serial(state.port, 'BaudRate',115200, ...\n 'Timeout',state.timeout, ...\n 'Tag', 'Cognionics');\n elseif length(cog_ports)==1,\n state.sp= cog_ports;\n if strcmp(state.sp.Status, 'open'),\n fclose(state.sp);\n end\n else\n error('multiple ports connected to Cognioncs found');\n end\n state.sp.InputBufferSize= 5*state.nBytesPerPoll;\n \n fopen(state.sp);\n % Poll data several times to get into a more stable state\n for q= 1:3,\n fread(state.sp, state.sp.InputBufferSize, 'uint8');\n end\n state.packetNo=[]; \n state.buffer= [];\n state.lastx= zeros(1, state.nChans);\n state.lastMrkDesc= 256;\n state.scale= 1000000/2^24;\n if isempty(state.filtHd),\n reset(state.filtHd);\n end\n output= {state};\n \nelseif isequal(varargin{1}, 'close'),\n cog_ports= instrfind('Tag', 'Cognionics');\n if ~isempty(cog_ports),\n fclose(cog_ports);\n %delete(cog_ports); % shutdown port completely?\n end\n output= {};\nelseif length(varargin)~=1,\n error('Except for INIT/CLOSE case, only one input argument expected');\n \nelse\n if ~isstruct(varargin{1}),\n error('First input argument must be ''init'', ''close'', or a struct');\n end\n state= varargin{1};\n %while state.sp.BytesAvailable1);\n if ~isempty(ilost), \n if state.verbose,\n fprintf('[ACQ-COG] interpolating %d lost packets after packet #%d\\n', ...\n [dpc(ilost)-1, packet_counter(ilost)]');\n end\n [cntx, mapping]= ...\n bbciutil_cognionicsInterpolate(cntx, packet_counter, state);\n mrkTime= 1/state.fs * mapping(iNonvoid)';\n end\n state.lastx= cntx(end,:);\n \n % Apply filter if requested (dfilt.filter automatically saves the state)\n if ~isempty(state.filtHd),\n cntx= filter(state.filtHd, cntx, 1);\n end\n \n output= {cntx, mrkTime, mrkDesc(iNonvoid), state};\nend\nvarargout= output(1:nargout);\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/online/acquisition/bbci_acquire_cognionics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.1690720937026987}} {"text": "function [msi] = read_bti_m4d(filename);\n\n% READ_BTI_M4D\n%\n% Use as\n% msi = read_bti_m4d(filename)\n\n% Copyright (C) 2007, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip\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: read_bti_m4d.m 945 2010-04-21 17:41:20Z roboos $\n\n[p, f, x] = fileparts(filename);\nif ~strcmp(x, '.m4d')\n % add the extension of the header\n filename = [filename '.m4d'];\nend\n\nfid = fopen(filename, 'r');\nif fid==-1\n error(sprintf('could not open file %s', filename));\nend\n\n% start with an empty header structure\nmsi = struct;\n\n% these header elements contain strings and should be converted in a cell-array\nstrlist = {\n 'MSI.ChannelOrder'\n };\n\n% these header elements contain numbers and should be converted in a numeric array\n% 'MSI.ChannelScale'\n% 'MSI.ChannelGain'\n% 'MSI.FileType'\n% 'MSI.TotalChannels'\n% 'MSI.TotalEpochs'\n% 'MSI.SamplePeriod'\n% 'MSI.SampleFrequency'\n% 'MSI.FirstLatency'\n% 'MSI.SlicesPerEpoch'\n% the conversion to numeric arrays is implemented in a general fashion\n% and all the fields above are automatically converted\nnumlist = {};\n\nline = '';\n\nmsi.grad.label = {};\nmsi.grad.pnt = zeros(0,3);\nmsi.grad.ori = zeros(0,3);\nwhile ischar(line)\n line = cleanline(fgetl(fid));\n if isempty(line) || (length(line)==1 && all(line==-1))\n continue\n end\n\n sep = strfind(line, ':');\n if length(sep)==1\n key = line(1:(sep-1));\n val = line((sep+1):end);\n elseif length(sep)>1\n % assume that the first separator is the relevant one, and that the\n % next ones are part of the value string (e.g. a channel with a ':' in\n % its name\n sep = sep(1);\n key = line(1:(sep-1));\n val = line((sep+1):end);\n elseif length(sep)<1\n % this is not what I would expect\n error('unexpected content in m4d file');\n end\n\n if ~isempty(strfind(line, 'Begin'))\n sep = strfind(key, '.');\n sep = sep(end);\n key = key(1:(sep-1));\n\n % if the key ends with begin and there is no value, then there is a block\n % of numbers following that relates to the magnetometer/gradiometer information.\n % All lines in that Begin-End block should be treated seperately\n val = {};\n lab = {};\n num = {};\n ind = 0;\n while isempty(strfind(line, 'End'))\n line = cleanline(fgetl(fid));\n if isempty(line) || (length(line)==1 && all(line==-1)) || ~isempty(strfind(line, 'End'))\n continue\n end\n ind = ind+1;\n % remember the line itself, and also cut it into pieces\n val{ind} = line;\n % the line is tab-separated and looks like this\n % A68 0.0873437 -0.075789 0.0891512 0.471135 -0.815532 0.336098\n sep = find(line==9); % the ascii value of a tab is 9\n sep = sep(1);\n lab{ind} = line(1:(sep-1));\n num{ind} = str2num(line((sep+1):end));\n\n end % parsing Begin-End block\n val = val(:);\n lab = lab(:);\n num = num(:);\n num = cell2mat(num);\n % the following is FieldTrip specific\n if size(num,2)==6\n msi.grad.label = [msi.grad.label; lab(:)];\n % the numbers represent position and orientation of each magnetometer coil\n msi.grad.pnt = [msi.grad.pnt; num(:,1:3)];\n msi.grad.ori = [msi.grad.ori; num(:,4:6)];\n else\n error('unknown gradiometer design')\n end\n end\n \n % the key looks like 'MSI.fieldname.subfieldname'\n fieldname = key(5:end);\n\n % remove spaces from the begin and end of the string\n val = strtrim(val);\n\n % try to convert the value string into something more usefull\n if ~iscell(val)\n % the value can contain a variety of elements, only some of which are decoded here\n if ~isempty(strfind(key, 'Index')) || ~isempty(strfind(key, 'Count')) || any(strcmp(key, numlist))\n % this contains a single number or a comma-separated list of numbers\n val = str2num(val);\n elseif ~isempty(strfind(key, 'Names')) || any(strcmp(key, strlist))\n % this contains a comma-separated list of strings\n val = tokenize(val, ',');\n else\n tmp = str2num(val);\n if ~isempty(tmp)\n val = tmp;\n end\n end\n end\n\n % assign this header element to the structure\n msi = setsubfield(msi, fieldname, val);\n\nend % while ischar(line)\n\nfclose(fid);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION to remove spaces from the begin and end\n% and to remove comments from the lines\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction line = cleanline(line)\nif isempty(line) || (length(line)==1 && all(line==-1))\n return\nend\ncomment = findstr(line, '//');\nif ~isempty(comment)\n line(min(comment):end) = ' ';\nend\nline = strtrim(line);\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/fileio/private/read_bti_m4d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.16860167735435194}} {"text": "%%%%%%%%%%%%%%%\n%%\nif true,\n clear all;close all;\n varList = {'CR_dtr','numcell_full','CellXYZ','anat_yx','anat_yz','anat_zx','ave_stack','fpsec','frame_turn'};\nelse\n % or without 'CR_dtr', keeping it from previous step:\n clearvars -except 'CR_dtr'; % 'CR_z_dtr';\n varList = {'numcell_full','CellXYZ','anat_yx','anat_yz','anat_zx','ave_stack','fpsec','frame_turn'};\nend\n\n%%\nM_dir = GetFishDirectories();\nM_stimset = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2];\n\nsave_dir = GetCurrentDataDir();\n\ndshift = 2; % differential shift between fictive and fluo, manually chosen\n\n%% MANUAL\nfor i_fish = 1,\n disp(['i_fish = ', num2str(i_fish)]);\n tic\n %% load data\n load(fullfile(M_dir{i_fish},['Fish' num2str(i_fish) '_direct_load_full_v6.mat']),varList{:}); % '_direct_load_nodiscard.mat'\n% load(fullfile(datadir,'frame_turn.mat'),'frame_turn');\n \n if size(frame_turn,1) 1,\n names = [names,{'tlists_raw','stimset'}];\n end\n \n for i = 1:length(names), % use loop to save variables into fields of CONST\n eval(['data.',names{i},'=', names{i},';']);\n end\n \n %% and save\n \n %%% new method with partitioning of main data\n newfishdir = fullfile(save_dir,['Data_F' num2str(i_fish) '_full.mat']);\n dimCR = size(CellResp);\n save(newfishdir,'data','dimCR','-v6');\n % custom function:\n SaveFileInPartsAppendv6(newfishdir,CellResp,'CellResp');\n% SaveFileInPartsAppendv6(newfishdir,CellRespZ,'CellRespZ');\n\n toc; beep\n \nend\n\n\n%% compute z-score\n% disp('compute z-score')\n% cell_resp_z_full = zscore(cell_resp_full')';\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/GUI preload processing/old/GUIpreload_step3_align.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.16791437772791293}} {"text": "function obj = viewMovieCreateSideBySide(obj)\n\t% Align signal to a stimulus and display images.\n\t% Biafra Ahanonu\n\t% branched from controllerAnalysis: 2014.08.01 [16:09:16]\n\t% inputs\n\t\t%\n\t% outputs\n\t\t%\n\n\t% changelog\n\t\t% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.\n\t% TODO\n\t\t%\n\n\timport ciapkg.api.* % import CIAtah functions in ciapkg package API.\n\t\n\t% =====================\n\t% fileFilterRegexp = obj.fileFilterRegexp;\n\tFRAMES_PER_SECOND = obj.FRAMES_PER_SECOND;\n\t% DOWNSAMPLE_FACTOR = obj.DOWNSAMPLE_FACTOR;\n\t% =====================\n\t% if strcmp(obj.analysisType,'group')\n\t% \tnFiles = length(obj.rawSignals);\n\t% else\n\t% \tnFiles = 1;\n\t% end\n\t% =====================\n\tmovieSettings = inputdlg({...\n\t\t'start:end frames (leave blank for all)',...\n\t\t'behavior:movie sample rate (downsample factor): ',...\n\t\t'imaging movie regexp:',...\n\t\t'video folder(s), separate multiple folders by a comma:',...\n\t\t'side-by-side save folder:',...\n\t\t'rotate second movie?',...\n\t\t'save movie type (hdf5 or tiff)',...\n\t\t'division factor behavior movie',...\n\t\t'normalize before combining? 0=no, 1=yes'},...\n\t\t'downsample settings',1,{...\n\t\t'1:500',...\n\t\tnum2str(obj.DOWNSAMPLE_FACTOR),...\n\t\tobj.fileFilterRegexp,...\n\t\tobj.videoDir{1},....\n\t\tobj.videoSaveDir,...\n\t\t'0',...\n\t\t'hdf5',...\n\t\t'10',...\n\t\t'0'});\n\n\tframeList = str2num(movieSettings{1});\n\tDOWNSAMPLE_FACTOR = str2num(movieSettings{2});\n\tobj.fileFilterRegexp = movieSettings{3}; fileFilterRegexp = obj.fileFilterRegexp;\n\tobj.videoDir = movieSettings{4}; videoDir = obj.videoDir;\n\tobj.videoSaveDir = movieSettings{5}; videoSaveDir = obj.videoSaveDir;\n\trotateSecondMovie = str2num(movieSettings{6});\n\tsaveMovieType = movieSettings{7};\n\tbehaviorMovieDivisionFactor = str2num(movieSettings{8});\n\tnormalizeMovies = str2num(movieSettings{9});\n\t% =====================\n\tvideoTrialRegExpList = {'yyyy_mm_dd_pNNN_mNNN_assayNN','yymmdd-mNNN-assayNN','yymmdd_mNNN_assayNN','subject_assay'};\n\tscnsize = get(0,'ScreenSize');\n\t[videoTrialRegExpIdx, ok] = listdlg('ListString',videoTrialRegExpList,'ListSize',[scnsize(3)*0.2 scnsize(4)*0.25],'Name','video string type (N = number)');\n\t% % =====================\n\t[fileIdxArray, idNumIdxArray, nFilesToAnalyze, nFiles] = obj.getAnalysisSubsetsToAnalyze();\n\tfor thisFileNumIdx = 1:nFilesToAnalyze\n\t\ttry\n\t\t\tfileNum = fileIdxArray(thisFileNumIdx);\n\t\t\tobj.fileNum = fileNum;\n\t\t\tdisplay(repmat('=',1,21))\n\t\t\t% display([num2str(thisFileNumIdx) '/' num2str(nFilesToAnalyze) ': ' obj.fileIDNameArray{obj.fileNum}]);\n\t\t\tdisplay([num2str(thisFileNumIdx) '/' num2str(nFilesToAnalyze) ' (' num2str(fileNum) '/' num2str(nFiles) '): ' obj.fileIDNameArray{obj.fileNum}]);\n\t\t\t% =====================\n\t\t\t% for backwards compatibility, will be removed in the future.\n\t\t\t% subject = obj.subjectNum{obj.fileNum};\n\t\t\t% assay = obj.assay{obj.fileNum};\n\t\t\t% =====================\n\t\t\t% frameList\n\t\t\tmovieList = getFileList(obj.inputFolders{obj.fileNum}, fileFilterRegexp);\n\t\t\t[imagingMovie] = loadMovieList(movieList,'convertToDouble',0,'frameList',frameList(:));\n\t\t\tif ~isempty(videoDir)\n\t\t\t\tif isempty(frameList)\n\t\t\t\t\tframeListTmp = 1:size(imagingMovie,3);\n\t\t\t\t\t% frameListTmp = 1:min(cellfun(@(x) size(x,3), primaryMovie));\n\t\t\t\telse\n\t\t\t\t\tframeListTmp = frameList;\n\t\t\t\tend\n\t\t\t\tvideoTrialRegExp = local_getVideoRegexp();\n\t\t\t\t% videoTrialRegExp\n\t\t\t\tvidList = getFileList(videoDir,videoTrialRegExp);\n\t\t\t\tif ~isempty(vidList)\n\t\t\t\t\t% get the movie\n\t\t\t\t\t% vidList\n\t\t\t\t\tbehaviorMovie = loadMovieList(vidList,'convertToDouble',0,'frameList',frameListTmp(:)*DOWNSAMPLE_FACTOR,'treatMoviesAsContinuous',1);\n\t\t\t\t\t% behaviorMovie = createMovieMontage(behaviorMovie,nAlignPts,timeVector,postOffset,preOffset,options.montageSuffix,savePathName,0);\n\t\t\t\t\t% [behaviorMovie] = createSideBySide(behaviorMovie,imagingMovie,'pxToCrop',[],'rotateSecondMovie',rotateSecondMovie);\n\t\t\t\t\t[behaviorMovie] = normalizeVector(single(behaviorMovie),'normRange','zeroToOne');\n\t\t\t\t\t[behaviorMovie] = normalizeMovie(behaviorMovie,'normalizationType','meanSubtraction');\n\t\t\t\t\tbehaviorMovie = behaviorMovie/behaviorMovieDivisionFactor;\n\n\t\t\t\t\t[behaviorMovie] = createSideBySide(imagingMovie,behaviorMovie,'pxToCrop',[],'rotateSecondMovie',rotateSecondMovie,'normalizeMovies',normalizeMovies);\n\t\t\t\t\tswitch saveMovieType\n\t\t\t\t\t\tcase 'hdf5'\n\t\t\t\t\t\t\tsavePathName = [videoSaveDir filesep obj.date{obj.fileNum} '_' obj.protocol{obj.fileNum} '_' obj.fileIDArray{obj.fileNum} '_sideBySide.h5'];\n\t\t\t\t\t\t\t[output] = writeHDF5Data(behaviorMovie,savePathName);\n\t\t\t\t\t\tcase 'tiff'\n\t\t\t\t\t\t\tsavePathName = [videoSaveDir filesep obj.date{obj.fileNum} '_' obj.protocol{obj.fileNum} '_' obj.fileIDArray{obj.fileNum} '_sideBySide.tif'];\n\t\t\t\t\t\t\ttiffOptions.comp = 'no';\n\t\t\t\t\t\t\tsaveastiff(behaviorMovie, savePathName, tiffOptions);\n\t\t\t\t\t\totherwise\n\t\t\t\t\t\t\t% body\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tcatch err\n\t\t\tdisplay(repmat('@',1,7))\n\t\t\tdisp(getReport(err,'extended','hyperlinks','on'));\n\t\t\tdisplay(repmat('@',1,7))\n\t\tend\n\tend\n\tfunction videoTrialRegExp = local_getVideoRegexp()\n\t\tswitch videoTrialRegExpIdx\n\t\t\tcase 1\n\t\t\t\tvideoTrialRegExp = [obj.date{obj.fileNum} '_' obj.protocol{obj.fileNum} '_' obj.fileIDArray{obj.fileNum}];\n\t\t\tcase 2\n\t\t\t\tdateTmp = strsplit(obj.date{obj.fileNum},'_');\n\t\t\t\tvideoTrialRegExp = strcat(dateTmp{1}(end-1:end),dateTmp{2},dateTmp{3},'-',obj.subjectStr{obj.fileNum},'-',obj.assay{obj.fileNum});\n\t\t\tcase 3\n\t\t\t\tvideoTrialRegExp = [obj.subjectStr{obj.fileNum} '_' obj.assay{obj.fileNum}]\n\t\t\totherwise\n\t\t\t\tvideoTrialRegExp = fileFilterRegexp\n\t\tend\n\tend\nend", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/@ciatah/viewMovieCreateSideBySide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.16767331372483665}} {"text": "clearvars;\nclose all;\n% Add path to stlTools\n% You can download the package for free from: \n% https://es.mathworks.com/matlabcentral/fileexchange/51200-stltools\naddpath('./stlTools');\n% Set the name of the mat file containing all the info of the 3D model\nMatFileName = '../../3d_models/a320_3d_model.mat';\n% Define the list of parts which will be part of the rigid aircraft body\n% First part should always be main aircraft body\nrigid_body_list = { 'Body_A320.stl','Engine_L_A320.stl','Engine_R_A320.stl'};\n% Define the color of each part\nrigid_body_colors = {0.8 * [1, 1, 1], 0.1 * [1, 1, 1], 0.1 * [1, 1, 1]};\n% Define the transparency of each part\nalphas = [ 1, 1, 1];\n% Define the model ofset to center the A/C Center of Gravity\noffset = [0,0,0];\n% Define the control surfaces\nControlsFieldNames = {...\n'model' 'label', 'color', 'rot_point', 'rot_vect', 'max_deflection'};\nControls = { \n'Aileron_L_A320.stl', 'A_L', 0.3*[0.8, 0.8, 1], [515.1,-1434,80.5]-offset, [ 0.2932,-0.9523, 0.0843], [-30, +30];\n'Aileron_R_A320.stl', 'A_R', 0.3*[0.8, 0.8, 1], [515.1,+1434,80.5]-offset, [ 0.2932, 0.9523, 0.0843], [-30, +30];\n'Rudder_A320.stl', 'RUD', 0.3*[0.8, 0.8, 1], [ 1954, 0,550.1]-offset,-[ 0.3064, 0, 0.9519], [-30, +30];\n'Elevator_L_A320.stl', 'STAB_L', 0.3*[0.8, 0.8, 1], [ 2037,-352.9,168.5]-offset, [-0.2952, 0.9481,-0.1179], [-30, +30];\n'Elevator_R_A320.stl', 'STAB_R', 0.3*[0.8, 0.8, 1], [ 2037,+352.9,168.5]-offset, [ 0.2952, 0.9481, 0.1179], [-30, +30];\n};\n% Definition of the Model3D data structure\n% Rigid body parts\nfor i = 1:length(rigid_body_list)\n Model3D.Aircraft(i).model = rigid_body_list{i};\n Model3D.Aircraft(i).color = rigid_body_colors{i};\n Model3D.Aircraft(i).alpha = alphas(i);\n % Read the *.stl file\n [Model3D.Aircraft(i).stl_data.vertices, Model3D.Aircraft(i).stl_data.faces, ~, Model3D.Aircraft(i).label] = stlRead(rigid_body_list{i});\n Model3D.Aircraft(i).stl_data.vertices = Model3D.Aircraft(i).stl_data.vertices - offset;\nend\n% Controls parts\nfor i = 1:size(Controls, 1)\n for j = 1:size(Controls, 2)\n Model3D.Control(i).(ControlsFieldNames{j}) = Controls{i, j};\n end\n % Read the *.stl file\n [Model3D.Control(i).stl_data.vertices, Model3D.Control(i).stl_data.faces, ~, ~] = stlRead( Model3D.Control(i).model);\n Model3D.Control(i).stl_data.vertices = Model3D.Control(i).stl_data.vertices - offset;\nend\n\n%% Save mat file\nsave(MatFileName, 'Model3D');\n\n%% Check the results\nplot3Dmodel(MatFileName)", "meta": {"author": "Ro3code", "repo": "aircraft_3d_animation", "sha": "fa0cdebd6988e11761eadd1b6f73a48b8c6a552e", "save_path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation", "path": "github-repos/MATLAB/Ro3code-aircraft_3d_animation/aircraft_3d_animation-fa0cdebd6988e11761eadd1b6f73a48b8c6a552e/import_stl_model/A320/import_stl_model_a320.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16745906275464992}} {"text": "function prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)\n% prepINITModel\n%\n% The purpose of this function is to run time-consuming calculation steps that are not\n% dependent on the RNA-Seq data.\n%\n% origRefModel The model to use. Expected to be something such as Human-GEM, \n% Mouse-GEM, etc.\n% taskStruct The essential tasks. Can be loaded with for example\n% taskStruct = parseTaskList('../data/metabolicTasks_Essential.txt');\n% spontRxnNames The spontaneous rxns. (opt, default {})\n% convertGenes If true the genes are converted to gene names (from \n% ENSEMBL) (opt, default false)\n% customRxnsToIgnore These reactions can be ignored in the ignore mask \n% (specifying b7=1) (opt, default = {})\n% extComp Name of the external compartment, typically 's' or 'e'. This\n% is used for identifying exch and import rxns (opt, default = 'e')\n% prepData The resulting prepData structure which is used as input to ftINIT\n%\n% Usage: prepData = prepINITModel(origRefModel, taskStruct, spontRxnNames, convertGenes, customRxnsToIgnore, extComp)\n\n\nif nargin < 3\n spontRxnNames = {}; \nend\n\nif nargin < 4\n convertGenes = false; \nend\n\nif nargin < 5\n customRxnsToIgnore = {}; \nend\n\nif nargin < 6\n extComp = 'e';\nend\n\ndisp('Step 1: Gene rules')\n[origRefModel.grRules, origRefModel.rxnGeneMat] = standardizeGrRules(origRefModel, true);\n\nif convertGenes %For mouse we might want to translate in the opposite direction - this has to be done before calling this function in that case.\n [origRefModel.grRules, origRefModel.genes, origRefModel.rxnGeneMat] = translateGrRules(origRefModel.grRules, 'Name');\nend\n\n\n% Get list of all dead-end/inacessible/constrained reactions in the model.\n% We don't merge linear dependent reactions here, that will happen later.\n% We also don't remove reversibility here, we don't want that in the final\n% models produced. Therefore, this is done as a separate step.\n% This takes quite some time to run\ndisp('Step 2: First simplification')\n[~,deletedDeadEndRxns] = simplifyModel(origRefModel,true,false,true,true,true);\n\n% get reduced model\ncModel = removeReactions(origRefModel,deletedDeadEndRxns,false,true);\n\n\n%Then, run the tasks to find out which reactions are essential. These rxns\n%will be forced to carry flux in the optimization later\n\n% determine reactions essential for tasks - takes ~10 min\n% need to add boundary mets first - but only to a temporary model, we don't\n% want those for further processing\ndisp('Step 3: Check tasks (~10 min)')\nif ~isempty(taskStruct)\n bModel = closeModel(cModel);\n [taskReport, essentialRxnMat, ~, essentialFluxes] = checkTasks(bModel,[],true,false,true,taskStruct);\n\n %extract the essential rxns:\n sel = sum(essentialRxnMat,2) > 0;\n selInd = find(sel);\n essentialRxns = bModel.rxns(selInd);%382 rxns for human-GEM\n\n %Find metabolites present in taskStruct. We want to avoid removing\n %these metabolites from the final model (even though they may no longer\n %participate in any reacitons) so that the final model is still able to\n %complete all of the tasks without any errors.\n taskMets = union(vertcat(taskStruct.inputs),vertcat(taskStruct.outputs));\n taskMets = union(taskMets, parseRxnEqu(vertcat(taskStruct.equations)));\n modelMets = strcat(cModel.metNames,'[',cModel.comps(cModel.metComps),']');\n [inModel,metInd] = ismember(taskMets,modelMets);\n essentialMetsForTasks = cModel.mets(metInd(inModel));%118 mets\n\n %Remove tasks that cannot be performed\n taskStruct(taskReport.ok == false) = [];\n\nelse\n essentialRxns = {};\n essentialMetsForTasks = {};\n taskReport = {};\nend\n\n\n% remove metabolites separately to avoid removing those needed for tasks\nunusedMets = cModel.mets(all(cModel.S == 0,2));%1248 in Human-GEM\ncModel = removeMets(cModel, setdiff(unusedMets,essentialMetsForTasks));\n\nif ~isempty(taskStruct)\n\n %Here, we decide on a direction in which the essential reactions should be forced.\n essentialRevDir = false(length(essentialRxns),1);\n pp = zeros(length(essentialRxns),1);\n nn = zeros(length(essentialRxns),1);\n for i = 1:length(selInd)\n pos = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) > 0);\n neg = sum(essentialFluxes(selInd(i),essentialRxnMat(selInd(i),:)) < 0);\n essentialRevDir(i) = pos < neg;\n pp(i) = pos;\n nn(i) = neg;\n end\n\n %sum(pp>0 & nn>0) %0, so it is not a big problem that different tasks share essential \n %reactions but in different directions, at least no such cases exist now, so we ignore this for now.\n\n %Now create a minimal model for the MILP - we want to make this as small as we can, but we\n %don't want to use this later when we create the final models - just for the first MILP.\n %We don't want boundary metabolites in here either.\n\n %We do a trick with the essential rxns here:\n %What we want is to get rid of the reversibility of the reactions, because reversible reactions require\n %an integer each in the MILP, and we can also get the case that it may be cheaper to force flux in the wrong direction, which \n %will probably not give the gap-filling of reactions that we want.\n %So, we simply change the reversible reactions to irreversible, and flip their direction if the direction\n %to force flux in is negative. We don't need to do anything else, runINIT will then handle all essential rxns\n %as irreversible (and will not add any integers etc. for them).\n\n minModel1 = cModel;\n %for the essential rxns where we should force flux in the positive direction, just make them irreversible\n %for the negative direction, we do the same, but also flip the direction of the reaction\n\n %first flip the reactions with negative direction\n %constructEquations(minModel1,minModel1.rxns(selInd(essentialRevDir))) %looks good\n minModel1 = reverseRxns(minModel1, minModel1.rxns(selInd(essentialRevDir)));\n %constructEquations(minModel2,minModel2.rxns(selInd(essentialRevDir))) %looks good\n\n %Then make them irreversible\n minModel1.rev(selInd) = 0;\n minModel1.lb(selInd) = 0;\nelse\n minModel1 = cModel;\nend\n%Now, remove reversibility on any reactions that can only be run in one direction - that simplifies the problem\n%This takes a long time to run (at least an hour or so).\n%This is an important step, we go from 5533 to 3734 reversible rxns, which reduces the size of the MILP,\n%since irreversible rxns are easier to handle.\ndisp('Step 4: Second simplification (~1 hour)')\nminModel2 = simplifyModel(minModel1,false,false,false,false,false,false,true);\n\ndisp('Step 5: Final work')\n\n%Now, merge all linear dependent rxns - this reduces the size of the model a lot.\n%Size goes from 11888 rxns to 7922 rxns for human-GEM, so this is an important step\n[minModel3,origRxnIds,groupIds]=mergeLinear(minModel2, {});\n\n%we now need to figure out what happened to the essential rxns in the merge step above.\n%Note that it would be ideal to run checkTasks on the result from mergeLinear, but that doesn't work.\n%The exchange rxns have in many cases been merged with other reactions, making it difficult to run\n%the tasks. So, instead we run checkTasks before, and figure out which merged reactions the \n%essential reactions belong to now\n\n%It may be possible to create a minModel2b, run mergeLinear on that (which is quick), and \n%then run checkTasks on the minimized model. Would be good to check if this gives the \n%same result, I'm not sure. The code would get less complicated.\n\n\nif ~isempty(taskStruct)\n\n %find all potential rxns\n rxnIndOrig = ismember(origRxnIds, essentialRxns);\n ids = unique(groupIds(rxnIndOrig));\n ids = ids(ids > 0);%0 means it has not been merged\n rxnCandidates = unique([essentialRxns;origRxnIds(ismember(groupIds, ids))]);%388, essentialRxns is 382\n newEssentialRxns = minModel3.rxns(ismember(minModel3.rxns,rxnCandidates));%196 in Human-GEM\n %setdiff(newEssentialRxns, essentialRxns)%only 2, that is very few\n %setdiff(essentialRxns, newEssentialRxns)%188, that is very many\n %It is probably the case that many essential reactions are linearly dependent on one another, which makes sense.\nelse\n newEssentialRxns = {};\nend\n%What is left now is to remove some rxns from the problem, such as exchange rxns and spontaneous rxns.\n%We set the rxn scores of these to exactly 0, and make sure no other scores are zero.\n%runINIT will then handle this, we do >0 and <0 to get positive and negative scores, the rest \n%are not included in the problem.\n%But, this has to happen in the scoring - we identify the reactions in the origrxns here, and then fix this\n%in the scoring for each sample (the function groupRxnScores handles this and is run for each sample).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%identify the reactions to ignore in the minModel2 \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%Identify reactions that should be ignored by tINIT, i.e. tINIT will not remove these regardless of score\n\n\n[~,exchRxnInd] = getExchangeRxns(minModel2);\ntoIgnoreExch = false(numel(minModel2.rxns),1);\ntoIgnoreExch(exchRxnInd) = true;\ntoIgnoreImportRxns = false(numel(minModel2.rxns),1);\ntoIgnoreSimpleTransp = false(numel(minModel2.rxns),1);\ntoIgnoreAdvTransp = false(numel(minModel2.rxns),1);\ntoIgnoreS = false(numel(minModel2.rxns),1);\n\n\n\n%sum(toIgnore) %1500 for Human-GEM\n%find simple transport reactions with no GPRs:\n%We really only skip the reactions with two metabolites\n%where they are the same but different compartments - only skip the transport into the cell for now\nnumMets = sum(minModel2.S ~= 0, 1);\nscomp = find(strcmp(minModel2.comps,extComp));\nfor i = 1:length(minModel2.rxns)\n %check that it has no GPR and that the rxn has two metabolites\n if strcmp(minModel2.grRules(i),'') && (numMets(i) == 2)\n metsComps = minModel2.metComps(minModel2.S(:,i) ~= 0);\n metNames = minModel2.metNames(minModel2.S(:,i) ~= 0);\n if metsComps(1) ~= metsComps(2) && (metsComps(1) == scomp || metsComps(2) == scomp) %different compartments, one is the extComp\n if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction\n toIgnoreImportRxns(i) = true;\n end\n elseif metsComps(1) ~= metsComps(2) %different compartments, no check for extComp\n if strcmp(metNames{1}, metNames{2}) %the same metabolite, it is a transport reaction\n toIgnoreSimpleTransp(i) = true;\n end\n end\n else %check for advanced \n metsInd = find(minModel2.S(:,i) ~= 0);\n %check that we have an even number of mets that is larger than 2 and that we don't have a GPR\n if rem(length(metsInd),2) == 0 && length(metsInd) > 2 && isempty(minModel2.grRules{i})\n %Now check that we have pairs of metabolites that are transported\n SVals = full(minModel2.S(metsInd,i));\n metNames = minModel2.metNames(metsInd);\n comps = minModel2.metComps(metsInd);\n success = true;\n while ~isempty(metNames)\n if length(metNames) < 2 %this should not happen\n error('We should never arrive here!');\n end\n metMatch = find(strcmp(metNames(2:length(metNames)),metNames{1})) + 1;\n if length(metMatch) ~= 1 %we want a match, and only one (if there is some other complex transport rxn, we skip that)\n success = false;\n break;\n end\n if (SVals(1) + SVals(metMatch)) ~= 0 %the stoichiometry is not right\n success = false;\n break;\n end\n if comps(1) == comps(metMatch) %they must be in different compartments (maybe this need not to be checked)\n success = false;\n break;\n end\n %now remove the pair and continue with the next\n SVals([1;metMatch]) = [];\n metNames([1;metMatch]) = [];\n comps([1;metMatch]) = [];\n end\n toIgnoreAdvTransp(i) = success;\n end \n end\nend\n\n%Spontaneous reactions:\ntoIgnoreSpont = ismember(minModel2.rxns, spontRxnNames);%only 10 rxns in human-GEM\n\n%rxns without GPRs in the s compartment (outside the cell)\nsCompInd = find(strcmp(minModel2.comps, extComp));\nfor i = 1:length(minModel2.rxns)\n metsInd = find(minModel2.S(:,i) ~= 0);\n %check that it has more than 1 metabolite (not exch rxn) and no GPR\n if length(metsInd) > 1 && isempty(minModel2.grRules{i})\n if all(minModel2.metComps(metsInd) == sCompInd)\n toIgnoreS(i) = true;\n end\n end\nend\n\ntoIgnoreAllWithoutGPRs = cellfun(@isempty,minModel2.grRules);\n\n\n%sum(toIgnore)%in total 2375 rxns in human-GEM\n%sum(toIgnoreAllTransp)%in total 3337 rxns in human-GEM, so 1,000 more\n\n%Now, try to scale the model to become more favorable for the solver.\n%In general, we try to make all fluxes as similar as possible.\n% There is room for improvement here, this function is pretty simple.\n% It only rescales reactions, while it would be possible to rescale\n% metabolites as well (ROS => kROS, albumin => millialbumin, etc., but\n% scaled freely with a mathematical method). It could potentially open up\n% for using less strict margins in the MILP, and make it run faster.\nscaledMinModel = rescaleModelForINIT(minModel3);\nscaledMinModel.ub(scaledMinModel.ub > 0) = 1000;\nscaledMinModel.lb(scaledMinModel.lb < 0) = -1000;\n\n% create data structure with pre-processing results\nprepData.taskReport = taskReport;\nprepData.essentialRxns = newEssentialRxns; %essential rxns in the minModel\nprepData.taskStruct = taskStruct;\nprepData.refModel = cModel;\nprepData.minModel = scaledMinModel;\nprepData.refModelWithBM = closeModel(cModel); %do this here so we don't have to do this for each sample\nprepData.groupIds = groupIds;\nprepData.essentialMetsForTasks = essentialMetsForTasks;\n\nprepData.toIgnoreExch = toIgnoreExch;\nprepData.toIgnoreImportRxns = toIgnoreImportRxns;\nprepData.toIgnoreSimpleTransp = toIgnoreSimpleTransp;\nprepData.toIgnoreAdvTransp = toIgnoreAdvTransp;\nprepData.toIgnoreSpont = toIgnoreSpont;\nprepData.toIgnoreS = toIgnoreS;\nprepData.toIgnoreCustomRxns = ismember(minModel2.rxns, customRxnsToIgnore);\nprepData.toIgnoreAllWithoutGPRs = toIgnoreAllWithoutGPRs;\n\nend", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/INIT/prepINITModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16745905587445778}} {"text": "function eeg_write_brainstorm(fileprefix,data)\n\n% eeg_write_brainstorm - Write EEG data into brainstorm format\n% \n% Useage: eeg_write_brainstorm(fileprefix, data)\n% \n% file - the path + filename, eg \"c:\\subj_data.mat\"\n% It is actually a fileprefix, as the _data.mat are\n% appended by this function (they are mandatory)\n% \n% data - a matlab structure with brainstorm data fields.\n% There are 2 essential fields (others are initialised):\n% \n% F a matrix of voltage values (in Volts) with\n% electrodes in rows and data points in columns.\n% Time Time is a row vector with time points (in sec)\n% for each column of the voltage data.\n% \n% This script does not convert the voltage data from uV to Volts\n% or the Time from msec to sec. Also, it assumes that the associated\n% Channel struct for this EEG data has the last Channel.Type = 'EEG REF'\n% so the ChannelFlag array output from this function contains a -1 at \n% index = size(data.F,1) + 1.\n% \n% Comment: See the brainstorm website for more info, at\n% http://neuroimage.usc.edu/.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:54 $\n\n% Licence: GNU GPL, no express or implied warranties\n% Author: 07/2001, Darren.Weber_at_radiology.ucsf.edu\n% 10/2002, Darren.Weber_at_radiology.ucsf.edu\n% modified warnings and channelflag\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfprintf('EEG_WRITE_BRAINSTORM...\\n'); tic;\n\nif isfield(data,'F'),\n F = data.F;\nelse\n msg = strcat('data structure must contain an ''F'' field.\\n',...\n 'F is a matrix of voltage values (in Volts)\\n',...\n 'with electrodes in rows and data points in columns.\\n');\n error(sprintf(msg));\nend\nif isfield(data,'Time'),\n Time = data.Time;\nelse\n msg = strcat('data structure must contain a ''Time'' field.\\n',...\n 'Time is a row vector with time points (in sec)\\n',...\n 'for each column of the voltage data.\\n');\n error(sprintf(msg));\nend\nif isfield(data,'ChannelFlag'),\n ChannelFlag = data.ChannelFlag;\nelse\n% msg = strcat('data structure can contain a ''ChannelFlag'' field.\\n',...\n% 'ChannelFlag is a row vector indicating the status\\n',...\n% 'of the electrodes (-1 is dead, 0 is ignored, 1 is good).\\n',...\n% 'Creating this vector = ones(1,size(data.F,1)).\\n');\n% fprintf(msg);\n\n ChannelFlag = [ones(1,size(F,1)), -1];\n fprintf('...assume data Nchannels + 1 is ref, so ChannelFlag(Nchannels + 1) = -1\\n');\nend\nif isfield(data,'NoiseCov'),\n NoiseCov = data.NoiseCov;\nelse\n% msg = strcat('data structure can contain a ''NoiseCov'' field.\\n',...\n% 'This is a square matrix the size of the electrodes\\n',...\n% 'Creating this vector = ones(size(data.F,1)).\\n');\n% fprintf(msg);\n NoiseCov = [];\nend\nif isfield(data,'SourceCov'),\n SourceCov = data.SourceCov;\nelse\n% msg = strcat('data structure can contain a ''SourceCov'' field.\\n',...\n% 'This is a square matrix the size of ImageGridLoc(?)\\n',...\n% 'Creating this matrix = [].\\n');\n% fprintf(msg);\n SourceCov = [];\nend\nif isfield(data,'Project'),\n Projector = data.Project;\nelse\n% msg = strcat('data structure can contain a ''Project'' field.\\n',...\n% 'Not sure what it is, but it is created for the ascii\\n',...\n% 'tutorial data. Creating this matrix = [].\\n');\n% fprintf(msg);\n Project = [];\nend\nif isfield(data,'Projector'),\n Projector = data.Projector;\nelse\n% msg = strcat('data structure can contain a ''Projector'' field.\\n',...\n% 'This is a matrix of size length of electrodes by rank,\\n',...\n% 'not necessarily orthogonal due to Good-Channel selections.\\n',...\n% 'Orthogonalized as ''U'', then the data are to be projected away\\n',...\n% 'from the projector as F'' = F - U*(U^t * F).\\n',...\n% 'Creating this matrix = [].\\n');\n% fprintf(msg);\n Projector = [];\nend\nif isfield(data,'Comment'),\n Comment = data.Comment;\nelse\n% msg = strcat('data structure can contain a ''Comment'' field.\\n',...\n% 'This is a character string describing the data.\\n',...\n% 'Creating this field = file.\\n');\n% fprintf(msg);\n Comment = fileprefix;\nend\nif isfield(data,'Device'),\n Device = data.Device;\nelse\n% msg = strcat('data structure can contain a ''Device'' field.\\n',...\n% 'This is a character string describing the device\\n',...\n% 'used to acquire the data (eg, SYNAMPS)\\n',...\n% 'Creating an empty field.\\n');\n% fprintf(msg);\n Device = 'Neuromag_Planar_122'; % the only supported device!\nend\n\n[path,file,ext] = fileparts(fileprefix);\next = '_data.mat';\n\nfile = fullfile(path,[file ext]);\n\nsave(file,'F','Time','ChannelFlag','NoiseCov','SourceCov',...\n 'Project','Projector','Comment','Device');\n\nfprintf('...wrote brainstorm data to:\\n\\t%s\\n', file);\n\nt = toc; fprintf('...done (%6.2f sec).\\n\\n',t);\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/bioelectromagnetism_ligth/eeg_write_brainstorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16740758118209162}} {"text": "classdef msh\n % MSH: Mesh class\n % Contains, handles, and builds properties of a mesh such as vertices,\n % an element table, bathymetry and ADCIRC style boundary types\n % Copyright (C) 2018 Keith Roberts & William Pringle\n %\n % Class constructor/read a mesh into a msh class.\n %\n % Options are specified as name/value pairs for this class.\n % NB: The file type is determined by suffix extension (e.g., 'fname.14')\n %\n % Usage:\n % obj = msh(varargin)\n %\n % Examples:\n % m = msh(); % returns a blank mesh object.\n % m = msh('fname.14'); % reads in from a fort.14 file\n % m = msh('fname','fname.14','aux',{'blah.13','otherfile.15'}); % reads in a fort.14 along with a fort.13 and fort.15\n % m = msh('points', point_array, 'elements', triangle_table); % reads in from points and elements format.\n %\n % varargin options:\n % i) 'fname' - The filename of the msh file.\n % ii) 'points' - a num_points x 2 array of points\n % iii) 'elements' - a num_elements x 3 array of triangles\n % indexing into points array.\n % iv) 'aux' - a cell-array with filenames of additional\n % files that pair with the mesh\n % v) 'nob' - 0/1 enable/disable the reading of\n % boundary conditions (nodestrings).\n % Default = 0 [i.e., will read in boundary conditions]\n %\n %\n % This program is free software: you can redistribute it and/or modify\n % it under the terms of the GNU General Public License as published by\n % the Free Software Foundation, either version 3 of the License, or\n % (at your option) any later version.\n %\n % This program is distributed in the hope that it will be useful,\n % but WITHOUT ANY WARRANTY; without even the implied warranty of\n % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n % GNU General Public License for more details.\n %\n % You should have received a copy of the GNU General Public License\n % along with this program. If not, see .\n properties\n title % mesh title\n p % vertices\n t % triangles\n b % bathy\n bd % land boundaries\n op % open boundaries\n bx % slope of bathy in x direction\n by % slope of bathy in y direction\n f11 % A structure for the fort11 (initial density) values\n f13 % A struct of the fort13 attributes\n f15 % A struct of the fort15 inputs\n f19 % A struct for the fort19 non-periodic elevation bc\n f20 % A struct for the fort20 non-periodic flux/ele radiation bc\n f24 % A struct of the fort24 SAL values\n f2001 % A struct for the fort2001 non-periodic flux/ele sponge bc\n f5354 % A struct for the fort53001/54001 tidal ele/flux sponge bc\n offset63 % A struct for the offset.63 dynamicwaterlevelcorrection file\n proj % Description of projected space (m_mapv1.4)\n coord % Description of projected space (m_mapv1.4)\n mapvar % Description of projected space (m_mapv1.4)\n pfix % fixed points that were constrained in msh\n egfix % fixed eges that were constraind in msh\n end\n\n methods\n function obj = msh(varargin)\n\n % Check for m_map dir\n if exist('m_proj','file')~=2\n error('The program m_map was not found. Please read the user guide')\n end\n % Check for utilties dir\n if ~exist('inpoly.m','file')\n error('The utilities directory was not found. Please read the user guide')\n end\n % Check for dataset dir\n if exist('datasets','dir')~=7\n warning('We suggest you to place your files in a folder called datasets. Please read the user guide')\n end\n\n % just want a blank mesh object\n if nargin == 0\n obj.title = 'OceanMesh2D';\n return\n end\n\n fname = [];\n aux = {};\n nob = 0;\n % if only one arg. then assume filename of mesh file...\n if nargin == 1\n % Mesh file name\n fname = varargin{1};\n else\n % Otherwise, name value pairs specified.\n % Parse other varargin\n for kk = 1:2:length(varargin)\n if strcmp(varargin{kk},'fname')\n fname = varargin{kk+1};\n elseif strcmp(varargin{kk},'points')\n obj.p = varargin{kk+1};\n elseif strcmp(varargin{kk},'elements')\n obj.t = varargin{kk+1};\n elseif strcmp(varargin{kk},'aux')\n aux = varargin{kk+1};\n elseif strcmp(varargin{kk},'nob')\n nob = varargin{kk+1};\n end\n end\n end\n\n % Return if we filled in points and or elements manually\n if ~isempty(obj.p) || ~isempty(obj.t)\n obj.title = 'Manual Input';\n return;\n end\n\n if isempty(fname)\n help(msh)\n error('See usage instructions above. Please specify the fname of the mesh as a name/value pair...');\n end\n\n if any(contains(fname,'.14')) || any(contains(fname,'.grd'))\n disp('INFO: An ADCIRC fort.14 file will be read...')\n bdflag = 1;\n if nob\n bdflag = 0;\n end\n [t,p,b,op,bd,title] = readfort14(fname,bdflag);\n obj.p = p; obj.t = t; obj.b = b;\n obj.bd = bd; obj.op = op;\n obj.title = title;\n % elseif any(contains(type,'otherformat'))\n % OTHER FORMAT READING GOES HERE.\n else\n % for now only handling fort.14 mesh type\n error('Please specify filename with suffix (e.g., fname.14)');\n end\n % loop over all extra files passed\n for f = 1 : length(aux)\n fname = aux{f};\n if any(contains(fname,'.13'))\n disp('INFO: ADCIRC fort.13 file will be read...')\n obj.f13 = readfort13(fname);\n end\n if any(contains(fname,'.15'))\n disp('INFO: ADCIRC fort.15 file will be read...')\n if isempty(obj.op) || isempty(obj.bd)\n error('Boundary data required to read f15...also read in f14.')\n end\n obj.f15 = readfort15(fname,obj.op,obj.bd);\n end\n if any(contains(fname,'.24'))\n if isempty(obj.p)\n error('No vertices present to readfort24')\n end\n if isempty(obj.f15)\n error(['No f15 present to readfort24.' ...\n ' (make sure fort.15 is listed before' ...\n ' fort.24 in aux cell array)'])\n end\n if obj.f15.ntif == 0\n error('No constituents in f15 to readfort24')\n end\n disp('INFO: ADCIRC fort.24 file will be read...')\n obj.f24 = readfort24( fname, obj.f15.ntif, ...\n length(obj.p), {obj.f15.tipotag.name} );\n end\n end\n\n end\n\n % write mesh to disk\n function write(obj,fname,type,varargin)\n % Usage:\n % write(obj,fname,type,varargin)\n %\n % Examples:\n % write(obj); % writes all available data to fort_1.xx (ADCIRC) files\n % write(obj,fname); % writes all available data to fname.xx (ADCIRC) files\n % write(obj,fname,'14'); % writes mesh data to fname.14 (ADCIRC) file\n % write(obj,fname,'gr3'); % writes mesh data to fname.gr3 (SCHISM) file\n % write(obj,fname,'ww3'); % writes mesh data to fname.ww3 (WaveWatchIII) file\n % write(obj,fname,{'13','14'}); % writes mesh data and f13 attribute data to fname.14 and fname.13 (ADCIRC) files\n % write(obj,fname,'24','netcdf'); % writes fort.24 SAL data to fname.24.nc netcdf file\n if nargin == 1\n fname = 'fort_1';\n end\n if nargin < 3\n if isempty(obj.p)\n error('No mesh, cannot write.')\n end\n\n % renumber it use RCM by default\n %obj = renum(obj) ;\n\n if isempty(obj.b)\n b_t = 0*obj.p(:,1);\n else\n b_t = obj.b;\n end\n writefort14( [fname '.14'], obj.t, obj.p, b_t, ...\n obj.op , obj.bd ,obj.title ) ;\n if ~isempty(obj.f13)\n writefort13( obj.f13, [fname '.13'] );\n end\n if ~isempty(obj.f15)\n writefort15( obj.f15, [fname '.15'], obj.bd );\n end\n if ~isempty(obj.f24)\n writefort24( obj.f24, [fname '.24'], obj.p, varargin);\n end\n if ~isempty(obj.f5354)\n writefort5354( obj.f5354, fname );\n end\n if ~isempty(obj.offset63)\n writeoffset63( obj.offset63, [fname '.offset.63'] );\n end\n else\n if any(contains(type,'14')) || any(contains(type,'ww3')) || ...\n any(contains(type,'gr3'))\n if isempty(obj.p)\n error('No mesh, cannot write.')\n end\n if isempty(obj.b)\n b_t = 0*obj.p(:,1);\n else\n b_t = obj.b;\n end\n if any(contains(type,'14'))\n writefort14( [fname '.14'] , obj.t, obj.p, b_t, ...\n obj.op , obj.bd ,obj.title ) ;\n end\n if any(contains(type,'gr3'))\n if ~isempty(obj.bd)\n % schism only accepts ibtype 0 or 1 for land bcs\n obj.bd.ibtype(obj.bd.ibtype == 21) = 1;\n obj.bd.ibtype(obj.bd.ibtype == 20) = 0;\n end\n writefort14( [fname '.gr3'] , obj.t, obj.p, b_t, ...\n obj.op , obj.bd ,obj.title ) ;\n end\n if any(contains(type,'ww3'))\n writeww3( [fname '.ww3'] , obj.t, obj.p, b_t, ...\n obj.op , obj.title ) ;\n end\n end\n if any(contains(type,'11')) && ~isempty(obj.f11)\n writefort11( obj.f11, [fname '.11'] );\n end\n if any(contains(type,'13')) && ~isempty(obj.f13)\n writefort13( obj.f13, [fname '.13'] );\n end\n if any(contains(type,'15')) && ~isempty(obj.f15)\n writefort15( obj.f15, [fname '.15'], obj.bd );\n end\n if any(contains(type,'19')) && ~isempty(obj.f19)\n writefort19( obj.f19, [fname '.19'] );\n end\n if any(contains(type,'20')) && ~isempty(obj.f20)\n writefort20( obj.f20, [fname '.20'] );\n end\n if any(contains(type,'2001')) && ~isempty(obj.f2001)\n writefort19( obj.f2001, [fname '.2001'] );\n end\n if any(contains(type,'24')) && ~isempty(obj.f24)\n writefort24( obj.f24, [fname '.24'], obj.p, varargin);\n end\n if any(contains(type,'5354')) && ~isempty(obj.f5354)\n writefort5354( obj.f5354, fname );\n end\n if any(contains(type,'offset')) && ~isempty(obj.offset63)\n writeoffset63( obj.offset63, [fname '.offset.63'] );\n end\n end\n end\n\n % general plot function\n function h = plot(obj,varargin)\n % h = plot(obj,varargin)\n %\n % 1) obj: msh object\n %\n % 2) varargin kwargs:\n %\n % 'type': plot type, choose from:\n % a) 'tri' - (default) plots the triangulation\n % b) 'bd' - same as tri but with nodestrings/boundary conditions plotted\n % c) 'ob' - outer boundary of the mesh\n % d) 'b' - plots the bathymetry\n % e) 'slp' - plots the bathymetric gradients\n % f) 'reso' - plots the element circumradius (resolution) based on the projection\n % g) 'resodx' - plots the gradient in 'reso'\n % h) 'qual' - plots the element quality\n % i) 'sponge' - plots the sponge zone/strength coefficients\n % j) 'transect' - plot a bathy transect through GUI\n % k) 'xx' - plots an arbitrary f13 attribute 'xx' by\n % contains search\n %\n % 'type' ADDITIONALS.\n % Add the following words inside the type character string to implement desired behaviors:\n % aa) 'notri': plot without the triangulation (used with 'bd' option)\n % bb) 'earth': use with 'reso' option to plot resolution using element edgelengths on the Earth\n % cc) 'log': use with options that use a colormap to plot the caxis in log space\n % dd) 'mesh': use with options that use a colormap to plot colors on the element\n % edges (a mesh look) instead of on the element faces (a surface look)\n %\n % 'proj': what available m_map projection to plot in e.g.,: 'equi', 'lamb', 'stereo'\n % Select 'none' to plot without the m_map projection.\n % Default is the projection of the msh object.\n %\n % 'subdomain': Plot a subdomain of the mesh bounded by the corner coordinates\n % (a bounding box: [west east; south north])\n %\n % options to refine the look of the plot:\n % i) 'colormap': number of colormap intervals and (optional) range:\n % [num_intervals] or;\n % [num_intervals caxis_lower caxis_upper]\n % ii) 'fontsize': figure fontsize\n % iii) 'backcolor': figure background RGB color (where mesh\n % doesn't exist), default is [1 1 1] => white\n % iv) 'holdon' : =1 to plot on existing figure (otherwise\n % will use new figure)\n % v) 'pivot' : value in meters for which to assume is datum when\n % plotting topo-bathymetry (default 0.0 m)\n % 'axis_limits' : Force the axes limits to be bounded by what\n % is passed in bbox. \n % 'cmap': The name of the cmocean colormap \n % (each option has different default) \n % type 'help cmocean' to see all the colormaps\n % available\n\n fsz = 12; % default font size\n bgc = [1 1 1]; % default background color\n cmap_int = 10; % default num of colormap intervals\n holdon = 0;\n pivot = 0.0; % assume datum is 0.0 m\n proj = 1;\n axis_limits = []; % use mesh extents to determine plot extents\n cmap = 1; % default value is specified in plot method \n leg_ind = [];\n \n projtype = []; \n type = 'tri'; \n subdomain = [];\n for kk = 1:2:length(varargin)\n if strcmp(varargin{kk},'fontsize')\n fsz = varargin{kk+1};\n elseif strcmp(varargin{kk},'backcolor')\n bgc = varargin{kk+1};\n elseif strcmp(varargin{kk},'colormap')\n cmap_int = varargin{kk+1};\n elseif strcmp(varargin{kk},'holdon')\n holdon = varargin{kk+1};\n elseif strcmp(varargin{kk}, 'pivot')\n pivot = varargin{kk+1};\n elseif strcmp(varargin{kk}, 'proj')\n projtype = varargin{kk+1};\n elseif strcmp(varargin{kk},'type')\n type = varargin{kk+1}; \n elseif strcmp(varargin{kk},'subdomain')\n subdomain = varargin{kk+1}; \n elseif strcmp(varargin{kk},'axis_limits')\n axis_limits = varargin{kk+1}; \n elseif strcmp(varargin{kk}, 'cmap')\n cmap = varargin{kk+1}; \n end\n end\n\n % kjr default behavior, just use what's in the .mat file\n if isempty(projtype)\n global MAP_PROJECTION MAP_VAR_LIST MAP_COORDS\n if ~isempty(obj.coord)\n % kjr 2018,10,17; Set up projected space imported from msh class\n MAP_PROJECTION = obj.proj ;\n MAP_VAR_LIST = obj.mapvar ;\n MAP_COORDS = obj.coord ;\n del = 0;\n projtype = MAP_PROJECTION.name;\n else\n error(['no native projection in msh class, please specify the plotting projection: ' ...\n 'plot(m,''type'',''tri'',''proj'',''lamb''), or no projection: plot(m,''type'',''tri'',''proj'',''none'')'])\n end\n end\n\n if strcmp(projtype,'none')\n proj = 0;\n end\n\n % Handle user specified subdomain\n if ~isempty(subdomain)\n % i.e. is a bounding box\n subdomain = [subdomain(1,1) subdomain(2,1);\n subdomain(1,1) subdomain(2,2); ...\n subdomain(1,2) subdomain(2,2);\n subdomain(1,2) subdomain(2,1); ...\n subdomain(1,1) subdomain(2,1)];\n % Get a subdomain given by bou\n [obj,kept] = extract_subdomain(obj,subdomain,'nscreen',0);\n obj = map_mesh_properties(obj,'ind',kept);\n end\n\n % Set up projected space\n del = setProj(obj,proj,projtype,0,axis_limits) ;\n\n if del\n % This deletes any elements straddling the -180/180\n % boundary for plotting purposes (doesn't for stereo)\n xt = [obj.p(obj.t(:,1),1) obj.p(obj.t(:,2),1) ...\n obj.p(obj.t(:,3),1) obj.p(obj.t(:,1),1)];\n dxt = diff(xt,[],2);\n obj.t(abs(dxt(:,1)) > 180 | abs(dxt(:,2)) > 180 | ...\n abs(dxt(:,3)) > 180,:) = [];\n end\n\n logaxis = 0;\n idxl = strfind(type,'log');\n if ~isempty(idxl)\n logaxis = 1; type(idxl:idxl+2) = [];\n end\n mesh = 0;\n idxl = strfind(type,'mesh');\n if ~isempty(idxl)\n mesh = 1; type(idxl:idxl+3) = [];\n end\n earthres = 0;\n idxl = strfind(type,'earth');\n if ~isempty(idxl)\n earthres = 1; type(idxl:idxl+4) = [];\n end\n tri = 1;\n idxl = strfind(type,'notri');\n if ~isempty(idxl)\n tri = 0; type(idxl:idxl+4) = [];\n end\n\n % Make new figure if not holdon\n if ~holdon\n figure;\n end\n hold on\n\n switch type\n % parse aux options first\n case('tri')\n if proj\n m_triplot(obj.p(:,1),obj.p(:,2),obj.t);\n else\n simpplot(obj.p,obj.t);\n end\n case('bd')\n legend_names = {'open ocean boundary','outer no-flux boundary',...\n 'inner no-flux boundary','subgrid scale barriers'};\n if tri\n if proj\n m_triplot(obj.p(:,1),obj.p(:,2),obj.t);\n else\n simpplot(obj.p,obj.t);\n end\n end\n if ~isempty(obj.bd)\n for nb = 1 : obj.bd.nbou\n if obj.bd.ibtype(nb) == 24 || obj.bd.ibtype(nb) == 94\n if sum(leg_ind == 4) == 0\n leg_ind(end+1) = 4;\n end\n if proj\n % plot front facing\n m_plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'g-','linewi',1.2);\n % plot back facing\n h(4) = m_plot(obj.p(obj.bd.ibconn(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.ibconn(1:obj.bd.nvell(nb),nb),2),'y-','linewi',1.2);\n else\n % plot front facing\n plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'g-','linewi',1.2);\n % plot back facing\n h(4) = plot(obj.p(obj.bd.ibconn(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.ibconn(1:obj.bd.nvell(nb),nb),2),'y-','linewi',1.2);\n end\n elseif obj.bd.ibtype(nb) == 20\n if sum(leg_ind == 2) == 0\n leg_ind(end+1) = 2;\n end\n if proj\n h(2) = m_plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'r-','linewi',1.2);\n else\n h(2) = plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'r-','linewi',1.2);\n end\n else\n if sum(leg_ind == 3) == 0\n leg_ind(end+1) = 3;\n end\n if proj\n h(3) = m_plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'g-','linewi',1.2);\n else\n h(3) = plot(obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),1),...\n obj.p(obj.bd.nbvv(1:obj.bd.nvell(nb),nb),2),'g-','linewi',1.2);\n end\n end\n end\n end\n if ~isempty(obj.op)\n for nb = 1 : obj.op.nope\n if sum(leg_ind == 1) == 0\n leg_ind(end+1) = 1;\n end\n if proj\n h(1) = m_plot(obj.p(obj.op.nbdv(1:obj.op.nvdll(nb),nb),1),...\n obj.p(obj.op.nbdv(1:obj.op.nvdll(nb),nb),2),'b-','linewi',3.2);\n else\n h(1) = plot(obj.p(obj.op.nbdv(1:obj.op.nvdll(nb),nb),1),...\n obj.p(obj.op.nbdv(1:obj.op.nvdll(nb),nb),2),'b-','linewi',1.2);\n end\n end\n end\n if isempty(obj.bd) && isempty(obj.op)\n disp('boundaries are empty!');\n end\n case('ob') % outer boundary of mesh\n [~,bpt] = extdom_edges2(obj.t,obj.p);\n if proj\n m_plot(bpt(:,1),bpt(:,2),'r.');\n else\n plot(bpt(:,1),bpt(:,2),'r.');\n end\n case('b')\n if logaxis\n q = log10(max(1,abs(obj.b))); % plot on log scale\n else\n q = obj.b;\n end\n if cmap == 1\n cmap = '-topo'; \n end\n plotter(cmap,1,'depth below datum [m]',true);\n title('mesh topo-bathy');\n case('slp')\n slp = hypot(obj.bx,obj.by);\n if logaxis\n q = log10(slp); % plot on log scale\n else\n q = slp;\n end\n if cmap == 1\n cmap = 'thermal';\n end\n plotter(cmap,3,'topographic gradient',false);\n case('reso')\n % Get bar lengths\n if earthres\n [bars,barlen] = GetBarLengths(obj,0);\n % sort bar lengths in ascending order\n [barlen,IA] = sort(barlen,'descend');\n bars = bars(IA,:);\n % get the minimum bar length for each node\n [B1,IB] = unique(bars(:,1),'last');\n [B2,IC] = unique(bars(:,2),'last');\n d1 = NaN*obj.p(:,1); d2 = NaN*obj.p(:,1);\n d1(B1) = barlen(IB); d2(B2) = barlen(IC);\n z = min(d1,d2);\n yylabel = 'minimum connected bar length [m]';\n else\n % get the points on the current projection\n [X,Y]= m_ll2xy(obj.p(:,1),obj.p(:,2));\n % get the circumcenter radius of each element\n TR = triangulation(obj.t,X,Y);\n [~,cr] = circumcenter(TR);\n % Get the element connectivity\n [vtoe,nne] = VertToEle(obj.t);\n % Make sure null value adds zero contribution\n cr(end+1) = 0;\n vtoe(vtoe == 0) = length(obj.t) + 1;\n % Sum up all element contributions to each node and\n % divide by number of connected elements\n z = sum(cr(vtoe))./nne;\n % scale by earth radius\n Re = 6378.137e3; z = Re*z;\n yylabel = 'element circumradius [m]';\n end\n if logaxis\n q = log10(z); % plot on log scale with base\n else\n q = z;\n end\n if cmap == 1\n cmap = 'thermal';\n end\n plotter(cmap,0,yylabel,false);\n title('mesh resolution');\n case('resodx')\n TR = triangulation(obj.t,obj.p(:,1),obj.p(:,2));\n [cc,cr] = circumcenter(TR);\n for i = 1 : length(obj.t)\n cl = cr(i) ;\n for j = 1 : 3\n z(obj.t(i,j),1) = cl;\n end\n end\n [Hx,Hy] = Unstruc_Bath_Slope( obj.t,obj.p(:,1),obj.p(:,2),z);\n HH = hypot(Hx,Hy);\n if logaxis\n q = log10(HH); % plot on log scale with base\n else\n q = HH;\n end\n if cmap == 1\n cmap = 'balance';\n end\n plotter(cmap,3,'change in resolution',true);\n title('Relaxation rate of topology');\n case('qual')\n q = gettrimeshquan(obj.p, obj.t);\n nq = zeros(length(obj.p),1) + 1.0 ;\n for i = 1 : length(obj.t)\n for j = 1 : 3\n nm = obj.t(i,j);\n nq(nm) = min(nq(nm),q.qm(i));\n end\n end\n if logaxis\n q = log10(nq); % plot on log scale with base\n else\n q = nq;\n end\n if cmap == 1\n cmap = 'matter'; \n end\n plotter(cmap,3,'area-length ratio',false);\n title('Mesh quality metric');\n case('sponge')\n ii = find(contains({obj.f13.defval.Atr(:).AttrName},'sponge'));\n defval = obj.f13.defval.Atr(ii).Val;\n userval = obj.f13.userval.Atr(ii).Val;\n values = userval(2,:);\n if proj\n m_fastscatter(obj.p(:,1),obj.p(:,2),defval(1)*ones(length(obj.p),1));\n m_fastscatter(obj.p(userval(1,:),1),obj.p(userval(1,:),2),values');\n else\n fastscatter(obj.p(:,1),obj.p(:,2),defval(1)*ones(length(obj.p),1));\n fastscatter(obj.p(userval(1,:),1),obj.p(userval(1,:),2),values');\n end\n if cmap == 1 \n cmap = 'deep'; \n end\n colormap(cmocean(cmap));\n colorbar;\n case('transect')\n if proj\n error('To plot transects, you must plot with proj=0!');\n end\n cmap = cmocean('ice',256);\n subplot(2,1,1)\n trisurf(obj.t,obj.p(:,1),obj.p(:,2),obj.b); view(2);\n alpha 0.75\n shading interp;\n colormap(cmap); cb=colorbar; ylabel(cb,'m below geoid');\n axis equal\n h = imline;\n pos = h.getPosition;\n text(pos(1,1),pos(1,2),'Start','color','r');\n text(pos(2,1),pos(2,2),'End','color','r');\n [la,lo]=interpm(pos(:,2),pos(:,1),5/111e3);\n plot(lo,la,'r.')\n transect = [lo,la]; clearvars lo la\n if ~isempty(obj.b)\n F = scatteredInterpolant(obj.p(:,1),obj.p(:,2),obj.b);\n else\n error('Bathy must be on mesh to plot transects!');\n end\n bOnTransect = F(transect) ;\n subplot(2,1,2);\n plot(-bOnTransect,'linewi',2) ;\n disp(mean(bOnTransect))\n title('Bathymetry along transect');\n ylabel('m below geoid');\n xlabel('Points along transect')\n otherwise\n disp(['Trying to plot arbitrary f13 attribute: ' type])\n if ~isempty(obj.f13)\n ii = find(contains({obj.f13.defval.Atr.AttrName},type));\n jj = find(contains({obj.f13.userval.Atr.AttrName},type));\n if isempty(ii)\n error(['no f13 attribute of ' type ' found']);\n elseif length(ii) > 1\n disp({obj.f13.defval.Atr(ii).AttrName})\n error(['more than one f13 attribute matched ' type]);\n end\n defval = obj.f13.defval.Atr(ii).Val;\n userval = obj.f13.userval.Atr(jj).Val;\n defval = reshape(defval,1,[]);\n q = obj.p(:,1)*0 + defval;\n q(userval(1,:),:) = userval(2:end,:)';\n % just take the inf norm\n q = max(q,[],2); \n if logaxis\n q = abs(q); \n q(q == 0) = min(q(q > 0));\n if length(cmap_int) >= 3\n rd = ceil(-log10(cmap_int(2)));\n else\n rd = ceil(-log10(min(q))); \n end\n q = log10(q);\n else\n if length(cmap_int) >= 3 \n rd = ceil(-log10((cmap_int(3)-cmap_int(2))/cmap_int(1)));\n else\n rd = ceil(-log10((max(q) - min(q))/cmap_int(1)));\n end \n end\n if cmap == 1\n cmap = lansey(cmap_int(1)); \n end\n plotter(cmap,rd+1,'',false);\n ax = gca;\n ax.Title.String = obj.f13.defval.Atr(ii).AttrName;\n ax.Title.Interpreter = 'none';\n else\n error('f13 structure is empty!');\n end\n end\n ax = gca;\n ax.FontSize = fsz;\n ax.Color = bgc;\n if proj == 1\n % now add the box\n m_grid('FontSize',fsz,'bac',bgc);\n end\n if ~isempty(leg_ind)\n legend(h(leg_ind),legend_names(leg_ind),'location','best')\n end\n\n function plotter(cmap,round_dec,yylabel,apply_pivot)\n % applies the plot for the quantiy 'q' and specific\n % colormap/colorbar inputs\n if proj\n if mesh\n m_trimesh(obj.t,obj.p(:,1),obj.p(:,2),q);\n else\n m_trisurf(obj.t,obj.p(:,1),obj.p(:,2),q);\n end\n else\n if mesh\n trimesh(obj.t,obj.p(:,1),obj.p(:,2),q);\n else\n trisurf(obj.t,obj.p(:,1),obj.p(:,2),q);\n shading flat;\n end\n view(2);\n end\n numticks = cmap_int(1)+1;\n cb = colorbar;\n if logaxis\n if length(cmap_int) >= 3\n desiredTicks = round(10.^(linspace(...\n log10(cmap_int(2)),...\n log10(cmap_int(3)),numticks)),round_dec);\n else\n desiredTicks = round(10.^(linspace(min(q),...\n max(q),numticks)),round_dec);\n end\n caxis([log10(min(desiredTicks)) log10(max(desiredTicks))]);\n cb.Ticks = log10(desiredTicks);\n for tck = 1 : length(desiredTicks)\n cb.TickLabels{tck} = num2str(desiredTicks(tck));\n end\n else\n if length(cmap_int) >= 3\n desiredTicks = round(linspace(cmap_int(2),...\n cmap_int(3),numticks),round_dec);\n else\n desiredTicks = round(linspace(min(q),...\n max(q),numticks),round_dec);\n end\n caxis([min(desiredTicks) max(desiredTicks)]);\n cb.Ticks = desiredTicks;\n for tck = 1 : length(desiredTicks)\n cb.TickLabels{tck} = num2str(desiredTicks(tck));\n end\n end\n if apply_pivot\n cmocean(cmap,cmap_int(1),'pivot',pivot);\n else\n try \n cmocean(cmap,cmap_int(1));\n catch\n colormap(cmap)\n end\n end\n ylabel(cb,yylabel,'fontsize',fsz);\n end\n % EOF PLOT\n end\n\n % renumber mesh min. bw\n function obj=renum(obj)\n\n np=length(obj.p); nt=length(obj.t);\n % Calculate adjacency matrix of t\n S = sparse(obj.t(:,[1,1,2,2,3,3]),obj.t(:,[2,3,1,3,1,2]),1,np,np);\n W = sum(S,2);\n if any(W==0)\n error('Invalid mesh. Hanging nodes found. Retriangulate.');\n end\n % calc bw\n [i,j] = find(S);\n bw = max(i-j) + 1;\n disp(['Initial bandwidth is ',num2str(bw)]);\n\n % renumber with minimizing bw\n perm = symrcm(S);\n R = S(perm,perm);\n prn = obj.p(perm,:);\n if ~isempty(obj.b)\n obj.b = obj.b(perm);\n end\n\n if ~isempty(obj.bx)\n obj.bx = obj.bx(perm);\n obj.by = obj.by(perm);\n end\n\n if ~isempty(obj.f24)\n obj.f24.Val = obj.f24.Val(:,:,perm);\n end\n\n obj.p = prn;\n perm_inv(perm(1:np)) = ( 1 : np );\n ttemp = obj.t ;\n for ie = 1 : nt\n nm1 = ttemp(ie,1) ;\n nm2 = ttemp(ie,2) ;\n nm3 = ttemp(ie,3) ;\n ttemp(ie,1) = perm_inv(nm1);\n ttemp(ie,2) = perm_inv(nm2);\n ttemp(ie,3) = perm_inv(nm3);\n end\n obj.t = ttemp ;\n % compare bw\n [i,j] = find(R);\n bw = max(i-j) + 1;\n disp(['Renumbered bandwidth is ',num2str(bw)]);\n\n % renum the nodestrings\n if ~isempty(obj.op) && obj.op.nope > 0\n disp('Renumbering the elevation specified boundary nodestrings...');\n for ib = 1 : obj.op.nope\n node = obj.op.nbdv(1:obj.op.nvdll(ib),ib);\n obj.op.nbdv(1:obj.op.nvdll(ib),ib) = perm_inv(node);\n end\n end\n\n if ~isempty(obj.bd) && obj.bd.nbou > 0\n disp('Renumbering the flux boundary nodestrings...');\n for ib = 1 : obj.bd.nbou\n tempcell{ib} = obj.bd.nbvv(1:obj.bd.nvell(ib),ib);\n end\n temp = cell2mat(tempcell');\n ex = find(temp~=0) ;\n temp(ex) = perm_inv(temp(ex))';\n temp = mat2cell(temp,cellfun(@length,tempcell));\n nbvv = zeros(size(obj.bd.nbvv,1),size(obj.bd.nbvv,2));\n for ib = 1 : obj.bd.nbou\n for iv = 1 : obj.bd.nvell(ib)\n nbvv(iv,ib) = temp{ib}(iv,:);\n end\n end\n obj.bd.nbvv = nbvv;\n\n % renumber the various components of the weir connectivity\n if isfield(obj.bd,'ibconn')\n for ib = 1 : obj.bd.nbou\n tempcell{ib} = obj.bd.ibconn(1:obj.bd.nvell(ib),ib);\n end\n temp = cell2mat(tempcell');\n ex = find(temp~=0) ;\n temp(ex) = perm_inv(temp(ex))';\n temp = mat2cell(temp,cellfun(@length,tempcell));\n ibconn = zeros(size(obj.bd.nbvv,1),size(obj.bd.nbvv,2));\n for ib = 1 : obj.bd.nbou\n for iv = 1 : obj.bd.nvell(ib)\n ibconn(iv,ib) = temp{ib}(iv,:);\n end\n end\n obj.bd.ibconn = ibconn;\n end\n end\n\n if ~isempty(obj.f13)\n disp('Renumbering the fort.13...');\n for i = 1 : obj.f13.nAttr\n idx = obj.f13.userval.Atr(i).Val(1,:);\n idx = perm_inv(idx);\n obj.f13.userval.Atr(i).Val(1,:) = idx;\n end\n end\n\n if ~isempty(obj.f5354)\n disp('Renumbering the fort.5354...');\n idx = perm_inv(obj.f5354.nodes);\n obj.f5354.nodes = idx;\n end\n end\n\n % interp bathy/slope\n function obj = interp(obj,geodata,varargin)\n % obj = interp(obj,geodata,varargin)\n % Puts bathy and slopes on the msh obj (a wrapper for GridData).\n % 'geodata' input may be a geodata class or a netCDF dem filename char.\n % 'geodata' may also be a cell array of geodata classes and dems and\n % interp will loop over all them.\n %\n % optional varargins are as follows (copied from GridData):\n % K - vector of relevant nodes to search. This can\n % significantly speed up the calculation by either\n % only interpolating part of the mesh or\n % intepolating whole mesh but in segments. Function\n % automatically removes uncessary portions of DEM\n % Example to call:\n % K = find( obj.p(:,1) >= lon_min & ...\n % obj.p(:,2) <= lon_max);\n % obj = interp(obj,dem,'K',K);\n %\n % type - type is either 'depth', 'slope' or 'all'\n % 'all' is the default (both slope and depth).\n % 'slope' to gets the gradients of DEM\n %\n % interp - interp is either the normal griddedInterpolant\n % options in MATLAB or is 'CA' (default). Note: 'CA'\n % applies linear griddedInterpolant when the DEM\n % and grid sizes are similar.\n %\n % N - enlarge cell-averaging stencil by factor N (only\n % relevant for CA interpolation method).\n % default value N=1.\n %\n % nan - 'fill' to fill in any NaNs everywhere\n % - 'fillinside' to fill NaNs only in DEM extents\n %\n % mindepth - ensure the minimum depth is bounded in the\n % interpolated region\n %\n % maxdepth - ensure the maximum depth is bounded in the\n % interpolated region\n %\n % ignoreOL - = 0 [default]: interpolate data without masking overland\n % = 1 : Mask overland data which may help for seabed-only interpolation\n % slope_calc - = 'rms' [default]: Compute cell-averaged slope based on root-mean-square\n % = 'abs' : Compute cell-averaged slope based on mean of absolute value\n % invert - = 0 : does not invert values of the dem\n % (i.e., keeps the sign of the topography the same as the dem)\n % = 1 [default]: inverts the values of the dem\n % (underwater is positive depth)\n % lut - A look up table (lut). See nlcd and ccap in\n % datasets/ for examples\n \n % if give cell of geodata or dems then interpolate all\n if iscell(geodata) || isstring(geodata)\n for i = 1:length(geodata)\n if isempty(varargin)\n obj = GridData(geodata{i},obj);\n else\n obj = GridData(geodata{i},obj,varargin);\n end\n end\n else\n if isempty(varargin)\n obj = GridData(geodata,obj);\n else\n obj = GridData(geodata,obj,varargin);\n end\n end\n % Inverting if necessary\n invert = 1;\n tI = find(strcmp(varargin,'invert'));\n if ~isempty(tI)\n invert = varargin{tI+1};\n end\n % the output from GridData is underwater positive value so no\n % inversion means flipping back\n if ~invert\n obj.b = -obj.b;\n end\n\n % Checking the data...\n type = 'all';\n tI = find(strcmp(varargin,'type'));\n if ~isempty(tI)\n type = varargin{tI+1};\n end\n % Test for nans\n if strcmp(type,'all') || strcmp(type,'depth')\n % In depths\n Inan = sum(isnan(obj.b));\n if Inan > 0\n warning('NaNs have been found in the bathymetry')\n end\n end\n if strcmp(type,'all') || strcmp(type,'slope')\n % In slope\n Inan = sum(isnan(obj.bx)) + sum(isnan(obj.by));\n if Inan > 0\n warning('NaNs have been found in the slope')\n end\n end\n % Compute slope of b (not the values of bx/by)\n if strcmp(type,'all') || strcmp(type,'depth')\n [edge,elen] = GetBarLengths(obj,0);\n mbe = obj.b(edge);\n slope = abs(diff(mbe,[],2))./elen;\n disp(['Maximum topographic gradient is ' num2str(max(slope))])\n if max(slope) > 0.1\n warning(['Maximum topographic gradient is larger than ' ...\n '0.1, which might cause problems for simulation. ' ...\n 'Consider using the \"lim_bathy_slope\" msh class method']);\n end\n end\n end\n\n function [obj,qual] = clean(obj,varargin)\n % [obj,qual] = clean(obj,varargin)\n % obj - msh object\n % varargin - optional base cleaning type followed by optional\n % name-value pairs as listed below:\n %\n % base cleaning types: 'medium' (or 'default'), 'passive', 'aggressive'\n %\n % optional name-value pairs\n % 'db' - boundary element cutoff quality (0 - 1)\n % 'ds' - perform smoothing? (0 [no], 1 [direct implicit], 2 [hill-climbing])\n % 'con' - upper bound on connectivity (6-19)\n % 'djc' - dj_cutoff (0 - 1 [area portion] or > 1 [km^2])\n % 'sc_maxit' - max iterations for deletion of singly connected\n % elements ( >= 0, if set to 0 operation not performed)\n % 'mqa' - allowable minimum element quality (0 - 1); setting\n % this too value high may prevent convergence\n % 'nscreen' - print info to screen? (default = 1)\n % 'pfix' - fixed points to keep (default empty)\n % 'proj' -to project or not (default = 1)\n\n if ~isempty(varargin)\n if iscell(varargin{1}); varargin = varargin{1}; end\n end\n % keep for parsing to recursive function\n varargino = varargin;\n\n % Fixing up the mesh automatically\n disp('Beginning mesh cleaning and smoothing operations...');\n\n %process categorical cleaning options\n if any(strcmp(varargin,'passive'))\n disp('Employing passive option')\n opt.db = 0.1; opt.ds = 0; opt.con = 0; opt.djc = 0;\n opt.sc_maxit = 0; opt.mqa = 1e-4; opt.renum = 0;\n varargin(strcmp(varargin,'passive')) = [];\n elseif any(strcmp(varargin,'aggressive'))\n disp('Employing aggressive option')\n opt.db = 0.5; opt.ds = 2; opt.con = 9; opt.djc = 0.25;\n opt.sc_maxit = inf; opt.mqa = 0.5; opt.renum = 1;\n varargin(strcmp(varargin,'aggressive')) = [];\n else\n disp('Employing default (medium) option or user-specified opts')\n opt.db = 0.25; opt.ds = 2; opt.con = 9; opt.djc = 0.1;\n opt.sc_maxit = 0; opt.mqa = 0.25; opt.renum = 1;\n varargin(strcmp(varargin,'default')) = [];\n varargin(strcmp(varargin,'medium')) = [];\n end\n % set defaults\n opt.nscreen = 1; opt.projL = 1; pfixV = [];\n % process user-defined individual cleaning options\n optstring = {'nscreen','pfix','proj','con','djc','db','ds',...\n 'sc_maxit','mqa','renum'};\n for ii = 1:2:length(varargin)\n jj = find(strcmp(varargin{ii},optstring));\n if isempty(jj)\n error(['Unrecognized input option: ' varargin{ii}])\n elseif jj == 1\n opt.nscreen = varargin{ii + 1};\n elseif jj == 2\n pfixV = varargin{ii + 1};\n elseif jj == 3\n opt.projL = varargin{ii + 1};\n elseif jj == 4\n opt.con = varargin{ii + 1};\n elseif jj == 5\n opt.djc = varargin{ii + 1};\n elseif jj == 6\n opt.db = varargin{ii + 1};\n elseif jj == 7\n opt.ds = varargin{ii + 1};\n elseif jj == 8\n opt.sc_maxit = varargin{ii + 1};\n elseif jj == 9\n opt.mqa = varargin{ii + 1};\n elseif jj == 10\n obj.renum = varargin{ii + 1};\n end\n end\n\n % display options\n disp('INFO: The following cleaning options have been enabled..')\n disp(opt)\n disp(['length of pfix = ' num2str(length(pfixV))])\n\n if opt.projL\n global MAP_PROJECTION MAP_VAR_LIST MAP_COORDS\n if ~isempty(obj.coord)\n MAP_PROJECTION = obj.proj ;\n MAP_VAR_LIST = obj.mapvar ;\n MAP_COORDS = obj.coord ;\n end\n % transform to projected coordinates\n [obj.p(:,1),obj.p(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n if ~isempty(pfixV)\n [pfixV(:,1),pfixV(:,2)] = m_ll2xy(pfixV(:,1),pfixV(:,2));\n end\n end\n\n % \"fix\" mesh and carry\n obj = fixmeshandcarry(obj);\n\n LT = size(obj.t,1);\n\n if opt.db\n while 1\n % Begin by just deleting poor mesh boundary elements\n tq = gettrimeshquan(obj.p,obj.t);\n % Get the elements that have a boundary bar\n bdbars = extdom_edges2(obj.t,obj.p);\n bdnodes = unique(bdbars(:));\n vtoe = VertToEle(obj.t);\n bele = unique(vtoe(:,bdnodes)); bele(bele == 0) = [];\n tqbou = tq.qm(bele);\n % Delete those boundary elements with quality < opt.db\n if min(tqbou) >= opt.db; break; end\n obj.t(bele(tqbou < opt.db),:) = [];\n obj = fixmeshandcarry(obj);\n end\n if opt.nscreen\n disp(['Deleted ' num2str(LT-size(obj.t,1)) ...\n ' bad boundary elements'])\n end\n % kjr, collapse small triangles together\n [obj.p,obj.t] = ...\n collapse_thin_triangles(obj.p,obj.t,opt.db);\n end\n\n % Make mesh traversable\n obj = Make_Mesh_Boundaries_Traversable(obj,opt.djc,opt.nscreen);\n\n % Delete elements with single edge connectivity\n obj = Fix_single_connec_edge_elements(obj,opt.sc_maxit,opt.nscreen);\n\n % Renumber the mesh here\n if opt.renum\n obj = renum(obj);\n end\n\n % Reduce the mesh connectivity to maximum of con-1\n % May not always work without error\n if opt.con > 6\n try\n obj = bound_con_int(obj,opt.con);\n catch\n warning('Could not reduce connectivity mesh');\n end\n end\n\n % Now do the smoothing if required\n if opt.ds\n if opt.ds == 2\n % Perform the hill-climbing smoothing\n [obj.p,~,obj.t,~] = smooth2(obj.p,[],obj.t);\n else\n % Perform the direct smoothing\n [obj.p,obj.t] = direct_smoother_lur(obj.p,obj.t,...\n pfixV,opt.nscreen);\n end\n end\n\n % Checking and displaying element quality\n tq = gettrimeshquan( obj.p, obj.t);\n mq_m = mean(tq.qm);\n mq_l = min(tq.qm);\n mq_s = std(tq.qm);\n mq_l3sig = mq_m - 3*mq_s;\n qual = [mq_m,mq_l3sig,mq_l];\n LTn = size(obj.t,1);\n\n if mq_l < opt.mqa && LT ~= LTn\n % Need to clean it again\n disp('Poor or overlapping elements, cleaning again')\n disp(['(Min Qual = ' num2str(mq_l) ')'])\n % repeat without projecting (already projected)\n ii = find(strcmp(varargino,'proj'), 1);\n if ~isempty(ii)\n varargino{ii+1} = 0;\n else\n varargino{end+1} = 'proj';\n varargino{end+1} = 0;\n end\n ii = find(strcmp(varargino,'pfix'), 1);\n if ~isempty(ii)\n varargino{ii+1} = pfixV;\n end\n obj = clean(obj,varargino(:));\n elseif opt.nscreen\n disp(['number of nodes is ' num2str(length(obj.p))])\n disp(['mean quality is ' num2str(mq_m)])\n disp(['min quality is ' num2str(mq_l)])\n end\n\n % Do the transformation back\n if opt.projL\n [obj.p(:,1),obj.p(:,2)] = m_xy2ll(obj.p(:,1),obj.p(:,2));\n end\n end\n\n function obj = lim_bathy_slope(obj,dfdx,overland)\n %obj = lim_bathy_slope(obj,dfdx,overland)\n % overland = 0; limits both bathy and topography\n % overland = 1; limits only topography\n % overland = -1; limits only bathy\n if nargin < 3\n overland = 0;\n end\n if overland == 0\n % Call bathy then topo\n obj = lim_bathy_slope(obj,dfdx,-1);\n obj = lim_bathy_slope(obj,dfdx,+1);\n return\n end\n\n % Limit to topo or bathymetric slope to dfdx on the edges\n imax = 100;\n [edge,elen] = GetBarLengths(obj,0);\n bt = obj.b;\n if overland == -1\n I = bt < 0;\n word = 'bathymetric';\n elseif overland == 1\n I = bt > 0;\n word = 'topographic';\n end\n bt(I) = 0;\n bt(~I) = -overland*bt(~I);\n [bnew,flag] = limgrad(edge,elen,bt,dfdx,imax);\n if flag\n obj.b(~I) = -overland*bnew(~I);\n disp(['Successfully limited ' word ' slope to ' ...\n num2str(dfdx) ' in limgrad function'])\n else\n warning(['Could not limit ' word ' slope to ' ...\n num2str(dfdx) ' in limgrad function'])\n end\n end\n\n % re-direct makens to make_bc\n function obj = makens(obj,type,varargin)\n % 'makens' is deprecated. Please use 'make_bc'\n obj = make_bc(obj,type,varargin);\n end\n\n % make_bc: make boundary conditions\n function obj = make_bc(obj,type,varargin)\n % obj = make_bc(obj,type,varargin)\n %\n % Applies boundary conditions to the mesh.\n % Uses the ADCIRC formatting and 'ibtype' integers\n % that refer to the boundary condition type.\n %\n % obj: msh class obj\n % type: 'auto', 'outer', 'inner', 'delete', or 'weirs'\n %\n % ---------\n % 'auto' - automatically applies elevation and no-flux bcs to mesh based on geodata class\n % NB: Use 'auto_outer' option to only apply bcs to the outermost\n % polygon and ignore the islands\n % varargins:\n % varargin{1}: geodata class\n % NB: User may supply an empty varargin{1} if you have interpolated depths\n % to your mesh in which case the 'depth' based classification will be enforced\n % varargin{2} (optional): method of classification:\n % - 'distance': classifies as ocean based on distance to shoreline\n % - 'depth': classifies as ocean based on depth\n % - 'both' [default]: must satisfy both depth and distance criteria\n % varargin{3} (optional):\n % - if varargin{2} is 'distance' or 'both': the distance in geographic degrees\n % from shoreline beyond which edge is classifed as ocean (default is 10*gdat.gridspace)\n % - if varargin{2} is 'depth': the depth below which a boundary is\n % classifed as ocean (default is 10 m)\n % varargin{4} (optional):\n % - if varargin{2} is 'both': the depth below which a boundary is\n % classifed as ocean (default is 10 m)\n % - if varargin{2} is not 'both': the minimum number of\n % vertices for a boundary to be classifed as ocean (default is 10)\n % varargin{5} (optional):\n % - if varargin{2} is 'both': the minimum number of\n % vertices for a boundary to be classifed as ocean (default is 10)\n %\n % ---------\n % 'outer' - applies user-defined bc to a segment of the outer mesh polygon\n % varargins:\n % varargin{1}: direction (0 = anti-clockwise, 1 = clockwise)\n % varargin{2} (optional): vertex # to start at\n % varargin{3} (optional): vertex # to end at\n % varargin{4} (optional): flux (1) or elevation (2) nodestring\n % varargin{5} (optional): if flux, no-flux (20) or river (22) flux nodestring\n %\n % ---------\n % 'inner' - applies no-flux bcs to all inner mesh polygons (i.e., islands)\n % varargins:\n % varargin{1} (optional): ibtype to set (default = 21)\n %\n % ---------\n % 'weirs' - applies weir bcs to all weirs passed in your gdat.\n % varargins:\n % varargin{1}: geodata class that had crestlines passed.\n %\n % ---------\n % 'delete' - deletes a user-clicked land/mainland boundary condition from a msh.\n % varargins:\n % index of land/mainland boundary to delete \n\n if nargin < 2\n error('Needs type: one of \"auto\", \"outer\", \"inner\", \"delete\", or \"weirs\"')\n end\n if iscell(varargin{1})\n varargin = varargin{1};\n end\n L = 1e3;\n switch type\n case{'auto','auto_outer'}\n % automatically applies elevation and no-flux bcs to mesh based on geodata class\n outer_only = false;\n if contains(type,'outer'); outer_only = true; end\n if isempty(varargin)\n error('must supply a geodata class for \"auto\" as third input')\n end\n gdat = varargin{1};\n if isempty(gdat)\n disp(['gdat is empty: enforcing the ' ...\n 'depth-based \"auto\" option.'])\n classifier = 'depth';\n else\n if ~isa(gdat,'geodata')\n error('third input must be a geodata class for \"auto\"')\n end\n dist_lim = 10*gdat.gridspace;\n classifier = 'both';\n end\n depth_lim = -10;\n cut_lim = 10;\n if length(varargin) > 1 && ~isempty(varargin{2})\n classifier = varargin{2};\n end\n switch classifier\n case{'distance'}\n if length(varargin) > 2 && ~isempty(varargin{3})\n dist_lim = varargin{3};\n end\n if length(varargin) > 3 && ~isempty(varargin{4})\n cut_lim = varargin{4};\n end\n case('depth')\n if (isempty(obj.b) || sum(obj.b) == 0) && ...\n (isempty(gdat) || isempty(gdat.Fb))\n if isempty(obj.b) || sum(obj.b) == 0\n warning('No depths on the mesh')\n end\n if ~isempty(gdat) && isempty(gdat.Fb)\n warning('No DEM info in gdat')\n end\n error('Cannot use \"depth\" classification criteria for above reasons')\n end\n if length(varargin) > 2 && ~isempty(varargin{3})\n depth_lim = -varargin{3};\n end\n if length(varargin) > 3 && ~isempty(varargin{4})\n cut_lim = varargin{4};\n end\n case('both')\n if (isempty(obj.b) || sum(obj.b) == 0) && ...\n (isempty(gdat) || isempty(gdat.Fb))\n if isempty(obj.b) || sum(obj.b) == 0\n warning('No depths on the mesh')\n end\n if ~isempty(gdat) && isempty(gdat.Fb)\n warning('No DEM info in gdat')\n end\n error('Cannot use \"both\" classification criteria for above reasons')\n end\n if length(varargin) > 2 && ~isempty(varargin{3})\n dist_lim = varargin{3};\n end\n if length(varargin) > 3 && ~isempty(varargin{4})\n depth_lim = -varargin{4};\n end\n if length(varargin) > 4 && ~isempty(varargin{5})\n cut_lim = varargin{4};\n end\n end\n\n\n % Check for global mesh\n Le = find(obj.p(:,1) < -179, 1);\n Ri = find(obj.p(:,1) > 179, 1);\n if ~isempty(Le) && ~isempty(Ri)\n error('Detected global mesh, cannot apply \"auto\" makens. Try \"inner\" option')\n end\n\n % Get the boundary edges and mid-points\n etbv = extdom_edges2(obj.t,obj.p);\n x = obj.p(:,1); y = obj.p(:,2);\n x_mid = mean(x(etbv),2);\n y_mid = mean(y(etbv),2);\n eb_mid = [x_mid, y_mid];\n clear x y x_mid y_mid\n\n % classify each boundary edge\n % eb_class is 1 if it is classed as ocean\n switch classifier\n case{'both','distance'}\n % process gdat info\n land = [];\n if ~isempty(gdat.mainland)\n land = gdat.mainland;\n land(isnan(land(:,1)),:) = [];\n end\n if ~isempty(gdat.inner)\n inner = gdat.inner;\n inner(isnan(inner(:,1)),:) = [];\n land = [land; inner];\n end\n if ~isempty(land)\n [~,ldst] = ourKNNsearch(land',eb_mid',1);\n else\n % set distance to be larger than dist_lim \n % everywhere when no land exists\n ldst = eb_mid(:,1)*0 + 2*dist_lim\n end \n eb_class = ldst > dist_lim;\n if strcmp(classifier,'both')\n % ii) based on depth\n if ~isempty(obj.b) && sum(abs(obj.b)) > 0\n eb_depth = -mean(obj.b(etbv),2);\n elseif ~isempty(gdat)\n eb_depth = gdat.Fb(eb_mid);\n end\n eb_class = eb_class & eb_depth < depth_lim;\n end\n case('depth')\n % ii) based on depth\n if ~isempty(obj.b) && sum(abs(obj.b)) > 0\n eb_depth = -mean(obj.b(etbv),2);\n elseif ~isempty(gdat)\n eb_depth = gdat.Fb(eb_mid);\n end\n eb_class = eb_depth < depth_lim;\n end\n\n [polys,poly_idxs] = extdom_polygon(etbv,obj.p,1);\n\n % classify each boundary polygon.\n nope = 0; neta = 0; nbou = 0; nvel = 0;\n npolys = length(polys);\n\n for i = 1:npolys\n % Get the edge numbers for this polygon\n idv = poly_idxs{i};\n poly_ed = [idv(1:end-1) idv(2:end)];\n eb_class_t = 0*poly_ed(:,1);\n % make sure that the order of polygon and\n % the order of the edges in etbv are the same\n [~,ed_id1,poly_id1] = intersect(etbv,poly_ed,'rows','stable');\n eb_class_t1 = eb_class(ed_id1);\n eb_class_t(poly_id1) = eb_class_t1;\n [~,ed_id2,poly_id2] = intersect(fliplr(etbv),poly_ed,'rows','stable');\n eb_class_t2 = eb_class(ed_id2);\n eb_class_t(poly_id2) = eb_class_t2;\n\n % check if part of polygon is an ocean\n eb_sum = sum(eb_class_t);\n if eb_sum > 0\n % % Consists of both ocean and mainland\n\n % If a boundary segment is composed of both\n % ocean and mainland, then the whole segment is\n % 'cut up' into segments. Special care is\n % taken to ensure the ocean\n % type boundary starts following then by mainland\n % etc.\n Cuts = find(diff(eb_class_t) ~= 0);\n\n % Do not include open boundary that is\n % smaller than cutlim vertices across\n rm = false(length(Cuts),1);\n if eb_class_t(1)\n st = 2;\n else\n st = 1;\n end\n for ii = st:2:length(Cuts)\n if ii == length(Cuts)\n if length(idv) - Cuts(ii) + ...\n Cuts(1) - 1 < cut_lim\n rm([1 end]) = 1;\n end\n else\n if Cuts(ii+1) - Cuts(ii) < cut_lim\n rm(ii:ii+1) = 1;\n end\n end\n end\n Cuts(rm) = [];\n\n ns = 1;\n for ii = 1:length(Cuts)+1\n if ii > length(Cuts)\n idv_t = [idv(ns:end); idv(1)];\n else\n ne = Cuts(ii);\n idv_t = idv(ns:ne);\n ns = ne;\n end\n if mod(ii,2) == eb_class_t(1)\n % make this segment mainland\n nope = nope + 1;\n nvdll(nope) = length(idv_t);\n neta = neta + nvdll(nope);\n ibtypee(nope) = 0;\n nbdv(1:nvdll(nope),nope) = idv_t';\n else\n % make this segment ocean\n nbou = nbou + 1;\n nvell(nbou) = length(idv_t);\n nvel = nvel + nvell(nbou);\n ibtype(nbou) = 20;\n nbvv(1:nvell(nbou),nbou) = idv_t';\n end\n end\n if outer_only\n break;\n end\n else\n % % polygon is an island\n nbou = nbou + 1;\n nvell(nbou) = length(idv);\n nvel = nvel + nvell(nbou);\n nbvv(1:nvell(nbou),nbou) = idv';\n ibtype(nbou) = 21;\n end\n end\n\n % enter our results in the msh op and bd fields\n if nope > 0\n % ocean boundary\n obj.op.nope = nope ;\n obj.op.neta = neta ;\n obj.op.nvdll = nvdll ;\n obj.op.ibtype = ibtypee ;\n obj.op.nbdv = nbdv;\n end\n\n if nbou > 0\n % land boundary\n obj.bd.nbou = nbou ;\n obj.bd.nvel = nvel ;\n obj.bd.nvell = nvell ;\n obj.bd.ibtype = ibtype ;\n obj.bd.nbvv = nbvv ;\n end\n\n case('auto_old')\n % % keeping the old auto for regression\n if isempty(varargin)\n error('third input must be a geodata class for auto makens')\n end\n gdat = varargin{1};\n if ~isa(gdat,'geodata')\n error('third input must be a geodata class for auto makens')\n end\n cutlim = 10; depthlim = 10;\n if length(varargin) > 1 && ~isempty(varargin{2})\n cutlim = varargin{2};\n end\n if length(varargin) > 2 && ~isempty(varargin{3})\n depthlim = varargin{3};\n end\n % Check for global mesh\n Le = find(obj.p(:,1) < -179, 1);\n Ri = find(obj.p(:,1) > 179, 1);\n if ~isempty(Le) && ~isempty(Ri)\n error('Detected global mesh, cannot apply \"auto\" makens. Try \"inner\" option')\n end\n\n % Get the boundaries\n [etbv,~] = extdom_edges2(obj.t,obj.p);\n [~,poly_idx] = extdom_polygon(etbv,obj.p,1);\n\n outerbox = gdat.outer(1:find(isnan(gdat.outer(:,1)),1,'first'),:);\n if ~isempty(gdat.mainland)\n mainland = gdat.mainland;\n mainland(isnan(mainland(:,1)),:) = [];\n end\n if ~isempty(gdat.inner)\n inner = gdat.inner;\n inner(isnan(inner(:,1)),:) = [];\n end\n\n % Get geodata outer and mainland polygons\n nope = 0; neta = 0; nbou = 0; nvel = 0;\n island_check = true; mainland_been = false;\n\n % loop through all the polygons\n for poly_count = 1 : length(poly_idx)\n idv = poly_idx{poly_count};\n %\n if ~mainland_been\n [~,odst] = ourKNNsearch(outerbox(1:end-1,:)',obj.p(idv,:)',1);\n if ~isempty(gdat.mainland)\n [~,mdst] = ourKNNsearch(mainland',obj.p(idv,:)',1);\n else\n mdst = 1e4;\n end\n end\n if ~isempty(gdat.inner)\n if island_check\n [~,idst] = ourKNNsearch(inner',obj.p(idv,:)',1);\n if min(odst) < min(idst) || ...\n min(mdst) < min(idst)\n island_check = false;\n end\n end\n if island_check || mainland_been\n % must be an island\n nbou = nbou + 1;\n nvell(nbou) = length(idv);\n nvel = nvel + nvell(nbou);\n nbvv(1:nvell(nbou),nbou) = idv';\n ibtype(nbou) = 21;\n continue\n end\n end\n mainland_been = true;\n if ~isempty(gdat.mainland)\n % set the bathy values\n if ~isempty(gdat.Fb)\n zvalue = gdat.Fb(obj.p(idv,:));\n else\n % Dummy all underwater\n zvalue = 0*obj.p(idv,1) - 1e4;\n end\n\n % find the boundaries that are mainland\n main = mdst < odst | zvalue > -depthlim;\n\n % indices of switch\n Cuts = find(diff(main) ~= 0);\n\n % Do not include open boundary that is\n % smaller than cutlim vertices across\n rm = false(length(Cuts),1);\n if main(1); st = 1; else; st = 2; end\n for ii = st:2:length(Cuts)\n if ii == length(Cuts)\n if length(main) - Cuts(ii) + ...\n Cuts(1) - 1 < cutlim\n rm([1 end]) = 1;\n end\n else\n if Cuts(ii+1) - Cuts(ii) < cutlim\n rm(ii:ii+1) = 1;\n end\n end\n end\n Cuts(rm) = [];\n\n if isempty(Cuts)\n if sum(main)/length(main) > 0.5\n % get mainland\n nbou = nbou + 1;\n nvell(nbou) = length(idv);\n nvel = nvel + nvell(nbou);\n ibtype(nbou) = 20;\n nbvv(1:nvell(nbou),nbou) = idv';\n else\n % get ocean\n nope = nope + 1;\n nvdll(nope) = length(idv);\n neta = neta + nvdll(nope);\n ibtypee(nope) = 0;\n nbdv(1:nvdll(nope),nope) = idv';\n end\n else\n % loop through each cut\n for loop = 1:length(Cuts)\n if loop < length(Cuts)\n idv_temp = idv(Cuts(loop):Cuts(loop+1));\n else\n % need to loop back to start\n idv_temp = [idv(Cuts(loop):end); idv(1:Cuts(1))];\n end\n % Break up idv_temp into L chunks\n N = ceil(length(idv_temp)/L);\n LE = ceil(length(idv_temp)/N);\n ns = 1;\n for nn = 1:N\n ne = min(ns + LE - 1,length(idv_temp));\n idv_t = idv_temp(ns:ne);\n if ~main(Cuts(loop)+1)\n % Get ocean\n nope = nope + 1;\n nvdll(nope) = length(idv_t);\n neta = neta + nvdll(nope);\n ibtypee(nope) = 0;\n nbdv(1:nvdll(nope),nope) = idv_t;\n else\n % Get mainland\n nbou = nbou + 1;\n nvell(nbou) = length(idv_t);\n nvel = nvel + nvell(nbou);\n ibtype(nbou) = 20;\n nbvv(1:nvell(nbou),nbou) = idv_t;\n end\n ns = ne + 1;\n end\n end\n end\n else\n % must be ocean\n nope = nope + 1;\n nvdll(nope) = length(idv);\n neta = neta + nvdll(nope);\n ibtypee(nope) = 0;\n nbdv(1:nvdll(nope),nope) = idv';\n end\n end\n\n if nope > 0\n % ocean boundary\n obj.op.nope = nope ;\n obj.op.neta = neta ;\n obj.op.nvdll = nvdll ;\n obj.op.ibtype = ibtypee ;\n obj.op.nbdv = nbdv;\n end\n\n if nbou > 0\n % land boundary\n obj.bd.nbou = nbou ;\n obj.bd.nvel = nvel ;\n obj.bd.nvell = nvell ;\n obj.bd.ibtype = ibtype ;\n obj.bd.nbvv = nbvv ;\n end\n\n case{'inner','islands'}\n\n nbou = 0;\n nvel = 0;\n ibt = 21;\n if ~isempty(varargin)\n ibt = varargin{1};\n end\n disp(['setting ibtype to ' num2str(ibt)])\n\n [etbv,~] = extdom_edges2(obj.t,obj.p);\n [poly,poly_idx,max_ind] = extdom_polygon(etbv,obj.p,1);\n\n % the largest polygon will be a combination of ocean and mainland\n % boundaries. Deal with this first, then remove it from the polygon\n poly(max_ind) = [];\n poly_idx(max_ind) = [];\n\n % loop through the remaining polygons\n nvell = zeros(1,length(poly)); ibtype = nvell + ibt;\n nbvv = zeros(max(cellfun('length',poly_idx)),length(poly));\n for nbou = 1 : length(poly)\n vso = poly{nbou};\n idv = poly_idx{nbou};\n % islands\n nvell(nbou) = length(vso);\n nvel = nvel + nvell(nbou);\n nbvv(1:nvell(nbou),nbou) = int32(idv');\n end\n nbvv = int32(nbvv);\n\n % ocean boundary\n if isempty(obj.op)\n obj.op.nope = 0 ;\n obj.op.neta = 0 ;\n obj.op.nvdll = 0 ;\n obj.op.ibtype = 0 ;\n obj.op.nbdv = 0;\n end\n\n % land boundary\n if nbou == 0\n disp('No islands found!')\n else\n if isempty(obj.bd)\n obj.bd.nbou = nbou ;\n obj.bd.nvel = nvel ;\n obj.bd.nvell = nvell ;\n obj.bd.ibtype = ibtype ;\n obj.bd.nbvv = nbvv ;\n else\n obj.bd.nbou = obj.bd.nbou + nbou ;\n obj.bd.nvel = obj.bd.nvel + nvel ;\n maxold = max(obj.bd.nvell);\n maxnew = max(nvell);\n if maxold < maxnew\n obj.bd.nbvv(end+1:end+maxnew-maxold,:) = 0;\n elseif maxold > maxnew\n nbvv(end+1:end+maxold-maxnew,:) = 0;\n end\n obj.bd.nvell = [obj.bd.nvell nvell];\n obj.bd.ibtype = [obj.bd.ibtype ibtype];\n obj.bd.nbvv = [obj.bd.nbvv nbvv];\n end\n end\n\n case('outer')\n if isempty(varargin)\n error('must specify direction of boundary in third entry')\n end\n dir = varargin{1};\n\n [bnde,bpts] = extdom_edges2(obj.t,obj.p);\n\n if length(varargin) < 3\n % use this to figure out the vstart and vend\n figure, plot(bpts(:,1),bpts(:,2),'k.');\n %hold on; fastscatter(obj.p(:,1),obj.p(:,2),obj.b) ;\n caxis([-10 10]) ; axis equal ;\n title('use data cursor to identify vstart and vend');\n dcm_obj = datacursormode(gcf);\n set(dcm_obj,'UpdateFcn',{@myupdatefcn2,bpts})\n\n % Use data cursor to get the values of the boundary nodes.\n vstart=input('Enter the value for vstart : ');\n vend=input('Enter the value for vend : ');\n\n bndidx = unique(bnde(:));\n vstart = bndidx(vstart);\n vend = bndidx(vend);\n else\n vstart = varargin{2}; vend = varargin{3};\n if length(varargin) >= 4\n type = varargin{4};\n if length(varargin) >= 5\n type2 = varargin{5};\n else\n type2 = type;\n end\n [~,~,obj.op,obj.bd] = extract_boundary(vstart,vend,bnde,obj.p,...\n dir,obj.op,obj.bd,type,type2); %<--updates op and bd.\n return;\n end\n end\n [~,~,obj.op,obj.bd] = extract_boundary(vstart,vend,bnde,obj.p,...\n dir,obj.op,obj.bd); %<--updates op and bd.\n\n case('delete')\n \n temp = obj.bd.nbvv;\n bounodes=obj.bd.nbvv ;\n idx=sum(bounodes~=0);\n bounodes=bounodes(:) ;\n bounodes(bounodes==0)=[] ;\n boupts = obj.p(bounodes,:) ;\n idx2=[0,cumsum(idx)]'+1;\n k = 0 ;\n for i = 1 : length(idx2)-1\n k = k + 1 ;\n bounodes(idx2(i):idx2(i+1)-1,2) = k ;\n end\n \n if isempty(varargin)\n % have the user select the nodestring '\n plot(obj,'type','bd','proj','none') ;\n \n \n dcm_obj = datacursormode(gcf);\n title('use data cursor to select nodestring to be deleted');\n pause\n c_info = getCursorInfo(dcm_obj);\n [tmp(:,1),tmp(:,2)]=m_ll2xy(boupts(:,1),boupts(:,2));\n idx3 = ourKNNsearch(boupts',c_info.Position',1) ;\n del = bounodes(idx3,2) ; %<- get the nodestring index\n pltid = temp(:,del) ; pltid(pltid==0)=[] ;\n hold on; m_plot(obj.p(pltid,1),obj.p(pltid,2),'r-','linewi',2) ;\n else\n del = varargin{1}; \n end\n disp(['Deleting boundary with index ',num2str(del)]) ;\n \n obj.bd.nbvv(:,del)=[];\n if isfield(obj.bd,'ibconn')\n obj.bd.ibconn(:,del)=[];\n obj.bd.barinht(:,del)=[]; \n obj.bd.barincfsb(:,del)=[];\n obj.bd.barincfsp(:,del)=[];\n end\n num_delnodes = idx(del) ;\n obj.bd.nbou = obj.bd.nbou - 1 ;\n obj.bd.nvell(del)=[] ;\n obj.bd.ibtype(del)=[] ;\n obj.bd.nvel = obj.bd.nvel - num_delnodes ;\n\n\n case('weirs')\n if isempty(varargin)\n error('Third input must be a geodata class obj')\n end\n gdat = varargin{1};\n if ~isa(gdat,'geodata')\n error('The third input must be a geodata class object you used create the mesh with.')\n end\n ar = 0; hts = 0; count = 0;\n if length(varargin) > 1 && ~isempty(varargin{2})\n ar = varargin{2};\n end\n if length(varargin) > 2 && ~isempty(varargin{3})\n hts = varargin{3};\n end\n\n % identifying and adding internal weir type boundaries (ibtype=24)\n for ii = 1 : length(gdat.ibconn_pts) % for each weir\n [front_nn, d1] = ourKNNsearch(obj.p',gdat.ibconn_pts{ii}(:,1:2)',1);\n [back_nn, d2] = ourKNNsearch(obj.p',gdat.ibconn_pts{ii}(:,3:4)',1);\n rm = d1 > 1e-9 & d2 > 1e-9;\n front_nn(rm) = [] ; back_nn(rm) = [] ;\n nn = [front_nn,back_nn] ;\n for iii = 1 : length(nn)\n rm2(iii,1)=length(unique(nn(iii,:)))~=2 ;\n end\n front_nn(rm2) = [] ; back_nn(rm2) = [] ;\n clearvars rm2 ;\n % % visualize node pairs\n % plot(obj,'tri',0) ;\n % hold on; plot(obj.p(front_nn,1),obj.p(front_nn,2),'r.') ;\n % hold on; plot(obj.p(back_nn,1),obj.p(back_nn,2),'gs') ;\n\n % add to the boundary struct\n if ~isempty(obj.bd)\n % unpack current boundaries\n nbou = obj.bd.nbou;\n nvel = obj.bd.nvel;\n nvell = obj.bd.nvell;\n nbvv = obj.bd.nbvv;\n ibtype = obj.bd.ibtype;\n\n % append on the weir\n nbou = nbou + 1;\n nvell(nbou) = length(front_nn) ; % only list front facing nodes in nbvv for barriers\n nvel = nvel + nvell(nbou);\n nbvv(1:nvell(nbou),nbou) = front_nn;\n ibtype(nbou) = 24;\n\n % repackage it\n obj.bd.nbou = nbou ;\n obj.bd.nvel = nvel ;\n obj.bd.nvell = nvell ;\n obj.bd.ibtype = ibtype ;\n obj.bd.nbvv = nbvv ;\n else\n % create a new boundary struct\n % initialize arrays\n nbou = 0 ;\n nvel = 0 ;\n nvell = [] ;\n ibtype= [] ;\n nbvv = [] ;\n\n % append on the weir\n nbou = nbou + 1;\n nvell(nbou) = length(front_nn) ; % only list front facing nodes in nbvv for barriers\n nvel = nvel + nvell(nbou);\n nbvv(1:nvell(nbou),nbou) = front_nn;\n ibtype(nbou) = 24;\n\n % package it\n obj.bd.nbou = nbou ;\n obj.bd.nvel = nvel ;\n obj.bd.nvell = nvell ;\n obj.bd.ibtype = ibtype ;\n obj.bd.nbvv = nbvv ;\n end\n\n % either append or create new weir connectivity tables\n if isfield(obj.bd,'ibconn')\n % then append\n ibconn = obj.bd.ibconn ;\n barinht = obj.bd.barinht ;\n barincfsb = obj.bd.barincfsb ;\n barincfsp = obj.bd.barincfsp ;\n ibconn(1:nvell(nbou),nbou) = back_nn ; % only list back facing nodes in ibconn for barriers\n % Opt 1) ask the user for a dataset to give the\n % crestline (barinht) ;\n if ar == 0\n ar = input('Type 1 to enter weir crest height or type 2 to specify dataset...') ;\n if ar==1\n % fixed value for weir crests\n ht = input('Enter value in meters ABOVE the geoid for the height of the weir...') ;\n disp('-----------------------------------------------------------') ;\n elseif ar==2\n % working on it !\n %\n error('NOT WORKING YET')\n end\n else\n count = count + 1;\n ht = hts(count);\n end\n barinht(1:nvell(nbou),nbou) = ht ;\n barincfsb(1:nvell(nbou),nbou) = 1 ; % these are standard values\n barincfsp(1:nvell(nbou),nbou) = 1 ; % these are standard values\n else\n % then create new\n ibconn = nbvv*0 ;\n ibconn(1:nvell(nbou),nbou) = back_nn ; % only list back facing nodes in ibconn for barriers\n barinht = [] ;\n barincfsb = [];\n barincfsp = [] ;\n % Opt 1) ask the user for a dataset to give the crestline\n % height (barinht)\n if ar == 0\n ar = input('Type 1 to enter weir crest height or type 2 to specify dataset...') ;\n if ar==1\n % fixed value for weir crests\n ht = input('Enter value in meters ABOVE the geoid for the height of the weir...') ;\n disp('-----------------------------------------------------------') ;\n elseif ar==2\n % working on it !\n %\n error('NOT WORKING YET')\n end\n else\n count = count + 1;\n ht = hts(count);\n end\n barinht(1:nvell(nbou),nbou) = ht ;\n barincfsb(1:nvell(nbou),nbou) = 1 ; % these are standard values\n barincfsp(1:nvell(nbou),nbou) = 1 ; % these are standard values\n end\n % now add them back\n obj.bd.ibconn = ibconn ;\n obj.bd.barinht = barinht ;\n obj.bd.barincfsb = barincfsb ;\n obj.bd.barincfsp = barincfsp ;\n end\n otherwise\n error(['unrecognized type = ',type])\n end\n\n function txt = myupdatefcn2(~,event_obj,myarray)\n pos = get(event_obj,'Position');\n ind = find(abs(myarray(:,1)-pos(1)) 0\n disp(['Locking points a distance of ' ...\n num2str(lock_dis) ' deg away from intersection'])\n else\n disp(['Locking points more than 2*maximum edge ' ...\n 'length in obj1 away from intersection'])\n end\n end\n %%%%%%%%%%%%%%% end of parsing inpiuts %%%%%%%%%%\n\n p1 = obj1.p; t1 = obj1.t;\n p2 = obj2.p; t2 = obj2.t;\n\n pfix1 = obj1.pfix; nfix1 = length(pfix1);\n pfix2 = obj2.pfix; nfix2 = length(pfix2);\n\n % all combined edge constraints\n nfix = nfix1+nfix2 ;\n pfixx = [pfix1; pfix2] ;\n\n global MAP_PROJECTION MAP_COORDS MAP_VAR_LIST\n if ~isempty(obj2.coord)\n if any(min(obj1.p) < min(obj2.p)) || ...\n any(max(obj1.p) > max(obj2.p))\n objt = obj2; objt.p = [objt.p; obj1.p];\n objt.p(1,:) = min(objt.p) - 1e-3;\n objt.p(2,:) = max(objt.p) + 1e-3;\n setProj(objt,1,obj2.proj.name);\n else\n % kjr 2018,10,17; Set up projected space imported from msh class\n MAP_PROJECTION = obj2.proj ;\n MAP_VAR_LIST = obj2.mapvar ;\n MAP_COORDS = obj2.coord ;\n end\n else\n if max(abs(obj2.p(:,2)) > 85)\n projname = 'stereo';\n else\n projname = 'trans';\n end\n setProj(obj2,1,projname);\n end\n\n % check to see if we can do the trivial merge\n extract = 0;\n if strcmp(type,'matche')\n extract = 1;\n elseif ~strcmp(type,'match')\n try\n cell2 = extdom_polygon(extdom_edges2(t2,p2),p2,-1,0);\n poly_vec2 = cell2mat(cell2');\n [edges2] = Get_poly_edges(poly_vec2);\n catch\n error('Mesh 2 is invalid. Please execute msh.clean on object');\n end\n in = inpoly(obj1.p,poly_vec2,edges2);\n if sum(in) == 0\n disp('no points in obj1 found in obj2, switch to \"match\" case')\n type = 'match';\n end\n end\n\n switch(type)\n case {'match','matche'}\n %% Matching meshes - may be overlapping but there are\n %% vertices that uniquely match so that the overlapping\n %% can be extracted and then obj1, obj2 concentated together\n % extract the inner region of obj1 (inset) from obj2 (base)\n % assuming that the inset fits perfectly in the base\n obj1o = obj1; \n if extract\n [p1(:,1),p1(:,2)] = m_ll2xy(p1(:,1),p1(:,2)) ;\n [p2(:,1),p2(:,2)] = m_ll2xy(p2(:,1),p2(:,2)) ;\n obj1.p = p1; obj2.p = p2;\n bou = get_boundary_of_mesh(obj1,1);\n [~,outer] = max(cellfun(@length,bou));\n [obj2,ind] = extract_subdomain(obj2,bou{outer},...\n 'centroid',1,'keep_inverse',1);\n obj2 = map_mesh_properties(obj2,'ind',ind);\n [obj2.p(:,1),obj2.p(:,2)] = m_xy2ll(obj2.p(:,1),obj2.p(:,2));\n obj2 = obj2.clean(cleanargin);\n clear ind\n end\n % concatenate\n m1 = cat(obj1o,obj2);\n merge = msh(); merge.p = m1.p; merge.t = m1.t;\n obj1 = obj1o;\n clear m1 obj1o\n otherwise\n %% Abitrary non-matching overlapping meshes\n % Project both meshes into the space of the global mesh\n [p1(:,1),p1(:,2)] = m_ll2xy(p1(:,1),p1(:,2)) ;\n [p2(:,1),p2(:,2)] = m_ll2xy(p2(:,1),p2(:,2)) ;\n if nfix > 0\n [pfixx(:,1),pfixx(:,2)] = m_ll2xy(pfixx(:,1),pfixx(:,2));\n end\n\n % checking for weirs in obj1 to keep\n if ~isempty(obj1.bd) && any(obj1.bd.ibtype == 24)\n disp('Weirs found in obj1, extracting to ensure they are preserved')\n [p1,t1,pwin1,twin1] = extractWeirs(p1,t1,obj1);\n end\n\n % checking for weirs in obj2 to keep\n if ~isempty(obj2.bd) && any(obj2.bd.ibtype == 24)\n disp('Weirs found in obj2, extracting to ensure they are preserved')\n [p2,t2,pwin2,twin2] = extractWeirs(p2,t2,obj2);\n end\n\n disp('Forming outer boundary for base...')\n try\n cell2 = extdom_polygon(extdom_edges2(t2,p2),p2,-1,0);\n poly_vec2 = cell2mat(cell2');\n [edges2] = Get_poly_edges(poly_vec2);\n catch\n error('Mesh 2 is invalid. Please execute msh.clean on object');\n end\n\n disp('Forming outer boundary for inset...')\n try\n [cell1] = extdom_polygon(extdom_edges2(t1,p1),p1,-1,0);\n poly_vec1 = cell2mat(cell1');\n [edges1] = Get_poly_edges(poly_vec1);\n catch\n error('Mesh 1 is invalid. Please execute msh.clean on object');\n end\n\n % Delete the region in the global mesh that is in the\n % intersection with inset.\n disp('Deleting intersection...');\n in1 = inpoly(p2(t2(:,1),:),poly_vec1,edges1);\n in2 = inpoly(p2(t2(:,2),:),poly_vec1,edges1);\n in3 = inpoly(p2(t2(:,3),:),poly_vec1,edges1);\n t2(in1 & in2 & in3,:) = [];\n % We need to delete straggling elements that are\n % generated through the above deletion step\n pruned2 = msh() ; pruned2.p = p2; pruned2.t = t2;\n pruned2 = Make_Mesh_Boundaries_Traversable(...\n pruned2,prune_djc,1);\n t2 = pruned2.t; p2 = pruned2.p;\n % get new poly_vec2\n if strcmp(type,'arb')\n cell2 = extdom_polygon(extdom_edges2(t2,p2),p2,-1,0);\n poly_vec2 = cell2mat(cell2');\n [edges2] = Get_poly_edges(poly_vec2);\n end\n\n disp('Merging...')\n DTbase = delaunayTriangulation(p1);\n DTbase.Points(end+(1:length(p2)),:) = p2;\n if nfix > 0\n bdx = ourKNNsearch(DTbase.Points',pfixx',1);\n else\n bdx = [];\n end\n\n % Prune triangles outside both domains.\n disp('Pruning...')\n for ii = 1:2\n % The loop makes sure to remove only small connectivity for the boundaries\n if ii == 2\n % To remove small connectivity or bad elements\n [~, enum] = VertToEle(tm);\n bdbars = extdom_edges2(tm,pm);\n bdnodes = unique(bdbars(:));\n I = find(enum <= 4);\n nn = setdiff(I',[bdx; bdnodes]);\n DTbase.Points(unique(nn),:) = [];\n end\n\n pm = DTbase.Points; tm = DTbase.ConnectivityList;\n\n pmid = (pm(tm(:,1),:)+pm(tm(:,2),:)+pm(tm(:,3),:))/3;\n\n %in1 is inside the inset boundary polygon\n in1 = inpoly(pmid,poly_vec1,edges1);\n\n %in2 is inside the global boundary polygon\n in2 = inpoly(pmid,poly_vec2,edges2);\n\n % remove triangles that aren't in the global mesh or\n % aren't in the inset mesh\n del = (~in1 & ~in2);\n tm(del,:) = [];\n end\n\n merge = msh() ; merge.p = pm; merge.t = tm ;\n\n if ~isempty(cleanargin)\n % convert to degrees to calculate distance\n [t_p1(:,1),t_p1(:,2)] = m_xy2ll(p1(:,1),p1(:,2));\n [t_mrg(:,1),t_mrg(:,2)] = m_xy2ll(merge.p(:,1),merge.p(:,2));\n [t_p2(:,1),t_p2(:,2)] = m_xy2ll(p2(:,1),p2(:,2));\n if lock_dis == 0\n % lock anything vertices more than 2*dmax away\n % from intersection\n [~,dst] = ourKNNsearch(t_p1',t_p1',2);\n dmax = max(dst(:,2));\n lock_dis = 2*dmax;\n end\n % determining the locked vertices\n [~,dst1] = ourKNNsearch(t_p1',t_mrg',1);\n [~,dst2] = ourKNNsearch(t_p2',t_mrg',1);\n locked = [merge.p(dst1 > lock_dis | dst2 > lock_dis,:); pfixx];\n cleanargin{pfix_loc} = locked;\n % iteration is done in clean if smoothing creates neg quality\n merge = clean(merge,cleanargin);\n end\n clear pm tm pmid p1 t1 p2 t2\n\n merge.pfix = pfixx ;\n % edges don't move but they are no longer valid after merger\n merge.egfix = [];\n\n % put the weirs from obj1 back into merge\n if ~isempty(obj1.bd) && any(obj1.bd.ibtype == 24)\n disp('Putting the weirs from obj1 back into merged mesh')\n wm = msh(); wm.p = pwin1; wm.t = twin1;\n merge = cat(merge,wm);\n end\n\n % put the weirs from obj2 back into merge\n if ~isempty(obj2.bd) && any(obj2.bd.ibtype == 24)\n disp('Putting the weirs from obj2 back into merged mesh')\n wm = msh(); wm.p = pwin2; wm.t = twin2;\n merge = cat(merge,wm);\n end\n\n % convert back to lat-lon wgs84\n [merge.p(:,1),merge.p(:,2)] = ...\n m_xy2ll(merge.p(:,1),merge.p(:,2));\n\n if nfix > 0\n [merge.pfix(:,1),merge.pfix(:,2)] = ...\n m_xy2ll(pfixx(:,1),pfixx(:,2));\n end\n end\n\n merge.proj = MAP_PROJECTION ;\n merge.coord = MAP_COORDS ;\n merge.mapvar = MAP_VAR_LIST ;\n\n % Check element order\n merge = CheckElementOrder(merge);\n\n if ~isempty(cleanargin) && ...\n (strcmp(type,'match') || strcmp(type,'matche'))\n % let's clean if match type\n merge = clean(merge,cleanargin);\n end\n\n % Carry over bathy and gradients\n if ~isempty(obj1.b) && ~isempty(obj2.b)\n disp('Carrying over bathy and slope values.')\n merge.b = 0*merge.p(:,1);\n [idx1,dst1] = ourKNNsearch(obj1.p',merge.p',1);\n [idx2,dst2] = ourKNNsearch(obj2.p',merge.p',1);\n merge.b( dst1 <= dst2) = obj1.b( idx1(dst1 <= dst2));\n merge.b( dst2 < dst1 ) = obj2.b( idx2(dst2 < dst1) );\n if ~isempty(obj1.bx) && ~isempty(obj2.bx)\n merge.bx = 0*merge.b; merge.by = 0*merge.b;\n merge.bx(dst2 < dst1) = obj2.bx(idx2(dst2 < dst1));\n merge.bx(dst1 <= dst2) = obj1.bx(idx1(dst1 <= dst2));\n merge.by(dst2 < dst1) = obj2.by(idx2(dst2 < dst1));\n merge.by(dst1 <= dst2) = obj1.by(idx1(dst1 <= dst2));\n end\n end\n\n if ~isempty(obj1.f13)\n disp('Carrying over obj1 f13 data + any corresponding obj2 f13 data')\n if ~isempty(obj2.f13) \n ob2name = {obj2.f13.userval.Atr.AttrName};\n else\n ob2name = {};\n end\n merge.f13 = obj1.f13;\n merge.f13.NumOfNodes = size(merge.p,1);\n for ii = 1:merge.f13.nAttr\n attname = merge.f13.userval.Atr(ii).AttrName;\n idx1 = obj1.f13.userval.Atr(ii).Val(1,:)';\n val1 = obj1.f13.userval.Atr(ii).Val(2:end,:)';\n idx1 = ourKNNsearch(merge.p',obj1.p(idx1,:)',1);\n jj = find(contains(ob2name,attname));\n if ~isempty(jj)\n disp(['Carrying over obj1 and obj2 ' attname]) \n idx2 = obj2.f13.userval.Atr(jj).Val(1,:)';\n val2 = obj2.f13.userval.Atr(jj).Val(2:end,:)';\n idx2 = ourKNNsearch(merge.p',obj2.p(idx2,:)',1);\n idx = [idx1; idx2];\n val = [val1; val2];\n else\n disp(['Carrying over obj1 ' attname]) \n idx = idx1; val = val1;\n end\n [idx,I] = sort(idx,'ascend');\n userval = [double(idx) val(I,:)];\n merge.f13.userval.Atr(ii).Val = userval';\n end\n end\n\n if ~isempty(obj1.bd) && any(obj1.bd.ibtype == 24)\n disp('Carrying over weir nodestrings from obj1.')\n merge = carryoverweirs(merge,obj1);\n end\n\n if ~isempty(obj2.bd) && any(obj2.bd.ibtype == 24)\n disp('Carrying over weir nodestrings from obj2.')\n if exist('obj2o','var'); obj2 = obj2o; end\n merge = carryoverweirs(merge,obj2);\n end\n\n disp('NB: f15, obj2 f13 data not in obj1, non-weir nodestrings etc. are not carried over.')\n\n end\n\n function obj = cat(obj,obj1)\n % obj = cat(obj,obj1)\n % cat two non-overlapping meshes\n pin = obj1.p; tin = obj1.t;\n [~,d] = ourKNNsearch(pin',pin',2);\n d = max(d,[],2); mind = min(d);\n [idx,d] = ourKNNsearch(obj.p',pin',1);\n ind = 1:size(pin,1);\n LIA = ismember(tin(:),ind(d < mind));\n tin(LIA) = idx(tin(LIA));\n tin(~LIA) = tin(~LIA) + length(obj.p);\n obj.p = [obj.p; pin];\n obj.t = [obj.t; tin];\n % append to b and bx, by to avoid error in fixmeshandcarry\n if ~isempty(obj.b)\n obj.b = [obj.b; NaN(size(pin,1),1)];\n end\n if ~isempty(obj.bx)\n obj.bx = [obj.bx; NaN(size(pin,1),1)];\n obj.by = [obj.by; NaN(size(pin,1),1)];\n end\n obj = fixmeshandcarry(obj);\n end\n\n function obj = trim(obj,threshold)\n % obj = trim(obj,threshold)\n % trim a mesh excluding elevations above the threshold\n % (given threshold should be positive for overland)\n if isempty(obj.b) || all(obj.b == 0)\n error('need bathy on mesh')\n end\n bem = max(obj.b(obj.t),[],2); % only trim when all vertices\n obj.t(bem < -threshold,:) = []; % of element are above the threshold.\n obj = fixmeshandcarry(obj);\n end\n\n function obj = fixmeshandcarry(obj)\n % obj = fixmeshandcarry(obj);\n % \"fixes\" mesh and carries mesh properties over\n % e.g., b, bx, by, f13, f24, f5354 dat\n [obj.p,obj.t,pix] = fixmesh(obj.p,obj.t);\n % carry over...\n obj = map_mesh_properties(obj,'ind',pix);\n end\n\n\n function obj = CheckElementOrder(obj,proj)\n if nargin == 1\n proj = 0;\n end\n vx = obj.p(:,1); vy = obj.p(:,2);\n xt = [vx(obj.t(:,1)) vx(obj.t(:,2)) ...\n vx(obj.t(:,3)) vx(obj.t(:,1))];\n yt = [vy(obj.t(:,1)) vy(obj.t(:,2)) ...\n vy(obj.t(:,3)) vy(obj.t(:,1))];\n dxt = diff(xt,[],2);\n dyt = diff(yt,[],2);\n for ii = 1:3\n iii = ii - 1; if iii == 0; iii = 3; end\n I = abs(dxt(:,ii)) > 180 & abs(dxt(:,iii)) > 180;\n xt(I,ii) = xt(I,ii) + 360*sign(dxt(I,ii));\n end\n xt(:,end) = xt(:,1);\n % Get new diff\n dxt = diff(xt,[],2);\n Area = dxt(:,3).*-dyt(:,2) + dxt(:,2).*dyt(:,3);\n if ~isempty(find(Area < 0, 1))\n disp([num2str(sum(Area < 0)) ...\n ' elements found that are not in counterclockwise order'])\n if proj\n global MAP_PROJECTION MAP_VAR_LIST MAP_COORDS\n % kjr 2018,10,17; Set up projected space imported from msh class\n MAP_PROJECTION = obj.proj ;\n MAP_VAR_LIST = obj.mapvar ;\n MAP_COORDS = obj.coord ;\n [pt(:,1),pt(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n else\n pt = obj.p;\n end\n [~,tt] = fixmesh(pt,obj.t);\n obj.t(Area < 0,:) = tt(Area < 0,:);\n obj = CheckElementOrder(obj,~proj);\n else\n disp('All elements now in counterclockwise order')\n end\n end\n\n function obj = carryoverweirs(obj,obj1)\n idx1 = nearest_neighbor_map(obj, obj1,'precise');\n if isempty(obj.bd)\n obj.bd.nbou=0;\n obj.bd.nvell=[];\n obj.bd.nvel=[];\n obj.bd.nbvv=[];\n obj.bd.ibconn=[];\n obj.bd.ibtype=[];\n obj.bd.barinht=[];\n obj.bd.barincfsb=[];\n obj.bd.barincfsp=[];\n end\n % starting boundary number\n startBou = obj.bd.nbou + 1 ;\n % number of new weir boundaries\n jj = obj1.bd.ibtype == 24;\n obj.bd.nbou = obj.bd.nbou + sum(jj);\n % types of boundaries\n obj.bd.ibtype = [obj.bd.ibtype obj1.bd.ibtype(jj)];\n % new boundaries come after what's already on\n obj.bd.nvell = [obj.bd.nvell obj1.bd.nvell(jj)];\n % nvel is twice the number of nodes on each boundary\n obj.bd.nvel = 2*sum(obj.bd.nvell);\n % nbvv is a matrix of boundary nodes\n [nr1,nc1]=size(obj.bd.nbvv);\n nc2 = sum(jj); nr2 = sum(obj1.bd.nvell(jj));\n nbvv_old = obj.bd.nbvv;\n ibconn_old = obj.bd.ibconn;\n barinht_old = obj.bd.barinht;\n barincfsb_old = obj.bd.barincfsb;\n barincfsp_old = obj.bd.barincfsp;\n\n obj.bd.nbvv = zeros(max(nr1,nr2),max(nc1,nc1+nc2));\n obj.bd.ibconn = zeros(max(nr1,nr2),max(nc1,nc1+nc2));\n obj.bd.barinht = zeros(max(nr1,nr2),max(nc1,nc1+nc2));\n obj.bd.barincfsb = zeros(max(nr1,nr2),max(nc1,nc1+nc2));\n obj.bd.barincfsp = zeros(max(nr1,nr2),max(nc1,nc1+nc2));\n\n obj.bd.nbvv(1:nr1,1:nc1)=nbvv_old;\n obj.bd.ibconn(1:nr1,1:nc1)=ibconn_old;\n obj.bd.barinht(1:nr1,1:nc1)=barinht_old;\n obj.bd.barincfsb(1:nr1,1:nc1)=barincfsb_old;\n obj.bd.barincfsp(1:nr1,1:nc1)=barincfsp_old;\n\n % remap\n jj = find(jj);\n for ii = startBou:obj.bd.nbou\n idx = ii - (startBou-1) ;\n idx = jj(idx);\n nodes = full(obj1.bd.nbvv(1:obj1.bd.nvell(idx),idx));\n nodes2 = full(obj1.bd.ibconn(1:obj1.bd.nvell(idx),idx));\n\n obj.bd.nbvv(1:obj.bd.nvell(ii),ii) = idx1(nodes);\n obj.bd.ibconn(1:obj.bd.nvell(ii),ii) = idx1(nodes2);\n obj.bd.barinht(1:obj.bd.nvell(ii),ii) = ...\n obj1.bd.barinht(1:obj1.bd.nvell(idx),idx);\n obj.bd.barincfsb(1:obj.bd.nvell(ii),ii) = ...\n obj1.bd.barincfsb(1:obj1.bd.nvell(idx),idx);\n obj.bd.barincfsp(1:obj.bd.nvell(ii),ii) = ...\n obj1.bd.barincfsp(1:obj1.bd.nvell(idx),idx);\n end\n end\n\n function [out1,barlen,bars] = CalcCFL(obj,dt,type)\n if isempty(obj.b)\n error('Bathymetry is required to estimate the Courant number');\n end\n if nargin < 3\n % use spherical haversine distances\n type = 0;\n end\n\n g = 9.81; % gravity\n [bars,barlen] = GetBarLengths(obj,type);\n % sort bar lengths in ascending order\n [barlen,IA] = sort(barlen,'ascend');\n bars = bars(IA,:);\n % get the minimum bar length for each node\n [B1,IB] = unique(bars(:,1),'first');\n [B2,IC] = unique(bars(:,2),'first');\n d1 = NaN*obj.p(:,1); d2 = NaN*obj.p(:,1);\n d1(B1) = barlen(IB); d2(B2) = barlen(IC);\n d = min(d1,d2);\n\n % wavespeed in ocean (second term represents orbital\n % velocity at 0 degree phase for 1-m amp. wave).\n U = sqrt(g*max(obj.b,1)) + sqrt(g./max(obj.b,1));\n if nargin > 1 && ~isempty(dt)\n % Get CFL from input dt\n CFL = dt*U(:)./d; % <-- from the wave celerity\n out1 = CFL;\n else\n CFL = 1.0;\n dt = d.*CFL./U; % <-- from the wave celerity\n out1 = dt;\n end\n end\n\n function [bars,barlen] = GetBarLengths(obj,type)\n % [bars,barlen] = GetBarLengths(obj,type)\n % Get bars and bar lengths of the elements in msh object\n % set type = 0 for bar lengths computed using Harvesine formula\n % set type = 1 for bar lengths computed using CCP with\n % correction factor for x-direction\n if nargin < 2\n type = 0;\n end\n bars = [obj.t(:,[1,2]); obj.t(:,[1,3]); obj.t(:,[2,3])]; % Interior bars duplicated\n bars = unique(sort(bars,2),'rows'); % Bars as node pairs\n if nargout == 1; return; end\n if type == 0\n % Compute based on Haversine spherical earth distances\n long = zeros(length(bars)*2,1);\n lat = zeros(length(bars)*2,1);\n long(1:2:end) = obj.p(bars(:,1),1);\n long(2:2:end) = obj.p(bars(:,2),1);\n lat(1:2:end) = obj.p(bars(:,1),2);\n lat(2:2:end) = obj.p(bars(:,2),2);\n % Get spherical earth distances for bars\n barlen = m_lldist(long,lat);\n barlen = barlen(1:2:end)*1e3; % L = Bar lengths in meters\n elseif type == 1\n % Compute based on CPP with sfac correction factor for x-direction\n sfea = obj.p(:,2); sfac = cosd(mean(sfea)) ./ cosd(sfea);\n sfacelemid = mean(sfac(obj.t),2);\n vtoe = VertToEle(obj.t);\n vtoe(vtoe == 0) = length(obj.t) + 1;\n sfacelemid(end+1) = NaN;\n conbar1 = vtoe(:,bars(:,1));\n conbar2 = vtoe(:,bars(:,2));\n sfacbar1 = max(sfacelemid(conbar1));\n sfacbar2 = max(sfacelemid(conbar2));\n sfac = max(sfacbar1,sfacbar2)';\n % add safety factor for high latitudes (this is quite critical)\n sfac = sfac.*ceil(sfac/10);\n [x, y] = CPP_conv( obj.p(:,1), obj.p(:,2) );\n barlen = hypot(diff(x(bars),[],2)./sfac,diff(y(bars),[],2));\n end\n\n function [ x,y ] = CPP_conv( lon,lat )\n %CPP_conv Converts lat and lon to x and y\n lon0 = mean(lon) * pi/180; lat0 = mean(lat) * pi/180;\n\n R = 6378206.4;\n lonr = lon * pi/180; latr = lat * pi/180;\n x = R * (lonr - lon0) * cos(lat0);\n y = R * latr;\n end\n end\n\n function obj = bound_courant_number(obj,dt,cr_max,cr_min,varargin)\n % obj = bound_courant_number(obj,dt,cr_max,cr_min,varargin)\n % Decimate/refine a mesh to achieve Cr max/min bounds for\n % optimal numerical performance.\n %\n % Takes a mesh and removes and adds nodes to produce an updated\n % mesh that satisfies the given timestep requirements of the\n % user (i.e., cr_min > Cr(obj) < cr_max)\n %\n % INPUTS\n % dt is the desired timestep to run the simulation (in seconds)\n % cr_max is the desired maximum Courant number (optional,\n % default is 0.5). Set to zero to skip.\n % cr_min is the desired minimum Courant number (optional,\n % default is 0). Set to zero to skip.\n % varargin(1) is maximum number of iterations (maxIT) to attempt bound.\n % by default this is 10.\n %\n % OUTPUTS\n % obj is a mesh where the regions that were modified now\n % respect the Courant bounds.\n\n\n % AUTHORSHIP:\n % kjr, chl, und, 2017 (originally checktimestep)\n % kjr, chl, und, 2018 <--updated for projected spaces\n % wjp, chl, und, 2019 <--updates to carry over slopes and\n % using the msh clean, and CFL calc type option\n % kjr, poli, usp 2020 <--Rewrote and generalized. Now add and as well as delete\n % to achieve min and max. Courant bound.\n\n % Set up input args and catch errors.\n if nargin < 2\n help bound_courant_number\n error('Please supply correct input args...See help printout above');\n end\n\n % no cr_max, use default\n if nargin < 3\n cr_max = 0.5;\n end\n\n % no cr_min supplied\n if nargin < 4\n cr_min = 0;\n end\n % else both cr_max and cr_min have been supplied\n % determine number of maximum iterations\n if nargin > 4\n maxIT = varargin{1};\n else\n maxIT = 10;\n end\n\n disp(['Desired time step is ' num2str(dt) ' s'])\n\n %% Deal with any projection information for accurate bar\n % length calculations.\n type = 0; %<-- 0 == Haversine, 1 == CPP with correction factor\n\n % Conduct initial check of Courant number to return early if possible\n Cr = real(CalcCFL(obj,dt,type));\n if max(Cr) <= cr_max && min(Cr) >= cr_min \n disp('Courant number constraints are already satisfied')\n return\n end\n\n % deleting boundary conditions which are difficult to recompute when\n % the triangulation changes\n obj.bd = []; obj.op = [];\n \n if ~isempty(obj.coord)\n % kjr 2018,10,17; Set up projected space imported from msh class\n global MAP_PROJECTION MAP_VAR_LIST MAP_COORDS\n MAP_PROJECTION = obj.proj ;\n MAP_VAR_LIST = obj.mapvar ;\n MAP_COORDS = obj.coord ;\n else\n lon_mi = min(obj.p(:,1)); lon_ma = max(obj.p(:,1));\n lat_mi = min(obj.p(:,2)); lat_ma = max(obj.p(:,2));\n m_proj('Trans','lon',[lon_mi lon_ma],'lat',[lat_mi lat_ma]) ;\n end\n\n %% Project into space..\n [obj.p(:,1),obj.p(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n\n %% Make bathy interpolant for reprojection later on.\n F = scatteredInterpolant(obj.p(:,1),obj.p(:,2),obj.b,...\n 'linear','nearest');\n\n % OPTIONALLY BOUND THE MAXIMUM COURANT NUMBER BY DELETING\n if cr_max > eps % if cr_max is set to 0 this is skipped\n disp(['Editing the mesh to bound max. Courant number to ' num2str(cr_max)])\n it = 0; % iteration counter\n\n if ~isempty(obj.pfix)\n [pf(:,1),pf(:,2)] = m_ll2xy(obj.pfix(:,1),obj.pfix(:,2));\n else\n pf = [];\n end\n con = 9;\n badnump = 1e10;\n tic\n while 1\n [obj.p(:,1),obj.p(:,2)] = m_xy2ll(obj.p(:,1),obj.p(:,2));\n Cr = real(CalcCFL(obj,dt,type));\n [obj.p(:,1),obj.p(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n bad = Cr > cr_max;\n badnum = sum(bad);\n\n display(['Number of maximum Cr bound violations ',num2str(badnum)]);\n disp(['Max Cr is : ',num2str(max(Cr))]);\n if it == maxIT; break; end\n if badnum == 0; break; end\n if badnump - badnum <= 0; con = con + 1; end\n it = it + 1;\n obj = DecimateTria(obj,bad);\n % Clean up the new mesh (already projected) without direct\n % smoothing (we have used local smooting in DecmimateTria\n obj = clean(obj,'passive','proj',0,'pfix',pf,'con',con);\n % Overwrite the nearest-neighbour interp of b in clean with linear interp\n obj.b = F(obj.p(:,1),obj.p(:,2));\n badnump = badnum;\n end\n toc\n disp(['Achieved max Cr of ',num2str(max(Cr)),...\n ' after ',num2str(it),' iterations.']);\n end\n\n % OPTIONALLY BOUND THE MINIMUM COURANT NUMBER BY REFINING\n if cr_min > eps %if cr_min is set to 0 this is skipped\n disp(['Editing the mesh to bound min. Courant number to ' num2str(cr_min)])\n it = 0; % iteration counter\n\n if ~isempty(obj.pfix)\n [pf(:,1),pf(:,2)] = m_ll2xy(obj.pfix(:,1),obj.pfix(:,2));\n else\n pf = [];\n end\n\n tic\n while 1\n [obj.p(:,1),obj.p(:,2)] = m_xy2ll(obj.p(:,1),obj.p(:,2));\n Cr = real(CalcCFL(obj,dt,type));\n [obj.p(:,1),obj.p(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n bad = Cr < cr_min;\n badnum = sum(bad);\n \n display(['Number of minimum Cr bound violations ',num2str(badnum)]);\n disp(['Min. Cr is : ',num2str(min(Cr))]);\n if it == maxIT; break; end\n if badnum == 0; break; end\n it = it + 1;\n\n % save old msh object for mapping\n obj_old = obj;\n \n % refine select elements using an octree approach\n obj = RefineTrias(obj_old,bad);\n\n % map back properties\n obj = map_mesh_properties(obj,'msh_old',obj_old);\n \n % put bathy back on with linear interp\n obj.b = F(obj.p(:,1),obj.p(:,2));\n\n end\n end\n \n % find nans\n if ~isempty(find(isnan(obj.b), 1))\n warning('NaNs in bathy found')\n end\n\n % convert back to lat-lon wgs84\n [obj.p(:,1),obj.p(:,2)] = m_xy2ll(obj.p(:,1),obj.p(:,2));\n\n % Check Element order\n obj = CheckElementOrder(obj);\n \n % Call itself recursively to make sure both criteria are satisifed\n obj = bound_courant_number(obj,dt,cr_max,cr_min,maxIT);\n \n % Last display message \n disp(['All msh attributes have been carried over except for boundary ' ... \n 'conditions which need to be recomputed. Since the triangulation ' ...\n 'has changed it may pay to recompute other attributes as well']);\n return;\n\n function obj = DecimateTria(obj,bad)\n % helper function to delete triangles to achieve max. Cr\n % bound.\n m_old = obj; % save original mesh object for mapping\n % form outer polygon of mesh for cleaning up.\n poly_cell = get_boundary_of_mesh(obj,1);\n % Deleting any polylines less than three points (last point is NaN)\n poly_cell(cellfun(@length,poly_cell) < 4) = [];\n poly_vec1 = cell2mat(poly_cell');\n clear poly_cell\n [edges1] = Get_poly_edges(poly_vec1);\n % delete the points that violate the cfl, locally retriangulate, and then locally smooth\n DTbase = delaunayTriangulation(obj.p(:,1),obj.p(:,2));\n DTbase.Points(find(bad),:) = [];\n pm = DTbase.Points; tm = DTbase.ConnectivityList;\n pmid = (pm(tm(:,1),:)+pm(tm(:,2),:)+pm(tm(:,3),:))/3;\n in1 = inpoly(pmid,poly_vec1,edges1);\n tm(~in1,:) = []; [pm,tm] = fixmesh(pm,tm);\n % Delete shitty boundary elements iteratively\n badbound = 1;\n while ~isempty(find(badbound, 1))\n tq1 = gettrimeshquan(pm,tm);\n % Get the elements that have a boundary bar\n bnde = extdom_edges2(tm,pm);\n bdnodes = unique(bnde(:));\n vtoe = VertToEle(tm);\n bele = unique(vtoe(:,bdnodes)); bele(bele == 0) = [];\n tqbou = tq1.qm(bele);\n badbound = bele(tqbou < 0.1);\n % Delete those boundary elements with quality < 0.1\n tm(badbound,:) = [];\n end\n [pm,tm] = fixmesh(pm,tm);\n if sum(bad) < size(pm,1)*0.1\n % find all the points nearby each \"bad\" point.\n idx = ourKNNsearch(pm',obj.p(find(bad),:)',12);\n idx = idx(:);\n idx = unique(idx);\n constr = setdiff((1:length(pm))',idx);\n [pm,tm] = smoothmesh(pm,tm,constr,50,0.01);\n else\n warning('Adapation would result in potentially catastrophic lose of connectivity, try adapting to a smaller timestep');\n end\n obj.p = pm; obj.t = tm;\n obj = map_mesh_properties(obj,'msh_old',m_old);\n end\n\n function obj = RefineTrias(obj,bad)\n % helper function to refine triangles to achieve min.\n % Courant bound\n ptemp = obj.p; ttemp = obj.t;\n [vtoe,nne]=VertToEle(ttemp);\n badTrias = vtoe(:,bad);\n badTrias(badTrias==0)=[];\n badTrias=unique(badTrias);\n edges = [ttemp(:,[1,2]); ttemp(:,[1,3]); ttemp(:,[2,3])];\n edges = unique(sort(edges,2),'rows');\n yesrefine = false(length(ttemp),1);\n yesrefine(badTrias,:)=true;\n tnum=ones(length(ttemp),1);\n [pnew,~,tnew] = tridiv2(ptemp,edges,ttemp,tnum,yesrefine);\n obj.p = pnew; obj.t = tnew;\n end\n\n end\n\n\n function obj = CheckTimestep(obj,dt,varargin)\n % This function has been deprecated. Use \"bound_courant_number\" instead.\n % obj = CheckTimestep(obj,dt,varargin)\n % varargin(1) is desired CFL (< 1) or maximum iterations (> 1)\n % varargin(2) is desired dj_cutoff\n %\n % Decimate mesh to achieve CFL condition for stability.\n %\n % Takes a mesh and removes triangles and nodes to produce a mesh\n % that satisfies the given timestep requirements of the user by\n % incrementally modifying the triangulation nearby each edge\n % that violates the CFL.\n % kjr, chl, und, 2017\n % kjr, chl, und, 2018 <--updated for projected spaces\n % wjp, chl, und, 2019 <--updates to carry over slopes and\n % using the msh clean, and CFL calc type option\n\n error('This function has been deprecated. Use \"bound_courant_number\" instead')\n\n end\n\n\n function [] = GatherStationsFromKML(obj,kmlfile,ofname,varargin)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Read a kml file created in google maps to get coordinates of\n % stations that lie within the meshes extents.\n % (Note we can move the stations to reasonable locations off land etc in google\n % maps before exporting to kml).\n %\n %\n % Inputs:\n % obj - msh object\n % kmlfile - kml filename dowloaded from William Pringle's tidal database.\n % ofname - filename of csv containing stations that fall within the mesh.\n % const (optional) - A cell-array of constitutents to validate against.\n % By default will be all major 8 (\n % {'M2','S2','N2','K2','K1','O1','P1','Q1'});\n % Source (optional) - A cell-array of the source databases\n % in order of priority/reliability. By default it is:\n % sources = {'Truth_Pelagic','Truth_Shelf','NOAA','JMA','AUS_Tides',...\n % 'KHAO','GESLA','UHSLC_Fast','Truth_Coast',...\n % 'Various_Publications','ST727','IHO',};\n % Outputs:\n %\n % Author: William Pringle\n % Changes by Keith Roberts: merged code into msh class and added input parser for name/value pairs, 2018-03-22\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% Variables to set\n if nargin < 3, error('Not enough input arguments!'); end\n\n if ~isempty(varargin)\n names = {'const','Source'};\n for ii = 1:length(names)\n ind = find(~cellfun(@isempty,strfind(varargin(1:2:end),names{ii})));\n if ~isempty(ind)\n if ii == 1\n const = varargin{ind*2};\n else\n Source = varargin{ind*2};\n end\n end\n end\n\n else\n % Set the constituents we wanna look at\n const = {'M2','S2','N2','K2','K1','O1','P1','Q1'};\n Source = {'Truth_Pelagic','Truth_Shelf','NOAA','JMA','AUS_Tides',...\n 'KHAO','GESLA','UHSLC_Fast','Truth_Coast',...\n 'Various_Publications','ST727','IHO',};\n end\n\n %% Reading the kml\n T = [];\n for kml = kmlfile\n kmlS = kml2struct(kml{1});\n % Getting rid of unnecessary shit\n T_n = struct2table(kmlS);\n T_n.Geometry = [];\n T_n.BoundingBox = [];\n %T.Description = [];\n T_n = T_n(:,[1 3 4 2 5]);\n T_n.Source = T_n.StyleUrl;\n T_n.StyleUrl = [];\n T = [T; T_n];\n end\n\n %% Convert description to amp and phases\n obs = NaN(height(T),length(const)*2);\n for i = 1:height(T)\n if strcmp(T.Source{i}(end-5:end),'0288D1') % light blue\n T.Source{i} = 'Truth_Pelagic';\n elseif strcmp(T.Source{i}(end-5:end),'FFEA00') % yellow\n T.Source{i} = 'Truth_Shelf';\n elseif strcmp(T.Source{i}(end-5:end),'0F9D58') % green\n T.Source{i} = 'Truth_Coast';\n elseif strcmp(T.Source{i}(end-5:end),'757575') % grey\n T.Source{i} = 'NOAA';\n elseif strcmp(T.Source{i}(end-5:end),'673AB7') % dark purple\n T.Source{i} = 'JMA';\n elseif strcmp(T.Source{i}(end-5:end),'FF5252') % coral\n T.Source{i} = 'KHAO';\n elseif strcmp(T.Source{i}(end-5:end),'7CB342') % light green\n T.Source{i} = 'GESLA';\n elseif strcmp(T.Source{i}(end-5:end),'A52714') % medium red\n T.Source{i} = 'UHSLC_Fast';\n elseif strcmp(T.Source{i}(end-5:end),'FFD600') % austrlian gold\n T.Source{i} = 'AUS_Tides';\n elseif strcmp(T.Source{i}(end-5:end),'880E4F') % dark blue\n T.Source{i} = 'ST727';\n elseif strcmp(T.Source{i}(end-5:end),'3949AB') % dark blue\n T.Source{i} = 'IHO';\n elseif strcmp(T.Source{i}(end-5:end),'9C27B0') % light purple\n T.Source{i} = 'Various_Publications';\n end\n Descrip = T.Description(i); Descrip = Descrip{1};\n cc = 0;\n for c = const\n cc = cc + 1;\n % Get position in description of the constituent\n Positions = regexp(Descrip,[c{1} '_']);\n Positions = find(~cellfun(@isempty,Positions));\n if isempty(Positions); continue; end\n if length(Positions) > 2\n % M2 seasonal shit\n Positions(1:2) = [];\n end\n amp = Descrip(Positions(1));\n s = strfind(amp,' ');\n obs(i,cc*2-1) = str2double(amp{1}(s{1}+1:end));\n phs = Descrip(Positions(2));\n s = strfind(phs,' ');\n obs(i,cc*2) = str2double(phs{1}(s{1}+1:end));\n end\n end\n % Make names\n for ii = 1:length(const)\n const_names{2*ii-1} = [const{ii} '_amp'];\n const_names{2*ii} = [const{ii} '_phs'];\n end\n T1 = array2table(obs,'VariableNames',const_names);\n T.Description = [];\n % Combine\n T = [T T1];\n\n %% Only keep stations within our domain\n bnde = extdom_edges2(obj.t,obj.p);\n poly = extdom_polygon(bnde,obj.p,0);\n\n k=0; poly_vec=[];\n for i = 1 : length(poly)\n for ii = 1 : length(poly{i})\n k = k + 1;\n poly_vec(k,:) = poly{i}(ii,:);\n end\n k = k + 1;\n poly_vec(k,:) = [NaN,NaN];\n end\n edges = Get_poly_edges(poly_vec);\n in = inpoly([T.Lon,T.Lat],poly_vec,edges);\n T = T(in,:);\n %% Delete duplicates\n radius = 0.08/60; % only take one station within 1 min box\n [~,IA] = uniquetol([T.Lon T.Lat],radius,'ByRows',true,...\n 'DataScale',1,'OutputAllIndices',true);\n % Just initialise T_new randomly\n T_new = T(1:length(IA),:);\n delete = []; nn = 0;\n for ii = 1:length(IA)\n T_temp = T(IA{ii},:);\n % We want to pick the source in heirachial order\n for s = Source\n exp_s = regexp(T_temp.Source,s{1});\n exp_s = find(~cellfun(@isempty,exp_s));\n if ~isempty(exp_s)\n if length(exp_s) > 1\n end\n T_new(ii,:) = T_temp(exp_s,:);\n break\n end\n end\n if isempty(exp_s)\n nn = nn + 1;\n delete(nn) = ii;\n end\n end\n T_new(delete,:) = [];\n % sorting\n [~,IA] = sort(T_new.Name);\n T_new = T_new(IA,:);\n [~,IA] = sort(T_new.Source);\n T_new = T_new(IA,:);\n\n %% Write to the .csv\n % Output table of the names and positions\n writetable(T_new(IA,:),ofname)\n % %% Populate the f15\n % % elevation\n % obj.f15.nstae = obj.f15.nstae + numel(find(Sta_type(:,1)));\n % obj.f15.elvstaloc = [obj.f15.elvstaloc;\n % [Sta_lon(Sta_type(:,1) == 1) ...\n % Sta_lat(Sta_type(:,1) == 1)]];\n % obj.f15.elvstaname = [obj.f15.elvstaname;\n % strcat(Sta_name(Sta_type(:,1) == 1),' ID:',...\n % Sta_ID(Sta_type(:,1) == 1))];\n\n end\n\n function [ef,efx,efy]=reconstructEdgefx(obj,efdx)\n % Given a msh object, reconstruct the edge function resolution\n % with a resolution equal to efdx in WGS84 degrees.\n efdx = efdx/111e3;\n\n TR = triangulation(obj.t,obj.p(:,1),obj.p(:,2));\n [~,cr] = circumcenter(TR);\n\n for i = 1 : length(obj.t)\n cl = cr(i) ;\n for j = 1 : 3\n z(obj.t(i,j)) = cl;\n end\n end\n\n bbox = [min(obj.p); max(obj.p)]';\n [efx,efy] = ndgrid(bbox(1,1):efdx:bbox(1,2),...\n bbox(2,1):efdx:bbox(2,2));\n F = scatteredInterpolant(obj.p(:,1),obj.p(:,2),z','linear','linear');\n\n ef = F(efx,efy);\n\n bnde = extdom_edges2(obj.t,obj.p);\n poly1=extdom_polygon(bnde,obj.p,1);\n for i = 1 : length(poly1)\n poly1{i} = [poly1{i} ; NaN NaN];\n end\n poly_vec1=cell2mat(poly1');\n edges1=Get_poly_edges(poly_vec1);\n in = inpoly([efx(:),efy(:)],poly_vec1,edges1);\n ef(~in) = NaN;\n end\n\n function [centroids,bc] = baryc(obj)\n centroids = (obj.p(obj.t(:,1),:)+obj.p(obj.t(:,2),:)+obj.p(obj.t(:,3),:))/3;\n if nargout > 1 && ~isempty(obj.b)\n bc = (obj.b(obj.t(:,1))+obj.b(obj.t(:,2))+obj.b(obj.t(:,3)))/3;\n end\n end\n\n function [obj3] = minus(obj1,obj2)\n % Given two overlapping triangulations described in msh objects\n % obj1 and obj2, remove the triangles in obj1 with centroids\n % that are in the boundary of obj2.\n % Here the notion of \"in\" is defined as being with the polygon\n % that is the boundary of obj2.\n %\n % NOTE: The first mesh must define a region that inclues the region\n % of obj2 but not the entitery, otherwise the algorithm removes\n % all of obj1 and segfaults.\n % Author: keith, und, chl, 2018\n bnde = extdom_edges2(obj2.t,obj2.p);\n poly = extdom_polygon(bnde,obj2.p,-1);\n polyc= cell2mat(poly');\n edges=Get_poly_edges(polyc);\n\n centroids = baryc(obj1) ;\n in = inpoly(centroids,polyc,edges);\n\n tempp = obj1.p;\n tempt = obj1.t;\n\n tempt(in,:) = [] ;\n [tempp,tempt]=fixmesh(tempp,tempt) ;\n\n obj3 = msh();\n obj3.p = tempp; obj3.t = tempt;\n obj3 = renum(obj3);\n\n end\n\n\n function obj = bound_con_int(obj,nvl) %nvu,\n % bound_con_int updates all interior nodes that are connected\n % to more than 7 nodes and less than 21 so that every node is\n % connected to at most 7 nodes. It also makes sure there are no\n % small connectivity less than 5 nodes. A springing routine is used locally\n % to help smooth out the updates. Note that specifying NVL one can\n % fix nodes with connectivity of NVL or higher and leave the others.\n %\n % NOTE: fem_struct.nei should already be a component, if not one is\n % computed.\n %\n %\n % Variables\n % fem_struct -- is the finite element structure from the opnml suite.\n % fem -- the updated finite element structure.\n % Note: fem.x,fem.y,fem.z,fem.e, fem.nei, and fem.ar\n % get updated.\n % fem.bnd does not need to be updated.\n % nvl -- lower limit of connectivity to fix should be 8 <= nvl <= 20\n % nvu -- upper limit of connectivity to fix should be 4 usually\n %\n % Usage -- fem = reduce_con_int(fem_struct);\n %\n % Name: reduce_con_int.m\n % Written by: Ben Holladay (SEAP Student 2004)\n % Date: June 22,2004\n % Modified: Aug. 30, 2004, Chris Massey\n % Jan. 10, 2006, Chris Massey\n % Aug. 15, 2006, Chris Massey - Cleaned up comments.\n % Sept. 19, 2006, Chris Massey -- fixed bug\n % Aug. 22, 2007, Chris Massey -- fixed bug\n % Apr. 25, 2018, Chris Massey -- Added nvl option to fix nodes\n % with connectivity higher than or equal to nvl.\n % Apr. 26, 2018, Keith Roberts--Merged into msh class for\n % OceanMesh software\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % save object for mapping\n obj_old = obj;\n\n % convert msh obj to fem_struct\n bnde=extdom_edges2(obj.t,obj.p);\n fem_struct.x = obj.p(:,1);\n fem_struct.y = obj.p(:,2);\n fem_struct.e = obj.t;\n if ~isempty(obj.b)\n fem_struct.z = obj.b;\n else\n fem_struct.z = obj.p(:,1)*0;\n end\n fem_struct.bnd = bnde;\n fem_struct.ar = fem_struct.z*0.0;\n fem_struct.name= 'temp';\n if ~isempty(obj.f15) || ~isempty(obj.f13)\n warning('Reduce nodal connectivity will migrate your nodal attributes using nearest neighbor interpolation and earse your control file.');\n end\n\n %Ensure the appropriate number of input arguements is given, checks that the\n %fem_struct is valid.\n if nargin == 0\n error('Not enough input arguments; need a valid fem_struct.');\n end\n if ~is_valid_struct(fem_struct)\n error('Input argument to reduce_con_bnd must be a valid fem_struct.');\n end\n % % Make sure that the upper limit of connectivity count falls\n % % no larger than 4 nodes\n % if nargin < 2\n % if nvl > 4\n % disp('Connectivity Upper Limit must not be greater than 4. Resetting');\n % nvu = 4;\n % end\n % else\n % nvu = 4;\n % end\n\n %Make sure that the lower limit of connecitivity count falls between\n % 8 and 20 nodes\n if nargin == 2\n if nvl < 8\n disp('Connectivity Lower Limit must be at least 8. Resetting');\n nvl = 8;\n end\n if nvl > 20\n disp('Connectivity Lower Limit must not be greater than 20. Resetting');\n nvl = 20;\n end\n else\n nvl = 8;\n end\n\n %Sets the intial fem_struct variables and determines the max\n %connectivity. Displays errors if the connectivity is to high.\n\n % List of all nodes not on the boundary;\n tmpnodes = setdiff(1:1:length(fem_struct.x),unique(fem_struct.bnd(:)));\n bndrynodes = unique(fem_struct.bnd(:));\n\n nelems = size(fem_struct.e,1);\n\n % Determine if fem_struct.nei is present, if not added it.\n try\n nc = size(fem_struct.nei(tmpnodes,:),2);\n catch\n disp(' ');\n disp('A neighbor list was not present in the finite element structure.');\n disp('One is being added now.');\n fem_struct.nei = ele2nei(fem_struct.e,fem_struct.x,fem_struct.y);\n disp(' ');\n disp('The neigbor list was successfully added.');\n nc = size(fem_struct.nei(tmpnodes,:),2);\n end\n\n nelems_orig = nelems;\n nnodes_orig = length(fem_struct.x);\n nc_orig = nc;\n\n [~,J1] = find(fem_struct.nei(bndrynodes,:)~=0);\n highbndry = max(J1);\n clear J1\n\n %nsmall = any(fem_struct.nei(j,nvu+1));\n\n if nc > 21\n error(['The connectivity is too high and must be brought down to at least',...\n '20 by hand.']);\n end\n\n if nc <= nvl-1\n disp(['The grids nodal connectivity is not higher than ',num2str(nvl),', nothing will be done.']);\n disp('Returning the original mesh.');\n return\n end\n\n disp(' ')\n disp('NOTE: NO UPDATING IS DONE FOR BOUNDARY NODES.');\n disp(' ')\n\n %Begins loop to update nodes.\n tempr = size(fem_struct.nei,2);\n if tempr < nvl-1 %7\n tempr = 0;\n else\n tmpr = length(find(fem_struct.nei(tmpnodes,nvl)~=0));\n end\n imax = 20;i = 1;\n i2flag = 1;\n fixedint=[];\n disp('Beginning the update loop')\n disp(' ')\n while tempr ~= 0 && i <= imax\n disp(['Pass number ',num2str(i,'%4.0f'),' through the loop'])\n\n %tmpnodes2 = tmpnodes;\n %iupdnn=find(fem_struct.nei(tmpnodes,nvl)~=0); %nodes with high connectivity\n %tmpnodes = tmpnodes(iupdnn);\n %clear tmpnodes2\n nnodes = size(fem_struct.nei(tmpnodes,:),1);\n\n j2 = 1;\n while j2 <= nnodes\n jj = tmpnodes(j2);\n temp2 = fem_struct.nei(jj,nvl); %8;\n if temp2 ~= 0\n testnei = fem_struct.nei(jj,:);\n % TCM -- Begin -- 09/19/2006\n %temp1 = sum(ismember((fem_struct.nei(j,:)),0)); TCM\n %tempnc = nc - temp1; TCM\n tempnc = sum(~ismember((fem_struct.nei(jj,:)),0)); %TCM\n % TCM -- END -- 09/19/2006\n\n disp(['Updating node number ',num2str(jj),' using',' fix ',num2str(tempnc)]);\n switch tempnc\n case {13,14,15,16,17,18,19,20}\n fem_struct = update1320nbr(fem_struct,jj);\n case 12\n fem_struct = update12nbr(fem_struct,jj);\n case 11\n fem_struct = update11nbr(fem_struct,jj);\n case 10\n fem_struct = update10nbr(fem_struct,jj);\n case 9\n fem_struct = update9nbr(fem_struct,jj);\n case 8\n fem_struct = update8nbr(fem_struct,jj);\n otherwise\n disp('Already fixed.')\n end\n if sum(testnei) == sum(fem_struct.nei(jj,:)) %?? What is this test?\n fixedint(i2flag) = jj;\n temp1 = find(fem_struct.nei(jj,:) ~= 0,1,'last');\n fixedintnei(i2flag) = temp1;\n i2flag = i2flag + 1;\n end\n end\n if size(fem_struct.nei,2) < nvl %8\n j2 = nnodes + 1;\n else\n j2 = j2 + 1;\n end\n end\n\n %Check if any nodes where added to the do not update lists.\n try\n fixedint = fixedint;\n fixedintnei = fixedintnei;\n catch\n fixedint = 1:0;\n fixedintnei = 1:0;\n end\n\n %Create do not update list for interior nodes.\n\n %newnei = fem_struct.nei(fixedint,:);\n %temp1 = ismember(fem_struct.nei(fixedint,:),0);\n %temp2 = sum(temp1,2);\n %temp3 = [(size(fem_struct.nei,2))-temp2];\n %temp4 = fixedintnei' - temp3;\n %temp5 = find(temp4 < 0);\n %fixedint(temp5) = [];\n %fixedintnei(temp5) = [];\n %temp6 = size(temp5,1);\n %i2flag = i2flag - temp6;\n\n int = setdiff(1:length(fem_struct.x),bndrynodes);\n\n tmpnodes = setdiff(int,fixedint);\n\n i = i + 1;\n %tmpnodes = setdiff(1:1:length(fem_struct.x),unique(fem_struct.bnd(:)));\n if size(fem_struct.nei,2) > nvl-1\n tempr = length(find(fem_struct.nei(tmpnodes,nvl) ~= 0));\n else\n tempr = 0;\n end\n end\n\n\n\n %Creates the output structure.\n fem = fem_struct;\n [~,J1] = find(fem_struct.nei(tmpnodes,:)~=0);\n highint = max(J1);\n\n fem.nei = fem.nei(:,1:max(highint,highbndry));\n fem = el_areas(fem);\n\n\n % Display a message that we reached the maximum number of loop iterations\n % prior to minimizing the interior nodal connectivity list\n if i>imax && highint > nvl-1 %7\n disp(' ')\n disp(['Maximum loop iteration count of ',num2str(imax),' was',...\n ' exceeded before all interior nodes']);\n disp('reached their miniminal connecitvity.');\n end\n\n % Display a summary of mesh updates.\n disp(' ')\n disp([num2str(size(fem.e,1)-nelems_orig),' elements have been added']);\n disp([num2str(length(fem.x)-nnodes_orig),' nodes have been added']);\n disp(['Maximum interior nodal connectivity was reduced from ',...\n num2str(nc_orig), ' to ',num2str(highint),'.']);\n disp(['The maximum nodal connectivity for a boundary node',...\n ' is ',num2str(highbndry),'.']);\n disp(' ');\n\n\n % kjr convert back to msh obj.\n obj.p = [fem_struct.x,fem_struct.y];\n obj.t = fem_struct.e;\n obj = map_mesh_properties(obj,'msh_old',obj_old);\n end\n\n function obj = flipEdge(obj,j,k)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %Line_swap is mesh refining tool that swaps an edge that two elements\n % share. It reconnects the elements so that the edge they share has been\n % flipped. This routine only operates on one line at a time and can only be\n % used if the two elements share an edge. This routine can operate on any\n % elemnet, even boundry elements, unless the new elements formed by the line\n % swap would overlap existing elements. No nodes are moved by this routine.\n % The fem.e and fem.ar are the only fields that are updated. If no .nei file\n % is present then none will be generated; however, if one is present then\n % it will be updated to reflect the new connectivity.\n %\n % Calls: is_valid_struct.m\n %\n % Usage: fem = line_swap(fem_struct,j,k);\n %\n % Variables:\n % fem -- the new split finite element mesh.\n % fem_struct -- the finite element grid structure from the opnml suite.\n % Note: fem_struct.nei will not be generated if not present\n % j -- element number for one element used in the line swap.\n % k -- element number for one element used in the line swap.\n % Note: j and k can be interchanged.\n %\n % Filename: line_swap.m\n % Created by: Ben Holladay\n % Date: June 8, 2005\n % Last Modified:\n % Oct. 26, 2007 -- Chris Massey, NRL 7322\n % Changed when line swap can not be performed due to mesh tangling,\n % from an error call to a display message and return original fem.\n % Last Modified:\n % Added into msh class for OceanMesh2D software--kjr, chl, und,\n % April 2018.\n %%%\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % convert msh obj to fem_struct\n bnde=extdom_edges2(obj.t,obj.p);\n fem_struct.x = obj.p(:,1);\n fem_struct.y = obj.p(:,2);\n fem_struct.e = obj.t;\n if ~isempty(obj.b)\n fem_struct.z = obj.b;\n else\n fem_struct.z = obj.p(:,1)*0;\n end\n fem_struct.bnd = bnde;\n fem_struct.ar = obj.b*0.0;\n fem_struct.name= 'temp';\n if ~isempty(obj.f15) || ~isempty(obj.f13)\n warning('Reduce nodal connectivity will erase your nodal attributes and control file. Go on?');\n pause\n end\n\n %Ensure the apropriate number of input arguements is given, checks that the\n %fem_struct is valid.\n if nargin == 0\n error('Not enough input arguments; need a fem_struct and two element numbers.');\n end\n if ~is_valid_struct(fem_struct)\n error('Input argument to line swap must be a valid fem_struct.');\n end\n if nargin == 1\n error(['Input arguments must include a valid fem_struct and two element ' , ...\n 'numbers that share an edge.']);\n elseif nargin == 2\n error('Two element numbers must be given.');\n elseif nargin == 3\n if j <= 0 | j > size(fem_struct.e,1) | j ~= floor(j)\n error(['Element numbers must positive integers that are less than ',...\n 'the maximum number of elements.']);\n end\n if k <= 0 | k > size(fem_struct.e,1) | k ~= floor(k)\n error(['Element numbers must positive integers that are less than ',...\n 'the maximum number of elements.']);\n end\n else\n error('Too many input arguments.');\n end\n\n\n %Sets the intial fem_struct variables.\n x = fem_struct.x;\n y = fem_struct.y;\n enodes = fem_struct.e;\n ar = fem_struct.ar;\n\n %Determine if the elements share a common edge.\n elems = enodes([j;k],:);\n comp = unique(intersect(elems(1,:),elems(2,:)));\n if length(comp) < 2\n error('The elements do not share a common edge.');\n end\n\n %Indentify each node for swapping.\n [nodes,ti,tj] = unique(elems);\n temp1 = setdiff((1:6),ti);\n temp1 = elems(temp1);\n temp2 = setdiff(nodes,temp1);\n\n %Determine if the angle between the elements is too big for line_swap to\n %effectively operate on it.\n a2 = (x(enodes([j;k],3))-x(enodes([j;k],2))).^2+(y(enodes([j;k],3))-y(enodes([j;k],2))).^2;\n b2 = (x(enodes([j;k],1))-x(enodes([j;k],3))).^2+(y(enodes([j;k],1))-y(enodes([j;k],3))).^2;\n c2 = (x(enodes([j;k],2))-x(enodes([j;k],1))).^2+(y(enodes([j;k],2))-y(enodes([j;k],1))).^2;\n A = (180/pi)*acos((b2+c2-a2)./(2*sqrt(b2).*sqrt(c2)));\n B = (180/pi)*acos((c2+a2-b2)./(2*sqrt(c2).*sqrt(a2)));\n C = (180/pi)*acos((a2+b2-c2)./(2*sqrt(a2).*sqrt(b2)));\n ang = [A,B,C];\n temp3 = find(temp1(1) == elems);\n temp4 = find(temp1(2) == elems);\n temp5 = ang(temp3);\n temp6 = ang(temp4);\n temp5 = sum(temp5);\n temp6 = sum(temp6);\n if temp5 >= 180 | temp6 >= 180\n disp(['The line cannot be swapped because the new elements would '...\n 'create overlapping elements.']);\n fem = fem_struct;\n return\n elseif temp5 >= 135 | temp6 >= 135\n disp(['Warning: The elements created will contain large angles.']);\n end\n clear a2 b2 c2 A B C ang\n\n %Swap the lines in the enodes list.\n temp3 = setdiff(elems(1,:),temp1);\n temp4 = setdiff(elems(2,:),temp1);\n temp5 = find(elems(1,:) == temp1(1));\n elems(1,temp5) = temp4;\n temp6 = find(elems(2,:) == temp1(2));\n elems(2,temp6) = temp3;\n clear temp5 temp6;\n\n %Recomputes the areas for the new elements.\n xnodes = x(elems);\n ynodes = y(elems);\n temparea = 0.5*(xnodes(:,1).*(ynodes(:,2)-ynodes(:,3))+xnodes(:,2).*...\n (ynodes(:,3)-ynodes(:,1))+xnodes(:,3).*(ynodes(:,1)-ynodes(:,2)));\n clear xnodes ynodes x y;\n\n %Addes the new elements and areas to the global lists.\n enodes([j;k,],:) = elems;\n ar([j;k]) = temparea(:);\n clear elems temparea;\n\n %Create the output structure.\n fem = fem_struct;\n fem.e = enodes;\n fem.ar = ar;\n\n %Updates the nei if present.\n try\n nei = fem_struct.nei;\n nei = [nei,zeros((size(nei,1)),1)];\n tempnei = nei([temp1(:);temp2(:)],:);\n temp3 = find(tempnei(1,:) == temp1(2));\n temp4 = setdiff(1:(size(tempnei,2)),temp3);\n tempnei(1,:) = ([tempnei(1,temp4),0]);\n temp3 = find(tempnei(2,:) == temp1(1));\n temp4 = setdiff(1:(size(tempnei,2)),temp3);\n tempnei(2,:) = ([tempnei(2,temp4),0]);\n temp3 = find(tempnei(3,:) == temp1(1) | tempnei(3,:) == temp1(2));\n if abs(temp3(1)-temp3(2)) == 1\n tempnei(3,:) = [tempnei(3,(1:temp3(1))),temp2(2),tempnei(3,((temp3(2)):(end-1)))];\n else\n tempnei(3,:) = [temp2(2),tempnei(3,(1:end-1))];\n end\n temp3 = find(tempnei(4,:) == temp1(1) | tempnei(4,:) == temp1(2));\n if abs(temp3(1)-temp3(2)) == 1\n tempnei(4,:) = [tempnei(4,(1:temp3(1))),temp2(1),tempnei(4,((temp3(2)):(end-1)))];\n else\n tempnei(4,:) = [temp2(1),tempnei(4,(1:end-1))];\n end\n nei([temp1(:);temp2(:)],:) = tempnei;\n temp3 = find(nei(:,end) ~= 0);\n if isempty(temp3) == 1\n nei = nei(:,(1:end-1));\n end\n temp3 = find(nei(:,end) ~= 0);\n if isempty(temp3) == 1\n nei = nei(:,(1:end-1));\n end\n fem.nei = nei;\n catch\n end\n\n % kjr convert back to msh obj.\n obj.p = []; obj.b = []; obj.t =[];\n obj.p = [fem_struct.x,fem_struct.y];\n obj.b = fem_struct.z;\n obj.t = fem_struct.e;\n end\n\n function mfixed = MergeFP(muw,mfp)\n %%%%%%%\n % Merges a watertight mesh muw with a mesh that contains both\n % over and underwater sections mfp. This method assumes mfp has\n % been created by edge locking the shoreline and using fixed\n % points.\n %\n % INPUTS:\n % muw: watertight msh object\n % mfp: watertight msh with the floodplain using edge locking\n %\n % OUTPUTS:\n % mfixed: a final merged msh that seamlessly mates with the\n % underwater mesh.\n % kjr, April 2019\n\n m3 = mfp - muw ;\n\n dt = delaunayTriangulation(muw.p) ;\n\n dt.Points(end+(1:length(m3.p)),:) = m3.p ;\n\n tmp = mfp;\n\n tmp.p = dt.Points ; tmp.t = dt.ConnectivityList;\n\n % delete points outside mfp and muw\n bnde = extdom_edges2(mfp.t,mfp.p) ;\n polyt=extdom_polygon(bnde,mfp.p,-1,0,20) ;\n polyt=cell2mat(polyt') ;\n\n ee = Get_poly_edges(polyt) ;\n bc = baryc(tmp) ;\n infp = inpoly(bc,polyt,ee) ;\n\n bnde = extdom_edges2(muw.t,muw.p) ;\n polyt=extdom_polygon(bnde,muw.p,-1,0,20) ;\n polyt=cell2mat(polyt') ;\n\n ee = Get_poly_edges(polyt) ;\n bc = baryc(tmp) ;\n inuw = inpoly(bc,polyt,ee) ;\n\n tmp.t(~infp & ~inuw,:) = [] ;\n\n [tmp.p,tmp.t] = fixmesh(tmp.p,tmp.t) ;\n\n mfixed = tmp ;\n\n mfixed = renum(mfixed) ;\n\n\n end\n\n function [pfix,egfix] = extractFixedConstraints(obj)\n %%%%%%%\n % Extract boundary of mesh in no order.\n % INPUTS: msh_obj\n % OUTPUTS: the points and edges of the mesh\n % NOTE: You can visualize these constraints by\n % drawedge2(pfix,egfix);\n % kjr, April 2019\n [egfix,pfix] = extdom_edges2(obj.t,obj.p) ;\n if ~isempty(obj.op) && obj.op.nope > 0\n disp('detected ocean boundary, removing these fixed points')\n ocean = unique(obj.op.nbdv(:));\n [~,IA] = intersect(egfix(:,1),ocean);\n [~,IB] = intersect(egfix(:,2),ocean);\n DEL1 = unique([IA;IB]);\n egfix(DEL1,:) = [];\n pfix = obj.p(unique(egfix(:)),:);\n end\n egfix = renumberEdges(egfix) ;\n end\n\n function [boundary, bou_index] = get_boundary_of_mesh(obj,ascell)\n % [boundary, bou_index] = get_boundary_of_mesh(obj,ascell)\n %\n % Returns the boundary of the mesh and/or the mesh indices of\n % the boundary\n %\n % INPUTS: msh_obj\n % OUTPUTS: msh boundary in one of two forms:\n % 1) NaN-delimited vector in a \"walking\" order (ascell == 0 [default])\n % 2) A cell for each polygon (ascell = 1)\n %\n % kjr, April 2019\n % wjp, Oct 2020\n %\n if nargin < 2 || isempty(ascell)\n ascell = 0;\n end\n bnde = extdom_edges2(obj.t,obj.p) ;\n try\n [boundary,bou_index] = extdom_polygon(bnde,obj.p,-1) ;\n catch\n warning('ALERT: Boundary of mesh is not walkable. Returning polylines.');\n [boundary,bou_index] = extdom_polygon(bnde,obj.p,-1,1) ;\n end\n if ascell; return; end\n boundary = cell2mat(boundary');\n bou_index = cell2mat(bou_index');\n end\n\n function obj = map_mesh_properties(obj,varargin)\n % obj = map_mesh_properties(obj,varargin)\n % Map properties of a msh obj (e.g., bathymetry, f13) given a subset of integers, 'ind'.\n % Assumes that the msh.p and msh.t components of the mesh have already\n % been changed. A common usage would be after receiving the indices as\n % an output from the `fixmesh` function. However, these mapping indices can also be derived\n % from nearest neighbor interpolation\n %\n % Usage:\n % obj = map_mesh_properties(obj,'ind',index_mapping);\n % obj = map_mesh_properties(obj,'msh_old',old_msh_object);\n %\n % varargin options:\n % i) 'ind' - A mapping from an old mesh to a new mesh.\n % the old mesh and new mesh ideally\n % shouldn't have changed much\n % ii) 'msh_old' - an old mesh object from which `ind` are calculated to perform the mapping\n %\n\n % Name value pairs specified.\n % Parse other varargin\n ind = [];\n m_old = obj; \n for kk = 1:2:length(varargin)\n if strcmp(varargin{kk},'msh_old')\n m_old = varargin{kk+1};\n elseif strcmp(varargin{kk},'ind')\n ind = varargin{kk+1};\n end\n end\n if isempty(ind)\n ind = nearest_neighbor_map(m_old, obj);\n end\n if ~isempty(m_old.b)\n obj.b = m_old.b(ind);\n end\n % topographic gradients\n if ~isempty(obj.bx)\n obj.bx = m_old.bx(ind);\n end\n if ~isempty(obj.by)\n obj.by = m_old.by(ind);\n end\n % open boundary info\n if ~isempty(obj.op) && obj.op.nope > 0\n for ib = 1 : obj.op.nope\n idx_old = obj.op.nbdv(1:obj.op.nvdll(ib),ib);\n % Only keep idx_old that is common to ind and map to ind\n [~,~,idx_new] = intersect(idx_old,ind,'stable');\n % if a polygon\n if ~isempty(idx_new) && ...\n length(idx_new) == length(idx_old)-1 && idx_old(end) == idx_old(1)\n idx_new(end+1) = idx_new(1);\n end\n % Get the new length of this boundary\n obj.op.nvdll(ib) = length(idx_new);\n % Reset and reload the nbdv for this boundary\n obj.op.nbdv(:,ib) = 0;\n obj.op.nbdv(1:obj.op.nvdll(ib),ib) = idx_new;\n end\n obj.op.neta = sum(obj.op.nvdll);\n if obj.op.neta == 0\n % Remove open boundary info...\n obj.op = [];\n else\n % Remove zero length boundary and unnessary part from the nbdv\n obj.op.nbdv = obj.op.nbdv(1:max(obj.op.nvdll),:);\n zero_bound = obj.op.nvdll == 0;\n obj.op.nope = sum(~zero_bound);\n obj.op.ibtype(zero_bound) = [];\n obj.op.nvdll(zero_bound) = [];\n obj.op.nbdv(:,zero_bound) = [];\n end\n end\n % land boundary info\n if ~isempty(obj.bd) && obj.bd.nbou > 0\n for ib = 1 : obj.bd.nbou\n nvell_old = obj.bd.nvell(ib);\n idx_old = obj.bd.nbvv(1:nvell_old,ib);\n % Only keep idx_old that is common to ind and map to ind\n [~,idx_new] = ismember(idx_old,ind); % allows for repeats\n idx_new(idx_new == 0) = [];\n % Get the new length of this boundary\n obj.bd.nvell(ib) = length(idx_new);\n % Reset and reload the nbdv for this boundary\n obj.bd.nbvv(:,ib) = 0;\n obj.bd.nbvv(1:obj.bd.nvell(ib),ib) = idx_new;\n %\n % Proceed only if the ibconn field exists and if ibtype\n % is one of 4, 5, 24, 25\n if ~isfield(obj.bd,'ibconn'); continue; end\n if obj.bd.ibtype(ib) ~= 4 && obj.bd.ibtype(ib) ~= 5 && ...\n obj.bd.ibtype(ib) ~= 24 && obj.bd.ibtype(ib) ~= 25\n continue; \n end\n idx_old = obj.bd.ibconn(1:nvell_old,ib);\n % Only keep idx_old that is common to ind and map to ind\n [~,idx_new] = ismember(idx_old,ind);\n idx_new(idx_new == 0) = [];\n nconn = length(idx_new);\n % Check the new length of this boundary\n if nconn ~= obj.bd.nvell(ib)\n warning(['ibconn of subset has a different length to nbvv. ' ...\n 'Setting boundary length to smallest of the two. ' ...\n 'To avoid this message make sure the weir is fully within the subset.'])\n disp(['boundary number = ' num2str(ib)])\n disp(['length of nbvv = ', num2str(obj.bd.nvell(ib))])\n disp(['length of ibconn = ' num2str(nconn)])\n obj.bd.nvell(ib) = min(nconn,obj.bd.nvell(ib));\n end\n % Reset and reload the ibconn for this boundary\n obj.bd.ibconn(:,ib) = 0;\n obj.bd.ibconn(1:obj.bd.nvell(ib),ib) = idx_new(1:obj.bd.nvell(ib));\n end\n obj.bd.nvel = sum(obj.bd.nvell);\n if obj.bd.nvel == 0\n % Remove land boundary info...\n obj.bd = [];\n else\n % Remove unnessary part from the nbdv\n obj.bd.nbvv = obj.bd.nbvv(1:max(obj.bd.nvell),:); \n obj.bd.nbvv(:,obj.bd.nvell == 0) = [];\n if isfield(obj.bd,'ibconn')\n obj.bd.ibconn = obj.bd.ibconn(1:max(obj.bd.nvell),:);\n obj.bd.barinht = obj.bd.barinht(1:max(obj.bd.nvell),:);\n obj.bd.barincfsb = obj.bd.barincfsb(1:max(obj.bd.nvell),:);\n obj.bd.barincfsp = obj.bd.barincfsp(1:max(obj.bd.nvell),:);\n obj.bd.ibconn(:,obj.bd.nvell == 0) = [];\n obj.bd.barinht(:,obj.bd.nvell == 0) = []; \n obj.bd.barincfsb(:,obj.bd.nvell == 0) = []; \n obj.bd.barincfsp(:,obj.bd.nvell == 0) = []; \n end\n obj.bd.ibtype(obj.bd.nvell == 0) = [];\n obj.bd.nvell(obj.bd.nvell == 0) = [];\n obj.bd.nbou = length(obj.bd.nvell);\n end\n end\n % f13\n if ~isempty(m_old.f13)\n obj.f13 = m_old.f13; \n obj.f13.NumOfNodes = length(ind);\n for att = 1:obj.f13.nAttr\n % Get the old index for this attribute\n idx_old = m_old.f13.userval.Atr(att).Val(1,:);\n val_old = m_old.f13.userval.Atr(att).Val(2:end,:);\n % Only keep idx and val that is common to ind and map to ind\n [~,ind_new,idx_new] = intersect(idx_old,ind);\n val_new = val_old(:,ind_new);\n \n % find indices of new nodes\n [~,ind_added] = setdiff(obj.p,m_old.p,'rows');\n if ~isempty(ind_added)\n defval = m_old.f13.defval.Atr(att).Val;\n userval = m_old.f13.userval.Atr(att).Val;\n defval = reshape(defval,1,[]);\n values = m_old.p(:,1)*0 + defval;\n values(userval(1,:),:) = userval(2:end,:)';\n % for the new indices give the closest value in m_old\n % for any given nodal attribute\n tmp = ourKNNsearch(m_old.p',obj.p(ind_added,:)',1);\n val_new2 = values(tmp,:); \n idx_new = [idx_new; ind_added];\n val_new = [val_new'; val_new2]'; \n [idx_new, C] = unique(idx_new); \n val_new = val_new(:,C); \n end \n % Put the uservalues back into f13 struct\n obj.f13.userval.Atr(att).AttrName = m_old.f13.userval.Atr(att).AttrName;\n obj.f13.userval.Atr(att).Val = [idx_new'; val_new];\n obj.f13.userval.Atr(att).usernumnodes = length(idx_new);\n end\n end\n % f24\n if ~isempty(obj.f24)\n obj.f24.Val = m_old.f24.Val(:,:,ind);\n end\n % f5354\n if ~isempty(obj.f5354)\n idx_old = m_old.f5354.nodes;\n [~,idx_new] = intersect(idx_old,ind);\n obj.f5354.nodes = idx_new;\n end\n % EOF\n end\n\n function obj = pruneOverlandMesh(obj,elev,djc)\n %%%%%%%\n % Removes overland extent greater than certain elevation about\n % geoid of the mesh.\n % INPUTS: msh_obj and height above the geoid whereby elements with\n % an average depth greater than elev are pruned from the mesh.\n % OUTPUS: a msh_obj with the overland extents removed.\n % april 2019, kjr\n if nargin < 3\n djc = 0.25;\n end\n [obj.p(:,1),obj.p(:,2)] = m_ll2xy(obj.p(:,1),obj.p(:,2));\n Fb = scatteredInterpolant(obj.p(:,1),obj.p(:,2),obj.b,'linear','nearest') ;\n c = (obj.b(obj.t(:,1),:)+obj.b(obj.t(:,2),:)+obj.b(obj.t(:,3),:))/3;\n obj.t(c < -elev,:) = [];\n [pp,tt] = fixmesh(obj.p,obj.t) ;\n obj.p = pp; obj.t = tt;\n obj = Make_Mesh_Boundaries_Traversable(obj,djc,1);\n obj = renum(obj) ;\n obj.b = Fb(obj.p) ;\n [obj.p(:,1),obj.p(:,2)] = m_xy2ll(obj.p(:,1),obj.p(:,2));\n end\n\n function obj = interpFP(obj,gdat,muw,gdatuw,minb,CAN)\n %%%%%%%\n % Interpolate topography onto a mesh with floodplain\n % Interpolates bathymetry underwater using a grid-scale\n % averaging with a minimum depth of 1-m.\n % Then it uses a 3x multipler for grid-scale averaging\n % to interpolate overland topography.\n % Finally, it updates the bathymetry on the outputted msh\n % to match the underwater and the overland sections.\n %\n %%%%%%%\n % INPUTS\n % obj: msh_obj to interpolate topograhy/bathy on\n % gdat:geodata obj that contains DEM (could be cell-array of\n % gdats)\n % muw: msh_obj of only the watertight portion of the domain\n %\n %%%%%%%\n % OUTPUTS:\n % a msh_obj with bathy/topo on its vertices\n %\n % kjr, april 2019\n\n % parsing some inputs (or set to default)\n if nargin < 5\n minb = 1;\n end\n if nargin < 6\n CAN = 3;\n end\n\n bnde = extdom_edges2(muw.t,muw.p) ;\n bou = extdom_polygon(bnde,muw.p,-1) ;\n bou = cell2mat(bou') ;\n\n dmy1 = obj; % land + uw\n\n ee = Get_poly_edges(bou);\n in = inpoly(dmy1.p,bou,ee) ;\n\n % get the \"on\"\n on = ismembertol(dmy1.p,muw.p,1e-5,'ByRows',true);\n\n obj.b = (1:length(obj.p(:,1)))'*0 ;\n\n if ~iscell(gdat); gdat = {gdat}; end\n\n for i = 1 : length(gdat)\n if isempty(gdat{i}.Fb)\n disp(['Entry ',num2str(i), ' does not contain DEM, skipping']);\n continue\n end\n if i == 1\n in2 = true(size(obj.b));\n else\n in2 = inpoly(dmy1.p,gdat{i}.boubox(1:end-1,:)) ;\n end\n dmy1 = interp(obj,gdatuw(i),'type','depth','ignoreOL',1);\n\n dmy2 = interp(obj,gdat(i),'type','depth','N',CAN) ; % use smooth overland\n\n if ~isempty(gdat{i}.mainlandb) || ~isempty(gdat{i}.innerb)\n riverbound = [];\n if ~isempty(gdat{i}.mainlandb)\n notlakem = find(~contains(gdat{i}.mainlandb_type,'lake'));\n isnan1 = find(isnan(gdat{i}.mainlandb(:,1)));\n for l = 1:length(notlakem)\n if notlakem(l) == 1; isn1 = 1; else\n isn1 = isnan1(notlakem(l)-1)+1; end\n isn2 = isnan1(notlakem(l))-1;\n riverbound = [riverbound; ...\n gdat{i}.mainlandb(isn1:isn2,:)];\n end\n end\n if ~isempty(isempty(gdat{i}.innerb))\n notlakei = find(~contains(gdat{i}.innerb_type,'lake'));\n isnan1 = find(isnan(gdat{i}.innerb(:,1)));\n for l = 1:length(notlakei)\n if notlakei(l) == 1; isn1 = 1; else\n isn1 = isnan1(notlakei(l)-1)+1; end\n isn2 = isnan1(notlakei(l))-1;\n riverbound = [riverbound; ...\n gdat{i}.innerb(isn1:isn2,:)];\n end\n end\n\n % kjr 2018,10,17; Set up projected space imported from msh class\n dmyriver = dmy2;\n dmyriver.p = [dmyriver.p; riverbound(:,1:2)];\n setProj(dmyriver,1,obj.proj.name)\n [rvb(:,1),rvb(:,2)] = ...\n m_ll2xy(riverbound(:,1),riverbound(:,2));\n [dmp(:,1),dmp(:,2)] = m_ll2xy(dmy2.p(:,1),dmy2.p(:,2));\n F = scatteredInterpolant(rvb(:,1),rvb(:,2),...\n riverbound(:,3),'natural','nearest');\n offset = F(dmp);\n % change above land\n dmy2.b = min(0,dmy2.b + offset);\n % change minb based on river height\n minb = max(1,dmy1.b*0 + minb - offset);\n end\n uw = in | on | dmy1.b > 0;\n dmy1.b = max(dmy1.b,minb); % bound the depth by minb\n obj.b(uw & in2,1) = dmy1.b(uw & in2,1) ;\n obj.b(~uw & in2,1) = dmy2.b(~uw & in2,1) ;\n\n end\n\n end\n\n\n function poly = get_poly(obj, auto)\n % obj = get_poly(obj, auto)\n % Get the walkable polygon around a hole in the\n % mesh by clicking the starting point.\n % Common use case would be to re-mesh an area of the mesh.\n %\n % Input(s)\n % obj - msh object\n % auto - whether user clicks or not to draw polygon\n %\n % Return(s)\n % poly - a cell-array of polygons\n %\n % See also Examples/Example_12_Remeshing_Patches.m\n %\n % Created by Keith Roberts, 2020, USP\n dir = 1;\n\n if nargin < 3\n auto = 1;\n end\n\n [bnde,bpts] = extdom_edges2(obj.t,obj.p);\n\n if auto == 1\n [poly] = extdom_polygon(bnde,obj.p,dir);\n else\n % use this to figure out the vstart and vend\n figure, plot(bpts(:,1),bpts(:,2),'k.');\n %hold on; fastscatter(obj.p(:,1),obj.p(:,2),obj.b) ;\n caxis([-10 10]) ; axis equal ;\n title('Use the data cursor to identify the starting point');\n dcm_obj = datacursormode(gcf);\n set(dcm_obj,'UpdateFcn',{@myupdatefcn2,bpts})\n\n % Use data cursor to get the values of the boundary nodes.\n vstart=input('Enter the index for the starting point : ');\n\n bndidx = unique(bnde(:));\n vstart = bndidx(vstart);\n vend = vstart; % assume start is end\n\n [poly,~,~,~] = extract_boundary(vstart,vend,bnde,obj.p,dir,[],[],0,0);\n end\n\n function txt = myupdatefcn2(~,event_obj,myarray)\n pos = get(event_obj,'Position');\n ind = find(abs(myarray(:,1)-pos(1)) 0);\n airway_mapped_image_raw(:) = airway_mapped_image_raw(nearest_centreline_index(:));\n airway_mapped_image_raw(airway_image.RawImage ~= 1) = 0;\n airway_mapped_image.ChangeRawImage(airway_mapped_image_raw);\n \n \n airway_mapped_image.ChangeColorLabelParentChildMap(parent_map, child_map)\nend\n\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/Airways/PTKMapAirwayCentrelineToImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1668532833091155}} {"text": "function varargout = asinh(varargin)\n\nswitch class(varargin{1})\n\n case 'sdpvar'\n varargout{1} = InstantiateElementWise(mfilename,varargin{:});\n\n case 'char'\n\n operator = CreateBasicOperator('increasing','callback'); \n operator.derivative = @(x)((1 + x.^2).^-0.5);\n operator.inflection = [-inf 1 0 -1];\n operator.range = [-700 700];\n \n varargout{1} = [];\n varargout{2} = operator;\n varargout{3} = varargin{3};\n\n otherwise\n error(['SDPVAR/' upper(mfilename) ' called with weird argument']);\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/asinh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.1666735130621011}} {"text": "% STD_UNIFORMSETINDS - Check uniform channel distribution across datasets\n%\n% Usage: \n% >> boolval = std_uniformsetinds(STUDY); \n% Inputs:\n% STUDY - EEGLAB STUDY\n%\n% Outputs:\n% boolval - [0|1] 1 if uniform\n%\n% Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010-\n\n% Copyright (C) Arnaud Delorme\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\nfunction uniformchannels = std_uniformsetinds( STUDY );\n\nuniformchannels = 1;\nfor c = 1:length(STUDY.changrp(1).setinds(:))\n tmpind = cellfun(@(x)(length(x{c})), { STUDY.changrp(:).setinds }); \n if length(unique(tmpind)) ~= 1\n uniformchannels = 0;\n end\nend\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/studyfunc/std_uniformsetinds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.1663938573730485}} {"text": "function xV = runOptimExample(varargin)\n%Script runOptimExample(show)\n%Runs a simple weighted least-squares IMRT fluence map optimization optimization problem.\n%JOD, first version 7 Sept 05.\n%The user should edit the following several lines to specify the prescription\n%doses and the relevant anatomical structures, and relative weights (normalized by\n%the number of voxels per structure). To be replaced by a GUI.\n%If input 'show' is specified as 1, dose will be computed and re-imported\n%into CERR.\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nglobal planC optimS\n\n%-----------parse inputs---------------------%\n\n\nshow = 0;\nIMIndex = 1;\nif length(varargin) == 2\n IMIndex = varargin{1};\n show = varargin{2};\nend\n\ndisp('Begin building input data...')\ntic\n%=======Specify the prescription============%\n\n\n% structNamesC = {'CTV 7200_3mm','CTV 5400_3mm',30, ...\n% 'brainstem_3mm', 'cord_3mm', 27, 28, 29,31,32};\nstructNamesC = {30,...\n 'brainstem_3mm', 'cord_3mm', 27, 28, 29,31,32};\n\n%Note: capitalization is ignored\n%Numbers or names are used.\n%Names are less error-prone unless the name is a\n%complicated derived name.\n\n%27 = anchor zone\n%28 = lt parotid - ctv\n%29 = rt parotid - ctv\n%30 = CTV 4950 - CTV 7200\n\nrelWeightsV = [30,5,5,5,5,0.01,0.01,0.01,0.01,0.01];\n%relative weights of terms. These represent my\n%last guess.\n\ndesiredDoseV = [72 * 1.03,54 * 1.03,49.5 * 1.03,0,0,0,0,0,0,0]; %put desired doses here\n%Desired doses. Bumped up to reduce the size of cold spots.\n\ndoseScale = max(desiredDoseV);\n\ndesiredDoseScaledV = desiredDoseV/doseScale;\n\nstartC = 10; %starting point for beam weights.\n\noptimS.maxBeamVal = 18; %Put a limit on beam values.\n%The problem is scaled such that values over this\n%represent mostly noise.\n\nindexS = planC{end};\n\n%numBeams = length(planC{indexS.IM}(IMIndex).IMSetup(end).beams);\nnumBeams = length(planC{indexS.IM}(IMIndex).IMDosimetry(end).beams);\n\n%=========Match structure names to indices============%\n\n%dumpmemmex\n\n%loop to match structure names\n\nind = indexS.structures;\nnumStructs = length(planC{ind});\n\nfor i = 1 : length(structNamesC)\n match = 0;\n for j = 1 : numStructs\n toMatch = structNamesC{i};\n if ischar(toMatch)\n strName = planC{ind}(j).structureName;\n if strcmpi(toMatch,strName)==1\n structIndicesV(i) = j;\n match = 1;\n end\n else\n structIndicesV(i) = toMatch; %using number instead\n match = 1;\n end\n end\n if match ~=1\n error('Structure not found')\n end\nend\n\noptimS.structIndicesV = structIndicesV;\n\n%========Build the influence matrices===========%\n\nIM = planC{indexS.IM};\nIM = IM(IMIndex); %takes the last computed plan.\n\nif length(IM) > 1\n warning('More than one IM structure. Using the last computed...')\nend\n\n%disp('Assembling influence matrix...')\n\n%Assemble inflM:\n%optimS.inflM = [];\n%numVoxelsV = [];\n%for i = 1 : length(structIndicesV)\n% inflTmp = getInfluenceM(IM.IMDosimetry, structIndicesV(i));\n% numVoxelsV(i) = size(inflTmp,1);\n% optimS.inflM = [optimS.inflM; inflTmp];\n% dumpmemmex\n%end\n%clear inflTmp\n%optimS.scaleFactor = max(optimS.inflM(:));\n%optimS.inflM = optimS.inflM/optimS.scaleFactor;\n\n%Assemble voxel prescription doses:\n%optimS.desiredVoxelDosesV = [];\n%for i = 1 : length(structIndicesV)\n% optimS.desiredVoxelDosesV = [optimS.desiredVoxelDosesV; desiredDoseV(i) * ones(numVoxelsV(i),1)];\n%end\n\n%Assemble voxel weights:\n%optimS.voxelWeightsV = [];\n%for i = 1 : length(structIndicesV)\n% optimS.voxelWeightsV = [optimS.voxelWeightsV; relWeightsV(i) * ones(numVoxelsV(i),1)/numVoxelsV(i)];\n%end\n\n%Get scale factor to make good beamlet weights on the order of 1.\n%\nhighestMean = 0;\nfor i = 1 : length(structIndicesV)\n inflTmp = getInfluenceM(IM.IMDosimetry, structIndicesV(i));\n %Get all contributions above median dose for beamlets = 1.\n doseV = inflTmp * ones(size(inflTmp,2),1);\n [row,col,vals] = find(doseV([doseV > 0.5 * max(doseV)]));\n highestMean = mean(vals) * [highestMean < mean(vals)] + [highestMean >= mean(vals)] * highestMean;\n %dumpmemmex\nend\n\ninflScaleFactor = highestMean * numBeams;\n%inflScaleFactor = 1;\n%Scale so that good optimization solution vectors have 'on' beamlet values of about 1.\n\n%------Construct matrices for quadratic programming------%\n\n%Construct weighted Hessian and 'f'/linear term\noptimS.HessM = 0;\noptimS.fV = 0;\nfor i = 1 : length(structIndicesV)\n inflTmp = getInfluenceM(IM.IMDosimetry, structIndicesV(i));\n numVoxels = size(inflTmp,1);\n optimS.HessM = optimS.HessM + relWeightsV(i) * inflTmp' * inflTmp / (numVoxels * inflScaleFactor^2);\n optimS.fV = optimS.fV - relWeightsV(i) * desiredDoseScaledV(i) * ones(1,numVoxels) * inflTmp ...\n / (inflScaleFactor * numVoxels);\n %dumpmemmex\nend\n\n\nnumPBs = size(inflTmp,2);\n\n%add upper and lower bounds to pencil beam variables\n\nLB = zeros(numPBs,1);\n\nUB = ones(numPBs,1) * optimS.maxBeamVal;\n\n%optimset('tolfun',0.00000000001,'maxiter',500,'display','on')\n\noptions = optimset('tolfun',1e-11,'maxiter',500,'display','on');\n\nAeq = [];\nbeq = [];\nA = [];\nb = [];\n\nx0V = startC * ones(numPBs,1);\n\ndisp('Begin optimization...')\n%dumpmemmex\n\n[xV, feval, exit, outputflag, lambda] = quadprog(optimS.HessM,optimS.fV,A,b,Aeq,beq,LB,UB,x0V,options);\n\noutputflag\n\nfigure\nbar(xV)\n\nif show == 1\n dose3D = getIMDose(IM.IMDosimetry, xV * doseScale / inflScaleFactor,'skin');\n showIMDose(dose3D,'LSQ demo1 JOD')\nend\n\n%put solution into planC\nplanC{indexS.IM}(IMIndex).IMDosimetry.solutions = xV;\n\n\ntoc\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/optim example/runOptimExample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.1661845727967275}} {"text": "function y = autopilot(uu,P)\n%\n% autopilot for mavsim\n% \n% Modification History:\n% 2/11/2010 - RWB\n% 5/14/2010 - RWB\n% 9/30/2014 - RWB\n% \n\n % process inputs\n NN = 0;\n% pn = uu(1+NN); % inertial North position\n% pe = uu(2+NN); % inertial East position\n h = uu(3+NN); % altitude\n Va = uu(4+NN); % airspeed\n% alpha = uu(5+NN); % angle of attack\n% beta = uu(6+NN); % side slip angle\n phi = uu(7+NN); % roll angle\n theta = uu(8+NN); % pitch angle\n chi = uu(9+NN); % course angle\n p = uu(10+NN); % body frame roll rate\n q = uu(11+NN); % body frame pitch rate\n r = uu(12+NN); % body frame yaw rate\n% Vg = uu(13+NN); % ground speed\n% wn = uu(14+NN); % wind North\n% we = uu(15+NN); % wind East\n% psi = uu(16+NN); % heading\n% bx = uu(17+NN); % x-gyro bias\n% by = uu(18+NN); % y-gyro bias\n% bz = uu(19+NN); % z-gyro bias\n NN = NN+19;\n Va_c = uu(1+NN); % commanded airspeed (m/s)\n h_c = uu(2+NN); % commanded altitude (m)\n chi_c = uu(3+NN); % commanded course (rad)\n NN = NN+3;\n t = uu(1+NN); % time\n \n autopilot_version = 2;\n % autopilot_version == 1 <- used for tuning\n % autopilot_version == 2 <- standard autopilot defined in book\n % autopilot_version == 3 <- Total Energy Control for longitudinal AP\n switch autopilot_version\n case 1,\n [delta, x_command] = autopilot_tuning(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P);\n case 2,\n [delta, x_command] = autopilot_uavbook(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P);\n case 3,\n [delta, x_command] = autopilot_TECS(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P);\n end\n y = [delta; x_command];\nend\n \n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Autopilot versions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% autopilot_tuning\n% - used to tune each loop\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [delta, x_command] = autopilot_tuning(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P)\n\n mode = 5;\n switch mode\n case 1, % tune the roll loop\n phi_c = chi_c; % interpret chi_c to autopilot as course command\n delta_a = roll_hold(phi_c, phi, p, P);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n delta_e = P.u_trim(1);\n delta_t = P.u_trim(4);\n theta_c = 0;\n case 2, % tune the course loop\n if t==0,\n phi_c = course_hold(chi_c, chi, r, 1, P);\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n end \n delta_a = roll_hold(phi_c, phi, p, P);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n delta_e = P.u_trim(1);\n delta_t = P.u_trim(4);\n theta_c = 0;\n case 3, % tune the throttle to airspeed loop and pitch loop simultaneously\n theta_c = 20*pi/180 + h_c;\n chi_c = 0;\n if t==0,\n phi_c = course_hold(chi_c, chi, r, 1, P);\n delta_t = airspeed_with_throttle_hold(Va_c, Va, 1, P);\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n delta_t = airspeed_with_throttle_hold(Va_c, Va, 0, P);\n end\n delta_e = pitch_hold(theta_c, theta, q, P);\n delta_a = roll_hold(phi_c, phi, p, P);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n case 4, % tune the pitch to airspeed loop \n chi_c = 0;\n delta_t = P.u_trim(4);\n if t==0,\n phi_c = course_hold(chi_c, chi, r, 1, P);\n theta_c = airspeed_with_pitch_hold(Va_c, Va, 1, P);\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n theta_c = airspeed_with_pitch_hold(Va_c, Va, 0, P);\n end\n delta_a = roll_hold(phi_c, phi, p, P);\n delta_e = pitch_hold(theta_c, theta, q, P);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n case 5, % tune the pitch to altitude loop \n chi_c = 0;\n if t==0,\n phi_c = course_hold(chi_c, chi, r, 1, P);\n theta_c = altitude_hold(h_c, h, 1, P);\n delta_t = airspeed_with_throttle_hold(Va_c, Va, 1, P);\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n theta_c = altitude_hold(h_c, h, 0, P);\n delta_t = airspeed_with_throttle_hold(Va_c, Va, 0, P);\n end\n delta_a = roll_hold(phi_c, phi, p, P);\n delta_e = pitch_hold(theta_c, theta, q, P);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n case 6, % tune the pitch loop\n phi_c = 0;\n theta_c = 20*pi/180 + h_c;\n delta_a = P.u_trim(2);\n delta_r = 0; % no rudder\n % use trim values for elevator and throttle while tuning the lateral autopilot\n delta_e = pitch_hold(theta_c, theta, q, P);\n delta_t = P.u_trim(4);\n end\n %----------------------------------------------------------\n % create outputs\n \n % control outputs\n delta = [delta_e; delta_a; delta_r; delta_t];\n % commanded (desired) states\n x_command = [...\n 0;... % pn\n 0;... % pe\n h_c;... % h\n Va_c;... % Va\n 0;... % alpha\n 0;... % beta\n phi_c;... % phi\n %theta_c*P.K_theta_DC;... % theta\n theta_c;\n chi_c;... % chi\n 0;... % p\n 0;... % q\n 0;... % r\n ];\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% autopilot_uavbook\n% - autopilot defined in the uavbook\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [delta, x_command] = autopilot_uavbook(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P)\n\n %----------------------------------------------------------\n % lateral autopilot\n if t==0,\n % assume no rudder, therefore set delta_r=0\n delta_r = 0;%coordinated_turn_hold(beta, 1, P);\n phi_c = course_hold(chi_c, chi, r, 1, P);\n\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n delta_r = 0;%coordinated_turn_hold(beta, 0, P);\n end\n delta_a = roll_hold(phi_c, phi, p, P);\n \n \n %----------------------------------------------------------\n % longitudinal autopilot\n \n % define persistent variable for state of altitude state machine\n persistent altitude_state;\n persistent initialize_integrator;\n % initialize persistent variable\n if h<=P.altitude_take_off_zone, \n altitude_state = 1;\n elseif h<=h_c-P.altitude_hold_zone, \n altitude_state = 2;\n elseif h>=h_c+P.altitude_hold_zone, \n altitude_state = 3;\n else\n altitude_state = 4;\n end\n initialize_integrator = 1;\n% display(altitude_state);\n % implement state machine\n switch altitude_state,\n case 1, % in take-off zone\n delta_t = 0.5;\n theta_c = P.theta_max;\n case 2, % climb zone\n delta_t = 0.5;\n theta_c = airspeed_with_pitch_hold(Va_c, Va, 0, P);\n case 3, % descend zone\n delta_t = 0;\n theta_c = airspeed_with_pitch_hold(Va_c, Va, 0, P);\n case 4, % altitude hold zone\n delta_t = airspeed_with_throttle_hold(Va_c, Va, flag, P);\n theta_c = altitude_hold(h_c, h, flag, P);\n end\n \n delta_e = pitch_hold(theta_c, theta, q, P);\n % artificially saturation delta_t\n delta_t = sat(delta_t,1,0);\n \n \n %----------------------------------------------------------\n % create outputs\n \n % control outputs\n delta = [delta_e; delta_a; delta_r; delta_t];\n % commanded (desired) states\n x_command = [...\n 0;... % pn\n 0;... % pe\n h_c;... % h\n Va_c;... % Va\n 0;... % alpha\n 0;... % beta\n phi_c;... % phi\n %theta_c*P.K_theta_DC;... % theta\n theta_c;\n chi_c;... % chi\n 0;... % p\n 0;... % q\n 0;... % r\n ];\n \n y = [delta; x_command];\n \n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% autopilot_TECS\n% - longitudinal autopilot based on total energy control systems\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [delta, x_command] = autopilot_TECS(Va_c,h_c,chi_c,Va,h,chi,phi,theta,p,q,r,t,P)\n\n %----------------------------------------------------------\n % lateral autopilot\n if t==0,\n % assume no rudder, therefore set delta_r=0\n delta_r = 0;%coordinated_turn_hold(beta, 1, P);\n phi_c = course_hold(chi_c, chi, r, 1, P);\n\n else\n phi_c = course_hold(chi_c, chi, r, 0, P);\n delta_r = 0;%coordinated_turn_hold(beta, 0, P);\n end\n delta_a = roll_hold(phi_c, phi, p, P); \n \n \n %----------------------------------------------------------\n % longitudinal autopilot based on total energy control\n \n \n delta_e = 0;\n delta_t = 0;\n \n \n %----------------------------------------------------------\n % create outputs\n \n % control outputs\n delta = [delta_e; delta_a; delta_r; delta_t];\n % commanded (desired) states\n x_command = [...\n 0;... % pn\n 0;... % pe\n h_c;... % h\n Va_c;... % Va\n 0;... % alpha\n 0;... % beta\n phi_c;... % phi\n %theta_c*P.K_theta_DC;... % theta\n theta_c;\n chi_c;... % chi\n 0;... % p\n 0;... % q\n 0;... % r\n ];\n \n y = [delta; x_command];\n \nend\n \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Autopilot functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction delta_a = roll_hold(phi_c, phi, p, P)\n persistent integrator;\n persistent error_d1;\n if isempty(integrator) % reset (initialize) persistent variables when flag==1\n integrator = 0;\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = phi_c - phi; % compute the current error\n integrator = integrator + (P.Ts / 2) * (error + error_d1); % update integrator\n error_d1 = error; % update the error for next time through the loop\n delta_a = sat(... % implement PID control\n P.kp_phi * error + ... % proportional term\n P.ki_phi * integrator - ... % integral term\n P.kd_phi * p,... % derivative term\n P.delta_a_max, -P.delta_a_max ... % ensure abs(u)<=limit\n );\n if P.ki_phi~=0 % implement integrator anti-windup\n u_unsat = P.kp_phi * error + P.ki_phi * integrator - P.kd_phi * p;\n integrator = integrator + P.Ts / P.ki_phi * (delta_a - u_unsat);\n end\nend\n\nfunction phi_c = course_hold(chi_c, chi, r, flag, P)\n persistent integrator;\n persistent error_d1;\n if isempty(integrator) % reset (initialize) persistent variables when flag==1\n integrator = 0;\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = chi_c - chi; % compute the current error\n integrator = integrator + (P.Ts / 2) * (error + error_d1); % update integrator\n error_d1 = error; % update the error for next time through the loop\n phi_c = sat(... % implement PID control\n P.kp_chi * error + ... % proportional term\n P.ki_chi * integrator, ... % integral term\n P.roll_max, -P.roll_max ... % ensure abs(u)<=limit\n );\n if P.ki_chi~=0 % implement integrator anti-windup\n u_unsat = P.kp_chi * error + P.ki_chi * integrator;\n integrator = integrator + P.Ts / P.ki_chi * (phi_c - u_unsat);\n end\nend\n\nfunction delta_e = pitch_hold(theta_c, theta, q, P)\n persistent error_d1;\n if isempty(error_d1) % reset (initialize) persistent variables when flag==1\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = theta_c - theta; % compute the current error\\\n error_d1 = error; % update the error for next time through the loop\n delta_e = sat(... % implement PID control\n P.kp_theta * error - ... % proportional term\n P.kd_theta * q,... % derivative term\n P.delta_e_max, -P.delta_e_max ... % ensure abs(u)<=limit\n );\nend\n\nfunction delta_t = airspeed_with_throttle_hold(Va_c, Va, flag, P)\n persistent integrator;\n persistent error_d1;\n if isempty(integrator) % reset (initialize) persistent variables when flag==1\n integrator = 0;\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = Va_c - Va; % compute the current error\n integrator = integrator + (P.Ts / 2) * (error + error_d1); % update integrator\n error_d1 = error; % update the error for next time through the loop\n delta_t = sat(... % implement PID control\n P.kp_v * error + ... % proportional term\n P.ki_v * integrator, ... % integral term\n P.delta_t_max, P.delta_t_min ... % ensure abs(u)<=limit\n );\n if P.ki_v~=0 % implement integrator anti-windup\n u_unsat = P.kp_v * error + P.ki_v * integrator;\n integrator = integrator + P.Ts / P.ki_v * (delta_t - u_unsat);\n end\nend\n\nfunction theta_c = airspeed_with_pitch_hold(Va_c, Va, flag, P)\n persistent integrator;\n persistent error_d1;\n if isempty(integrator) % reset (initialize) persistent variables when flag==1\n integrator = 0;\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = Va_c - Va; % compute the current error\n integrator = integrator + (P.Ts / 2) * (error + error_d1); % update integrator\n error_d1 = error; % update the error for next time through the loop\n theta_c = sat(... % implement PID control\n P.kp_v2 * error + ... % proportional term\n P.ki_v2 * integrator, ... % integral term\n P.pitch_max, -P.pitch_max ... % ensure abs(u)<=limit\n );\n if P.ki_v2~=0 % implement integrator anti-windup\n u_unsat = P.kp_v2 * error + P.ki_v2 * integrator;\n integrator = integrator + P.Ts / P.ki_v2 * (theta_c - u_unsat);\n end\nend\n\nfunction theta_c = altitude_hold(h_c, h, flag, P)\n persistent integrator;\n persistent error_d1;\n if isempty(integrator) % reset (initialize) persistent variables when flag==1\n integrator = 0;\n error_d1 = 0; % _d1 means delayed by one time step\n end\n error = h_c - h; % compute the current error\n integrator = integrator + (P.Ts / 2) * (error + error_d1); % update integrator\n error_d1 = error; % update the error for next time through the loop\n theta_c = sat(... % implement PID control\n P.kp_h * error + ... % proportional term\n P.ki_h * integrator, ... % integral term\n P.pitch_max, -P.pitch_max ... % ensure abs(u)<=limit\n );\n if P.ki_h~=0 % implement integrator anti-windup\n u_unsat = P.kp_h * error + P.ki_h * integrator;\n integrator = integrator + P.Ts / P.ki_h * (theta_c - u_unsat);\n end \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% sat\n% - saturation function\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction out = sat(in, up_limit, low_limit)\n if in > up_limit,\n out = up_limit;\n elseif in < low_limit;\n out = low_limit;\n else\n out = in;\n end\nend\n \n ", "meta": {"author": "chengji253", "repo": "Multiple-fixed-wing-UAVs-flight-simulation-platform", "sha": "7c1fa69d9033355461c0753c2a7408a9bcf1e3e7", "save_path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform", "path": "github-repos/MATLAB/chengji253-Multiple-fixed-wing-UAVs-flight-simulation-platform/Multiple-fixed-wing-UAVs-flight-simulation-platform-7c1fa69d9033355461c0753c2a7408a9bcf1e3e7/platform_code/uavA1/autopilot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.1661473599358223}} {"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": "% Make ANALYZE 7.5 data structure specified by a 3D or 4D matrix.\n% Optional parameters can also be included, such as: voxel_size,\n% origin, datatype, and description.\n%\n% Once the ANALYZE structure is made, it can be saved into ANALYZE 7.5\n% format data file using \"save_untouch_nii\" command (for more detail,\n% type: help save_untouch_nii).\n%\n% Usage: ana = make_ana(img, [voxel_size], [origin], [datatype], [description])\n%\n% Where:\n%\n%\timg:\t\ta 3D matrix [x y z], or a 4D matrix with time\n%\t\t\tseries [x y z t]. When image is in RGB format,\n%\t\t\tmake sure that the size of 4th dimension is\n%\t\t\talways 3 (i.e. [R G B]). In that case, make\n%\t\t\tsure that you must specify RGB datatype to 128.\n%\n%\tvoxel_size (optional):\tVoxel size in millimeter for each\n%\t\t\t\tdimension. Default is [1 1 1].\n%\n%\torigin (optional):\tThe AC origin. Default is [0 0 0].\n%\n%\tdatatype (optional):\tStorage data type:\n%\t\t2 - uint8, 4 - int16, 8 - int32, 16 - float32,\n%\t\t64 - float64, 128 - RGB24\n%\t\t\tDefault will use the data type of 'img' matrix\n%\t\t\tFor RGB image, you must specify it to 128.\n%\n%\tdescription (optional):\tDescription of data. Default is ''.\n%\n% e.g.:\n% origin = [33 44 13]; datatype = 64;\n% ana = make_ana(img, [], origin, datatype); % default voxel_size\n%\n% ANALYZE 7.5 format: http://www.rotman-baycrest.on.ca/~jimmy/ANALYZE75.pdf\n%\n% - Jimmy Shen (jimmy@rotman-baycrest.on.ca)\n%\nfunction ana = make_ana(varargin)\n\n ana.img = varargin{1};\n dims = size(ana.img);\n dims = [4 dims ones(1,8)];\n dims = dims(1:8);\n\n voxel_size = [0 ones(1,3) zeros(1,4)];\n origin = zeros(1,5);\n descrip = '';\n\n switch class(ana.img)\n case 'uint8'\n datatype = 2;\n case 'int16'\n datatype = 4;\n case 'int32'\n datatype = 8;\n case 'single'\n datatype = 16;\n case 'double'\n datatype = 64;\n otherwise\n error('Datatype is not supported by make_ana.');\n end\n\n if nargin > 1 & ~isempty(varargin{2})\n voxel_size(2:4) = double(varargin{2});\n end\n\n if nargin > 2 & ~isempty(varargin{3})\n origin(1:3) = double(varargin{3});\n end\n\n if nargin > 3 & ~isempty(varargin{4})\n datatype = double(varargin{4});\n\n if datatype == 128 | datatype == 511\n dims(5) = [];\n dims = [dims 1];\n end\n end\n\n if nargin > 4 & ~isempty(varargin{5})\n descrip = varargin{5};\n end\n\n if ndims(ana.img) > 4\n error('NIfTI only allows a maximum of 4 Dimension matrix.');\n end\n\n maxval = round(double(max(ana.img(:))));\n minval = round(double(min(ana.img(:))));\n\n ana.hdr = make_header(dims, voxel_size, origin, datatype, ...\n\tdescrip, maxval, minval);\n ana.filetype = 0;\n ana.ext = [];\n ana.untouch = 1;\n\n switch ana.hdr.dime.datatype\n case 2\n ana.img = uint8(ana.img);\n case 4\n ana.img = int16(ana.img);\n case 8\n ana.img = int32(ana.img);\n case 16\n ana.img = single(ana.img);\n case 64\n ana.img = double(ana.img);\n case 128\n ana.img = uint8(ana.img);\n otherwise\n error('Datatype is not supported by make_ana.');\n end\n\n return;\t\t\t\t\t% make_ana\n\n\n%---------------------------------------------------------------------\nfunction hdr = make_header(dims, voxel_size, origin, datatype, ...\n\tdescrip, maxval, minval)\n\n hdr.hk = header_key;\n hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);\n hdr.hist = data_history(origin, descrip);\n\n return;\t\t\t\t\t% make_header\n\n\n%---------------------------------------------------------------------\nfunction hk = header_key\n\n hk.sizeof_hdr = 348;\t\t\t% must be 348!\n hk.data_type = '';\n hk.db_name = '';\n hk.extents = 0;\n hk.session_error = 0;\n hk.regular = 'r';\n hk.hkey_un0 = '0';\n\n return;\t\t\t\t\t% header_key\n\n\n%---------------------------------------------------------------------\nfunction dime = image_dimension(dims, voxel_size, datatype, maxval, minval)\n\n dime.dim = dims;\n dime.vox_units = 'mm';\n dime.cal_units = '';\n dime.unused1 = 0;\n dime.datatype = datatype;\n\n switch dime.datatype\n case 2,\n dime.bitpix = 8; precision = 'uint8';\n case 4,\n dime.bitpix = 16; precision = 'int16';\n case 8,\n dime.bitpix = 32; precision = 'int32';\n case 16,\n dime.bitpix = 32; precision = 'float32';\n case 64,\n dime.bitpix = 64; precision = 'float64';\n case 128\n dime.bitpix = 24; precision = 'uint8';\n otherwise\n error('Datatype is not supported by make_ana.');\n end\n\n dime.dim_un0 = 0;\n dime.pixdim = voxel_size;\n dime.vox_offset = 0;\n dime.roi_scale = 1;\n dime.funused1 = 0;\n dime.funused2 = 0;\n dime.cal_max = 0;\n dime.cal_min = 0;\n dime.compressed = 0;\n dime.verified = 0;\n dime.glmax = maxval;\n dime.glmin = minval;\n\n return;\t\t\t\t\t% image_dimension\n\n\n%---------------------------------------------------------------------\nfunction hist = data_history(origin, descrip)\n\n hist.descrip = descrip;\n hist.aux_file = 'none';\n hist.orient = 0;\n hist.originator = origin;\n hist.generated = '';\n hist.scannum = '';\n hist.patient_id = '';\n hist.exp_date = '';\n hist.exp_time = '';\n hist.hist_un0 = '';\n hist.views = 0;\n hist.vols_added = 0;\n hist.start_field = 0;\n hist.field_skip = 0;\n hist.omax = 0;\n hist.omin = 0;\n hist.smax = 0;\n hist.smin = 0;\n\n return;\t\t\t\t\t% data_history\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/external/NIfTI_20140122/make_ana.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16560404493596292}} {"text": "%% processing for concentrations\nif contains(lower(param.method),'conc')\n if ~isfield(param,'maxConc')\n param.maxConc=1e4;\n end\n if ~isfield(param,'externalNetFluxBounds')\n if isfield(model,'dxl') || isfield(model,'dxu')\n param.externalNetFluxBounds='dxReplacement';\n else\n param.externalNetFluxBounds='original';\n end\n end\n \n nMetabolitesPerRxn = sum(model.S~=0,1)';\n bool = nMetabolitesPerRxn~=1 & ~model.SConsistentRxnBool;\n if any(bool)\n warning('Exchange reactions involving more than one metabolite, check bounds on x - x0')\n disp(model.rxns(bool))\n end\n \n if any(~model.SConsistentRxnBool)\n\n switch param.externalNetFluxBounds\n case 'original'\n if param.printLevel>0\n fprintf('%s\\n','Using existing external net flux bounds without modification.')\n end\n if (isfield(model,'dxl') && any(model.dxl~=0)) || (isfield(model,'dxu') && any(model.dxu~=0))\n error('Option clash between param.externalNetFluxBounds=''original'' and (isfield(model,''dxl'') && any(model.dxl~=0)) || (isfield(model,''dxu'') && any(model.dxu~=0))')\n end\n %\n vel = lb(~model.SConsistentRxnBool);\n veu = ub(~model.SConsistentRxnBool);\n %force initial and final concentration to be equal\n model.dxl = zeros(m,1);\n model.dxu = zeros(m,1);\n case 'dxReplacement'\n %TODO\n error('revise how net to initial and final conc bounds are dealt with')\n if ~isfield(model,'dxl')\n %close bounds by default\n model.dxl = zeros(m,1);\n if exist('B','var')\n dxlB = -B*model.lb(~model.SConsistentRxnBool);\n model.dxl(dxlB~=0)=dxlB(dxlB~=0);\n end\n end\n if ~isfield(model,'dxu')\n %close bounds by default\n model.dxu = zeros(m,1);\n if exist('B','var')\n dxuB = -B*model.ub(~model.SConsistentRxnBool);\n model.dxu(dxuB~=0)=dxuB(dxuB~=0);\n end\n end\n %eliminate all exchange reactions\n B = B*0;\n vel = lb(~model.SConsistentRxnBool)*0;\n veu = ub(~model.SConsistentRxnBool)*0;\n otherwise\n error(['param.externalNetFluxBounds = ' param.externalNetFluxBounds ' is an unrecognised input'])\n end\n else\n model.dxl = -inf*ones(m,1);\n model.dxu = inf*ones(m,1);\n end\n \n clear lb ub\n \n \n if ~isfield(model,'x0l')\n model.x0l = zeros(m,1);\n end\n if ~isfield(model,'x0u')\n model.x0u = param.maxConc*ones(m,1);\n end\n if ~isfield(model,'xl')\n model.xl = zeros(m,1);\n end\n if ~isfield(model,'xu')\n model.xu = param.maxConc*ones(m,1);\n end\n \n if ~isfield(model,'u0') || isempty(model.u0)\n model.u0='zero';\n end\n if ischar(model.u0)\n switch model.u0\n case 'rand'\n u0=rand(m,1);\n case 'one'\n u0=ones(m,1);\n case 'zero'\n u0=zeros(m,1);\n otherwise\n error('unrecognised option for model.u0')\n end\n else\n if length(model.u0)==size(model.S,1)\n u0 = columnVector(model.u0);\n else\n if length(model.u0)==1\n u0=ones(m,1)*model.u0;\n else\n error('model.u0 is of incorrect dimension')\n end\n end\n if any(~isfinite(u0))\n error('u0 must be finite')\n end\n end\n \n %assume concentrations are in uMol\n if ~isfield(model,'concUnit')\n concUnit = 10-6;\n end\n \n % Define constants\n if isfield(model,'gasConstant') && isfield(model,'T')\n if isfield(model,'gasConstant')\n gasConstant = model.gasConstant;\n else\n %8.31446261815324 J K^-1 mol^-1\n gasConstant = 8.3144621e-3; % Gas constant in kJ K^-1 mol^-1\n end\n if isfield(model,'T')\n temperature = model.T;\n else\n temperature = 310.15;\n end\n %dimensionless\n u0 = u0/(gasConstant*temperature);\n end\n \n if ~isfield(model,'f') || isempty(model.f)\n model.f='one';\n end\n if ischar(model.f)\n switch model.f\n case 'rand'\n f=N'*rand(m,1);\n case 'one'\n f=ones(m,1);\n case 'two'\n f=ones(m,1)*2;\n end\n else\n if length(model.f)==size(model.S,1)\n f = columnVector(model.f);\n else\n if length(model.f)==1\n f=ones(m,1)*model.f;\n end\n end\n if any(~isfinite(f))\n error('f must all be finite')\n end\n end\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/base/solvers/entropicFBA/processConcConstraints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.16560404283086338}} {"text": "RadarName = 'staddon_clutter';\nRadarCoords.lat = 50.346069;\nRadarCoords.lon = -4.113670;\n\nRadarCoords_lat = 50.339026;\nRadarCoords_lon = -4.126307;\n\n% Load dataset\nload(strcat(RadarName,'.mat'));\nload('gnn_llr_clutter_a_fakephd.mat');\n\nlon_lim = [-4.176846509809199,-4.103030078951917];\nlat_lim = [50.297532151330770,50.337022151330770];\n\nlon_lim_obs = [-4.16737200000000,-4.14897200000000];\nlat_lim_obs = [50.3537860000000,50.3617750000000];\n% radar_meas_convert;\n\n\n% Map plot\nfigure('units','normalized','outerposition',[0 0 .5 0.8])\nax(1) = gca;\nplot_google_map('Axis',ax(1),'APIKey','AIzaSyBXKujdtXRZiqya1soVS9pxBzYR4g7aGvM','Resize',3,'Scale',2,'MapType','satellite');\naxis(ax(1),[lon_lim(1) lon_lim(2) lat_lim(1) lat_lim(2)])\nplots = [];\nhold on;\n\nN = size(MeasurementScans,2); % Simulation length\n\nTracks = [TrackList, DeletedTracks];\n\n\n%% PLot detections\nfor k=2:N\n \n% MeasurementList = MeasurementScans(k);\n% if(MeasurementList.NumMeasurements>0)\n% % Convert measurements to LLA and plot them\n% % [lat,lon,~] = ned2geodetic(MeasurementList.Vectors(2,:),...\n% % MeasurementList.Vectors(1,:),...\n% % 0,...\n% % RadarCoords.lat,...\n% % RadarCoords.lon,...\n% % 0,...\n% % referenceEllipsoid('wgs84'));\n% latlon = [MeasurementList.Metadata.LatLon];\n% lat = latlon(1,:);\n% lon = latlon(2,:);\n% plots(end+1) = plot(ax(1), lon,lat,'y.','MarkerSize', 4);\n% end\nend\n\n%% Plot all existing tracks\n\nfor j=1:numel(Tracks)\n track = Tracks{j};\n% if find(t==track.Tag.ID,1)\n% continue\n% end\n % Convert track trajectory to LLA and plot it\n means = [track.Trajectory.Mean];\n [lat,lon,~] = ned2geodetic(means(3,:),...\n means(1,:),...\n 0,...\n RadarCoords.lat,...\n RadarCoords.lon,...\n 0,...\n referenceEllipsoid('wgs84'));\n traj_length = size(lon,2);\n\n plots(end+1) = plot(ax(1), lon(:,1),lat(:,1),'go','MarkerSize',15,'LineWidth',2);\n t = [51806, 6423, 8579, 82699, 37841];\n td = [28571, 57088, 46505, 50816];\n if (find(t == track.Tag.ID,1))\n plots(end+1) = plot(ax(1), lon, lat,'-','LineWidth',4,'Color', [0.9856, 0.7372, 0.2537]);\n plots(end+1) = plot(ax(1), lon, lat,'-.w','LineWidth',1);\n elseif(find(td==track.Tag.ID,1))\n % Delayed initiation\n plots(end+1) = plot(ax(1), lon, lat,'-','LineWidth',4,'Color', [0.0265, 0.6137, 0.8135]);\n plots(end+1) = plot(ax(1), lon, lat,'-.w','LineWidth',1);\n else\n plots(end+1) = plot(ax(1), lon, lat,'-.w','LineWidth',2);\n end\n plots(end+1) = plot(ax(1), lon(:,end),lat(:,end),'rx','MarkerSize',15,'LineWidth',2);\n% text(ax(1), lon(:,1), lat(:,1), num2str(track.Tag.ID),'FontSize',18,'Color','g');\n\n % Convert track velocity to LLA and plot it\n% [lat_vel,lon_vel,~] = ned2geodetic(track.State.Mean(4,end),...\n% track.State.Mean(2,end),...\n% 0,...\n% lat(:,end),...\n% lon(:,end),...\n% 0,...\n% referenceEllipsoid('wgs84'));\n% lat_vel = lat_vel-lat(:,end);\n% lon_vel = lon_vel-lon(:,end);\n% plots(end+1) = quiver(ax(1), lon(:,end),lat(:,end),20*lon_vel,20*lat_vel,'r','LineWidth',1.5);\n% if ShowTrackInfo\n% end\n \nend\n\n%% Plot region of high clutter\nx = [-469.710602736631,-2572.92295458513,-2516.31234127506,-1320.74163107899,-835.307363807233, -469.710602736631];\ny = [-4915.41679013513,-4065.50122858976,-2858.60918927224,-1380.19032924249,-1261.08679763585, -4915.41679013513];\n% x = [-2858.62556879160,-2856.97056906902,-108.925126527319,-108.988225201227,-2858.62556879160];\n% y = [-4044.74840882411,-974.655039469575,-975.424226884065,-4045.51804181679,-4044.74840882411];\n[y,x,~] = ned2geodetic(y,...\n x,...\n 0,...\n RadarCoords.lat,...\n RadarCoords.lon,...\n 0,...\n referenceEllipsoid('wgs84'));\nplots(end+1) = plot(ax(1), x, y, 'r-', 'LineWidth', 2);\n\nplot(ax(1), RadarCoords_lon,RadarCoords_lat,...\n '-s','MarkerSize',10,...\n 'MarkerEdgeColor','red',...\n 'MarkerFaceColor',[1 .6 .6]);\n%% Draw fragmented tracks\npos = [-4.129656720082580,50.304822261284470,0.004444050429163,0.002011064814816]; \nrectangle(ax(1), 'Position', pos, 'LineWidth', 2, 'EdgeColor', 'c');\npos = [-4.167167518620260,50.307747446469660,0.003464852876975,0.002513831018518]; \nrectangle(ax(1), 'Position', pos, 'LineWidth', 2, 'EdgeColor', 'c');\npos = [-4.169427205279155,50.312455166377070,0.003163561322454,0.002056770833327]; \nrectangle(ax(1), 'Position', pos, 'LineWidth', 2, 'EdgeColor', 'c');\npos = [-4.129656720082580,50.302994020543736,0.002485655324787,0.001508298611107]; \nrectangle(ax(1), 'Position', pos, 'LineWidth', 2, 'EdgeColor', 'c');\n% x = [-4.12945334365527,-4.12917944224207,-4.12739908305628,-4.12753603376287,-4.12945334365527];\n% y = [50.3032914000914,50.3022941778692,50.3023772797210,50.3034576037951,50.3032914000914];\n% plot(ax(1), x,y, 'c-','LineWidth', 2); \n%% PLot false tracks\npos = [-4.130334626080249,50.326669738136324,0.004293404651903,0.004753425925927];\nrectangle(ax(1), 'Position', pos, 'LineWidth', 2, 'EdgeColor', 'm');\n\n%% Legend\nh1 = plot(NaN, NaN, 'o','MarkerSize', 5, 'MarkerFaceColor', 'y', 'MarkerEdgeColor','k');\nh2 = plot(NaN, NaN, 's','MarkerSize',10,...\n 'MarkerEdgeColor','red',...\n 'MarkerFaceColor',[1 .6 .6]);\nh3 = plot(NaN, NaN, 'ms', 'MarkerSize',15,'LineWidth', 2);\nh4 = plot(NaN, NaN, 'r-', 'LineWidth', 2);\nh5 = plot(NaN, NaN, 'go','MarkerSize',15,'LineWidth',2);\nh6 = plot(NaN, NaN, 'rx','MarkerSize',15,'LineWidth',2);\nh7 = plot(NaN, NaN, 'cs','MarkerSize',15,'LineWidth',2);\nh8 = plot(NaN, NaN, 'b-','MarkerSize',15,'LineWidth',4);\nh9 = plot(NaN, NaN, '-','LineWidth',4,'Color', [0.9856, 0.7372, 0.2537]);\nh10 = plot(NaN, NaN, '-', 'LineWidth',4, 'Color', [0.0265, 0.6137, 0.8135]);\nlegend([h4, h5, h6, h3, h7, h9, h10], 'High-clutter Region', 'Track Birth', 'Track Death','False Tracks', 'Fragmentation Examples', 'Bonus Tracks', 'Delayed Initiation', 'Location','northeast');\n% legend([h4, h5, h6], 'High-clutter Region', 'Track Birth', 'Track Death','Location','northeast');\n% legend([h1, h3, h5, h6, h9], 'Detections', 'Obscured Region', 'Track Birth', 'Track Death', 'Delayed Initiation', 'Location','southeast');\n% legend([h1, h2, h3, h4], 'Detections', 'Radar Position', 'Obscured Region', 'High-clutter region');\n% legend([h1, h3, h5, h6, h7, h8], 'Detections', 'Obscured Region', 'Track Birth', 'Track Death', 'Fragmentation Examples', 'Jump-track','Location','southeast');\n% legend([h1, h2, h3, h4], 'Detections', 'Radar Position', 'Obscured Region', 'High-clutter region');\n% xlabel('Longitude');\n% ylabel('Latitude');\nset(ax(1),'YTickLabel',[]);\nset(ax(1),'XTickLabel',[]);\n", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Workspace/Generic/plot_clutter_results_llr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.16542185209333213}} {"text": "function events = in_events_video(sFile, ChannelMat, EventFile, format)\n% IN_EVENTS_VIDEO: Read video events information from a text file \n%\n% USAGE: events = in_events_video(sFile, ChannelMat, EventFile) \n% \n% EventFile must be text file in the form hh:mm:ss:ff\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, Elizabeth Bock, 2012-2014\n\n%% ===== READ FILE =====\n% Read text file\nfid = fopen(EventFile);\n\nnEvents = 0;\nwhile(1)\n tline = fgetl(fid);\n if tline<0\n break;\n end\n % Convert string hh:mm:ss:ff -> hhmmssff\n spl = str_split(tline,':');\n nEvents = nEvents + 1;\n EventsMat(nEvents) = str2double([spl{1:4}]);\nend\nfclose(fid)\n\n\n%% ===== CONVERT VIDEO TIME TO FILE TIME =====\n% read the video channel from the recording\niVideo = find(strcmpi({ChannelMat.Channel(:).Type}, 'Video'));\nif isempty(iVideo)\n error('No video time channel in this file');\nend\n[F, TimeVector] = in_fread(sFile, ChannelMat, [], round(sFile.prop.times .* sFile.prop.sfreq), iVideo);\n\n% Read channel data for each event\niEvents = bst_closest(EventsMat, F);\neveTimes = TimeVector(iEvents);\n\n%% ===== CONVERT TO BRAINSTORM STRUCTURE =====\n% Initialize list of events\nevents = db_template('event');\n% Ask for a label\nres = java_dialog('input', 'Please enter a label for this event:', 'Event Label');\nif isempty(res)\n events.label = '1';\nelse\n events.label = res;\nend\nevents.times = eveTimes;\nevents.epochs = ones(1, length(eveTimes)); % Epoch: set as 1 for all the occurrences\nevents.color = [];\nevents.reactTimes = [];\nevents.select = 1;\nevents.channels = [];\nevents.notes = [];\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_events_video.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.16520537336353272}} {"text": "function runCommissioned(energy, fieldSize, FFA, FFB, FFDistance, nhist, r, c, s, batch)\n% 'runBinEnergy'\n% JC 1/29/06\n% How to use\n%> runBinEnergy 18 20 4 100000000\n%\n% Written by JC. Dec 2005\n% Run DPM for the different energy bins, for optimize the photon spectrum later.\n%\"input\" is the .MAT file have DPMIN, CTscan, and indV\n%DPMIN - DPM input structure\n%CTscan - DPM scan structure\n%indV = sub2ind(getUniformizedSize(planC), r, c, s); see DPMInfluence.m\n%line 72\n%DPMIN_CTscan_indV DMPIN, CTScan, indV\n%\"number\" is how many bins we're going to divide the whole energy range\n% Typical value for \"number\" is 20\n%nhis - number of histories\n%\n% JC Oct 18, 2006 use target to flattening filter distance as 12.5cm instead of 9.5cm\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\nsetappdata(0, 'usenativesystemdialogs', false)\ncurrentDir = cd;\n\n[FileName,path] = uigetfile('*.mat','Select MAT file containing DPMIN, CTscan, & indV, p');\n\nif path == 0\n errordlg('File Should exist');\n error('File Should exist');\nend\n\ncd(path);\nload (FileName, 'DPMIN', 'CTscan', 'indV')\ncd(currentDir);\n\n%% Get the commissioned parameters from a .mAT file\n[FileName,path] = uigetfile('*.mat','Select MAT file containing p ener a enerFF aFF');\n\nif path == 0\n errordlg('File Should exist');\n error('File Should exist');\nend\n\ncd(path);\nload (FileName, 'p', 'ener', 'a', 'enerFF', 'aFF')\ncd(currentDir);\n\nif (class(energy)== 'char')\n energy = str2num(energy);nhist = str2num(nhist); batch = str2num(batch);\n r = str2num(r); c = str2num(c); s = str2num(s); fieldSize = str2num(fieldSize);\nend\n\n[FileName,path] = uigetfile('*.*','Select dpm.dll to execute');\n\nif path == 0\n errordlg('File Should exist');\n error('File Should exist');\nend\n\ncd(path)\n% need ./local to run dpm. if no. crush.\n% so creat it\nmkdir local\n\nrand('state',sum(100*clock));\n\n% DPMIN.FlatFilterA = -0.21300000000000;\n% DPMIN.FlatFilterB= -0.10000000000000;\n% DPMIN.FlatFilterDist = 12.50000000000000;\nDPMIN.FlatFilterA = str2num(FFA);\nDPMIN.FlatFilterB= str2num(FFB);\nDPMIN.FlatFilterDist = str2num(FFDistance);\n\n% Add input ParticleType as 0 for photon or -1 for electron\nDPMIN.ParticleType = 0;\nDPMIN.SourceEnergy = energy;\n% Jan 12, 2008\n% Now \"nhist\" is defined as photons/cm^2 beamlet.\n% Turn on Softening flag, for source model.\nDPMIN.NumParticles = nhist*fieldSize*fieldSize;\nDPMIN.Softening = 1;\n\nDPMIN.IsoDistance = 100;\nDPMIN.IncreaseFluence = 0;\nDPMIN.OnlyHorn = 0;\nDPMIN.UseFlatFilter = 0;\nDPMIN.UsePhotSpectrum = 1;\nDPMIN.OutputError = 0;\nDPMIN.RandSeeds = [rand*1000 rand*10000];\nDPMIN.PhotSpectrum =[ener', a'];\n\nif (DPMIN.ParticleType == 0)\n DPMIN.Prefix = 'pre4phot'\nelseif (DPMIN.ParticleType == -1)\n DPMIN.Prefix = 'pre4elec'\nelse\n error('DPMIN.ParticleType has to be 0 or -1')\nend\n\n% generratePB.\nbeamletSize = min(fieldSize,1);\ngenerateOpenfieldPB(fieldSize, fieldSize, beamletSize);\nfilename = ['PB_', num2str(fieldSize), 'x', num2str(fieldSize), '_PBsize', num2str(beamletSize), 'cm.mat']\ndisp ('load PB info from above filename.')\nload (filename, 'xPosV', 'yPosV', 'beamlet_delta_x', 'beamlet_delta_y', 'w_field');\n\n% Load the Horn Coefficients.\nEnergy = '6MV10x10MDA.spectrum';\ninds = max(strfind(Energy, '.'));\n% filename:\nfid = fopen([Energy(1:inds-1), '_CosHorn', Energy(inds:end)]);\n% Here, the file extension \".spectrum\" is only for the purpose of being\n% consistent with other source model parameters files.\nif (fid == -1),\n disp(['Can not Open CosHorn file',[Energy(1:inds-1), '_CosHorn', Energy(inds:end)]]);\nend\ntline = fgetl(fid);\ntline = fgetl(fid);\nCosHorn = fscanf(fid,'%g',[2 inf]); % It has two rows now.\nCosHorn = CosHorn';\ncosOffAxisAngle = DPMIN.IsoDistance ./ ...\n (sqrt((xPosV.^2+ yPosV.^2 + DPMIN.IsoDistance.^2)));\nHorn = interp1(CosHorn(:,1), CosHorn(:,2), cosOffAxisAngle, 'linear');\n\nDPMIN\n\ndoseV_PM_total = zeros(size(indV'));\ndoseV_EF_total = zeros(size(indV'));\n\nfor i = 1 : length(xPosV)\n\n source = DPMIN.SourceXYZ;\n\n % scale 40cm/100cm back from the iso center.\n % 0.5*0.4 = (half field size on the plus/minus sides; 0.5;\n % (distance from source-to-jaw: 40cm / isodistance 100cm = 0.4)\n % == 0.2\n % DPMIN.ClmtCorner1 = [source(1)-0.2*fieldSize source(2)+40 source(3)+0.2*fieldSize];\n % DPMIN.ClmtCorner2 = [source(1)+0.2*fieldSize source(2)+40 source(3)+0.2*fieldSize];\n % DPMIN.ClmtCorner3 = [source(1)+0.2*fieldSize source(2)+40 source(3)-0.2*fieldSize];\n %load (filename, 'xPosV', 'yPosV', 'beamlet_delta_x', 'beamlet_delta_y', 'w_field');\n\n DPMIN.ClmtCorner1 = [source(1)-0.2*beamlet_delta_x(i) source(2)+40 source(3)+0.2*beamlet_delta_y(i)];\n DPMIN.ClmtCorner2 = [source(1)+0.2*beamlet_delta_x(i) source(2)+40 source(3)+0.2*beamlet_delta_y(i)];\n DPMIN.ClmtCorner3 = [source(1)+0.2*beamlet_delta_x(i) source(2)+40 source(3)-0.2*beamlet_delta_y(i)];\n\n tic; doseV = dpm(DPMIN, CTscan); toc\n % Add the Horn coefficients\n doseV_PM_total = doseV_PM_total + (1+Horn(i))*doseV;\n\n %% Run only Flat Filter\n DPMIN.OnlyHorn = 0;\n DPMIN.UseFlatFilter = 1;\n %% Test, use 5 times particiles for EF.\n DPMIN.NumParticles = DPMIN.NumParticles*p(6)*5;\n DPMIN.PhotSpectrum = [enerFF', aFF'];\n DPMIN.RandSeeds = [rand*1000 rand*10000];\n tic; doseV = dpm(DPMIN, CTscan); toc\n doseV_EF_total = doseV_PM_total + doseV;\n\nend\n\n% At the end of the run, save the results.\n\ncd(currentDir);\ndose3D = zeros(r,c,s);\ndose3D(indV) = doseV_PM_total;\nfilename = ['dose3D_PM_', num2str(batch),'.mat'];\nsave(filename, 'dose3D');\n\ndose3Dsum = sum(a)*dose3D;\n\ndose3D = zeros(r,c,s);\ndose3D(indV) = doseV_EF_total;\nfilename = ['dose3D_EF_', num2str(batch), '.mat'];\nsave (filename, 'dose3D');\ndose3Dsum = dose3Dsum + dose3D*sum(aFF); % sum(aFF) == sum(a)*p(6);\n\nfilename = ['dose3Dsum_', num2str(batch), '.mat'];\nsave(filename,'dose3Dsum');\n\nreturn;\n\n\n% No Longer valide. Do not use.\n% % % %% Run OnlyHorn\n% % % DPMIN.NumParticles = DPMIN.NumParticles*p(7); % scale down the number of particles by the relative fluence weight of Horn.\n% % % DPMIN.OnlyHorn = 1;\n% % % DPMIN.RandSeeds = [rand*1000 rand*10000];\n% % %\n% % % cd(path);\n% % % tic; doseV = dpm(DPMIN, CTscan); toc\n% % % cd(currentDir);\n% % %\n% % % dose3D = zeros(r,c,s);\n% % % dose3D(indV) = doseV;\n% % % filename = ['dose3D_Horn', num2str(batch), '.mat'];\n% % % save (filename, 'dose3D');\n% % % dose3Dsum = dose3Dsum + dose3D*sum(a)*p(7);\n\n\n\n% Run electron\n% Since for 6MV, the relative electron contribution is only about 0.1%, so\n% it's negligible.\n% DPMIN.\n% DPMIN.Prefix = 'pre4elec';\n% DPMIN.UseFlatFilter = 0\n%\n% cd(path);\n% tic; doseV = dpm(DPMIN, CTscan); toc\n% cd(currentDir);\n%\n% dose3D = zeros(r,c,s);\n% dose3D(indV) = doseV;\n% filename = ['dose3D_elec.mat'];\n% save(filename,'dose3D');\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/BeamModelCommission/runCommissioned.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.165053065317002}} {"text": "% addpath(genpath('./matlab'));\n% caffe('init_finetune', '/home/winsty/caffe/examples/objectness/imagenet_deploy_solver.prototxt', '/media/windisk/imagenet_snapshot/caffe_objectness_train_iter_100000');\n% tic;\n\n% test single frame\ncaffe('set_batch_size', 1);\n\n\ntrack_dir = dir('../trackingDataset');\ntrack_dir = track_dir(3:52);\nfor i = 1:50\n dataname = track_dir(i).name;\n im = imread(['../trackingDataset/' dataname '/img/0001.jpg' ]);\n if strcmp(dataname,'Jogging')\n grt = importdata(['../trackingDataset/' dataname '/groundtruth_rect.1.txt']);\n %[x,y,width,height] = importdata(['../trackingDataset/' dataname '/groundtruth_rect.2.txt']);\n x = grt(1,1); y = grt(1,2);\n width = grt(1,3); height = grt(1,4);\n else\n grt = importdata(['../trackingDataset/' dataname '/groundtruth_rect.txt']);\n x = grt(1,1); y = grt(1,2);\n width = grt(1,3); height = grt(1,4);\n end\n\n padding_x = max(x-width/2,1); padding_y = max(y-height/2,1);\n w = min(2*width, size(im,2)-padding_x);\n h = min(2*height, size(im,1)-padding_y);\n crop_img = im(padding_y:(padding_y+h), padding_x:(padding_x+w), :);\n\n crop_img = im;\n crop_img = imresize(crop_img, [100,100]);\n crop_img = single(crop_img);\n if(size(crop_img,3) == 1)\n \tcrop_img = repmat(crop_img, [1,1,3]);\n end\n ori_img = crop_img/255;\n crop_img = crop_img(:,:,[3 2 1]) - 120;\n box = zeros(1,1,4,8,'single');\n image_batch = zeros(100,100,3,8,'single');\n image_batch(:,:,:,1) = permute(crop_img, [2,1,3]);\n\n % dummy target\n box(:, :, :, 1) = [0, 0, -1, -1];\n input = {image_batch; box};\n caffe('forward', input);\n fea = caffe('extract_feature', 'fc11');\n fea = fea{1};\n fea = reshape(fea(1 : 2500), [50, 50]);\n fea = 1 ./ (1 + exp(-fea));\n mask = imresize(fea',[100,100]);\n for k = 1:3\n masked(:,:,k) = min(ori_img(:,:,k), mask);\n end\n h = figure; imshow([ori_img, masked]);\n saveas(h, [num2str(i) dataname '.jpg']);\n\nend\n", "meta": {"author": "flyers", "repo": "drone-tracking", "sha": "c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad", "save_path": "github-repos/MATLAB/flyers-drone-tracking", "path": "github-repos/MATLAB/flyers-drone-tracking/drone-tracking-c42e1833acfb858ac8f4ec69fa04ab02ac4c19ad/trackers/SODLT/external/caffe/easyverify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.31069437044942166, "lm_q1q2_score": 0.16504375722552186}} {"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": "function avw = ctf_mri2avw(mri)\n\n% avw = ctf_mri2avw(mri)\n%\n% The purpose of this function is to convert a CTF .mri volume into \n% an Analyze volume. The returned avw struct can be saved using avw_write.\n%\n% This function depends on the avw* functions availabe in the mri_toolbox\n% at http://eeg.sf.net/.\n%\n% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %\n% < > % \n% < DISCLAIMER: > %\n% < > %\n% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. > %\n% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR > %\n% < OFFICIAL USE. > %\n% < > %\n% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<> %\n%\n\n% $Revision: 1.1 $ $Date: 2009-01-30 03:49:27 $\n\n% Copyright (C) 2004 Darren L. Weber\n% \n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% History: 04/2004, Darren.Weber_at_radiology.ucsf.edu\n% - adapted from an appendex to CTF document\n% MRIConverter.pdf, which is copied at the end of this\n% function.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\navw = avw_hdr_make;\n\navw.fileprefix = strrep(mri.file,'.mri','');\n\nver = '[$Revision: 1.1 $]';\nfprintf('\\nCTF_MRI2AVW [v%s]\\n',ver(12:16)); tic;\n\n% CTF .mri files are always 256x256x256 voxels, 1mm^3\navw.hdr.dime.dim(2) = 256;\navw.hdr.dime.dim(3) = 256;\navw.hdr.dime.dim(4) = 256;\navw.hdr.dime.pixdim(2) = 1;\navw.hdr.dime.pixdim(3) = 1;\navw.hdr.dime.pixdim(4) = 1;\n\n% mri.hdr.dataSize = 1 or 2 (bytes), 8 or 16 bits\nif mri.hdr.dataSize == 1,\n avw.hdr.dime.bitpix = 8;\n avw.hdr.dime.datatype = 2;\nelse\n avw.hdr.dime.bitpix = 16;\n avw.hdr.dime.datatype = 4;\nend\n\n% This next step should always work correctly, given that avw structs\n% are always axial unflipped in the matlab workspace; the axial \n% unflipped orientation is \n% (+X left, +Y anterior, +Z superior); the ctf orientation is\n% (+X right, +Y posterior, +Z inferior), the complete opposite.\ntemp = flipdim(mri.img,1);\ntemp = flipdim(temp,2);\ntemp = flipdim(temp,3);\navw.img = temp;\n\nt=toc; fprintf('...done (%5.2f sec).\\n\\n',t);\n\nreturn\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/ctfimport1.03/ctf_mri2avw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16465058242182912}} {"text": "function generateDoseMeshes()\n%function clearDoseMeshes()\n%This function generatessurface meshes for the dose whose meshRep flag is\n%set to 1. Note that the The contourLevels are selected from current options.\n%\n%APA, 06/21/07\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nglobal planC\nindexS = planC{end};\n\n%Set Matlab path to directory containing the library\ncurrDir = cd;\nmeshDir = fileparts(which('libMeshContour.dll'));\ncd(meshDir)\n\n%Generate new dose meshes\ncontourLevels = getIsoDoseLevels;\nwaitbarH = waitbar(0,'Generating surface meshes for dose...');\nfor doseNum = 1:length(planC{indexS.dose})\n if isfield(planC{indexS.dose}(doseNum),'meshRep') && isnumeric(planC{indexS.dose}(doseNum).meshRep) && planC{indexS.dose}(doseNum).meshRep == 1\n doseUID = planC{indexS.dose}(doseNum).doseUID;\n doseVolume = planC{indexS.dose}(doseNum).doseArray;\n doseVolume = permute(doseVolume,[2 1 3]);\n [xVals, yVals, zVals] = getDoseXYZVals(planC{indexS.dose}(doseNum));\n calllib('libMeshContour','loadVolumeData',doseUID,xVals, yVals, zVals, double(doseVolume))\n for level = 1:length(contourLevels)\n calllib('libMeshContour','generateSurface', doseUID, [doseUID,'_',num2str(contourLevels(level))], double(contourLevels(level)), uint16(10));\n end\n calllib('libMeshContour','clear',doseUID)\n end\n waitbar(doseNum/length(planC{indexS.dose}),waitbarH)\nend\nclose(waitbarH)\n\n%switch back the current irectory\ncd(currDir)\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/MeshBasedInterp/generateDoseMeshes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.16465058242182906}} {"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": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright 2014 National Renewable Energy Laboratory and National \n% Technology & Engineering Solutions of Sandia, LLC (NTESS). \n% Under the terms of Contract DE-NA0003525 with NTESS, \n% the U.S. Government retains certain rights in this software.\n% \n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n% \n% http://www.apache.org/licenses/LICENSE-2.0\n% \n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef waveClass error\n error('Must define frequency range in waves.bem.range when zero hydro bodies are used (no .h5 file).');\n elseif isempty(obj.bem.range) && ~isempty(obj.bem.frequency)\n % Use .h5 file range if not defined in input file\n obj.bem.range = obj.bem.frequency;\n elseif ~isempty(obj.bem.range) && ~isempty(obj.bem.frequency)\n % check that input file frequency range is not larger than\n % available BEM data\n if obj.bem.range(1) < min(obj.bem.frequency) || obj.bem.range(1) > max(obj.bem.frequency)\n warning('Min frequency range outside BEM data, min frequency set to min BEM frequency')\n obj.bem.range(1) = min(obj.bem.frequency);\n end\n if obj.bem.range(2) < min(obj.bem.frequency) || obj.bem.range(2) > max(obj.bem.frequency)\n warning('Max frequency range outside BEM data, max frequency set to max BEM frequency')\n obj.bem.range(2) = max(obj.bem.frequency);\n end\n end\n \n obj.setWaterDepth(bemWaterDepth);\n \n switch obj.type\n case {'noWave','noWaveCIC'}\n if isempty(obj.omega) && strcmp(obj.period,'NOT DEFINED')\n obj.omega = min(obj.bem.range);\n obj.period = 2*pi/obj.omega;\n elseif isempty(obj.omega)\n obj.omega = 2*pi/obj.period;\n else\n obj.period = 2*pi/obj.omega;\n end\n obj.height = 0;\n obj.amplitude = obj.height/2;\n obj.wavenumber = calcWaveNumber(obj.omega,obj.waterDepth,g,obj.deepWater);\n obj.waveElevNowave(time);\n case {'regular','regularCIC'}\n if isempty(obj.omega) && strcmp(obj.period,'NOT DEFINED')\n obj.omega = min(obj.bem.range);\n obj.period = 2*pi/obj.omega;\n elseif isempty(obj.omega)\n obj.omega = 2*pi/obj.period;\n else\n obj.period = 2*pi/obj.omega;\n end\n obj.amplitude = obj.height/2;\n obj.wavenumber = calcWaveNumber(obj.omega,obj.waterDepth,g,obj.deepWater);\n obj.waveElevReg(rampTime, time);\n obj.wavePowerReg(g,rho);\n case {'irregular','spectrumImport'}\n if strcmp(obj.type,'spectrumImport')\n obj.height = 0;\n obj.period = 0;\n obj.bem.option = 'Imported';\n obj.spectrumType = 'spectrumImport';\n end \n minFrequency=min(obj.bem.range);\n maxFrequency=max(obj.bem.range); \n switch obj.bem.option\n case {'Traditional'}\n if isempty(obj.bem.count)\n obj.bem.count = 1000;\n end\n obj.omega = (minFrequency:(maxFrequency-minFrequency)/(obj.bem.count-1):maxFrequency)';\n obj.dOmega = ones(obj.bem.count,1).*(maxFrequency-minFrequency)./(obj.bem.count-1);\n case {'EqualEnergy'}\n bemCount_interp = 500000;\n obj.omega = (minFrequency:(maxFrequency-minFrequency)/bemCount_interp:maxFrequency)';\n obj.dOmega = mean(diff(obj.omega));\n if isempty(obj.bem.count)\n obj.bem.count = 500;\n end\n case {'Imported'}\n data = importdata(obj.spectrumFile);\n freqData = data(:,1);\n freqLoc = freqData >= min(obj.bem.range)/2/pi & freqData <= max(obj.bem.range)/2/pi;\n obj.omega = freqData(freqLoc).*2.*pi;\n obj.bem.count = length(obj.omega);\n obj.dOmega(1,1)= obj.omega(2)-obj.omega(1);\n obj.dOmega(2:obj.bem.count-1,1)=(obj.omega(3:end)-obj.omega(1:end-2))/2;\n obj.dOmega(obj.bem.count,1)= obj.omega(end)-obj.omega(end-1);\n end\n obj.setWavePhase;\n obj.irregWaveSpectrum(g,rho)\n obj.wavenumber = calcWaveNumber(obj.omega,obj.waterDepth,g,obj.deepWater);\n obj.waveElevIrreg(rampTime, time, obj.dOmega);\n case {'elevationImport'} % This does not account for wave direction\n % Import 'elevationImport' time-series here and interpolate\n data = importdata(obj.elevationFile) ; % Import time-series\n obj.waveElevUser(rampTime, maxIt, data, time);\n end\n end\n\n function listInfo(obj)\n % This method prints wave information to the MATLAB Command Window.\n \n fprintf('\\nWave Environment: \\n')\n switch obj.type\n case 'noWave'\n fprintf('\\tWave Type = No Wave (Constant Hydrodynamic Coefficients)\\n')\n fprintf('\\tHydro Data Wave Period, period (sec) \t= %G\\n',obj.period)\n case 'regular'\n fprintf('\\tWave Type = Regular Waves (Constant Hydrodynamic Coefficients)\\n')\n fprintf('\\tWave Height, height (m) = %G\\n',obj.height)\n fprintf('\\tWave Period, period (sec) = %G\\n',obj.period)\n case 'noWaveCIC'\n fprintf('\\tWave Type = No Wave (Convolution Integral Calculation)\\n')\n case 'regularCIC'\n fprintf('\\tWave Type = Regular Waves (Convolution Integral Calculation)\\n')\n fprintf('\\tWave Height, height (m) = %G\\n',obj.height)\n fprintf('\\tWave Period, period (sec) = %G\\n',obj.period)\n case 'irregular'\n if obj.phaseSeed == 0\n fprintf('\\tWave Type = Irregular Waves (Arbitrary Random Phase)\\n')\n else\n fprintf('\\tWave Type = Irregular Waves (Predefined Random Phase)\\n')\n end\n obj.printWaveSpectrumType;\n fprintf('\\tSignificant Wave Height, Hs (m) = %G\\n',obj.height)\n fprintf('\\tPeak Wave Period, Tp (sec) = %G\\n',obj.period)\n case 'spectrumImport'\n if size(importdata(obj.spectrumFile),2) == 3\n fprintf('\\tWave Type = Irregular waves with imported wave spectrum (Imported Phase)\\n')\n elseif obj.phaseSeed == 0\n fprintf('\\tWave Type = Irregular waves with imported wave spectrum (Random Phase)\\n')\n else\n fprintf('\\tWave Type = Irregular waves with imported wave spectrum (Seeded Phase)\\n')\n end\n obj.printWaveSpectrumType;\n case 'elevationImport'\n fprintf( '\\tWave Type = Waves with imported wave elevation time-history\\n')\n fprintf(['\\tWave Elevation Time-Series File \t= ' obj.elevationFile ' \\n'])\n end\n end\n \n function calculateElevation(obj,rampTime,timeseries)\n % Calculates the wave elevation based on the wave type.\n % Used by postProcess.m\n %\n % Parameters\n % ------------\n % waves : obj\n % waveClass object\n %\n % rampTime : float\n % ramp time from the simulation class\n %\n % timeseries : float array\n % Array of all simulation output time steps\n %\n switch obj.type\n case {'noWave','noWaveCIC'} \n obj.waveElevNowave(timeseries);\n\n case {'regular','regularCIC'}\n obj.waveElevReg(rampTime, timeseries);\n\n case {'irregular','spectrumImport'}\n obj.waveElevIrreg(rampTime, timeseries, obj.dOmega);\n\n case {'elevationImport'}\n % Wave elevation is a necessary pre-processing step for\n % the eta import case.\n % Used by waveClass.setup()\n end\n end \n \n function Z = waveElevationGrid(obj, t, X, Y, it, g)\n % This method calculates wave elevation on a grid at a given\n % time, used by: :func:`write_paraview_wave`.\n % \n % Parameters\n % ------------\n % waves: obj\n % waveClass object\n %\n % t : float\n % the current time\n %\n % X : matrix\n % (m x n) matrix of X coordinates at which to calculate the wave elevation\n %\n % Y : matrix\n % (m x n) matrix of Y coordinates at which to calculate the wave elevation\n %\n % it : time step iteration\n %\n % g : gravitational acceleration constant from simulationClass\n %\n %\n % Returns\n % ---------\n % Z : matrix\n % (m x n) matrix of Z coordinates of the wave elevation \n %\n switch obj.type \n case {'noWave','noWaveCIC'} \n Z = zeros (size (X)); \n case {'regular', 'regularCIC'} \n Xt = X*cos (obj.direction*pi/180) + Y * sin(obj.direction*pi/180); \n Z = obj.amplitude * cos(-1 * obj.wavenumber * Xt + obj.omega * t); \n case {'irregular', 'spectrumImport'}\n Z = zeros (size (X));\n for idir=1:length(obj.direction)\n Xt = X*cos(obj.direction(idir)*pi/180) + Y*sin(obj.direction(idir)*pi/180);\n for iw = 1:length(obj.omega)\n Z = Z + sqrt(obj.amplitude(iw)*obj.spread(idir).*obj.dOmega(iw)) * cos(-1*obj.wavenumber(iw)*Xt + obj.omega(iw)*t + obj.phase(iw,idir));\n end\n end\n case{'elevationImport'}\n if it ==1\n warning('Paraview wave surface discretization for qualitative purposes only.')\n end\n Z = zeros(size(X));\n WaveEle = obj.waveAmpTime(:,2);\n TimeWaveEle = obj.waveAmpTime(:,1);\n L = length(TimeWaveEle);\n Fs = 1/(TimeWaveEle(2)-TimeWaveEle(1));\n YY = fft(WaveEle);\n P2 = abs(YY/L);\n P1 = P2(1:round(L/2)+1);\n P1(2:end-1) = 2*P1(2:end-1);\n ff = Fs*(0:round(L/2))/L;\n PhasesEtaImp2 = angle(YY/L);\n PhasesEtaImp1 = PhasesEtaImp2(1:round(L/2)+1);\n kWaveEle = (2*pi.*ff).^2./g; % deep water wave approximation\n Xt = X*cos(obj.direction*pi/180) + Y*sin(obj.direction*pi/180);\n Zint=zeros(size(X));\n for iw = 2:length(ff)\n Zint = Zint + P1(iw) * cos(-1*kWaveEle(iw)*Xt + 2*pi*ff(iw).*t+ PhasesEtaImp1(iw));\n end\n Z = Zint;\n end \n end\n \n function plotElevation(obj,rampTime)\n % This method plots wave elevation time-history.\n %\n % Parameters\n % ------------\n % rampTime : float, optional\n % Specify wave ramp time to include in plot \n %\n % Returns\n % ------------\n % figure : fig\n % Plot of wave elevation versus time \n % \n \n arguments\n obj\n rampTime double {mustBeReal, mustBeNonNan, mustBeFinite} = 0\n end\n \n figure\n plot(obj.waveAmpTime(:,1),obj.waveAmpTime(:,2))\n title('Wave Surfave Elevation')\n if nargin==2\n hold on\n line([rampTime,rampTime],[1.5*min(obj.waveAmpTime(:,2)),1.5*max(obj.waveAmpTime(:,2))],'Color','k')\n title(['Wave Surface Elevation, Ramp Time ' num2str(rampTime) ' (s)'])\n end\n xlabel('Time (s)')\n ylabel('Elevation (m)')\n end\n \n function plotSpectrum(obj)\n % This method plots the wave spectrum.\n %\n % Returns\n % ------------\n % figure : fig\n % Plot of wave spectrum versus wave frequency\n % \n m0 = trapz(obj.omega,obj.spectrum);\n HsTest = 4*sqrt(m0);\n [~,I] = max(abs(obj.spectrum));\n wp = obj.omega(I);\n TpTest = 2*pi/wp;\n \n figure\n plot(obj.omega,obj.spectrum,'s-')\n hold on\n line([wp,wp],[0,max(obj.spectrum)],'Color','k')\n xlim([0 max(obj.omega)])\n title([obj.spectrumType, ' Spectrum, T_p= ' num2str(TpTest) ' [s], ' 'H_m_0= ' num2str(HsTest), ' [m]'])\n if strcmp(obj.spectrumType,'JS') == 1\n title([obj.spectrumType, ' Spectrum, T_p= ' num2str(TpTest) ' [s], H_m_0= ' num2str(HsTest), ' [m], gamma = ' num2str(obj.gamma)])\n end\n xlabel('Frequency (rad/s)')\n ylabel('Spectrum (m^2-s/rad)');\n end\n \n end\n \n methods (Access = 'protected')\n function setWavePhase(obj)\n % Sets the irregular wave's random phase\n % used by: :meth:`waveClass.setup`.\n if obj.phaseSeed ~= 0\n rng(obj.phaseSeed); % Phase seed = 1,2,3,...,etc\n else\n rng('shuffle'); % Phase seed shuffled\n end\n switch obj.bem.option\n case {'EqualEnergy','Traditional'}\n obj.phase = 2*pi*rand(length(obj.direction),obj.bem.count);\n case {'Imported'}\n data = importdata(obj.spectrumFile);\n if size(data,2) == 3\n freqData = data(:,1);\n freqLoc = freqData>=min(obj.bem.range)/2/pi & freqData<=max(obj.bem.range)/2/pi;\n phaseData = data(freqLoc,3);\n obj.phase = phaseData';\n else\n obj.phase = 2*pi*rand(1,obj.bem.count);\n end\n end\n obj.phase = obj.phase';\n end\n \n function setWaterDepth(obj,bemWaterDepth)\n % Set the water depth. If defined in input file, BEM depth is\n % not used. used by: :meth:`waveClass.setup`.\n if isempty(obj.waterDepth)\n if isempty(bemWaterDepth)\n error('Must define water depth in waves.waterDepth when zero hydro bodies (no .h5 file).');\n elseif strcmp(bemWaterDepth,'infinite')\n obj.deepWater = 1;\n obj.waterDepth = 200;\n fprintf('\\tInfinite water depth specified in BEM and \"waves.waterDepth\" not specified in input file.\\n')\n fprintf('Set water depth to 200m for visualization.\\n')\n else\n obj.deepWater = 0;\n obj.waterDepth = double(bemWaterDepth);\n end\n else\n if ~isempty(bemWaterDepth)\n warning('Because water depth is specified in the wecSimInputFile, the water depth from the BEM data is ignored')\n end\n end\n end\n \n function waveElevNowave(obj,timeseries)\n % Set noWave elevation time-history\n % used by: :meth:`waveClass.setup`. \n % Used by postProcess for variable step solvers\n obj.waveAmpTime = zeros(length(timeseries),2);\n obj.waveAmpTime(:,1) = timeseries;\n \n if ~isempty(obj.marker.location)\n SZwaveAmpTimeViz = size(obj.marker.location);\n obj.waveAmpTimeViz = zeros(length(timeseries),SZwaveAmpTimeViz(1)+1);\n obj.waveAmpTimeViz(:,1) = timeseries;\n end\n end\n \n function waveElevReg(obj,rampTime,timeseries)\n % Calculate regular wave elevation time history\n % used by: :meth:`waveClass.setup`. \n % Used by postProcess for variable step solvers\n maxIt = length(timeseries);\n rampFunction = (1+cos(pi+pi*timeseries/rampTime))/2;\n rampFunction(timeseries>=rampTime) = 1;\n\n obj.waveAmpTime = zeros(maxIt,2);\n obj.waveAmpTime(:,1) = timeseries;\n obj.waveAmpTime(:,2) = rampFunction.*(obj.amplitude*cos(obj.omega*timeseries));\n\n % Wave Marker\n if ~isempty(obj.marker.location)==1\n if width(obj.marker.location)~=2\n error('The coordinates of the visualization markers should have an ordinate (y-coordinate) and an abscissa (x-coordinate)')\n end\n end \n if ~isempty(obj.marker.location)\n SZwaveAmpTimeViz = size(obj.marker.location);\n obj.waveAmpTimeViz = zeros(maxIt,SZwaveAmpTimeViz(1)+1);\n for j = 1:SZwaveAmpTimeViz(1)\n obj.waveAmpTimeViz(:,1) = timeseries;\n obj.waveAmpTimeViz(:,j+1) = rampFunction.*obj.amplitude.*cos(obj.omega*timeseries - obj.wavenumber*(obj.marker.location(j,1).*cos(obj.direction*pi/180) + obj.marker.location(j,2).*sin(obj.direction*pi/180))); \n end\n end \n end \n \n function wavePowerReg(obj,g,rho)\n % Calculate wave power per unit wave crest for regular waves\n if obj.deepWater == 1\n % Deepwater Approximation\n obj.power = 1/(8*pi)*rho*g^(2)*(obj.amplitude).^(2).*obj.period; \n else\n % Full Wave Power Equation\n obj.power = rho*g*(obj.amplitude).^(2)/4*sqrt(g./obj.wavenumber.*tanh(obj.wavenumber.*obj.waterDepth))*(1+2*obj.wavenumber.*obj.waterDepth./sinh(2*obj.wavenumber.*obj.waterDepth));\n end\n end\n \n function irregWaveSpectrum(obj,g,rho)\n % Calculate wave spectrum vector (obj.amplitude)\n % Used by wavesIrreg (wavesIrreg used by: :meth:`waveClass.setup`.) \n frequency = obj.omega/(2*pi);\n Tp = obj.period;\n Hs = obj.height;\n switch obj.spectrumType\n case {'PM','JS'} \n % Pierson-Moskowitz Spectrum from IEC TS 62600-2 ED2 Annex C.2 (2019)\n bPM = (5/4)*(1/Tp)^(4);\n aPM = bPM*(Hs/2)^2;\n fSpectrum = (aPM*frequency.^(-5).*exp(-bPM*frequency.^(-4))); % Wave Spectrum [m^2-s] for 'EqualEnergy'\n if strcmp(obj.spectrumType,'JS')\n % JONSWAP Spectrum from IEC TS 62600-2 ED2 Annex C.2 (2019)\n fp = 1/Tp;\n siga = 0.07;sigb = 0.09; % cutoff frequencies for gamma function\n [lind,~] = find(frequency<=fp);\n [hind,~] = find(frequency>fp);\n gammaAlpha = zeros(size(frequency));\n if isempty(obj.gamma)\n TpsqrtHs = Tp/sqrt(Hs);\n if TpsqrtHs <= 3.6\n obj.gamma = 5;\n elseif TpsqrtHs > 5\n obj.gamma = 1;\n else\n obj.gamma = exp(5.75 - 1.15*TpsqrtHs);\n end\n end\n gammaAlpha(lind) = obj.gamma.^exp(-(frequency(lind)-fp).^2/(2*siga^2*fp^2));\n gammaAlpha(hind) = obj.gamma.^exp(-(frequency(hind)-fp).^2/(2*sigb^2*fp^2));\n C = 1 - 0.287*log(obj.gamma);\n fSpectrum = C*fSpectrum.*gammaAlpha; % Wave Spectrum [m^2-s]\n end\n obj.spectrum = fSpectrum./(2*pi); % Wave Spectrum [m^2-s/rad]\n case 'spectrumImport' % Imported Wave Spectrum\n data = importdata(obj.spectrumFile);\n freqData = data(:,1);\n S_data = data(:,2);\n freqLoc = freqData >= min(obj.bem.range)/2/pi & freqData <= max(obj.bem.range)/2/pi;\n fSpectrum = S_data(freqLoc); % Wave Spectrum [m^2-s] for 'EqualEnergy'\n obj.spectrum = fSpectrum./(2*pi); % Wave Spectrum [m^2-s/rad] for 'Traditional'\n fprintf('\\t\"spectrumImport\" uses the number of imported wave frequencies (not \"Traditional\" or \"EqualEnergy\")\\n')\n case {'BS'} \n error('Following IEC Standard, our Bretschneider Sprectrum (BS) option is exactly how the Pierson-Moskowitz (PM) Spectrum is defined. Please use PM instead');\n end\n % Power per Unit Wave Crest\n obj.wavenumber = calcWaveNumber(obj.omega,obj.waterDepth,g,obj.deepWater); %Calculate Wave Number for Larger Number of Frequencies Before Down Sampling in Equal Energy Method\n if obj.deepWater == 1\n % Deepwater Approximation\n obj.power = sum(1/2*rho*g^(2)*fSpectrum/(2*pi).*obj.dOmega./obj.omega);\n else\n % Full Wave Power Equation\n obj.power = sum((1/2)*rho*g.*fSpectrum/(2*pi).*obj.dOmega.*sqrt(g./obj.wavenumber.*tanh(obj.wavenumber.*obj.waterDepth)).*(1 + 2.*obj.wavenumber.*obj.waterDepth./sinh(2.*obj.wavenumber.*obj.waterDepth)));\n end\n %\n switch obj.bem.option\n case {'EqualEnergy'}\n m0 = trapz(frequency,abs(fSpectrum));\n numBins = obj.bem.count+1;\n a_targ = m0/(numBins);\n SfInt = cumtrapz(frequency,fSpectrum);\n wn(1) = 1;\n for kk = 1:numBins\n jj = 1;\n tmpa{kk}(1) = 0;\n while tmpa{kk}(jj)-kk*a_targ < 0\n tmpa{kk}(jj+1) = SfInt(wn(kk)+jj);\n jj = jj+1;\n if wn(kk)+jj >=length(fSpectrum)\n break\n end\n end\n [a_targ_real(kk),wna(kk)] = min(abs(tmpa{kk}-kk*a_targ));\n wn(kk+1) = wna(kk)+wn(kk);\n a_bins(kk) = trapz(frequency(wn(kk):wn(kk+1)),abs(fSpectrum(wn(kk):wn(kk+1))));\n end\n obj.omega = 2*pi*frequency(wn(2:end-1));\n obj.dOmega = [obj.omega(1)-2*pi*frequency(wn(1)); diff(obj.omega)];\n obj.spectrum = obj.spectrum(wn(2:end-1)); % Wave Spectrum [m^2-s/rad] \n end\n obj.amplitude = 2 * obj.spectrum; % Wave Amplitude [m]\n end\n\n function waveElevIrreg(obj,rampTime,timeseries,df)\n % Calculate irregular wave elevetaion time history\n % used by: :meth:`waveClass.setup`.\n % Used by postProcess for variable time step \n maxIt = length(timeseries);\n rampFunction = (1+cos(pi+pi*timeseries/rampTime))/2;\n rampFunction(timeseries>=rampTime) = 1;\n\n obj.waveAmpTime = zeros(maxIt,2);\n obj.waveAmpTime(:,1) = timeseries;\n \n % Wave Markers\n if ~isempty(obj.marker.location)\n if width(obj.marker.location)~=2\n error('The coordinates of the visualization markers should have an ordinate (y-coordinate) and an abscissa (x-coordinate)')\n end\n end \n if ~isempty(obj.marker.location)\n SZwaveAmpTimeViz = size(obj.marker.location);\n obj.waveAmpTimeViz = zeros(maxIt,SZwaveAmpTimeViz(1)+1);\n obj.waveAmpTimeViz(:,1) = timeseries;\n end \n \n % Calculate eta\n for i = 1:length(timeseries)\n tmp = sqrt(obj.amplitude.*df*obj.spread);\n tmp1 = tmp.*real(exp(sqrt(-1).*(obj.omega.*timeseries(i) + obj.phase)));\n obj.waveAmpTime(i,2) = rampFunction(i)*sum(tmp1,'all');\n\n \n % Wave Markers\n if ~isempty(obj.marker.location)\n for j = 1:SZwaveAmpTimeViz(1)\n tmp14 = tmp.*real(exp(sqrt(-1).*(obj.omega.*timeseries(i) ...\n - obj.wavenumber*(obj.marker.location(j,1).*cos(obj.direction*pi/180) ...\n + obj.marker.location(j,2).*sin(obj.direction*pi/180)) + obj.phase)));\n obj.waveAmpTimeViz(i,j+1) = rampFunction(i).*sum(tmp14,'all');\n end \n end \n end\n end \n \n function waveElevUser(obj,rampTime,maxIt,data,time)\n % Calculate imported wave elevation time history\n % used by: :meth:`waveClass.setup`.\n rampFunction = (1+cos(pi+pi*time/rampTime))/2;\n rampFunction(time>=rampTime) = 1;\n \n obj.waveAmpTime = zeros(maxIt+1,2);\n data_t = data(:,1)'; % Data Time [s]\n data_x = data(:,2)'; % Wave Surface Elevation [m] \n obj.waveAmpTime(:,1) = time;\n obj.waveAmpTime(:,2) = rampFunction.*interp1(data_t,data_x,time);\n \n if any(~isempty(obj.marker.location))\n warning('Cannot use wave gauges or visualization markers with eta import. Gauges and markers removed.');\n obj.marker.location = [];\n end\n end\n \n function printWaveSpectrumType(obj)\n % Lists the wave spectrum type\n % Used by :meth:`waveClass.listInfo`.\n if strcmp(obj.spectrumType,'JS')\n fprintf('\\tSpectrum Type = JONSWAP \\n')\n elseif strcmp(obj.spectrumType,'PM')\n fprintf('\\tSpectrum Type = Pierson-Moskowitz \\n')\n elseif strcmp(obj.spectrumType,'spectrumImport')\n fprintf('\\tSpectrum Type = Imported Spectrum \\n')\n end\n end\n end\nend", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/waveClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16438044920366546}} {"text": "function boxes1 = cascade_test(model, prec, testset, year, suffix)\n\n% boxes1 = cascade_test(cls, model, testset, year, suffix)\n% Compute bounding boxes in a test set.\n% boxes1 are detection windows and scores.\n%\n% prec specifies the target level of precision that wish to achieve.\n% if you let prec = [], a threshold tuned to reach the prec-equals-recall\n% point will be selected.\n\n% Now we also save the locations of each filter for rescoring\n% parts1 gives the locations for the detections in boxes1\n% (these are saved in the cache file, but not returned by the function)\n\nsetVOCyear = year;\nglobals;\npascal_init;\n\ncls = model.class;\nids = textread(sprintf(VOCopts.imgsetpath, testset), '%s');\n\n[prec, recall, thresh] = cascade_thresh(model, year, prec);\nmodel.thresh = thresh;\npca = 5;\nmodel = cascade_model(model, model.year, pca, model.thresh);\n\n% run detector in each image\ntry\n load([cachedir cls '_boxes_' testset '_' suffix]);\ncatch\n times = zeros(length(ids), 2);\n % parfor gets confused if we use VOCopts\n opts = VOCopts;\n % parallel implementation disabled for single-threaded tests\n %parfor i = 1:length(ids);\n for i = 1:length(ids);\n if strcmp('inriaperson', cls)\n % INRIA uses a mixutre of PNGs and JPGs, so we need to use the annotation\n % to locate the image. The annotation is not generally available for PASCAL\n % test data (e.g., 2009 test), so this method can fail for PASCAL.\n rec = PASreadrecord(sprintf(opts.annopath, ids{i}));\n im = imread([opts.datadir rec.imgname]);\n else\n im = imread(sprintf(opts.imgpath, ids{i})); \n end\n th = tic();\n pyra = featpyramid(im, model);\n time_feat = toc(th);\n\n th = tic();\n [dets, boxes] = cascade_detect(pyra, model, model.thresh);\n time_det = toc(th);\n\n if ~isempty(boxes)\n [dets boxes] = clipboxes(im, dets, boxes);\n I = nms(dets, 0.5);\n boxes1{i} = dets(I,[1:4 end]);\n parts1{i} = boxes(I,:);\n else\n boxes1{i} = [];\n parts1{i} = [];\n end\n times(i,:) = [time_det time_feat];\n fprintf('%s: testing: %s %s, %d/%d (avg time %.3f)\\n', cls, testset, year, ...\n i, length(ids), mean(times(1:i,1)));\n end \n save([cachedir cls '_boxes_' testset '_' suffix], ...\n 'boxes1', 'parts1', 'times');\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u68c0\u6d4b\u7b97\u6cd5/star-cascade-master/cascade_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.16438044920366543}} {"text": "function obj = eq_hand_eye_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 = q0.^2;\nt3 = q0.^3;\nt4 = q1.^2;\nt6 = q1.^3;\nt7 = q2.^2;\nt8 = q2.^3;\nt9 = q3.^2;\nt10 = q3.^3;\nt5 = t2.^2;\nobj = [-coef_f1_q_sym1.*t5+coef_f0_q_sym18.*t4-coef_f1_q_sym11.*t2+coef_f0_q_sym12.*t4.^2+coef_f0_q_sym11.*q0.*q1+coef_f0_q_sym22.*q1.*q2+coef_f0_q_sym24.*q1.*q3-coef_f1_q_sym18.*q0.*q1-coef_f1_q_sym22.*q0.*q2-coef_f1_q_sym24.*q0.*q3+coef_f0_q_sym1.*q1.*t3+coef_f0_q_sym5.*q0.*t6-coef_f1_q_sym2.*q1.*t3-coef_f1_q_sym3.*q2.*t3-coef_f1_q_sym4.*q3.*t3+coef_f0_q_sym13.*q2.*t6+coef_f0_q_sym14.*q3.*t6+coef_f0_q_sym19.*q1.*t8+coef_f0_q_sym23.*q1.*t10-coef_f1_q_sym12.*q0.*t6-coef_f1_q_sym19.*q0.*t8-coef_f1_q_sym23.*q0.*t10+coef_f0_q_sym2.*t2.*t4-coef_f1_q_sym5.*t2.*t4+coef_f0_q_sym15.*t4.*t7-coef_f1_q_sym8.*t2.*t7+coef_f0_q_sym17.*t4.*t9-coef_f1_q_sym10.*t2.*t9+coef_f0_q_sym3.*q1.*q2.*t2+coef_f0_q_sym4.*q1.*q3.*t2+coef_f0_q_sym6.*q0.*q2.*t4+coef_f0_q_sym7.*q0.*q3.*t4+coef_f0_q_sym8.*q0.*q1.*t7+coef_f0_q_sym10.*q0.*q1.*t9-coef_f1_q_sym6.*q1.*q2.*t2-coef_f1_q_sym7.*q1.*q3.*t2+coef_f0_q_sym16.*q2.*q3.*t4-coef_f1_q_sym9.*q2.*q3.*t2+coef_f0_q_sym20.*q1.*q3.*t7+coef_f0_q_sym21.*q1.*q2.*t9-coef_f1_q_sym13.*q0.*q2.*t4-coef_f1_q_sym14.*q0.*q3.*t4-coef_f1_q_sym15.*q0.*q1.*t7-coef_f1_q_sym17.*q0.*q1.*t9-coef_f1_q_sym20.*q0.*q3.*t7-coef_f1_q_sym21.*q0.*q2.*t9+coef_f0_q_sym9.*q0.*q1.*q2.*q3-coef_f1_q_sym16.*q0.*q1.*q2.*q3;-coef_f2_q_sym1.*t5+coef_f0_q_sym22.*t7-coef_f2_q_sym11.*t2+coef_f0_q_sym19.*t7.^2+coef_f0_q_sym11.*q0.*q2+coef_f0_q_sym18.*q1.*q2+coef_f0_q_sym24.*q2.*q3-coef_f2_q_sym18.*q0.*q1-coef_f2_q_sym22.*q0.*q2-coef_f2_q_sym24.*q0.*q3+coef_f0_q_sym1.*q2.*t3+coef_f0_q_sym8.*q0.*t8+coef_f0_q_sym12.*q2.*t6+coef_f0_q_sym15.*q1.*t8-coef_f2_q_sym2.*q1.*t3-coef_f2_q_sym3.*q2.*t3-coef_f2_q_sym4.*q3.*t3+coef_f0_q_sym20.*q3.*t8+coef_f0_q_sym23.*q2.*t10-coef_f2_q_sym12.*q0.*t6-coef_f2_q_sym19.*q0.*t8-coef_f2_q_sym23.*q0.*t10+coef_f0_q_sym3.*t2.*t7+coef_f0_q_sym13.*t4.*t7-coef_f2_q_sym5.*t2.*t4+coef_f0_q_sym21.*t7.*t9-coef_f2_q_sym8.*t2.*t7-coef_f2_q_sym10.*t2.*t9+coef_f0_q_sym2.*q1.*q2.*t2+coef_f0_q_sym4.*q2.*q3.*t2+coef_f0_q_sym5.*q0.*q2.*t4+coef_f0_q_sym6.*q0.*q1.*t7+coef_f0_q_sym9.*q0.*q3.*t7+coef_f0_q_sym10.*q0.*q2.*t9+coef_f0_q_sym14.*q2.*q3.*t4+coef_f0_q_sym16.*q1.*q3.*t7+coef_f0_q_sym17.*q1.*q2.*t9-coef_f2_q_sym6.*q1.*q2.*t2-coef_f2_q_sym7.*q1.*q3.*t2-coef_f2_q_sym9.*q2.*q3.*t2-coef_f2_q_sym13.*q0.*q2.*t4-coef_f2_q_sym14.*q0.*q3.*t4-coef_f2_q_sym15.*q0.*q1.*t7-coef_f2_q_sym17.*q0.*q1.*t9-coef_f2_q_sym20.*q0.*q3.*t7-coef_f2_q_sym21.*q0.*q2.*t9+coef_f0_q_sym7.*q0.*q1.*q2.*q3-coef_f2_q_sym16.*q0.*q1.*q2.*q3;coef_f0_q_sym24.*t9-coef_f3_q_sym1.*t5-coef_f3_q_sym11.*t2+coef_f0_q_sym23.*t9.^2+coef_f0_q_sym11.*q0.*q3+coef_f0_q_sym18.*q1.*q3+coef_f0_q_sym22.*q2.*q3-coef_f3_q_sym18.*q0.*q1-coef_f3_q_sym22.*q0.*q2-coef_f3_q_sym24.*q0.*q3+coef_f0_q_sym1.*q3.*t3+coef_f0_q_sym10.*q0.*t10+coef_f0_q_sym12.*q3.*t6+coef_f0_q_sym17.*q1.*t10+coef_f0_q_sym19.*q3.*t8+coef_f0_q_sym21.*q2.*t10-coef_f3_q_sym2.*q1.*t3-coef_f3_q_sym3.*q2.*t3-coef_f3_q_sym4.*q3.*t3-coef_f3_q_sym12.*q0.*t6-coef_f3_q_sym19.*q0.*t8-coef_f3_q_sym23.*q0.*t10+coef_f0_q_sym4.*t2.*t9+coef_f0_q_sym14.*t4.*t9+coef_f0_q_sym20.*t7.*t9-coef_f3_q_sym5.*t2.*t4-coef_f3_q_sym8.*t2.*t7-coef_f3_q_sym10.*t2.*t9+coef_f0_q_sym2.*q1.*q3.*t2+coef_f0_q_sym3.*q2.*q3.*t2+coef_f0_q_sym5.*q0.*q3.*t4+coef_f0_q_sym7.*q0.*q1.*t9+coef_f0_q_sym8.*q0.*q3.*t7+coef_f0_q_sym9.*q0.*q2.*t9+coef_f0_q_sym13.*q2.*q3.*t4+coef_f0_q_sym15.*q1.*q3.*t7+coef_f0_q_sym16.*q1.*q2.*t9-coef_f3_q_sym6.*q1.*q2.*t2-coef_f3_q_sym7.*q1.*q3.*t2-coef_f3_q_sym9.*q2.*q3.*t2-coef_f3_q_sym13.*q0.*q2.*t4-coef_f3_q_sym14.*q0.*q3.*t4-coef_f3_q_sym15.*q0.*q1.*t7-coef_f3_q_sym17.*q0.*q1.*t9-coef_f3_q_sym20.*q0.*q3.*t7-coef_f3_q_sym21.*q0.*q2.*t9+coef_f0_q_sym6.*q0.*q1.*q2.*q3-coef_f3_q_sym16.*q0.*q1.*q2.*q3;t2+t4+t7+t9-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_hand_eye_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16416958677474155}} {"text": "function script_rfcn_VOC0712_ResNet101_OHEM_rpn()\n% script_rfcn_VOC0712_ResNet101_OHEM_rpn()\n% RFCN training and testing with OHEM using ResNet101 model and RPN\n% proposals\n% --------------------------------------------------------\n% R-FCN implementation\n% Modified from MATLAB Faster R-CNN (https://github.com/shaoqingren/faster_rcnn)\n% Copyright (c) 2016, Jifeng Dai\n% Licensed under The MIT License [see LICENSE for details]\n% --------------------------------------------------------\n\n\nclc;\nclear mex;\nclear is_valid_handle; % to clear init_key\nrun(fullfile(fileparts(fileparts(mfilename('fullpath'))), 'startup'));\n%% -------------------- CONFIG --------------------\nopts.caffe_version = 'caffe_rfcn';\nopts.gpu_id = auto_select_gpu;\nactive_caffe_mex(opts.gpu_id, opts.caffe_version);\n\n% model\nmodel = Model.ResNet101_for_RFCN_VOC0712_OHEM();\n% cache name\nopts.cache_name = 'rfcn_VOC0712_ResNet101_OHEM_rpn_resnet101';\n% config\nconf = rfcn_config_ohem('image_means', model.mean_image);\n% train/test data\nfprintf('Loading dataset...')\ndataset = [];\ndataset = Dataset.voc0712_trainval_sp(dataset, 'train', conf.use_flipped, 'resnet101');\ndataset = Dataset.voc2007_test_sp(dataset, 'test', false, 'resnet101');\nfprintf('Done.\\n');\n\n% do validation, or not\nopts.do_val = true; \n\n%% -------------------- TRAINING --------------------\n\nopts.rfcn_model = rfcn_train(conf, dataset.imdb_train, dataset.roidb_train, ...\n 'do_val', opts.do_val, ...\n 'imdb_val', dataset.imdb_test, ...\n 'roidb_val', dataset.roidb_test, ...\n 'solver_def_file', model.solver_def_file, ...\n 'net_file', model.net_file, ...\n 'cache_name', opts.cache_name, ...\n 'caffe_version', opts.caffe_version);\nassert(exist(opts.rfcn_model, 'file') ~= 0, 'not found trained model');\n\n%% -------------------- TESTING --------------------\n rfcn_test(conf, dataset.imdb_test, dataset.roidb_test, ...\n 'net_def_file', model.test_net_def_file, ...\n 'net_file', opts.rfcn_model, ...\n 'cache_name', opts.cache_name,...\n 'ignore_cache', true);\n\nend\n", "meta": {"author": "daijifeng001", "repo": "R-FCN", "sha": "94797e0e8d15998a9ab0a76cbac3281ad907f04a", "save_path": "github-repos/MATLAB/daijifeng001-R-FCN", "path": "github-repos/MATLAB/daijifeng001-R-FCN/R-FCN-94797e0e8d15998a9ab0a76cbac3281ad907f04a/experiments/script_rfcn_VOC0712_ResNet101_OHEM_rpn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16416958012879473}} {"text": "% mario_huggins.m - Nick Clark 28/9/2007\n%\n% USE HEADPHONES\n% WAIT A FEW SECONDS FOR PROCESSING\n% LISTEN CAREFULLY AND ENJOY!\n%\n% Just run this script with the huggins.m in the same directory or in your\n% path. This is a cool litle demo to show how huggins binaural pitch can\n% be made into chords. Thanks to James Humes on matlabcentral for inspiring\n% me to do this to the mario theme song . . man - this is probably the most\n% tragic way I have ever spent a Friday night.\n%\n% This demo only uses the alto and tenor parts as Huggins pitch is a\n% pretty weak percept at the best of times. You'll need a pretty good set\n% of headphones to hear this too - it will not work properly over\n% loudspeakers.\n\nt = 0.15; %single beat duration\nbase_pitch = 440; %tuning parameter 440Hz default\nintroONLY = 0; %set to one if you only want top hear the intro\nsr = 16e3;\n\n%%%%% Notes and timing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The transcription here was originally done by Stewart Bozarth and the\n% painstaking programming of the score into MATLAB code was taken from\n% James Humes' fileexchange submission\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif introONLY\n keysT = [ 56 56 0 56 0 52 56 0 59 0 0 47 0 0 ];\n keysA= [ 46 46 0 46 0 46 46 0 51 0 0 47 0 0 ];\n durA = [ t t t t t t t t t t 2*t t t 2*t];\nelse %whole song\n keysT = [ 56 56 0 56 0 52 56 0 59 0 0 47 0 0 52 0 47 0 44 0 0 49 0 51 0 50 49 0 47 0 56 0 59 0 61 0 57 59 0 56 0 52 54 51 0 52 0 47 0 44 0 0 49 0 51 0 50 49 0 47 0 56 0 59 0 61 0 57 59 0 56 0 52 54 51 0 0 59 58 57 55 0 56 0 48 49 52 0 49 52 54 0 59 58 57 55 0 56 0 64 0 64 64 0 0 0 59 58 57 55 0 56 0 48 49 52 0 49 52 54 0 55 0 0 54 0 52 0 0 0 0 59 58 57 55 0 56 0 48 49 52 0 49 52 54 0 59 58 57 55 0 56 0 64 0 64 64 0 0 0 59 58 57 55 0 56 0 48 49 52 0 49 52 54 0 55 0 0 54 0 52 0 0 0 52 52 0 52 0 52 54 0 56 52 0 49 47 0 0 52 52 0 52 0 52 54 56 0 0 52 52 0 52 0 52 54 0 56 52 0 49 47 0 0 56 56 0 56 0 52 56 0 59 0 0 47 0 0 56 52 0 47 0 48 0 49 57 0 57 49 0 0 51 0 61 0 61 0 61 0 59 0 57 0 56 52 0 49 47 0 0 56 52 0 47 0 48 0 49 57 0 57 49 0 0 47 57 0 57 57 0 56 0 54 0 52 0 0 0 52 0 47 0 44 0 49 51 49 48 50 48 47];\n keysA = [ 46 46 0 46 0 46 46 0 51 0 0 47 0 0 44 0 40 0 35 0 0 40 0 42 0 41 40 0 40 0 47 0 51 0 52 0 49 51 0 49 0 56 45 42 0 44 0 40 0 35 0 0 40 0 42 0 41 40 0 40 0 47 0 51 0 52 0 49 51 0 49 0 56 45 42 0 0 56 55 54 51 0 52 0 44 45 47 0 40 44 45 0 56 55 54 51 0 52 0 59 0 59 59 0 0 0 56 55 54 51 0 52 0 44 45 47 0 40 44 45 0 48 0 0 45 0 44 0 0 0 0 56 55 54 51 0 52 0 44 45 47 0 40 44 45 0 56 55 54 51 0 52 0 59 0 59 59 0 0 0 56 55 54 51 0 52 0 44 45 47 0 40 44 45 0 48 0 0 45 0 44 0 0 0 48 48 0 48 0 48 50 0 47 44 0 44 40 0 0 48 48 0 48 0 48 50 47 0 0 48 48 0 48 0 48 50 0 47 44 0 44 40 0 0 46 46 0 46 0 46 46 0 51 0 0 47 0 0 52 49 0 44 0 44 0 45 52 0 52 45 0 0 47 0 57 0 57 0 57 0 56 0 54 0 52 49 0 45 44 0 0 52 49 0 44 0 44 0 45 52 0 52 45 0 0 47 54 0 54 54 0 52 0 51 0 47 44 0 44 40 0 0 44 0 40 49 51 49 48 50 48 47];\n durA = [ t t t t t t t t t t 2*t t t 2*t t 2*t t 2*t t t t t t t t t t t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t t t t t t t t t t t 2*t t 2*t t 2*t t t t t t t t t t t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t t t t t t t t t t t 2*t 2*t t t t t t t t t t t t t t t 2*t t t t t t t t t t t t t 2*t 2*t t t t t t t t t t t t t t t 2*t t t t t 2*t t t 2*t 4*t 2*t t t t t t t t t t t t t t t 2*t t t t t t t t t t t t t 2*t 2*t t t t t t t t t t t t t t t 2*t t t t t 2*t t t 2*t 4*t t t t t t t t t t t t t t t 2*t t t t t t t t t 4*t 4*t t t t t t t t t t t t t t t 2*t t t t t t t t t t t 2*t t t 2*t t t t t 2*t t t t t t t t t 2*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t t t t t t t 2*t t t t t 2*t t t t t t t t t 2*t t t t t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t (2/3)*t t t t t t t 2*t t 2*t t 2*t t t 4*t 4*t t 6*t];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Convert key values and make song (may take some time - please wait)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfreqA = base_pitch*2.^((keysA-49)/12);\nfreqT = base_pitch*2.^((keysT-49)/12);\n\nsong = [0 0];\nfor n = 1:length(keysT)\n song = [song; huggins([freqA(n) freqT(n)],sr,durA(n))];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Add a 2.5kHz low-pass filter to make things a little less painful\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[b,a] = butter(4,2500*(sr^-1),'low');\nsong = filter(b,a,song);\n\nsoundsc(song, sr)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16647-super-mario-brothers-theme-huggins-illusion/mario_huggins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.16398525628387617}} {"text": "% ------------------------------------------------------------------------ \n% Copyright (C)\n% Torr Vision Group (TVG)\n% University of Oxford - UK\n% \n% Qizhu Li \n% August 2018\n% ------------------------------------------------------------------------ \n% This file is part of the weakly-supervised training method presented in:\n% Qizhu Li*, Anurag Arnab*, Philip H.S. Torr,\n% \"Weakly- and Semi-Supervised Panoptic Segmentation,\"\n% European Conference on Computer Vision (ECCV) 2018.\n% Please consider citing the paper if you use this code.\n% ------------------------------------------------------------------------\n% This function removes thing-class predictions outside their bounding \n% boxes.\n% INPUT:\n% - pred_label : prediction\n% - bbox_masks : object bounding box masks produced by make_bbox_masks.m \n% - thing_classes : list of train ids for thing classes\n% - ignore_label : label to ignore, normally 255\n%\n% OUTPUT:\n% - modified_label: processed prediction\n%\n% DEMO:\n% - See scripts/clean_label.m\n% ------------------------------------------------------------------------\n\nfunction modified_label = apply_bbox_prior(pred_label, bbox_masks, thing_classes, ignore_label)\nmodified_label = pred_label;\nfor j = reshape(thing_classes, 1, [])\n if isempty(bbox_masks{j+1})\n modified_label(modified_label == j) = ignore_label;\n else\n prediction_bbox_prior_mask = modified_label == j;\n gt_bbox_mask = bbox_masks{j+1};\n ignore_mask = and(prediction_bbox_prior_mask, ~gt_bbox_mask);\n modified_label(ignore_mask) = ignore_label;\n end\nend\nend", "meta": {"author": "qizhuli", "repo": "Weakly-Supervised-Panoptic-Segmentation", "sha": "80081fc42eff16977e6d83a1fec413eab79a4c02", "save_path": "github-repos/MATLAB/qizhuli-Weakly-Supervised-Panoptic-Segmentation", "path": "github-repos/MATLAB/qizhuli-Weakly-Supervised-Panoptic-Segmentation/Weakly-Supervised-Panoptic-Segmentation-80081fc42eff16977e6d83a1fec413eab79a4c02/scripts/apply_bbox_prior.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16387336119674775}} {"text": "function [region_feats, regions] = convFeat_to_poolFeat_multi_region(...\n multiple_region_params, conv_feats, boxes, random_scale)\n% convFeat_to_poolFeat_multi_region given the convolutional features of an \n% image, it adaptively pools fixed size region features for each bounding \n% box and for multiple type of regions. \n% \n% INPUTS:\n% 1) multiple_region_params: is a M x 1 vector of objects of type struct that \n% specify the region pooling parameters for each of the M types of regions\n% 2) conv_feats: is a K x 1 cell vector or vector of objects, with K >=1 \n% different type of convolutional features.\n% 3) boxes: a N x 4 array with the bounding box coordinates in the form of\n% [x0,y0,x1,y1] (where (x0,y0) is the top-left corner and (x1,y1) the \n% bottom left corner)\n% 4) random_scale: a boolean value that if set to true then each bounding\n% box is projected to the convolutional features of a random scale of the\n% image.\n% \n% OUTPUTS: \n% 1) region_feats: is a M x 1 cell array where region_feats{i} is a N x F_i\n% array with the region features of each of the N bounding boxes for the \n% i-th type of region. F_i is the number of features of the i-th type of\n% region.\n% 2) regions: is a M x 1 cell array with the region coordinates of each \n% bounding box and for each type of region. Specifically, regions{i} is a\n% N x 8 array that contains the region coordinates of each of the N bounding\n% boxes for the i-th type of region. Note that each region is represented \n% by 8 values [xo0, yo0, xo1, yo1, xi0, yi0, xi1, yi1] that correspond to\n% its outer rectangle [xo0, yo0, xo1, yo1] and its inner rectangle \n% [xi0, yi0, xi1, yi1]. \n% \n%\n% This file is part of the code that implements the following ICCV2015 accepted paper:\n% title: \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% authors: Spyros Gidaris, Nikos Komodakis\n% institution: Universite Paris Est, Ecole des Ponts ParisTech\n% Technical report: http://arxiv.org/abs/1505.01749\n% code: https://github.com/gidariss/mrcnn-object-detection\n% \n% Part of the code in this file comes from the SPP-Net code: \n% https://github.com/ShaoqingRen/SPP_net\n%\n% AUTORIGHTS\n% --------------------------------------------------------\n% Copyright (c) 2015 Spyros Gidaris\n% \n% \"Object detection via a multi-region & semantic segmentation-aware CNN model\"\n% Technical report: http://arxiv.org/abs/1505.01749\n% Licensed under The MIT License [see LICENSE for details]\n% ---------------------------------------------------------\n% Copyright (c) 2014, Shaoqing Ren\n% \n% This file is part of the SPP code and is available \n% under the terms of the Simplified BSD License provided in \n% LICENSE. Please retain this notice and LICENSE if you use \n% this file (or any portion of it) in your project.\n% --------------------------------------------------------- \n\n\nif ~exist('random_scale', 'var'), random_scale = false; end\n\nnum_regions = length(multiple_region_params);\nregion_feats = cell(num_regions,1);\nregions = cell(num_regions,1);\n\nfor p = 1:num_regions, region_feats{p} = single([]); end\nfor p = 1:num_regions, regions{p} = single([]); end\n\nif isempty(boxes), return; end\n\n% pool the region features the bounding boxes for each type of region\nif length(conv_feats) == 1\n for p = 1:num_regions \n [region_feats{p}, regions{p}] = convFeat_to_poolFeat(...\n multiple_region_params(p), conv_feats, boxes, random_scale);\n end\nelse\n if iscell(conv_feats)\n for p = 1:num_regions \n [region_feats{p}, regions{p}] = convFeat_to_poolFeat(...\n multiple_region_params(p), conv_feats{multiple_region_params(p).feat_id}, ...\n boxes, random_scale);\n end \n elseif isstruct(conv_feats)\n for p = 1:num_regions \n [region_feats{p}, regions{p}] = convFeat_to_poolFeat(...\n multiple_region_params(p), conv_feats(multiple_region_params(p).feat_id), ...\n boxes, random_scale);\n end \n end\nend\nend\n", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/adaptive_region_pooling/convFeat_to_poolFeat_multi_region.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16367130098114108}} {"text": "% pop_interp() - interpolate data channels\n%\n% Usage: EEGOUT = pop_interp(EEG, badchans, method);\n%\n% Inputs: \n% EEG - EEGLAB dataset\n% badchans - [integer array] indices of channels to interpolate.\n% For instance, these channels might be bad.\n% [chanlocs structure] channel location structure containing\n% either locations of channels to interpolate or a full\n% channel structure (missing channels in the current \n% dataset are interpolated).\n% method - [string] method used for interpolation (default is 'spherical').\n% 'invdist' uses inverse distance on the scalp\n% 'spherical' uses superfast spherical interpolation. \n% 'spacetime' uses griddata3 to interpolate both in space \n% and time (very slow and cannot be interupted).\n% Output: \n% EEGOUT - data set with bad electrode data replaced by\n% interpolated data\n%\n% Author: Arnaud Delorme, CERCO, CNRS, 2009-\n\n% Copyright (C) Arnaud Delorme, CERCO, 2009, arno@salk.edu\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfunction [EEG com] = pop_interp(EEG, bad_elec, method)\n\n com = '';\n if nargin < 1\n help pop_interp;\n return;\n end;\n \n if nargin < 2\n disp('Warning: interpolation can be done on the fly in studies'); \n disp(' this function will actually create channels in the dataset'); \n disp('Warning: do not interpolate channels before running ICA'); \n disp('You may define channel location to interpolate in the channel'); \n disp('editor and declare such channels as non-data channels'); \n \n enablenondat = 'off';\n if isfield(EEG.chaninfo, 'nodatchans')\n if ~isempty(EEG.chaninfo.nodatchans)\n enablenondat = 'on';\n end;\n end;\n cb_nondat = [ 'tmpchaninfo = EEG.chaninfo; [chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.nodatchans.labels } );' ...\n 'if ~isempty(chanlisttmp),' ...\n ' set(gcbf, ''userdata'', EEG.chaninfo.nodatchans(chanlisttmp));' ...\n ' set(findobj(gcbf, ''tag'', ''chanlist''), ''string'', chanliststr);' ... \n 'end;' ...\n 'clear chanlisttmp chanliststr tmpchaninfo;' ];\n \n cb_otherdat = [ 'tmpanswer = inputdlg2({ ''Dataset index'' }, ''Choose dataset'', 1, { '''' });' ...\n 'if ~isempty(tmpanswer),' ...\n ' tmpanswernum = round(str2num(tmpanswer{1}));' ...\n ' if ~isempty(tmpanswernum),' ...\n ' if tmpanswernum > 0 & tmpanswernum < length(ALLEEG),' ...\n ' tmpchans1 = ALLEEG(tmpanswernum).chanlocs;' ...\n ' tmpchans2 = EEG.chanlocs;' ...\n ' tmpchanlist = setdiff( { tmpchans1.labels }, { tmpchans2.labels } );' ...\n ' if ~isempty(tmpchanlist),' ...\n ' set(gcbf, ''userdata'', ALLEEG(tmpanswernum).chanlocs);' ...\n ' tmpchanlist(2,:) = { '' '' };' ...\n ' set(findobj(gcbf, ''tag'', ''chanlist''), ''string'', [ tmpchanlist{:} ]);' ...\n ' else,' ...\n ' warndlg2(''No new channels in this dataset'');' ...\n ' end;' ...\n ' else,' ...\n ' warndlg2(''Wrong index'');' ...\n ' end;' ...\n ' end;' ...\n 'end;' ...\n 'clear tmpanswer tmpanswernum;' ];\n \n uilist = { { 'Style' 'text' 'string' 'What channel(s) to interpolate' 'fontweight' 'bold' } ...\n { 'style' 'text' 'string' 'none' 'tag' 'chanlist' } ...\n { 'style' 'pushbutton' 'string' 'Select from non-data channels' 'callback' 'pop_interp(''nondatchan'',gcbf);' 'enable' enablenondat } ... \n { 'style' 'pushbutton' 'string' 'Select from other dataset' 'callback' 'pop_interp(''selectchan'',gcbf);'} ...\n { 'style' 'pushbutton' 'string' 'Use list of other dataset' 'callback' 'pop_interp(''uselist'',gcbf);'} ...\n { } ...\n { 'style' 'text' 'string' 'Interpolation method'} ...\n { 'style' 'popupmenu' 'string' 'Spherical|Planar (slow)' 'tag' 'method' } ...\n };\n \n geom = { 1 1 1 1 1 1 [1.8 1] };\n [res userdata tmp restag ] = inputgui( 'uilist', uilist, 'title', 'Interpolate channel(s) -- pop_interp()', 'geometry', geom, 'helpcom', 'pophelp(''pop_interp'')');\n if isempty(res) | isempty(userdata), return; end;\n \n if restag.method == 1\n method = 'spherical';\n else method = 'invdist';\n end;\n bad_elec = userdata.chans;\n \n com = sprintf('EEG = pop_interp(EEG, %s, ''%s'');', userdata.chanstr, method);\n if ~isempty(findstr('nodatchans', userdata.chanstr))\n eval( [ userdata.chanstr '=[];' ] );\n end;\n \n elseif isstr(EEG)\n command = EEG;\n clear EEG;\n fig = bad_elec;\n userdata = get(fig, 'userdata');\n \n if strcmpi(command, 'nondatchan')\n global EEG;\n tmpchaninfo = EEG.chaninfo;\n [chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.nodatchans.labels } );\n if ~isempty(chanlisttmp),\n userdata.chans = EEG.chaninfo.nodatchans();\n userdata.chanstr = [ 'EEG.chaninfo.nodatchans([' num2str(chanlisttmp) '])' ];\n set(fig, 'userdata', userdata);\n set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr);\n end;\n else\n global ALLEEG EEG;\n tmpanswer = inputdlg2({ 'Dataset index' }, 'Choose dataset', 1, { '' });\n if ~isempty(tmpanswer),\n tmpanswernum = round(str2num(tmpanswer{1}));\n if ~isempty(tmpanswernum),\n if tmpanswernum > 0 & tmpanswernum < length(ALLEEG),\n TMPEEG = ALLEEG(tmpanswernum);\n \n tmpchans1 = TMPEEG.chanlocs;\n if strcmpi(command, 'selectchan')\n chanlist = pop_chansel( { tmpchans1.labels } );\n else\n chanlist = 1:length(TMPEEG.chanlocs); % use all channels\n end\n \n % look at what new channels are selected\n tmpchans2 = EEG.chanlocs;\n [tmpchanlist chaninds] = setdiff( { tmpchans1(chanlist).labels }, { tmpchans2.labels } );\n if ~isempty(tmpchanlist),\n if length(chanlist) == length(TMPEEG.chanlocs)\n userdata.chans = TMPEEG.chanlocs;\n userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs' ];\n else\n userdata.chans = TMPEEG.chanlocs(chanlist(sort(chaninds)));\n userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs([' num2str(chanlist(sort(chaninds))) '])' ];\n end;\n set(fig, 'userdata', userdata);\n tmpchanlist(2,:) = { ' ' };\n set(findobj(gcbf, 'tag', 'chanlist'), 'string', [ tmpchanlist{:} ]);\n else\n warndlg2('No new channels selected');\n end;\n else\n warndlg2('Wrong index');\n end;\n end;\n end;\n end;\n return;\n end;\n \n EEG = eeg_interp(EEG, bad_elec, method);\n \n \n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/functions/popfunc/pop_interp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.16313351927624298}} {"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 [fboxes,cs] = transfer_friends(models, bboxes)\n%transfer friends onto detections\nerror('deprecated function.. see VOCinit');\n\nVOCinit;\n% if isfield(models{i},'detect_add_flip') && models{i}.detect_add_flip == 1\n% models{i}.gt_box = flip_box(models{i}.gt_box,[recs.size.height ...\n% recs.size.width]);\n% end\n\nhasfriends = cellfun(@(x)size(x.friendbb,1),models);\nhasfriends = find(hasfriends);\n\nfboxes = cell(1,length(bboxes));\ncs = cell(1,length(bboxes));\n\nfor i = 1:length(bboxes)\n curb = bboxes{i};\n goods = ismember(curb(:,6),hasfriends);\n curb = curb(goods,:);\n \n fboxes{i} = zeros(0,7);\n cs{i} = cell(0,1);\n for j = 1:size(curb,1)\n exid = curb(j,6);\n curg = models{exid}.gt_box;\n others = models{exid}.friendbb;\n \n if isfield(models{exid},'detect_add_flip') && models{exid}.detect_add_flip == 1\n sizeI = models{exid}.sizeI; \n %curg = flip_box(curg,sizeI);\n others = flip_box(others,sizeI);\n end\n\n xform_cd = find_xform(curg, curb(j,:));\n \n %news = others;\n \n if isfield(models{exid},'detect_add_flip') && models{exid}.detect_add_flip == 1\n others = flip_box(others,sizeI);\n end\n\n news = apply_xform(others,xform_cd);\n \n %if isfield(models{exid},'detect_add_flip') && models{exid}.detect_add_flip == 1\n % news = flip_box(news,sizeI);\n %end\n\n \n news(:,5) = j;\n news(:,6) = curb(j,6);\n news(:,7) = curb(j,end);\n fboxes{i} = [fboxes{i}; news];\n\n cs{i} = [cs{i} models{exid}.friendclass];\n\n end\n \nend\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/internal/experiments/transfer_friends.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1629168661698401}} {"text": "function [revisedModel,gapfilledReactions,replacedReactions]=debugModel(model,testResults,inputDataFolder,infoFilePath,microbeID,biomassReaction)\n% This function runs a suite of debugging functions on a refined\n% reconstruction produced by the DEMETER pipeline. Tests\n% are performed whether or not the models can produce biomass aerobically\n% and anaerobically, and whether or not unrealistically high ATP is\n% produced on a complex medium.\n%\n% USAGE:\n%\n% [revisedModel,gapfilledReactions,replacedReactions]=debugModel(model,testResults,inputDataFolder,infoFilePath,microbeID,biomassReaction)\n%\n% INPUTS\n% model: COBRA model structure\n% testResults: Structure with results of test run\n% inputDataFolder: Folder with input tables with experimental data\n% and databases that inform the refinement process\n% infoFilePath File with information on reconstructions to refine\n% microbeID: ID of the reconstructed microbe that serves as\n% the reconstruction name and to identify it in\n% input tables\n% biomassReaction: Reaction ID of the biomass objective function\n%\n% OUTPUT\n% revisedModel: Gapfilled COBRA model structure\n% gapfilledReactions: Reactions gapfilled to enable flux\n% replacedReactions: Reactions replaced because they were causing\n% futile cycles\n%\n% .. Author:\n% - Almut Heinken, 09/2020\n\ngapfilledReactions = {};\ncntGF=1;\nreplacedReactions = {};\n\ntol=0.0000001;\n\nmodel=changeObjective(model,biomassReaction);\n\n% implement complex medium\nconstraints = readtable('ComplexMedium.txt', 'Delimiter', 'tab');\nconstraints=table2cell(constraints);\nconstraints=cellstr(string(constraints));\n\n% Load reaction and metabolite database\ndatabase=loadVMHDatabase;\n\n% create a temporary summary file of the performed refinement\nsummary=struct;\nsummary.condGF={};\nsummary.targetGF={};\nsummary.relaxGF={};\n\n% rebuild model\nmodel = rebuildModel(model,database,biomassReaction);\n\n[AerobicGrowth, AnaerobicGrowth] = testGrowth(model, biomassReaction);\nif AnaerobicGrowth(1,1) < tol\n % find reactions that are preventing the model from growing\n % anaerobically\n % first gapfilling specialized for anaerobic growth\n [model,oxGapfillRxns,anaerGrowthOK] = anaerobicGrowthGapfill(model, biomassReaction, database);\n if ~isempty(oxGapfillRxns)\n summary.condGF=union(summary.condGF,oxGapfillRxns);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Enabling anaerobic growth';\n gapfilledReactions{cntGF,3}='Condition-specific gapfilling';\n gapfilledReactions(cntGF,4:length(oxGapfillRxns)+3)=oxGapfillRxns;\n cntGF=cntGF+1;\n end\n % then less targeted gapfilling\n model=changeRxnBounds(model,'EX_o2(e)',0,'l');\n [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction,biomassReaction,'max',database,1);\n model=changeRxnBounds(model,'EX_o2(e)',-10,'l');\n % export the gapfilled reactions\n if ~isempty(condGF)\n summary.condGF=union(summary.condGF,condGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Enabling anaerobic growth';\n gapfilledReactions{cntGF,3}='Condition-specific gapfilling';\n gapfilledReactions(cntGF,4:length(condGF)+3)=condGF;\n cntGF=cntGF+1;\n end\n if ~isempty(targetGF)\n summary.targetGF=union(summary.targetGF,targetGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Enabling anaerobic growth';\n gapfilledReactions{cntGF,3}='Targeted gapfilling';\n gapfilledReactions(cntGF,4:length(targetGF)+3)=targetGF;\n cntGF=cntGF+1;\n end\n if ~isempty(relaxGF)\n summary.relaxGF=union(summary.relaxGF,relaxGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Enabling anaerobic growth';\n gapfilledReactions{cntGF,3}='Gapfilling based on relaxFBA';\n gapfilledReactions(cntGF,4:length(relaxGF)+3)=relaxGF;\n cntGF=cntGF+1;\n end\nend\n\n[AerobicGrowth, AnaerobicGrowth] = testGrowth(model, biomassReaction);\nif AerobicGrowth(1,2) < tol\n % identify blocked reactions on complex medium\n model=useDiet(model,constraints);\n [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction,biomassReaction,'max',database);\n % export the gapfilled reactions\n if ~isempty(condGF)\n summary.condGF=union(summary.condGF,condGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on complex medium';\n gapfilledReactions{cntGF,3}='Condition-specific gapfilling';\n gapfilledReactions(cntGF,4:length(condGF)+3)=condGF;\n cntGF=cntGF+1;\n end\n if ~isempty(targetGF)\n summary.targetGF=union(summary.targetGF,targetGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on complex medium';\n gapfilledReactions{cntGF,3}='Targeted gapfilling';\n gapfilledReactions(cntGF,4:length(targetGF)+3)=targetGF;\n cntGF=cntGF+1;\n end\n if ~isempty(relaxGF)\n summary.relaxGF=union(summary.relaxGF,relaxGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on complex medium';\n gapfilledReactions{cntGF,3}='Gapfilling based on relaxFBA';\n gapfilledReactions(cntGF,4:length(relaxGF)+3)=relaxGF;\n cntGF=cntGF+1;\n end\nend\n\n% identify blocked biomass precursors on defined medium for the organism\n[growsOnDefinedMedium,constrainedModel,~] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction, inputDataFolder);\nif growsOnDefinedMedium == 0\n % find reactions that are preventing the model from growing\n [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(constrainedModel,biomassReaction,biomassReaction,'max',database,1);\n % export the gapfilled reactions\n if ~isempty(condGF)\n summary.condGF=union(summary.condGF,condGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on defined medium';\n gapfilledReactions{cntGF,3}='Condition-specific gapfilling';\n gapfilledReactions(cntGF,4:length(condGF)+3)=condGF;\n cntGF=cntGF+1;\n end\n if ~isempty(targetGF)\n summary.targetGF=union(summary.targetGF,targetGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on defined medium';\n gapfilledReactions{cntGF,3}='Targeted gapfilling';\n gapfilledReactions(cntGF,4:length(targetGF)+3)=targetGF;\n cntGF=cntGF+1;\n end\n if ~isempty(relaxGF)\n summary.relaxGF=union(summary.relaxGF,relaxGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}='Growth on defined medium';\n gapfilledReactions{cntGF,3}='Gapfilling based on relaxFBA';\n gapfilledReactions(cntGF,4:length(relaxGF)+3)=relaxGF;\n cntGF=cntGF+1;\n end\nend\n\n% if there are any false negative predictions\n% find what reactions should be added to enable agreement with experimental\n% data\n\nfields=fieldnames(testResults);\n\nfor i=1:length(fields)\n % define if objective should be maximized or minimized\n if any(contains(fields{i},{'Carbon_sources','Metabolite_uptake','Drug_metabolism'}))\n osenseStr = 'min';\n elseif any(contains(fields{i},{'Fermentation_products','Secretion_products','Bile_acid_biosynthesis','PutrefactionPathways'}))\n osenseStr = 'max';\n end\n FNlist = testResults.(fields{i});\n if size(FNlist,1)>1\n FNs = FNlist(find(strcmp(FNlist(:,1),microbeID)),2:end);\n FNs = FNs(~cellfun(@isempty, FNs));\n if ~isempty(FNs)\n for j=1:length(FNs)\n metExch=['EX_' database.metabolites{find(strcmp(database.metabolites(:,2),FNs{j})),1} '(e)'];\n if contains(fields{i},'PutrefactionPathways')\n % reaction ID itself provided\n metExch = FNs{j};\n end\n % find reactions that could be gap-filled to enable flux\n try\n [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,metExch,biomassReaction,osenseStr,database);\n catch\n condGF = {};\n targetGF = {};\n relaxGF = {};\n end\n % export the gapfilled reactions\n if ~isempty(condGF)\n summary.condGF=union(summary.condGF,condGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}=FNs{j};\n gapfilledReactions{cntGF,3}='Condition-specific gapfilling';\n gapfilledReactions(cntGF,4:length(condGF)+3)=condGF;\n cntGF=cntGF+1;\n end\n if ~isempty(targetGF)\n summary.targetGF=union(summary.targetGF,targetGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}=FNs{j};\n gapfilledReactions{cntGF,3}='Targeted gapfilling';\n gapfilledReactions(cntGF,4:length(targetGF)+3)=targetGF;\n cntGF=cntGF+1;\n end\n if ~isempty(relaxGF)\n summary.relaxGF=union(summary.relaxGF,relaxGF);\n \n gapfilledReactions{cntGF,1}=microbeID;\n gapfilledReactions{cntGF,2}=FNs{j};\n gapfilledReactions{cntGF,3}='Gapfilling based on relaxFBA';\n gapfilledReactions(cntGF,4:length(relaxGF)+3)=relaxGF;\n cntGF=cntGF+1;\n end\n end\n end\n end\nend\n\n% rebuild periplasmatic space if applies\ninfoFile = readInputTableForPipeline(infoFilePath);\n[model] = createPeriplasmaticSpace(model,microbeID,infoFile);\n\n% remove futile cycles if any exist\n[model, deletedRxns, addedRxns] = removeFutileCycles(model, biomassReaction, database);\nreplacedReactions{1,1}=microbeID;\nreplacedReactions{1,2}='Futile cycle correction';\nreplacedReactions{1,3}='To replace';\nreplacedReactions(1,4:length(deletedRxns)+3)=deletedRxns;\n\n% if any futile cycles remain\n[atpFluxAerobic, atpFluxAnaerobic] = testATP(model);\nif atpFluxAerobic > 200 || atpFluxAnaerobic > 150\n % let us try if running removeFutileCycles again will work\n [model, deletedRxns, addedRxns] = removeFutileCycles(model, biomassReaction, database);\n replacedReactions{1,1}=microbeID;\n replacedReactions{1,2}='Futile cycle correction';\n replacedReactions{1,3}='To replace';\n replacedReactions(1,4:length(deletedRxns)+3)=deletedRxns;\nend\n\n% add the gap-filling to model.comments field\nfor i=1:length(model.rxns)\n if strcmp(model.grRules{i},'demeterGapfill')\n model.grRules{i}=strrep(model.grRules{i},'demeterGapfill','');\n if ~isempty(find(strcmp(summary.condGF,model.rxns{i})))\n model.comments{i}='Added by DEMETER to enable flux with VMH-consistent constraints.';\n elseif ~isempty(find(strcmp(summary.targetGF,model.rxns{i})))\n model.comments{i}='Added by DEMETER during targeted gapfilling to enable production of required metabolites.';\n elseif ~isempty(find(strcmp(summary.relaxGF,model.rxns{i})))\n model.comments{i}='Added by DEMETER based on relaxFBA. Low confidence level.';\n end\n end\nend\n\n% rebuild and export the model\nrevisedModel = rebuildModel(model,database);\nrevisedModel = changeObjective(revisedModel,biomassReaction);\n% limit flux through sink reactions\nrevisedModel = changeRxnBounds(revisedModel,revisedModel.rxns(find(strncmp(revisedModel.rxns,'sink_',5)),1),-1,'l');\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/debugging/debugModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.16291685957460625}} {"text": "function [n, nm, nl, ts, names, m] = nex_marker(filename, varname)\n% nex_marker(filename, varname): Read a marker variable from a .nex file\n%\n% [n, nm, nl, ts, names, m] = nex_marker(filename, varname)\n%\n% INPUT:\n% filename - if empty string, will use File Open dialog\n% varname - variable name\n%\n% continuous (a/d) data come in fragments. Each fragment has a timestamp\n% and a number of a/d data points. The timestamp corresponds to\n% the time of recording of the first a/d value in this fragment.\n% All the data values stored in the vector d. \n% OUTPUT:\n% n - number of markers\n% nm - number of fields in each marker\n% nl - number of characters in each marker field\n% ts - array of marker timestamps (in seconds)\n% names - names of marker fields ([nm 64] character array)\n% m - character array of marker values [n nl nm]\n\n% original from Plexon, download from http://www.plexoninc.com (8/4/02)\n% modifications by 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\nn = 0;\nnm = 0;\nnl = 0;\nts = 0;\nm = 0;\nnames = 0;\n\nif(nargin ~= 2)\n disp('2 input arguments are required')\n return\nend\n\nif(ischar(filename) == 0)\n disp('input arguments should be character arrays')\n return\nend\n\nif(ischar(varname) == 0)\n disp('input arguments should be character arrays')\n return\nend\n\nif(length(filename) == 0)\n [fname, pathname] = uigetfile('*.nex', 'Select a Nex file');\n filename = strcat(pathname, fname);\nend\n\nfid = fopen(filename, 'r', 'ieee-le');\nif(fid == -1)\n disp('cannot open file');\n return\nend\n\ndisp(strcat('file = ', filename));\nmagic = fread(fid, 1, 'int32');\nversion = fread(fid, 1, 'int32');\ncomment = fread(fid, 256, 'char');\nfreq = fread(fid, 1, 'double');\ntbeg = fread(fid, 1, 'int32');\ntend = fread(fid, 1, 'int32');\nnvar = fread(fid, 1, 'int32');\nfseek(fid, 260, 'cof');\nname = zeros(1, 64);\nfound = 0;\nfor i=1:nvar\n type = fread(fid, 1, 'int32');\n var_version = fread(fid, 1, 'int32');\n name = fread(fid, [1 64], 'char');\n offset = fread(fid, 1, 'int32');\n n = fread(fid, 1, 'int32');\n dummy = fread(fid, 32, 'char');\n adfreq = fread(fid, 1, 'double');\n adtomv = fread(fid, 1, 'double');\n npw = fread(fid, 1, 'int32');\n nm = fread(fid, 1, 'int32');\n nl = fread(fid, 1, 'int32');\n dummy = fread(fid, 68, 'char');\n name = char(name);\n name = deblank(name);\n k = strcmp(name, deblank(varname));\n if(k == 1)\n if type ~= 6\n disp(sprintf('%s is not a marker variable', deblank(varname)));\n return;\n end\n found = 1;\n fseek(fid, offset, 'bof');\n ts = fread(fid, [1 n], 'int32');\n names = zeros(1,64);\n m = zeros(n, nl, nm);\n for j=1:nm\n names(j, :) = fread(fid, [1 64], 'char');\n for p = 1:n\n m(p, :, j) = fread(fid, [1 nl], 'char');\n end\n end\n break\n end\nend\n\nfclose(fid);\n\nif found == 0\n disp('did not find variable in the file');\nelse\n names = char(names);\n m = char(m);\n ts = ts/freq;\n disp(strcat('number of markers = ', num2str(n)));\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/nex_marker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.1628083676582191}} {"text": "function crossfeed(varargin)\n\n%CROSSFEED Checks for crossfeeding and duplicate data channels\n% CROSSFEED Reads a short snippet of data from an entire network and cross\n% correlates each trace against all others (without time shifting). Events\n% are then clustered and a directory of png images is written out showing\n% raw and filtered versions of the waveforms in each cluster. These images\n% can be used to check for data problems across the network. The image\n% directory is named FIG_yyyymmdd_HHMMSS according to the start time. \n%\n% CROSSFEED(STARTTIME) specify a start time in Matlab date format\n%\n% CROSSFEED(STARTTIME,DURATION) specify a trace duration in seconds.\n%\n% CROSSFEED(STARTTIME,DURATION,THRESHOLD) specify a cross correlation\n% threshold for clustering.\n%\n% CROSSFEED(STARTTIME,DURATION,THRESHOLD,NETWORK) specify a network to\n% examine.\n%\n% Using CROSSFEED with no arguments is equivalent to:\n% CROSSFEED( floor(now)-0.5 , 30 , 0.7 , 'AV' )\n%\n% Note that \"now\" is returned in local time. So the default data examined\n% is 8 to 9 hours old, assuming AKST/AKDT.\n%\n% -- CAVEATS --\n% This function is hardwired to run in the UAF Seis Lab assuming one day\n% archive databases that contain waveforms and station-related tables (to\n% get network affiliations)\n\n\n\n\n% READ ARGUMENTS AND SET DEFAULT VALUES\nif numel(varargin)>=1\n startTime = varargin{1};\nelse\n startTime = floor(now)-0.5;\nend\n\nif numel(varargin)>=2\n duration = varargin{2}/86400;\nelse\n duration = 30/86400;\nend\n\nif numel(varargin)>=3\n threshold = varargin{3};\nelse\n threshold = 0.7;\nend\n\nif numel(varargin)==4\n networkName = varargin{4};\nelse\n networkName = 'AV';\nend\n \n\n\n% GET CHANNEL LIST FROM DATABASE\ndbWfdisc = ['/aerun/sum/db/archive/archive_' datestr(startTime,'yyyy') '/archive_' datestr(startTime,'yyyy') '_' datestr(startTime,'mm') '_' datestr(startTime,'dd')];\ndisp(['Reading STA_CHANs for network ' networkName ' from database: ']);\ndisp([ ' ' dbWfdisc ' ...']);\n\ndb = dbopen(dbWfdisc,'r');\ndb = dblookup(db,'','wfdisc','','');\ndb1 = dblookup(db,'','affiliation','','');\ndb = dbjoin(db,db1);\ndb = dbsubset(db,['net==\"' networkName '\"']);\n[wfdisc.sta wfdisc.chan wfdisc.net] = dbgetv(db,'sta','chan','net');\ndbclose(db);\n\n\n% GET LIST OF UNIQUE STA CHANs \nstaChanNetList = strcat(wfdisc.sta,'#',wfdisc.chan,'#',wfdisc.net);\nstaChanNetList = unique(staChanNetList);\nfor n = 1:numel(staChanNetList)\n tmp = regexp(staChanNetList(n), '#', 'split');\n scnl(n) = scnlobject(tmp{1}{1},tmp{1}{2},tmp{1}{3},'');\nend\n\n\n% READ IN WAVEFORMS\ndisp(['Loading ' num2str(numel(scnl)) ' waveforms for this time period ...']);\ndisp([' start time: ' datestr(startTime)]);\ndisp([' duration: ' num2str(duration*86400) ' seconds']);\nds = datasource('antelope',dbWfdisc);\nw = waveform(ds,scnl,startTime,startTime+duration);\nw = demean(w);\nw = fillgaps(w,0);\nw = detrend(w);\n\n\n% PREP WAVEFORMS AND CROSS CORRELATE\nc = correlation(w);\nc = detrend(c);\nc = demean(c);\nc = taper(c);\nc = butter(c,[2 12]);\n%c = xcorr(c);\n\n\n% DO ZERO LAG XCORR\nD = get(c,'DATA');\nwcoeff = 1./sqrt(sum(D.*D));\n%wcoeff(find(wcoeff==Inf)) = 0;\ncorr = zeros(size(D,2));\nlag = zeros(size(D,2));\nfor col = 1:size(D,2)\n for row = 1:size(D,2)\n corr(col,row) = sum(D(:,col).*D(:,row)) .* wcoeff(col) .* wcoeff(row);\n end\nend\nf = find(corr<0);\ncorr(f) = 0;\nf = find(isnan(corr));\ncorr(f) = 0;\nc = set(c,'corr',corr);\nc = set(c,'lag',lag);\nc = linkage(c);\nc = cluster(c,threshold);\n\n\n\n% MAKE FIGURE DIRECTORY\ndirName = [networkName '_' datestr(startTime,'yyyy') datestr(startTime,'mm') datestr(startTime,'dd') '_' datestr(startTime,'HH') datestr(startTime,'MM') datestr(startTime,'SS')];\nif ~exist(dirName,'dir')\n disp(['Creating new directory: ' dirName]);\n mkdir(dirName);\nend\n\n\n% PLOT TRACE CLUSTERS\nindex = find(c,'BIG',2);\nclust = get(c,'CLUST');\ndisp('--> dbpick selection strings: ');\nfor n = 1:max(clust(index))\n f = find(clust==n);\n figure('Color','w','Position',[50 50 800 1100]);\n set(gcf,'DefaultAxesFontSize',14)\n \n % RAW TRACE FIGURE\n\n wOrig = set(w(f),'UNITS','normalized scale');\n wOrigCrop = extract(wOrig,'TIME',startTime+5/86400,startTime+25/86400);\n wOrigCrop = demean(detrend(wOrigCrop));\n for i = 1:numel(wOrigCrop)\n wOrigCrop(i) = 0.25 * wOrigCrop(i) ./ std(wOrigCrop(i)) + i; \n end\n wOrigCrop = set(wOrigCrop,'UNITS','normalized scale');\n\n subplot(2,1,1)\n plot(wOrigCrop);\n legend(wOrigCrop);\n xlim([0 20]);\n ylim([0 numel(wOrig)+1]);\n text(19.3,0.05 *(numel(wOrig)+1),['correlation threshold: ' num2str(threshold)],'HorizontalAlignment','Right','FontSize',12);\n text(19.3,0.10 *(numel(wOrig)+1),['trace duration: ' num2str(duration*86400) 's'],'HorizontalAlignment','Right','FontSize',12);\n text(19.3,0.15 *(numel(wOrig)+1),'Raw traces','HorizontalAlignment','Right','FontSize',12,'FontWeight','Bold');\n\n \n % PLOT FILTERED CROPPED TRACE\n subplot(2,1,2)\n c2 = subset(c,f);\n wFilt = waveform(c2);\n wFilt = set(wFilt,'UNITS','normalized scale');\n wFiltCrop = extract(wFilt,'TIME',startTime+10/86400,startTime+13/86400);\n for i = 1:numel(wOrig)\n wFiltCrop(i) = 0.25 * wFiltCrop(i) ./ std(wFiltCrop(i)); \n end\n plot(wFiltCrop,'Linewidth',1);\n legend(wFiltCrop);\n xlim([0 3]);\n ylim([-0.8 0.8]);\n text(2.9,-0.75,'Filtered on 2-12 Hz','HorizontalAlignment','Right','FontSize',12,'FontWeight','Bold');\n\n % WRITE OUT FIGURES\n subSta = get(wFilt,'STATION');\n subChan = get(wFilt,'CHANNEL');\n scList = [];\n fileName = [dirName '/overlays_' subSta{1} '_' subChan{1} '-' subSta{2} '_' subChan{2} '.png'];\n set(gcf, 'paperorientation', 'portrait');\n set(gcf, 'paperposition', [.25 .25 8 11] );\n print('-dpng',fileName);\n %\n close all\n \n \n % WRITE DBPICK TEXT\n scList = [];\n for i = 1:numel(subSta)\n scList = [scList subSta{i} ':' subChan{i} ','];\n end\n scList = scList(1:end-1);\n disp(['sc ' scList]);\nend\ndisp(['ts ' datestr(startTime,'yyyy/mm/dd HH:MM:SS')]);\n\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/uaf_internal/AEIC_AVO/+check/crossfeed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.16268002298873177}} {"text": "function F = in_fread_edf(sFile, sfid, SamplesBounds, ChannelsRange)\n% IN_FREAD_EDF: Read a block of recordings from a EDF/BDF file\n%\n% USAGE: F = in_fread_edf(sFile, sfid, SamplesBounds, ChannelsRange)\n% F = in_fread_edf(sFile, sfid, SamplesBounds) : Read all channels\n% F = in_fread_edf(sFile, sfid) : Read all channels, all the times\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2012-2023\n\n%% ===== PARSE INPUTS =====\nnChannels = sFile.header.nsignal;\niChanAnnot = find(strcmpi({sFile.header.signal.label}, 'EDF Annotations'));\niBadChan = find(sFile.channelflag == -1);\niChanSignal = setdiff(1:nChannels, iChanAnnot);\niChanWrongRate = find([sFile.header.signal(iChanSignal).sfreq] ~= max([sFile.header.signal(setdiff(iChanSignal,iBadChan)).sfreq])); \niChanSkip = union(iChanAnnot, iChanWrongRate);\n% By default: Read all the channels\nif (nargin < 4) || isempty(ChannelsRange)\n ChannelsRange = [1, nChannels];\nend\n% By default: Read all the file, at the main file frequency\nif (nargin < 3) || isempty(SamplesBounds)\n SamplesBounds = round(sFile.prop.times .* sFile.prop.sfreq);\nend\n\n% Block of times/channels to extract\nnReadChannels = double(ChannelsRange(2) - ChannelsRange(1) + 1);\n% Read annotations instead of real data ?\nisAnnotOnly = ~isempty(iChanAnnot) && (ChannelsRange(1) == ChannelsRange(2)) && ismember(ChannelsRange(1), iChanAnnot);\nisBdfStatus = strcmpi(sFile.format, 'EEG-BDF') && (ChannelsRange(1) == ChannelsRange(2)) && strcmpi(sFile.header.signal(ChannelsRange(1)).label, 'Status');\n% Data channels to read\nif isAnnotOnly\n % Read only on annotation channel\n iChanF = 1;\nelse\n % Remove all the annotation channels from the list of channels to read\n iChanF = setdiff(ChannelsRange(1):ChannelsRange(2), iChanSkip) - ChannelsRange(1) + 1;\n% if any(diff(iChanF) ~= 1)\n% error('All the data channels to read from the file must be contiguous (EDF Annotation channels must be at the end of the list).');\n% end\n if any(diff(iChanF) ~= 1)\n iChanLast = find(diff(iChanF) ~= 1, 1);\n iChanF = iChanF(1:iChanLast);\n else\n iChanLast = length(iChanF);\n end\n ChannelsRange = [iChanF(1), iChanF(iChanLast)] + ChannelsRange(1) - 1;\nend\n% Cannot read channels with different sampling rates at the same time\nif (ChannelsRange(1) ~= ChannelsRange(2))\n allFreq = [sFile.header.signal(ChannelsRange(1):ChannelsRange(2)).nsamples];\n if any(allFreq ~= allFreq(1))\n error(['Cannot read channels with mixed sampling rates at the same time.' 10 ...\n 'Mark as bad channels with different sampling rates than EEG.' 10 ...\n '(right-click on data file > Good/bad channels > Edit good/bad channels)']);\n end\nend\n% Number of time samples to read\nnTimes = round(sFile.header.reclen * sFile.header.signal(ChannelsRange(1)).sfreq);\niTimes = SamplesBounds(1):SamplesBounds(2);\n\n\n%% ===== READ ALL NEEDED EPOCHS =====\n% Detect which epochs are necessary for the range of data selected\nepochRange = floor(SamplesBounds ./ nTimes);\nepochsToRead = epochRange(1) : epochRange(2);\n% Initialize block of data to read\nif isAnnotOnly\n F = zeros(nReadChannels, 2 * length(iTimes));\nelse\n F = zeros(nReadChannels, length(iTimes));\nend\n% Marker that we increment when we add data to F\niF = 1;\n% Read all the needed epochs\nfor i = 1:length(epochsToRead)\n % Find the samples to read from this epoch\n BoundsEpoch = nTimes * epochsToRead(i) + [0, nTimes-1];\n BoundsRead = [max(BoundsEpoch(1), iTimes(1)), ...\n min(BoundsEpoch(2), iTimes(end))];\n iTimeRead = BoundsRead(1):BoundsRead(2);\n % Convert this samples into indices in this very epoch \n iTimeRead = iTimeRead - nTimes * epochsToRead(i);\n % New indices to read\n if isAnnotOnly\n iNewF = iF:(iF + 2*length(iTimeRead) - 1);\n else\n iNewF = iF:(iF + length(iTimeRead) - 1);\n end\n % Read epoch (full or partial)\n F(iChanF,iNewF) = edf_read_epoch(sFile, sfid, epochsToRead(i), iTimeRead, ChannelsRange, isAnnotOnly, isBdfStatus);\n % Increment marker\n iF = iF + length(iTimeRead);\nend\n\n\n\nend\n\n\n\n%% ===== READ ONE EPOCH =====\nfunction F = edf_read_epoch(sFile, sfid, iEpoch, iTimes, ChannelsRange, isAnnotOnly, isBdfStatus)\n % ===== COMPUTE OFFSETS =====\n nTimes = sFile.header.reclen * [sFile.header.signal.sfreq];\n nReadTimes = length(iTimes);\n nReadChannels = double(ChannelsRange(2) - ChannelsRange(1) + 1);\n iChannels = ChannelsRange(1):ChannelsRange(2);\n % Check that all the channels selected have the same freq rate\n if any(nTimes(iChannels) ~= nTimes(iChannels(1)))\n error('Cannot read at the same signals with different sampling frequency.');\n end\n % Size of one value \n if strcmpi(sFile.format, 'EEG-BDF')\n % BDF: int24 => 3 bytes\n bytesPerVal = 3;\n % Reading status or regular channel\n if isBdfStatus\n dataClass = 'ubit24';\n else\n dataClass = 'bit24';\n end\n else\n % EDF: int16 => 2 bytes\n bytesPerVal = 2;\n dataClass = 'int16';\n isBdfStatus = 0;\n end\n % Offset of the beginning of the recordings in the file\n offsetHeader = round(sFile.header.hdrlen);\n % Offset of epoch\n offsetEpoch = round(iEpoch * sum(nTimes) * bytesPerVal);\n % Channel offset\n offsetChannel = round(sum(nTimes(1:ChannelsRange(1)-1)) * bytesPerVal);\n % Time offset at the beginning and end of each channel block\n offsetTimeStart = round(iTimes(1) * bytesPerVal);\n offsetTimeEnd = round((nTimes(ChannelsRange(1)) - iTimes(end) - 1) * bytesPerVal);\n % ALL THE \"ROUND\" CALLS WERE ADDED AFTER DISCOVERING THAT THERE WERE SOMETIMES ROUNDING ERRORS IN THE MULTIPLICATIONS\n \n % Where to start reading in the file ?\n % => After the header, the number of skipped epochs, channels and time samples\n offsetStart = offsetHeader + offsetEpoch + offsetChannel + offsetTimeStart;\n % Number of time samples to skip after each channel\n offsetSkip = offsetTimeStart + offsetTimeEnd; \n\n \n % ===== READ DATA BLOCK =====\n % Position file at the beginning of the trial\n fseek(sfid, offsetStart, 'bof');\n % Read annotation data (char)\n if isAnnotOnly\n dataClass = 'uint8';\n nReadTimes = bytesPerVal * nReadTimes; % 1 byte instead of 2\n end\n % Read trial data\n % => WARNING: CALL TO FREAD WITH SKIP=0 DOES NOT WORK PROPERLY\n if (offsetSkip == 0)\n F = fread(sfid, [nReadTimes, nReadChannels], dataClass)';\n elseif (bytesPerVal == 2)\n precision = sprintf('%d*%s', nReadTimes, dataClass);\n F = fread(sfid, [nReadTimes, nReadChannels], precision, offsetSkip)';\n % => WARNING: READING USING ubit24 SOMETIMES DOESNT WORK => DOING IT MANUALLY\n elseif (bytesPerVal == 3)\n % Reading each bit independently\n precision = sprintf('%d*%s', 3*nReadTimes, 'uint8');\n F = fread(sfid, [3*nReadTimes, nReadChannels], precision, offsetSkip)';\n % Grouping the 3 bits together\n F = F(:,1:3:end) + F(:,2:3:end)*256 + F(:,3:3:end)*256*256;\n % 2-Complement (negative value indicated by most significant bit)\n if strcmpi(dataClass, 'bit24')\n iNeg = (F >= 256*256*128);\n F(iNeg) = F(iNeg) - 256*256*256;\n end\n end\n % Check that data block was fully read\n if (numel(F) < nReadTimes * nReadChannels)\n % Number of full time samples that were read\n nTimeTrunc = max(0, floor(numel(F) / nReadChannels) - 1);\n % Error message\n disp(sprintf('EDF> ERROR: File is truncated (%d time samples were read instead of %d). Padding with zeros...', nTimeTrunc, nReadTimes));\n % Pad data with zeros \n Ftmp = zeros(nReadTimes, nReadChannels);\n F = F';\n Ftmp(1:numel(F)) = F(:);\n F = Ftmp';\n end\n\n % Processing for BDF status file\n if isBdfStatus\n % Mask to keep only the first 16 bits (Triggers bits)\n % Bit 16 : High when new Epoch is started\n % Bit 17-19 : Speed bits 0 1 2\n % Bit 20 \t: High when CMS is within range\n % Bit 21 \t: Speed bit 3\n % Bit 22 \t: High when battery is low\n % Bit 23 : High if ActiveTwo MK2\n F = bitand(F, hex2dec('00FFFF'));\n % Processing for real data\n elseif ~isAnnotOnly\n % Convert to double\n F = double(F);\n % Apply gains\n F = bst_bsxfun(@rdivide, F, [sFile.header.signal(iChannels).gain]');\n% IN THEORY: THIS OFFSET SECTION IS USEFUL, BUT IN PRACTICE IT LOOKS LIKE THE VALUES IN ALL THE FILES ARE CENTERED ON ZERO\n% % Add offset \n% if isfield(sFile.header.signal, 'offset') && ~isempty(sFile.header.signal(1).offset)\n% % ...\n% end\n end\nend\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_fread_edf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.16263817108463047}} {"text": "function CPD = tabular_CPD(bnet, self, varargin)\n% TABULAR_CPD Make a multinomial conditional prob. distrib. (CPT)\n%\n% CPD = tabular_CPD(bnet, node) creates a random CPT.\n%\n% The following arguments can be specified [default in brackets]\n%\n% CPT - specifies the params ['rnd']\n% - T means use table T; it will be reshaped to the size of node's family.\n% - 'rnd' creates rnd params (drawn from uniform)\n% - 'unif' creates a uniform distribution\n% adjustable - 0 means don't adjust the parameters during learning [1]\n% prior_type - defines type of prior ['none']\n% - 'none' means do ML estimation\n% - 'dirichlet' means add pseudo-counts to every cell\n% - 'entropic' means use a prior P(theta) propto exp(-H(theta)) (see Brand)\n% dirichlet_weight - equivalent sample size (ess) of the dirichlet prior [1]\n% dirichlet_type - defines the type of Dirichlet prior ['BDeu']\n% - 'unif' means put dirichlet_weight in every cell\n% - 'BDeu' means we put 'dirichlet_weight/(r q)' in every cell\n% where r = self_sz and q = prod(parent_sz) (see Heckerman)\n% trim - 1 means trim redundant params (rows in CPT) when using entropic prior [0]\n% entropic_pcases - list of assignments to the parents nodes when we should use \n% the entropic prior; all other cases will be estimated using ML [1:psz]\n% sparse - 1 means use 1D sparse array to represent CPT [0]\n%\n% e.g., tabular_CPD(bnet, i, 'CPT', T)\n% e.g., tabular_CPD(bnet, i, 'CPT', 'unif', 'dirichlet_weight', 2, 'dirichlet_type', 'unif')\n%\n% REFERENCES\n% M. Brand - \"Structure learning in conditional probability models via an entropic prior\n% and parameter extinction\", Neural Computation 11 (1999): 1155--1182\n% M. Brand - \"Pattern discovery via entropy minimization\" [covers annealing]\n% AI & Statistics 1999. Equation numbers refer to this paper, which is available from\n% www.merl.com/reports/docs/TR98-21.pdf\n% D. Heckerman, D. Geiger and M. Chickering, \n% \"Learning Bayesian networks: the combination of knowledge and statistical data\",\n% Microsoft Research Tech Report, 1994\n\n\nif nargin==0\n % This occurs if we are trying to load an object from a file.\n CPD = init_fields;\n CPD = class(CPD, 'tabular_CPD', discrete_CPD(0, []));\n return;\nelseif isa(bnet, 'tabular_CPD')\n % This might occur if we are copying an object.\n CPD = bnet;\n return;\nend\nCPD = init_fields;\n\nns = bnet.node_sizes;\nps = parents(bnet.dag, self);\nfam_sz = ns([ps self]);\npsz = prod(ns(ps));\nCPD.sizes = fam_sz;\nCPD.leftright = 0;\nCPD.sparse = 0;\n\n% set defaults\nCPD.CPT = mk_stochastic(myrand(fam_sz));\nCPD.adjustable = 1;\nCPD.prior_type = 'none';\ndirichlet_type = 'BDeu';\ndirichlet_weight = 1;\nCPD.trim = 0;\nselfprob = 0.1;\nCPD.entropic_pcases = 1:psz;\n\n% extract optional args\nargs = varargin;\n% check for old syntax CPD(bnet, i, CPT) as opposed to CPD(bnet, i, 'CPT', CPT)\nif ~isempty(args) & ~isstr(args{1})\n CPD.CPT = myreshape(args{1}, fam_sz);\n args = [];\nend\n\nfor i=1:2:length(args)\n switch args{i},\n case 'CPT',\n T = args{i+1};\n if ischar(T)\n switch T\n case 'unif', CPD.CPT = mk_stochastic(myones(fam_sz));\n case 'rnd', CPD.CPT = mk_stochastic(myrand(fam_sz));\n otherwise, error(['invalid CPT ' T]); \n end\n else\n CPD.CPT = myreshape(T, fam_sz);\n end\n case 'prior_type', CPD.prior_type = args{i+1};\n case 'dirichlet_type', dirichlet_type = args{i+1};\n case 'dirichlet_weight', dirichlet_weight = args{i+1};\n case 'adjustable', CPD.adjustable = args{i+1};\n case 'clamped', CPD.adjustable = ~args{i+1};\n case 'trim', CPD.trim = args{i+1};\n case 'entropic_pcases', CPD.entropic_pcases = args{i+1};\n case 'sparse', CPD.sparse = args{i+1};\n otherwise, error(['invalid argument name: ' args{i}]); \n end\nend\n\nswitch CPD.prior_type\n case 'dirichlet',\n switch dirichlet_type\n case 'unif', CPD.dirichlet = dirichlet_weight * myones(fam_sz);\n case 'BDeu', CPD.dirichlet = (dirichlet_weight/psz) * mk_stochastic(myones(fam_sz));\n otherwise, error(['invalid dirichlet_type ' dirichlet_type])\n end\n case {'entropic', 'none'}\n CPD.dirichlet = [];\n otherwise, error(['invalid prior_type ' prior_type])\nend\n\n \n\n% fields to do with learning\nif ~CPD.adjustable\n CPD.counts = [];\n CPD.nparams = 0;\n CPD.nsamples = [];\nelse\n %CPD.counts = zeros(size(CPD.CPT));\n CPD.counts = zeros(prod(size(CPD.CPT)), 1);\n psz = fam_sz(1:end-1);\n ss = fam_sz(end);\n if CPD.leftright\n % For each of the Qps contexts, we specify Q elements on the diagoanl\n CPD.nparams = Qps * Q;\n else\n % sum-to-1 constraint reduces the effective arity of the node by 1\n CPD.nparams = prod([psz ss-1]);\n end\n CPD.nsamples = 0;\nend\n\nCPD.trimmed_trans = [];\nfam_sz = CPD.sizes;\n\n%psz = prod(fam_sz(1:end-1));\n%ssz = fam_sz(end);\n%CPD.trimmed_trans = zeros(psz, ssz); % must declare before reading\n\n%sparse CPT\nif CPD.sparse\n CPD.CPT = sparse(CPD.CPT(:));\nend\n\nCPD = class(CPD, 'tabular_CPD', discrete_CPD(~CPD.adjustable, fam_sz));\n\n\n%%%%%%%%%%%\n\nfunction CPD = init_fields()\n% This ensures we define the fields in the same order \n% no matter whether we load an object from a file,\n% or create it from scratch. (Matlab requires this.)\n\nCPD.CPT = [];\nCPD.sizes = [];\nCPD.prior_type = [];\nCPD.dirichlet = [];\nCPD.adjustable = [];\nCPD.counts = [];\nCPD.nparams = [];\nCPD.nsamples = [];\nCPD.trim = [];\nCPD.trimmed_trans = [];\nCPD.leftright = [];\nCPD.entropic_pcases = [];\nCPD.sparse = [];\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/CPDs/@tabular_CPD/tabular_CPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16262376709426707}} {"text": "function [out] = analyseThermoConstrainedModel(model, cumNormProbCutoff, printLevel, resultsBaseFileName)\n% USAGE:\n%\n% [out] = analyseThermoConstrainedModel(model, cumNormProbCutoff, printLevel, resultsBaseFileName)\n%\n% INPUTS:\n% model: structure with fields:\n%\n% * .DfGt0 - `m x 1` array of estimated standard transformed Gibbs\n% energies of formation.\n% * .DrGt0 - `n x 1` array of estimated standard transformed\n% reaction Gibbs energies.\n% * .DfGtMin - `m x 1` array of estimated lower bounds on\n% transformed Gibbs energies of formation.\n% * .DfGtMax - `m x 1` array of estimated upper bounds on\n% transformed Gibbs energies of formation.\n% * .DrGtMin - `n x 1` array of estimated lower bounds on\n% transformed reaction Gibbs energies.\n% * .DrGtMax - `n x 1` array of estimated upper bounds on\n% transformed reaction Gibbs energies.\n% * .quantDir - `n x 1` array indicating quantitatively assigned\n% reaction directionality. 1 for reactions that are\n% irreversible in the forward direction, -1 for\n% reactions that are irreversible in the reverse\n% direction, and 0 for reversible reactions.\n% cumNormProbCutoff: default = 0.2\n% printLevel: verbose level, default = 1\n% resultsBaseFileName:\n%\n% OUTPUT:\n% out:\n\nout=[];\n\nif ~exist('printLevel','var')\n printLevel=1;\nend\nif ~exist('cumNormProbCutoff','var')\n cumNormProbCutoff=0.2;\nelse\n if cumNormProbCutoff<0\n error('cumNormProbCutoff cannot be less than zero')\n end\nend\n\nif 1\n %statistics of directions\n fprintf('%s\\n','directionalityStats...');\n model=directionalityStats(model,cumNormProbCutoff,printLevel);\nend\n%OUTPUT\n% model.directions a structue of boolean vectors with different directionality\n% assignments where some vectors contain subsets of others\n%\n% qualtiative -> quantiative changed reaction directions\n% .directions.forwardForward\n% .directions.forwardReverse\n% .directions.forwardReversible\n% .directions.reversibleFwd\n% .directions.reversibleRev\n% .directions.reversibleReversible\n% .directions.tightened\n%\n% subsets of qualtiatively forward -> quantiatively reversible\n% .directions.forwardReversible_bydGt0\n% .directions.forwardReversible_bydGt0LHS\n% .directions.forwardReversible_bydGt0Mid\n% .directions.forwardReversible_bydGt0RHS\n%\n% .directions.forwardReversible_byConc_zero_fixed_DrG0\n% .directions.forwardReversible_byConc_negative_fixed_DrG0\n% .directions.forwardReversible_byConc_positive_fixed_DrG0\n% .directions.forwardReversible_byConc_negative_uncertain_DrG0\n% .directions.forwardReversible_byConc_positive_uncertain_DrG0\n\nif 1\n %report on directionality changes\n fprintf('%s\\n','directionalityChangeReport...');\n directionalityChangeReport(model,cumNormProbCutoff,printLevel,resultsBaseFileName)\nend\n\n% if 0\n% fprintf('\\n%s\\n','...standardGibbsFormationEnergyStats');\n% [nKeq,nGC,nNone]=standardGibbsFormationEnergyStats(model,figures);\n% end\n\nif 0\n %pie charts with proportions of reaction directionalities and changes in\n %directionality\n fprintf('%s\\n','directionalityStatFigures...');\n directionalityStatsFigures(model.directions,resultsBaseFileName)\nend\n\n%figures of reaction directionality changes\n%qualitatively forward now quantiatiavely reversible\nif any(model.directions.forward2Reversible)\n fprintf('%s\\n','forwardReversibleFigures...');\n if 0\n forwardReversibleFigures(model)\n else\n thorStandard=0;\n forwardReversibleFiguresCC(model,model.directions,thorStandard)\n end\nend\n\nreturn\n\n%create a vertical errorbar figure of the qualitatively forward transport reactions\n%that are quantitatively reversible, whether from group contribution or\n%Keq, that then need to be assigned to be forward, to limit the growth rate\n% i.e. abc transporters or reactions involving protons\nif any(model.directions.forwardReversible & model.transportRxnBool)\n forwardTransportQuantReverseFigures(model)\nend\n\n%vertical errorbar of qualitatively forward but quantitatively reverse\n%forward, probably reverse\n% .directions.forwardReversible_bydGt0RHS\n% .directions.forwardReversible_byConc_positive_fixed_DrG0\n% .directions.forwardReversible_byConc_positive_uncertain_DrG0\nfwdProbReverse=model.directions.forwardReversible_bydGt0RHS | ...\n model.directions.forwardReversible_byConc_positive_uncertain_DrG0| ...\n model.directions.forwardReversible_byConc_positive_fixed_DrG0;\nif any(fwdProbReverse) && 0\n forwardProbablyReverseFigures(model,directions)\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/thermo/directionalityReport/analyseThermoConstrainedModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.16242228223411295}} {"text": "classdef ThreeDimKspWindTunnelDragCoeffModel < AbstractDragCoefficientModel\n %ThreeDimKspWindTunnelDragCoeffModel Summary of this class goes here\n % Detailed explanation goes here\n\n properties\n slices(1,:) ThreeDimKWTDragCoefficientModelSlice\n\n speed(1,:) double\n altitude(:,1) double\n aoa(1,:) double\n data double\n\n gi\n end\n\n properties(Constant)\n enum = DragCoefficientModelEnum.ThreeDimWindTunnel\n end\n\n methods\n function obj = ThreeDimKspWindTunnelDragCoeffModel(dataSlices)\n obj.slices = dataSlices;\n obj.sortSlicesByAoA();\n end\n\n function CdA = getDragCoeff(obj, ut, rVect, vVect, bodyInfo, mass, altitude, pressure, density, vVectECEFMag, totalAoA, aoa, sideslip)\n arguments\n obj(1,1) ThreeDimKspWindTunnelDragCoeffModel\n ut(1,1) double \n rVect(3,1) double \n vVect(3,1) double \n bodyInfo(1,1) KSPTOT_BodyInfo\n mass(1,1) double\n altitude(1,1) double\n pressure(1,1) double\n density(1,1) double\n vVectECEFMag(1,1) double\n totalAoA(1,1) double = 0;\n aoa(1,1) double = 0;\n sideslip(1,1) double = 0;\n end\n\n CdA = obj.gi(altitude, vVectECEFMag, totalAoA);\n CdA = max([CdA, 0]);\n end\n\n function addSlice(obj, newSlice)\n obj.slices(end+1) = newSlice;\n obj.sortSlicesByAoA();\n end\n\n function removeSlice(obj, slice)\n obj.slices(obj.slices == slice) = [];\n obj.sortSlicesByAoA();\n end\n\n function tf = usesTotalAoA(obj)\n tf = true;\n end\n\n function tf = usesAoaAndSideslip(obj)\n tf = false;\n end\n\n function createGriddedInterpFromSlices(obj)\n obj.sortSlicesByAoA();\n\n obj.speed = obj.slices(1).twoDSlice.speed;\n obj.altitude = obj.slices(1).twoDSlice.altitude;\n obj.aoa = [obj.slices.aoa];\n\n obj.data = [];\n for(i=1:length(obj.slices)) %#ok<*NO4LP> \n slice = obj.slices(i);\n obj.data(:,:,i) = slice.twoDSlice.data;\n end\n\n gridVecs = {obj.altitude, obj.speed, obj.aoa};\n obj.gi = griddedInterpolant(gridVecs, obj.data, 'makima', 'nearest');\n end\n\n function sortSlicesByAoA(obj)\n AoAs = [obj.slices.aoa];\n [~,I] = sort(AoAs);\n obj.slices = obj.slices(I);\n end\n\n function [sliceGoodTf, messages] = getStatusOfSlices(obj)\n sliceGoodTf = true(1, length(obj.slices));\n messages = cell(1, length(obj.slices));\n\n AoAs = [obj.slices.aoa];\n \n for(i=1:length(obj.slices))\n slice = obj.slices(i);\n\n [thisSliceGoodTf, sliceMessages] = slice.getSliceStatus(); \n sliceGoodTf(i) = sliceGoodTf(i) && thisSliceGoodTf;\n messages{i} = horzcat(messages{i}, sliceMessages);\n\n if(length(obj.slices) == 1)\n sliceGoodTf(i) = false;\n messages{i}(end+1) = 'There must be at least two AoA data sets.';\n end\n\n if(i >= 2)\n subAoAs = AoAs;\n subAoAs(i) = [];\n if(any(AoAs(i) == subAoAs)) \n sliceGoodTf(i) = false;\n messages{i}(end+1) = 'Duplicate angle of attack data sets are not allowed.';\n end\n\n slice1 = obj.slices(1);\n twoDModelSlice1 = slice1.twoDSlice;\n \n altitudeSlice1 = twoDModelSlice1.altitude;\n speedSlice1 = twoDModelSlice1.speed;\n\n twoDModel = slice.twoDSlice;\n altitudeSliceI = twoDModel.altitude;\n speedSliceI = twoDModel.speed;\n\n if(numel(altitudeSliceI) == numel(altitudeSlice1))\n bool = altitudeSliceI(:) - altitudeSlice1(:) ~= 0;\n if(any(bool))\n sliceGoodTf(i) = false; \n messages{i}(end+1) = \"The altitude axis points do not match those of the first AoA data set. All axis points must be identical in all data sets.\";\n end\n else\n sliceGoodTf(i) = false; \n messages{i}(end+1) = \"There are not the same number of altitude axis points of those of the first AoA data set. All axis points must be identical in all data sets.\"; \n end\n\n\n if(numel(speedSliceI) == numel(speedSlice1))\n bool = speedSliceI(:) - speedSlice1(:) ~= 0;\n if(any(bool))\n sliceGoodTf(i) = false; \n messages{i}(end+1) = \"The speed axis points do not match those of the first AoA data set. All axis points must be identical in all data sets.\"; \n end\n else\n sliceGoodTf(i) = false; \n messages{i}(end+1) = \"There are not the same number of speed axis points of those of the first AoA data set. All axis points must be identical in all data sets.\"; \n end\n end\n\n if(sliceGoodTf(i) == true)\n messages{i} = \"No warnings or errors found.\";\n end\n end\n end\n\n function [listBoxStr, slices] = getListBoxStrs(obj)\n for(i=1:length(obj.slices))\n listBoxStr(i) = string(obj.slices(i).getListboxStr()); %#ok \n end\n\n slices = obj.slices;\n end\n\n function useTf = openEditDialog(obj, lvdData)\n out = AppDesignerGUIOutput({false});\n lvd_Edit3DKerbalWindTunnelDragPropertiesGUI_App(obj, lvdData, out);\n useTf = out.output{1};\n end\n end\n\n methods(Static)\n function obj = loadobj(obj)\n if(isempty(obj.slices))\n slice1 = ThreeDimKspWindTunnelDragCoeffModel.produceDataSlice(0, '');\n obj.addSlice(slice1);\n\n slice2 = ThreeDimKspWindTunnelDragCoeffModel.produceDataSlice(deg2rad(1), '');\n obj.addSlice(slice2);\n end\n\n try\n obj.createGriddedInterpFromSlices();\n catch ME\n % nothing to do here\n end\n end\n\n function slice = produceDataSlice(aoa, sliceDataFile)\n slice = ThreeDimKWTDragCoefficientModelSlice(aoa, sliceDataFile);\n end\n \n function dragCoeffModel = createDefault()\n slice1 = ThreeDimKspWindTunnelDragCoeffModel.produceDataSlice(0, '');\n slice2 = ThreeDimKspWindTunnelDragCoeffModel.produceDataSlice(deg2rad(1), '');\n slices = [slice1, slice2];\n \n dragCoeffModel = ThreeDimKspWindTunnelDragCoeffModel(slices);\n end\n end\nend", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_lvd/classes/ForceModels/aero/drag/three_dim_kerbal_wind_tunnel/@ThreeDimKspWindTunnelDragCoeffModel/ThreeDimKspWindTunnelDragCoeffModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3073580041760869, "lm_q1q2_score": 0.16207494962869567}} {"text": "function ft_realtime_fmriproxy(cfg)\n\n% FT_REALTIME_FMRIPROXY simulates an fMRI acquisition system by writing volumes in a\n% cycle of about 2 seconds. The voxel data is written as a column vector with X*Y*Z\n% channels, where X and Y are the readout and phase-encoding resolution, and Z is the\n% number of slices. The voxel data consists of a ellipsoid (a bit like a head) with\n% added lateralized activation (20 scan cycle) and noise.\n%\n% This function also writes out events of type='scan' and value='pulse' when the\n% simulated scanner initiates a scan, and value='ready' when a hypothetical\n% processing pipeline is finished with that scan, just after writing out the volume\n% data itself. There is an artificial delay of 1.3*TR between the two events.\n%\n% Use as\n% ft_realtime_fmriproxy(cfg)\n%\n% The target to write the data to is configured as\n% cfg.target.datafile = string, target destination for the data (default = 'buffer://localhost:1972')\n%\n% You can also select a resolution of the simulated volumes (default = [64,64,20]) like\n% cfg.voxels = [64 64 32]\n% and the repetition time (TR, default = 0.08*number of slices) in seconds using\n% cfg.TR = 2.0\n%\n% To stop this realtime function, you have to press Ctrl-C\n%\n% See also FT_REALTIME_SIGNALPROXY, FT_REALTIME_SIGNALVIEWER\n\n% Copyright (C) 2010, Stefan Klanke / 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% set the defaults\nif isempty(cfg) || ~isfield(cfg, 'target') || ~isfield(cfg.target, 'datafile')\n cfg.target.datafile = 'buffer://localhost:1972'; \nend\ncfg.target.dataformat = []; \n\nif isfield(cfg, 'voxels')\n voxels = cfg.voxels(1:3);\nelse\n voxels = [64 64 20];\nend\n\nif isfield(cfg,'TR')\n TR = cfg.TR;\n Tslice = TR / voxels(3);\nelse\n Tslice = 0.08;\n TR = Tslice * voxels(3);\nend\n\nnifti = [];\nnifti.dim = voxels;\nnifti.pixdim = [3.5 3.5 3.5]; % size of voxel in mm\nnifti.slice_duration = Tslice;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% create a FieldTrip compatible header structure\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nhdr = [];\nhdr.nChans = prod(voxels);\nhdr.nSamples = 0;\nhdr.Fs = 1/TR;\nhdr.nSamplesPre = 0;\nhdr.nTrials = 1; \nhdr.nifti_1 = encode_nifti1(nifti);\n\n% prepare two event structure that will go along with every sample/scan\nevp = [];\nevp.type = 'scan';\nevp.value = 'pulse';\nevp.offset = 0;\nevp.duration = 0;\nevp.sample = 0;\n\nevr = evp;\nevr.value = 'ready';\n\n% assume acquisition + processing takes 30% of a TR cycle\nTP = 0.3 * TR;\n\n% make some fake MRI data\n% Sphere = volume containing a spherical \"head\"\n% Left/Right = volume of same size, adds a bit of fake activation\nx = linspace(-1,1,voxels(1));\ny = linspace(-1,1,voxels(2));\nz = linspace(-1,1,voxels(3));\n[X,Y,Z] = meshgrid(x,y,z);\n\nR = sqrt(X.^2 + Y.^2 + Z.^2);\nSphere = single(1200 * (1./(1 + exp(40*(R-0.8)))));\nR = sqrt((X-0.4).^2 + Y.^2 + Z.^2);\nLeft = single(60 * (1./(1 + exp(40*(R-0.4)))));\nR = sqrt((X+0.4).^2 + Y.^2 + Z.^2);\nRight = single(60 * (1./(1 + exp(40*(R-0.4)))));\n\nstopwatch = tic;\n\n% write header to FieldTrip buffer\nft_write_data(cfg.target.datafile, single([]), 'header', hdr, 'dataformat', cfg.target.dataformat, 'append', false);\n\nnumPulse = 0;\nnumScan = 0;\n\nwhile true\n\t% simulate acquisition of pixeldata\n\tt0 = toc(stopwatch);\n\t\n\t% write 'scan pulse' event\n\tnumPulse = numPulse + 1;\n\tevp.sample = numPulse;\n\tfprintf('Sending pulse: %3i, clock time = %f\\n', numPulse, t0);\t\n\tft_write_event(cfg.target.datafile, evp);\n\t\n\tif numPulse > 1\n\t\t% fake acquisition + processing\n\t\tlateral = 0.5 + 0.5*sin(2*pi*numScan/20);\n\t\n\t\tNoise = single(30*randn(voxels));\n\t\tscan = single(Sphere + lateral*Left + (1-lateral)*Right + Noise);\n\t\n\t\ttp = toc(stopwatch);\n\t\tpause(TP - (tp-t0));\n\t\t\n\t\tft_write_data(cfg.target.datafile, scan(:), 'append', true);\n\t\t% write 'scan ready' event\n\t\tnumScan = numScan + 1;\n\t\tevr.sample = numScan;\n\t\tfprintf('Scans written: %3i, clock time = %f\\n', numScan, toc(stopwatch));\t\n\t\tft_write_event(cfg.target.datafile, evr);\n\tend\n\t\n\ttr = toc(stopwatch);\n\tpause(numPulse*TR - tr);\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/realtime/example/ft_realtime_fmriproxy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16193072216210555}} {"text": "function [TruePositives, FalseNegatives] = testFermentationProducts(model, microbeID, biomassReaction, database, inputDataFolder)\n% Performs an FVA and reports those fermentation products (exchange reactions)\n% that can be secreted by the model and should be secreted according to\n% data (true positives) and those fermentation products that cannot be secreted by\n% the model but should be secreted according to in vitro data (false\n% negatives).\n%\n% INPUT\n% model COBRA model structure\n% microbeID Microbe ID in carbon source data file\n% biomassReaction Biomass objective functions (low flux through BOF\n% required in analysis)\n% database Structure containing rBioNet reaction and metabolite\n% database\n% inputDataFolder Folder with experimental data and database files\n% to load\n%\n% OUTPUT\n% TruePositives Cell array of strings listing all fermentation products\n% (exchange reactions) that can be secreted by the model\n% and in in vitro data.\n% FalseNegatives Cell array of strings listing all fermentation products\n% (exchange reactions) that cannot be secreted by the model\n% but should be secreted according to in vitro data.\n%\n% .. Author:\n% Stefania Magnusdottir, Nov 2017\n% Almut Heinken, Jan 2018-reduced number of reactions minimized and\n% maximized to speed up the computation\n% March 2022 - changed code to string-matching to make it\n% more robust\n\nglobal CBT_LP_SOLVER\nif isempty(CBT_LP_SOLVER)\n initCobraToolbox\nend\n\n% read fermentation product table\ndataTable = readInputTableForPipeline([inputDataFolder filesep 'FermentationTable.txt']);\n\n% remove the reference columns\ndataTable(:,find(strncmp(dataTable(1,:),'Ref',3))) = [];\n\ncorrRxns = {'Acetate kinase (acetate producer or consumer)','EX_ac(e)';'Bifid shunt','EX_ac(e)';'Acetogen pathway','EX_ac(e)';'Formate producer','EX_for(e)';'D-lactate producer','EX_lac_D(e)';'L-lactate producer','EX_lac_L(e)';'Ethanol producer or consumer','EX_etoh(e)';'Succinate producer','EX_succ(e)';'Propionate from succinate','EX_ppa(e)';'Propionate from propane-1,2-diol','EX_ppa(e)';'Propionate from lactate (acrylate pathway)','EX_ppa(e)';'Propionate from threonine','EX_ppa(e)';'Wood-Werkman cycle','EX_ppa(e)';'Butyrate via butyryl-CoA: acetate CoA transferase','EX_but(e)';'Butyrate via butyrate kinase','EX_but(e)';'Butyrate from lysine via butyrate-acetoacetate CoA-transferase','EX_but(e)';'Butyrate from glutarate or glutamate','EX_but(e)';'Butyrate from 4-hydroxybutyrate or succinate','EX_but(e)';'Hydrogen from ferredoxin oxidoreductase','EX_h2(e)';'Hydrogen from formate hydrogen lyase','EX_h2(e)';'Methanogenesis','EX_ch4(e)';'Sulfate reducer','EX_h2s(e)';'Isobutyrate producer','EX_isobut(e)';'Isovalerate producer','EX_isoval(e)';'Acetoin producer','EX_actn_R(e)';'2,3-butanediol producer','EX_btd_RR(e)';'Indole producer','EX_indole(e)';'Phenylacetate producer','EX_pac(e)';'Butanol producer','EX_btoh(e)';'Valerate producer','EX_M03134(e)'};\n\nTruePositives = {}; % true positives (uptake in vitro and in silico)\nFalseNegatives = {}; % false negatives (uptake in vitro not in silico)\n\n% find microbe index in fermentation table\nmInd = find(strcmp(dataTable(:,1), microbeID));\nif isempty(mInd)\n warning(['Microbe \"', microbeID, '\" not found in fermentation product data file.'])\nelse\n % perform FVA to identify uptake metabolites\n % set BOF\n if ~any(ismember(model.rxns, biomassReaction)) || nargin < 3\n error(['Biomass reaction \"', biomassReaction, '\" not found in model.'])\n end\n model = changeObjective(model, biomassReaction);\n % set a low lower bound for biomass\n % model = changeRxnBounds(model, biomassReaction, 1e-3, 'l');\n % list exchange reactions\n exchanges = model.rxns(strncmp('EX_', model.rxns, 3));\n % open all exchanges\n model = changeRxnBounds(model, exchanges, -1000, 'l');\n model = changeRxnBounds(model, exchanges, 1000, 'u');\n\n % get the reactions to test\n rxns = {};\n for i=2:size(dataTable,2)\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n end\n end\n end\n\n % flux variability analysis on reactions of interest\n rxns = unique(rxns);\n rxns = rxns(~cellfun('isempty', rxns));\n rxnsInModel=intersect(rxns,model.rxns);\n if ~isempty(rxnsInModel)\n currentDir=pwd;\n try\n [minFlux, maxFlux, ~, ~] = fastFVA(model, 0, 'max', 'ibm_cplex', ...\n rxnsInModel, 'S');\n catch\n warning('fastFVA could not run, so fluxVariability is instead used. Consider installing fastFVA for shorter computation times.');\n cd(currentDir)\n [minFlux, maxFlux] = fluxVariability(model, 0, 'max', rxnsInModel);\n end\n\n % active flux\n flux = rxnsInModel(maxFlux > 1e-6);\n else\n flux = {};\n end\n\n % which reaction should carry flux according to in vitro data\n for i=2:size(dataTable,2)\n rxn={};\n if contains(version,'(R202') % for Matlab R2020a and newer\n if dataTable{mInd,i}==1\n rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n end\n else\n if strcmp(dataTable{mInd,i},'1')\n rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n end\n end\n if ~isempty(rxn)\n % add any that are not in model/not carrying flux to the false negatives\n if ~isempty(intersect(rxn,flux))\n TruePositives = union(TruePositives,rxn);\n else\n FalseNegatives=union(FalseNegatives,rxn);\n end\n end\n end\nend\n\n% replace reaction IDs with metabolite names\nif ~isempty(TruePositives)\n TruePositives = TruePositives(~cellfun(@isempty, TruePositives));\n TruePositives=strrep(TruePositives,'EX_','');\n TruePositives=strrep(TruePositives,'(e)','');\n\n for i=1:length(TruePositives)\n TruePositives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),TruePositives{i})),2};\n end\nend\n\n% warn about false negatives\nif ~isempty(FalseNegatives)\n FalseNegatives = FalseNegatives(~cellfun(@isempty, FalseNegatives));\n FalseNegatives=strrep(FalseNegatives,'EX_','');\n FalseNegatives=strrep(FalseNegatives,'(e)','');\n for i = 1:length(FalseNegatives)\n FalseNegatives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),FalseNegatives{i})),2};\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/reconstruction/demeter/suite/tests/testFermentationProducts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.16175153069276882}} {"text": "function test_pull1643\n\n% MEM 8gb\n% WALLTIME 00:40:00\n% DEPENDENCY ft_connectivity_plm ft_connectivityanalysis\n\n% create some dummy data\nntrl = 100;\nnsmp = 1000;\nfs = 1000;\nnchan = 3;\nfor k = 1:ntrl\n trial{1,k} = randn(nchan,nsmp);\n time{1,k} = (0:999)/fs;\nend\nfor k = 1:nchan\n label{k,1} = sprintf('chan%02d',k);\nend\ndata.trial = trial;\ndata.time = time;\ndata.label = label;\n\ncfg = [];\ncfg.method = 'plm';\nplm = ft_connectivityanalysis(cfg,data);\n\n% So far the test code only 'checks' whether it runs through, no checks are\n% done on the validity of the output structure (in terms of how it looks\n% w.r.t. fields etc., nor on the validity of the numeric results)\n\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_pull1643.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.16166383966719436}} {"text": "function opto = snirf2opto(probe, measurementList)\n\n% SNIRF2OPTO converts the SNIRF probe and measurementList structures to a FieldTrip\n% optode structure.\n%\n% See https://github.com/fNIRS/snirf/blob/master/snirf_specification.md\n%\n% The FieldTrip optode structure is defined in FT_DATATYPE_SENS\n%\n% See also OPTO2HOMER, BTI2GRAD, CTF2GRAD, FIF2GRAD, ITAB2GRAD, MNE2GRAD, NETMEG2GRAD, YOKOGAWA2GRAD, FT_DATATYPE_SENS\n\n% Copyright (C) 2020, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nnSrc = length(probe.sourceLabels);\nnDet = length(probe.detectorLabels);\n\nopto = [];\nopto.optolabel = cat(1, probe.sourceLabels(:), probe.detectorLabels(:)); % ensure that they are columns\n\nif ~isempty(probe.sourcePos3D)\n % use the 3D positions if available\n opto.optopos = cat(1, probe.sourcePos3D, probe.detectorPos3D);\nelse\n % use the 2D positions\n opto.optopos = cat(1, probe.sourcePos2D, probe.detectorPos2D);\n opto.optopos(:,3) = 0; % convert the positions to 3D\nend\n\nopto.optotype = cat(1, repmat({'transmitter'}, nSrc, 1), repmat({'receiver'}, nDet, 1));\nopto.wavelength = probe.wavelengths(:)';\n\nM = length(measurementList); % number of channels\nN = nSrc+nDet; % number of optodes\nK = numel(probe.wavelengths); % number of wavelengths\n\nopto.label = cell(M,1);\nfor i=1:M\n tx = measurementList(i).sourceIndex; % transmitter\n rx = measurementList(i).detectorIndex; % receiver\n wl = probe.wavelengths(measurementList(i).wavelengthIndex); % wavelength in nm\n opto.label{i} = sprintf('%s-%s [%dnm]', probe.sourceLabels{tx}, probe.detectorLabels{rx}, round(wl));\nend\n\n% the following specifies for each of the M channels at which wavelength each of the\n% N optodes transmits (positive integer from 1 to K), or receives (negative ingeger\n% from 1 to K), or does not contribute at all (zeros)\n\nopto.tra = zeros(M, N);\nfor i=1:M\n tx = measurementList(i).sourceIndex;\n rx = measurementList(i).detectorIndex + nSrc; % the transmitters are first in the list of optodes\n opto.tra(i, tx) = +measurementList(i).wavelengthIndex;\n opto.tra(i, rx) = -measurementList(i).wavelengthIndex;\nend\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/snirf2opto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.16166382985043165}} {"text": "addpath('testImage_Video/')\naddpath('model/')\n%for pic\nload('cars_meta.mat');\nload('cifar10NetRCNN.mat') %for detect\nload('AlexNet_New.mat');%for recognition\n\n%input image:\nframe=imread('6.jpg');\n%crop:\nframe=imresize(frame,[480 640]);\noutputImage=frame;\n % DetectRCNN(frame,cifar10NetRCNN);\n [bboxes, ~, ~] = detect(cifar10NetRCNN, frame);\n \n if ~isempty(bboxes)\n size_array=size(bboxes);\n length=size_array(1);\n for i=1:length\n box=bboxes(i,:);\n frame_=imcrop(frame,box);\n frame_=imresize(frame_,[227 227]);\n type_num=classify(AlexNet_New,frame_);\n outputImage=insertObjectAnnotation(outputImage, 'rectangle', box, class_names{type_num},'LineWidth',3);\n end\n end\n imshow(outputImage);\n", "meta": {"author": "chenjoya", "repo": "Vehicle_Detection_Recognition", "sha": "ba38afa600efb907e385e7a8178dcf2c0b9070cc", "save_path": "github-repos/MATLAB/chenjoya-Vehicle_Detection_Recognition", "path": "github-repos/MATLAB/chenjoya-Vehicle_Detection_Recognition/Vehicle_Detection_Recognition-ba38afa600efb907e385e7a8178dcf2c0b9070cc/Old/Pic_Detect_Recognition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16119282042023364}} {"text": "function loadAlignment\n% function loadAlignment\n%\n% loads bestrotvol.mat, converts it into a 4x4 homog transform matrix\n% and incorporates it into mrSESSION.alignment.\n%\n% 9/17/98 rmk\n% 4/29/99 BTB: Removed Inpts and Volpts fields, added tests for mrSESSION\n% field and coords.mat & coranal.mat files.\n% 8/2001 djh: updated to mrLoadRet-3.0\n\nglobal HOMEDIR mrSESSION\n\npathStr = fullfile(HOMEDIR,'bestrotvol.mat');\nif ~exist(pathStr,'file')\n myErrorDlg('No bestrotvol file. Run mrAlign3.');\nend\nload(pathStr);\n\nif isfield(mrSESSION, 'alignment')\n RESP = questdlg(['mrSESSION has an ''alignment'' field '...\n '(created when rotation was last saved). '...\n 'It was used to build any coords.mat and coranal.mat '...\n 'files you may have in Volume, Gray, and Flat directories.'...\n 'Permanently replace it with new alignment info? '], ...\n 'Question', 'Yes', 'No', 'Yes');\n if strcmp(RESP, 'Yes')\n rmfield(mrSESSION, 'alignment');\n else\n hmsgbox = msgbox(['Although you have updated the file bestrotvol.mat, ',...\n 'you have NOT updated mrSESSION.alignment, nor deleted any old ', ...\n 'coords.mat files from Volume, Gray, or Flat directories.'], 'Warning','warn'); \n drawnow\n return\n end\nend\n\n% If we've made it this far, go ahead an replace mrSESSION.alignment field. \n% 4x4 homog transform\nmrSESSION.alignment = inplane2VolXform(rot,trans,scaleFac); \nsaveSession\ndisp('mrSESSION.alignment has been updated and saved.');\n\n%%% Delete (after confirmation) old files that were built using previous alignment.\ncleanAllFlats\ncleanGray\ncleanVolume\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/File/loadAlignment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.1611928171412037}} {"text": "%\n% This HDR Toolbox demo creates an HDR radiance map:\n%\t 1) Read a stack of RAW images\n%\t 2) Read exposure values from the EXIF\n%\t 4) Build the radiance map using the stack and stack_exposure\n%\t 5) Save the radiance map in .hdr format\n%\t 6) Show the tone mapped version of the radiance map\n%\n% Author: Francesco Banterle\n% Copyright 2015 (c)\n%\n\nclear all;\n\ndisp('Note: this demo does not have RAW files due to room limits in the repository');\ndisp('please add a folder with RAW files in the variable ''name_folder''.');\nname_folder = ''; %Insert your raw stack folder\nformat = ''; %Insert your raw image format\n\ndisp('1) Read a stack of LDR images');\n% negative number for saturation -> will be computed from the stack.\n% With raw images this usually leads to artefacts in the highlights,\n% so it is recommended to check the correct white level from image metadata\nstack = ReadRAWStack(name_folder, format, -1);\n\ndisp('2) Read exposure values from the exif');\nstack_exposure = ReadRAWStackInfo(name_folder, format);\n\ndisp('4) Build the radiance map using the stack and stack_exposure');\n% Raw images are inherently linear, no need for CRF\nimgHDR = BuildHDR(stack, stack_exposure, 'linear', [], 'Deb97', 'log');\n\ndisp('5) Save the radiance map in the .hdr format');\nhdrimwrite(imgHDR, 'demos/output/stack_hdr_image_raw.exr');\n\ndisp('6) Show the tone mapped version of the radiance map with gamma encoding');\nh = figure(2);\nset(h, 'Name', 'Tone mapped version of the built HDR image');\nimgTMO = GammaTMO(ReinhardTMO(imgHDR, 0.18), 2.2, 0, 1);\nimwrite(imgTMO, 'demos/output/stack_hdr_image_tmo.png');\n", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/demos/demo_build_hdr_raw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.2598256264980406, "lm_q1q2_score": 0.16077501386222515}} {"text": "function [ons_secs, sqpar, verbose] = tapas_physio_crop_scanphysevents_to_acq_window(ons_secs, sqpar, verbose)\n% cropping of ons_secs into acquired scan/presentation session, augmenting\n% sqpar by scan-timing parameters from SCANPHYSLOG-file\n%\n% USAGE\n% function [ons_secs, sqpar] = ...\n% tapas_physio_crop_scanphysevents_to_acq_window(ons_secs, sqpar)\n%\n% IN\n% ons_secs - onsets of all physlog events in seconds\n% .spulse = onsets of slice scan acquisition\n% .cpulse = onsets of cardiac R-wave peaks\n% .r = time series of respiration\n% .svolpulse = onsets of volume scan acquisition\n% .t = time vector of logfile rows\n%\n% sqpar - sequence timing parameters\n% .Nslices - number of slices per volume in fMRI scan\n% .NslicesPerBeat - usually equals Nslices, unless you trigger\n% with the heart beat\n% .TR - repetition time in seconds\n% .Ndummies - number of dummy volumes\n% .Nscans - number of full volumes saved (volumes in nifti file,\n% usually rows in your design matrix)\n% onset_slice - slice whose scan onset determines the adjustment of the \n% regressor timing to a particular slice for the whole volume\n%\n% OUT\n% ons_secs - input ons_secs cropped to acquisition window\n% .raw - uncropped ons_secs-structure as input into this\n% function\n% sqpar - augmented input, also contains\n% .maxscan - acquired volumes during session running\n% .Nvols_paradigm - acquired volumes during paradigm running\n% .meanTR - mean repetition time (secs) over session\n%\n% Lars Kasper, August 2011\n% Copyright (C) 2013 Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n\n%% parameter settings\n Nscans = sqpar.Nscans;\n Ndummies = sqpar.Ndummies;\n NslicesPerBeat = sqpar.NslicesPerBeat;\n Nslices = sqpar.Nslices;\n\n spulse = ons_secs.spulse;\n svolpulse = ons_secs.svolpulse;\n cpulse = ons_secs.cpulse;\n c = ons_secs.c;\n r = ons_secs.r;\n c_is_reliable = ons_secs.c_is_reliable;\n r_is_reliable = ons_secs.r_is_reliable;\n fr = ons_secs.fr;\n t = ons_secs.t;\n ons_secs.raw = ons_secs;\n \n%% cut after end of paradigm window \nmaxscan = Nscans + Ndummies;\ntmax = ons_secs.spulse_per_vol{maxscan}(end);\n\ntstart = ons_secs.spulse_per_vol{1}(1);\ntend = ons_secs.spulse_per_vol{maxscan}(end);\n\nspulse((maxscan*Nslices+1):end) = [];\n\n% 1st heartbeat should be right before first scan, others cut\n% last heartbeat should be right after last scan; rest cut\n\nacqwindow = sort([find(cpulse<=tend & cpulse>=tstart); ...\n find(cpulsetend,1,'first')]);\n\nif ~isempty(cpulse), cpulse = cpulse(acqwindow); end;\n\n% same for respiratory signal\nacqwindow = sort([find(t<=tend & t>=tstart); ...\n find(ttend,1,'first')]);\n\n \nif ~isempty(r), r = r(acqwindow); end;\nif ~isempty(r_is_reliable), r_is_reliable = r_is_reliable(acqwindow); end;\nif ~isempty(c_is_reliable), c_is_reliable = c_is_reliable(acqwindow); end;\nif ~isempty(fr), fr = fr(acqwindow); end;\nif ~isempty(c), c = c(acqwindow); end;\n\nons_secs.t = t(acqwindow);\n\n% necessary vector for t1correction, all volume excitations needed\nsqpar.t = intersect(spulse,svolpulse);\nif maxscan Ex: '/myProject/WORKSPACE/RANDOM_FORESTS'\n% 2. nTrees: Number of decision-trees in the random forests.\n% --> Ex: 500\n% 3. seed: Numerical number to use as seed for random-forest construction.\n% --> Ex: 54288\n% 6. matlabPATH: Full path to the MATLAB executable on the system.\n% --> 'matlab' if a symbolic link to the matlab executable\n% was previously created. \n% -------------------------------------------------------------------------\n% OUTPUTS: Final out-of-bag prediction estimation results saved in a table\n% in 'pathRF'.\n% -------------------------------------------------------------------------\n% AUTHOR(S): Martin Vallieres \n% -------------------------------------------------------------------------\n% HISTORY:\n% - Creation: January 2017\n%--------------------------------------------------------------------------\n% STATEMENT:\n% This file is part of , \n% a package providing MATLAB programming tools for radiomics analysis.\n% --> Copyright (C) 2015-2017 Martin Vallieres\n%\n% This package is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This package is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this package. If not, see .\n% -------------------------------------------------------------------------\n\nstartpath = pwd;\n\ncd(pathRF), load('dataStruct')\nnameOutcomes = fieldnames(dataStruct); nOutcomes = numel(nameOutcomes);\n\ntime = 30; testCost = 0.25:0.25:5;\nmkdir('batchLog_RFvasari'), cd('batchLog_RFvasari'), pathBatch = pwd;\n\n\n% PRODUCE BATCH COMPUTATIONS\nsave('workspace','nTrees','dataStruct','nameOutcomes','seed','testCost'), batch = 0;\nfor o = 1:nOutcomes\n batch = batch + 1;\n nameScript = ['batch',num2str(batch),'_script.m'];\n fid = fopen(nameScript,'w');\n fprintf(fid,'load(''workspace'')\\n');\n fprintf(fid,['nameOutcome = nameOutcomes{',num2str(o),'};\\n']);\n fprintf(fid,['nVas = dataStruct.(nameOutcome).nVas;\\n']);\n fprintf(fid,['nText = dataStruct.(nameOutcome).nText;\\n']);\n fprintf(fid,['X = dataStruct.(nameOutcome).data(:,1:nVas);\\n']);\n fprintf(fid,['Y = dataStruct.(nameOutcome).outcome;\\n']);\n fprintf(fid,['cat = dataStruct.(nameOutcome).categories(1:nVas);\\n']);\n fprintf(fid,['[auc,sensitivity,specificity,accuracy] = predictionEstimationRF_LGG(X,Y,logical(cat),nTrees,seed,testCost);\\n']);\n fprintf(fid,['save(''result_batch',num2str(batch),''',''auc'',''sensitivity'',''specificity'',''accuracy'')\\n']);\n fprintf(fid,['system(''touch batch',num2str(batch),'_end'');\\n']);\n fprintf(fid,'clear all');\n fclose(fid);\n system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);\nend\n\n% WAITING LOOP\nwaitBatch(pathBatch,time,nOutcomes)\ndelete('workspace.mat')\n\n% GROUP RESULTS\ncd(pathBatch)\nbatch = 0; AUC = zeros(nOutcomes,1); Sensitivity = zeros(nOutcomes,1); Specificity = zeros(nOutcomes,1); Accuracy = zeros(nOutcomes,1);\nfor o = 1:nOutcomes\n batch = batch + 1;\n load(['result_batch',num2str(batch)]) % Variable 'auc', 'sensitivity', 'specificity', 'accuracy' gets out of here.\n AUC(o) = auc; Sensitivity(o) = sensitivity; Specificity(o) = specificity; Accuracy(o) = accuracy;\n delete(['result_batch',num2str(batch),'.mat'])\n clear auc sensitivity specificity accuracy\nend\ntab = table(AUC,Sensitivity,Specificity,Accuracy,'RowNames',nameOutcomes);\ncd(pathRF), save('tableSummary_Vasari','tab')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/LGG_study/Functions/performBatchRFvasari_LGG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.16021620816775203}} {"text": "function out=mrdivide(x,y)\n\nprecisionx=0; precisiony=0;\nif isa(x,'mp')\n precisionx=x(1).precision;\nend\nif isa(y,'mp')\n precisiony=y(1).precision;\nend\nprecision=max(precisionx,precisiony);\nex=numel(x);\ney=numel(y);\n\nif ey==1\n out=x./y;\nelse\n error('full mrdivide hasn''t been written for mp objects yet')\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/@mp/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352405, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16021620478231682}} {"text": "function [meshes, fnames] = meshImportFreesurferSurfaces(subjid, hemi, surfaces)\n% Import and save freesurfer surfaces in vistasoft form\n% [meshes, fnames] = meshImportFreesurferSurfaces(subjid, [hemi], [surfaces], [vw])\n%\n% Freesurfer autosegmentation produces at least 4 meshes per subject:\n% white, pial, inflated, and sphere. The white mesh is closest to what\n% vistasoft BuildMesh produces, and we take this to be the base mesh,\n% defining the initVertices for all meshes. We then create and one or more\n% meshes for one or both hemispheres, and save them as .mat files in\n% vistasoft format.\n%\n% Inputs:\n% subjid: Either the subjid recognized by freesurfer, or the path to the\n% freesurfer subject directory.\n% hemi: 'l', 'r', or 'b' (left, right, or both). [Default = 'b']\n% surfaces: cell array with one or more of 'white', 'pial', 'sphere',\n% 'inflated'\n% [Default = {'white' 'pial' 'sphere' 'inflated'};]\n% \n% Outputs:\n% meshes: structured array with vistasoft compatible meshes\n% fnames: paths to the created meshes\n%\n% Example:\n% % Install Ernie freesurfer directory and ernie vistasession\n% forceOverwrite = false;\n% fssubjectsdir = getenv('SUBJECTS_DIR');\n% mrtInstallSampleData('anatomy/freesurfer', 'ernie', fssubjectsdir, forceOverwrite);\n% erniePRF = mrtInstallSampleData('functional', 'erniePRF', [], forceOverwrite);\n% cd(erniePRF);\n% % Create and save meshes\n% [meshes, fnames] = meshImportFreesurferSurfaces('ernie');\n\n\nif notDefined('subjid'), help(mfilename); error('subjid is required'); end\nif notDefined('hemi'), hemi = 'b'; end\nif notDefined('surfaces'), surfaces = {'white' 'pial' 'sphere' 'inflated'}; end\n\n% open a hidden view to determine location to store meshes\n%vw = initHiddenInplane;\n\n% Check for subject directory\nif exist(subjid, 'dir')\n subjdir = subjid;\nelse \n fsPath = getenv('SUBJECTS_DIR');\n if ~exist(fsPath, 'dir'), error('Freesurfer subjects directory not found'); end\n subjdir = fullfile(fsPath, subjid);\nend\n\nif ~exist(subjdir, 'dir')\n error('Subject freesurfer directory %s not found', subjdir);\nend\n\nswitch lower(hemi(1))\n case 'l', hs.fs = 'lh'; hs.vista = 'Left'; \n case 'r', hs.fs = 'rh'; hs.vista = 'Right'; \n case 'b'\n hs(1).fs = 'lh'; hs(1).vista = 'Left'; \n hs(2).fs = 'rh'; hs(2).vista = 'Right'; \n otherwise\n error('Hemi %s not recognized', hemi);\nend\n\nnummeshes = length(hs) * length(surfaces);\nfnames = cell(1, nummeshes);\n\nfor h = 1:length(hs)\n \n % Read in the white mesh for this hemifield. This is the base mesh for\n % the hemifield. All other meshes will have the same initVertices, the\n % same curvature values (for coloration), and the same faces\n \n fsSurface = fullfile(subjdir, 'surf', sprintf('%s.%s', hs(h).fs, 'white'));\n msh0 = fs_meshFromSurface(fsSurface);\n msh0.name = sprintf('%s_white', hs(h).vista);\n\n % intialize the structured array meshes for output. This will contain\n % all the mesh structs created\n if h==1, meshes = msh0; end\n \n % Loop over surfaces for this hemisphere\n for ii = 1:length(surfaces)\n \n % Create this mesh and store it temporarily in the variable msh1\n fsSurface = fullfile(subjdir, 'surf', sprintf('%s.%s', hs(h).fs, surfaces{ii})); \n msh1 = fs_meshFromSurface(fsSurface);\n msh1.name = sprintf('%s_%s', hs(h).vista, surfaces{ii});\n \n % The mesh we will save is called msh, and combines values from the\n % white mesh (msh0) and the current mesh (msh1)\n msh = msh0;\n msh.vertices = msh1.vertices;\n msh.name = msh1.name; \n \n % Previously, we looked up the mesh directory stored in the mrVista\n % view structure. \n % savepth = viewGet(vw, 'MeshDir', hs(h).vista);\n savepth = fullfile('./3DAnatomy', hs(h).vista, '3DMeshes'); \n if ~exist(savepth, 'dir'), mkdir(savepth); end\n fname = fullfile(savepth, msh.name);\n save(fname, 'msh')\n \n % save for output\n meshnum = length(surfaces) * (h-1) + ii;\n meshes(meshnum) = msh;\n fnames{meshnum} = fname;\n \n end\n \nend\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrMesh/meshImportFreesurferSurfaces.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.15995305391763256}} {"text": "function organizeExperiments_Radiomics(pathFeatures,pathLR,pathCR,outcomes,timeToEvent,nPatient,nonTextName,fSetNames,paramSEP,baselineSEP,freedomSEP,textType,textName)\n\nstartpath = pwd;\n\n% INITIALIZATION\nroi = 'GTVtot'; % Using \"GTVtot\" ROI for all experiments\npermTrain = randperm(nPatient.HGJ + nPatient.CHUS); permTest = randperm(nPatient.HMR + nPatient.CHUM); % Random permutation of instances.\nnNonText = numel(nonTextName);\nnFset = numel(fSetNames);\nnameOutcomes = fieldnames(outcomes.HGJ); nOutcomes = numel(nameOutcomes);\nnTextType = numel(textType);\n\n\n% DATA ORGANIZATION\ntraining = struct; testing = struct;\nfor o = 1:nOutcomes\n \n % Organizing non-texture features\n cd(pathFeatures)\n train1 = load(['nonText_HGJ_',roi]); train1 = struct2cell(train1); train1 = train1{1};\n train2 = load(['nonText_CHUS_',roi]); train2 = struct2cell(train2); train2 = train2{1};\n test1 = load(['nonText_HMR_',roi]); test1 = struct2cell(test1); test1 = test1{1};\n test2 = load(['nonText_CHUM_',roi]); test2 = struct2cell(test2); test2 = test2{1};\n for i = 1:nNonText\n training.(nameOutcomes{o}).nonText.(nonTextName{i}).Data = [train1.(nonTextName{i}).Data;train2.(nonTextName{i}).Data];\n testing.(nameOutcomes{o}).nonText.(nonTextName{i}).Data = [test1.(nonTextName{i}).Data;test2.(nonTextName{i}).Data];\n training.(nameOutcomes{o}).nonText.(nonTextName{i}).Data = training.(nameOutcomes{o}).nonText.(nonTextName{i}).Data(permTrain);\n testing.(nameOutcomes{o}).nonText.(nonTextName{i}).Data = testing.(nameOutcomes{o}).nonText.(nonTextName{i}).Data(permTest);\n end\n\n % Organizing texture features\n for f = 1:nFset\n if strcmp(fSetNames{f},'PET') % Using only PET\n train1 = load(['text_HGJ_PT_',roi]); train1 = struct2cell(train1); train1 = train1{1};\n train2 = load(['text_CHUS_PT_',roi]); train2 = struct2cell(train2); train2 = train2{1};\n test1 = load(['text_HMR_PT_',roi]); test1 = struct2cell(test1); test1 = test1{1};\n test2 = load(['text_CHUM_PT_',roi]); test2 = struct2cell(test2); test2 = test2{1};\n train1 = {train1}; train2 = {train2};\n test1 = {test1}; test2 = {test2};\n training.(nameOutcomes{o}).text.(fSetNames{f}).param = paramSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).baseline = baselineSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).freedom = freedomSEP;\n training.(nameOutcomes{o}).text.(fSetNames{f}).paramName = {'Scale','Quant.algo','Ng'};\n textCellName = {'PT'};\n elseif strcmp(fSetNames{f},'CT') % Using only CT\n train1 = load(['text_HGJ_CT_',roi]); train1 = struct2cell(train1); train1 = train1{1};\n train2 = load(['text_CHUS_CT_',roi]); train2 = struct2cell(train2); train2 = train2{1};\n test1 = load(['text_HMR_CT_',roi]); test1 = struct2cell(test1); test1 = test1{1};\n test2 = load(['text_CHUM_CT_',roi]); test2 = struct2cell(test2); test2 = test2{1};\n train1 = {train1}; train2 = {train2};\n test1 = {test1}; test2 = {test2};\n training.(nameOutcomes{o}).text.(fSetNames{f}).param = paramSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).baseline = baselineSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).freedom = freedomSEP;\n training.(nameOutcomes{o}).text.(fSetNames{f}).paramName = {'Scale','Quant.algo','Ng'};\n textCellName = {'CT'};\n elseif strcmp(fSetNames{f},'PETCT') % Using both PET and CT\n train1_1 = load(['text_HGJ_PT_',roi]); train1_1 = struct2cell(train1_1); train1_1 = train1_1{1};\n train1_2 = load(['text_HGJ_CT_',roi]); train1_2 = struct2cell(train1_2); train1_2 = train1_2{1};\n train2_1 = load(['text_CHUS_PT_',roi]); train2_1 = struct2cell(train2_1); train2_1 = train2_1{1};\n train2_2 = load(['text_CHUS_CT_',roi]); train2_2 = struct2cell(train2_2); train2_2 = train2_2{1};\n test1_1 = load(['text_HMR_PT_',roi]); test1_1 = struct2cell(test1_1); test1_1 = test1_1{1};\n test1_2 = load(['text_HMR_CT_',roi]); test1_2 = struct2cell(test1_2); test1_2 = test1_2{1};\n test2_1 = load(['text_CHUM_PT_',roi]); test2_1 = struct2cell(test2_1); test2_1 = test2_1{1};\n test2_2 = load(['text_CHUM_CT_',roi]); test2_2 = struct2cell(test2_2); test2_2 = test2_2{1};\n train1 = {train1_1,train1_2}; train2 = {train2_1,train2_2};\n test1 = {test1_1,test1_2}; test2 = {test2_1,test2_2};\n training.(nameOutcomes{o}).text.(fSetNames{f}).param = paramSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).baseline = baselineSEP; \n training.(nameOutcomes{o}).text.(fSetNames{f}).freedom = freedomSEP;\n training.(nameOutcomes{o}).text.(fSetNames{f}).paramName = {'Scale','Quant.algo','Ng'};\n textCellName = {'PT','CT'};\n end\n\n for i = 1:numel(train1)\n sizeParam = size(train1{1});\n training.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}) = cell(sizeParam);\n testing.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}) = cell(sizeParam);\n for n = 1:numel(train1{1})\n for type = 1:nTextType\n for text = 1:numel(textName{type})\n training.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = [train1{i}{n}.(textType{type}).(textName{type}{text}).Data;train2{i}{n}.(textType{type}).(textName{type}{text}).Data];\n testing.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = [test1{i}{n}.(textType{type}).(textName{type}{text}).Data;test2{i}{n}.(textType{type}).(textName{type}{text}).Data];\n training.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = training.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data(permTrain);\n testing.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data = testing.(nameOutcomes{o}).text.(fSetNames{f}).(textCellName{i}){n}.(textType{type}).(textName{type}{text}).Data(permTest);\n end\n end\n end\n end\n end\nend\n\n% Organizing outcomes\nfor o = 1:nOutcomes\n training.(nameOutcomes{o}).outcome = [outcomes.HGJ.(nameOutcomes{o});outcomes.CHUS.(nameOutcomes{o})];\n testing.(nameOutcomes{o}).outcome = [outcomes.HMR.(nameOutcomes{o});outcomes.CHUM.(nameOutcomes{o})];\n training.(nameOutcomes{o}).timeToEvent = [timeToEvent.HGJ.(nameOutcomes{o});timeToEvent.CHUS.(nameOutcomes{o})];\n testing.(nameOutcomes{o}).timeToEvent = [timeToEvent.HMR.(nameOutcomes{o});timeToEvent.CHUM.(nameOutcomes{o})];\n training.(nameOutcomes{o}).outcome = training.(nameOutcomes{o}).outcome(permTrain);\n testing.(nameOutcomes{o}).outcome = testing.(nameOutcomes{o}).outcome(permTest);\n training.(nameOutcomes{o}).timeToEvent = training.(nameOutcomes{o}).timeToEvent(permTrain);\n testing.(nameOutcomes{o}).timeToEvent = testing.(nameOutcomes{o}).timeToEvent(permTest);\nend\n\n\ncd(pathLR), save('training','training'), save('testing','testing'), save('permTrain','permTrain'), save('permTest','permTest')\ncd(pathCR), save('training','training'), save('testing','testing'), save('permTrain','permTrain'), save('permTest','permTest')\n\ncd(startpath)\nend", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/STUDIES/HN_study/Functions/MULTIVARIABLE_MODELING/organizeExperiments_Radiomics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.30074559147595986, "lm_q1q2_score": 0.1597588771928643}} {"text": "function output = callsnopt(model)\n\n% Build trees etc. This common format is used for fmincon, snopt and ipopt\n% interfaces\nmodel = yalmip2nonlinearsolver(model);\n\nif ~model.derivative_available\n disp('Derivate-free call to snopt not yet implemented')\n error('Derivate-free call to snopt not yet implemented')\nend\n\n% Figure out which variables are artificially introduced to normalize\n% arguments in callback operators to simplify chain rules etc. We can do\n% our function evaluations and gradient computations in our lifted world,\n% but only expose the model in the original variables to the nonlinear\n% solver. \n% model = compressLifted(model);\n\nif model.options.savedebug\n save snoptdebug model\nend\n\nshowprogress('Calling SNOPT',model.options.showprogress);\n\nx0 = model.x0;\nsolveopt = 1;\nxlow = model.lb;\nxupp = model.ub;\nxmul = zeros(length(xupp),1);\nxstate = zeros(length(xupp),1);\n\nFupp = [ inf;\n repmat(0,length(model.bnonlinineq),1);\n repmat(0,nnz(model.K.q),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(0,length(model.b),1);\n repmat(0,length(model.beq),1)];\n \nFlow = [ -inf;\n repmat(-inf,length(model.bnonlinineq),1);\n repmat(-inf,nnz(model.K.q),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(-inf,length(model.b),1);\n repmat(0,length(model.beq),1)];\n\nFmul = zeros(length(Fupp),1);\nFstate = zeros(length(Fupp),1);\nObjAdd = 0;\nObjRow = 1;\nA = [];\niAfun = [];\njAvar = [];\n% Sparsity pattern of jacobian\nif ~isempty(Fupp)\n G = jacobiansparsityfromnonlinear(model); \nelse\n G = [];\nend\n% Add a row for objective. No sparsity declared\nG = [ones(1,size(G,2));G];\n[iGfun,jGvar] = find(G);\nmodel.sparsityElements = find(G);\n\nusrf = 'snopt_callback';\nsnopt_callback([],model);\n\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\nsolvertime = tic;\nif strcmpi(model.solver.version,'cmex')\n % Some old interface? Keep for safety\n if model.options.verbose == 0\n snscreen('off')\n else\n snscreen('on');\n end\n snseti('Minimize',1)\n [xout,F,xmul,Fmul,inform, xstate, Fstate, ns, ninf, sinf, mincw, miniw, minrw] = snoptcmex( solveopt, x0, xlow, xupp, xmul, xstate, Flow, Fupp, Fmul, Fstate,ObjAdd, ObjRow, A, iAfun(:), jAvar(:),iGfun(:), jGvar(:), usrf );\nelse\n Astruct.A = A;\n Astruct.row = iAfun;\n Astruct.col = jAvar;\n if model.options.verbose == 0\n model.options.snopt.screen = 'off';\n end\n [xout,F,inform,xmul,Fmul] = snopt(x0, xlow, xupp, xmul, xstate,Flow, Fupp, Fmul, Fstate, usrf,ObjAdd, ObjRow,A,G,model.options.snopt);\nend\n \nsolvertime = toc(solvertime);\n\nlambda = Fmul(2:end); \n\nif ~isempty(xout) && ~isempty(model.lift);\n x = zeros(length(model.linearindicies),1);\n x(model.lift.linearIndex) = xout;\n x(model.lift.liftedIndex) = model.lift.T*xout + model.lift.d;\n x = RecoverNonlinearSolverSolution(model,x);\nelse\n x = RecoverNonlinearSolverSolution(model,xout);\nend\n\nproblem = 0;\n\n% Internal format for duals\nD_struc = [];\n\n% Check, currently not exhaustive...\nswitch inform\n case {1}\n problem = 0;\n case {11,12,13,14,40,43,91} % 1 is sent when I test\n problem = 1;\n case 21\n problem = 2;\n case {31,32}\n problem = 3;\n case {2,3,33,41,42,43,44}\n problem = 4;\n case {71,72,73,74}\n problem = 16;\n otherwise \n problem = 11;\nend\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n solverinput.model = model; \nelse\n solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n solveroutput.x = x;\n solveroutput.F = F;\n solveroutput.xmul = xmul;\n solveroutput.inform=inform;\n solveroutput.Fstate=Fstate;\n solveroutput.ns = ns;\n solveroutput.ninf = ninf;\n solveroutput.sinf = sinf;\n solveroutput.mincw = mincw;\n solveroutput.miniw = miniw;\n solveroutput.miniw = miniw;\n \nelse\n solveroutput = [];\nend\n\n% Standard interface\noutput = createOutputStructure(x,D_struc,[],problem,'SNOPT',solverinput,solveroutput,solvertime);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callsnopt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.15917570551680593}} {"text": "% WriteSu : writes seismic data in the Seismic Unix format\n%\n% EX\n% WriteSu('datacube.su',data,'dt',.004,'Inline3D',Inline,'Crossline3D',Crossline,'cdpX',X,'cdpY',Y);\n%\n% to use a specific SEG revision use :\n% \n% to use a specific Data Sampling Format use :\n% WriteSu('test.su',seisdata,'dsf',1); % IBM FLAOTING POINT\n%\n% WriteSu('test.su',seisdata,'dsf'); \n%\n\n%\n% (C) 2001-2004, Thomas Mejer Hansen, thomas@cultpenguin.com\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\nfunction WriteSu(filename,data,varargin);\n\n[ns,ntraces]=size(data);\n\nif exist('dt')~=1\n dt=0.004;\n SegymatVerbose([mfilename,' - No dt set. Using dt=',num2str(dt)])\nend\n\nfor i=1:2:length(varargin)\n var=varargin{i};\n val=varargin{i+1};\n eval([var,'=[',num2str(val),'];']);\nend \n\n\nSegyHeader.SegyFormatRevisionNumber=256;\nSegyHeader.DataSampleFormat=5;\nSegyHeader.Rev=GetSegyHeaderBasics;\n\n\n% OPEN SEGY FILE HANDLE\nsegyid = fopen(filename,'w'); \n% segyid = fopen(filename,'w','b'); % BIG ENDIAN\n\nSegyTraceHeader=InitSegyTraceHeader(ns,dt*1e+6);\nfor i=1:ntraces;\n if (i/100)==round(i/100),SegymatVerbose(['writing trace ',num2str(i),' of ',num2str(ntraces)],1),end\n % Basic TraceHeader information\n %SegyTraceHeader.ns=ns;\n %SegyTraceHeader.dt=dt.*1e+6;\n % Update TraceHeader information if available\n if exist('cdpX')==1,SegyTraceHeader.cdpX = cdpX(i);end\n if exist('offset')==1,SegyTraceHeader.offset = offset(i);end\n if exist('cdpY')==1,SegyTraceHeader.cdpY = cdpY(i);end\n if exist('Inline3D')==1,SegyTraceHeader.Inline3D = Inline3D(i);end\n if exist('Crossline3D')==1,SegyTraceHeader.Crossline3D=Crossline3D(i);end\n % Write the Trace\n PutSegyTrace(segyid,data(:,i),SegyTraceHeader,SegyHeader);\nend\n\n% CLOSE SEGY FILE HANDLE \n \nfclose(segyid); \n", "meta": {"author": "cultpenguin", "repo": "segymat", "sha": "6470f59fd8184f0fff0d89383265417b461cc1da", "save_path": "github-repos/MATLAB/cultpenguin-segymat", "path": "github-repos/MATLAB/cultpenguin-segymat/segymat-6470f59fd8184f0fff0d89383265417b461cc1da/WriteSu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15909033769557512}} {"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 vt_video_main(visualDataFile, varargin)\n% NeuroSLAM System Copyright (C) 2018-2019 \n% NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n% Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n% The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n% The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n% Reference:\n% Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n% \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\n %% initial some variables\n % define a variable of visual template\n global VT; \n \n % define the number of visual templates\n global NUM_VT;\n NUM_VT = 1;\n \n % define a variable of previous vt id\n global PREV_VT_ID;\n PREV_VT_ID = 1;\n \n % define history of visual template\n global VT_HISTORY;\n global VT_HISTORY_FIRST;\n global VT_HISTORY_OLD;\n \n VT_HISTORY = [0];\n \n % for showing the comparing result between current imgs with templates\n global MIN_DIFF_CURR_IMG_VTS;\n MIN_DIFF_CURR_IMG_VTS = [0];\n \n global DIFFS_ALL_IMGS_VTS;\n DIFFS_ALL_IMGS_VTS = [0];\n \n % define a variable for showing sub vt imgage\n global SUB_VT_IMG;\n \n \n \n %% Process the parameters\n % parser some pameters\n \n % define the threshold for vt matching\n % This threshold determines whether a new view template is generated\n global VT_MATCH_THRESHOLD;\n \n % define the x, y range of visual template img\n global VT_IMG_CROP_Y_RANGE; % Row range\n global VT_IMG_CROP_X_RANGE; % Column range\n \n % Define resized range of visual template img for reducing resolution\n global VT_IMG_RESIZE_X_RANGE;\n global VT_IMG_RESIZE_Y_RANGE;\n \n % define x, y shift range for template matching\n % This determines how many +- pixels (therefore rotation) will be tested for match\n global VT_IMG_X_SHIFT;\n global VT_IMG_Y_SHIFT;\n \n % define decay of vt for updating vts\n % VT_GLOBAL_DECAY is subtracted for all the view templates at each time step\n % VT_ACTIVE_DECAY is added the best matching view template\n global VT_GLOBAL_DECAY;\n global VT_ACTIVE_DECAY; \n \n % define the patch size in x, y for patch normalisation\n global PATCH_SIZE_Y_K;\n global PATCH_SIZE_X_K;\n global BLOCK_READ;\n \n for i=1:(nargin-1)\n if ischar(varargin{i})\n switch varargin{i}\n case 'VT_MATCH_THRESHOLD', VT_MATCH_THRESHOLD = varargin{i+1}; \n \n case 'VT_IMG_CROP_Y_RANGE', VT_IMG_CROP_Y_RANGE = varargin{i+1};\n case 'VT_IMG_CROP_X_RANGE', VT_IMG_CROP_X_RANGE = varargin{i+1};\n \n case 'VT_IMG_RESIZE_X_RANGE', VT_IMG_RESIZE_X_RANGE = varargin{i+1};\n case 'VT_IMG_RESIZE_Y_RANGE', VT_IMG_RESIZE_Y_RANGE = varargin{i+1};\n\n case 'VT_IMG_X_SHIFT', VT_IMG_X_SHIFT = varargin{i+1}; \n case 'VT_IMG_Y_SHIFT', VT_IMG_Y_SHIFT = varargin{i+1}; \n \n case 'VT_GLOBAL_DECAY', VT_GLOBAL_DECAY = varargin{i+1};\n case 'VT_ACTIVE_DECAY', VT_ACTIVE_DECAY = varargin{i+1}; \n \n case 'PATCH_SIZE_Y_K', PATCH_SIZE_Y_K = varargin{i+1};\n case 'PATCH_SIZE_X_K', PATCH_SIZE_X_K = varargin{i+1};\n \n case 'BLOCK_READ', BLOCK_READ = varargin{i+1};\n end\n end\n end\n\n % define half offset for reversed matching\n global VT_IMG_HALF_OFFSET; \n VT_IMG_HALF_OFFSET = [0 floor(size(VT_IMG_CROP_X_RANGE) / 2)];\n\n gc_x = 1;\n gc_y = 1;\n gc_z = 1;\n \n hdc_yaw = 0;\n hdc_pitch = 0;\n \n\n VT(1).id = 1;\n VT(1).template(1) = 1;\n VT(1).decay = 0.7;\n VT(1).gc_x = gc_x;\n VT(1).gc_y = gc_y;\n VT(1).gc_z = gc_z;\n VT(1).hdc_yaw = hdc_yaw;\n VT(1).hdc_pitch = hdc_pitch;\n VT(1).first = 1; % don't want to inject energy as the vt is been created\n VT(1).numExp = 1;\n VT(1).exps(1).id = 1;\n \n VT(1).template = zeros(size(VT_IMG_CROP_Y_RANGE, 2), size(VT_IMG_CROP_X_RANGE, 2));\n\n %% read imgs as VT input\n\n % specify the movie and the frames to read\n [videoInfo, iStartFrame, totalFramesNum] = get_video_data_info(visualDataFile);\n\n for curFrame = 1 : totalFramesNum\n\n % read the visual data in blocks\n if (mod(curFrame, BLOCK_READ) == 1)\n [curVideoBlock] = read_video_block(videoInfo,curFrame, iStartFrame, totalFramesNum, BLOCK_READ);\n end\n\n % visual templates and visual odometry uses intensity so convert to grayscale\n [curImg] = get_current_frame_image(curVideoBlock, curFrame, BLOCK_READ);\n \n curGrayImg = rgb2gray(curImg);\n rawImg = im2double(curGrayImg);\n\n % get the most active view template\n [vt_id] = visual_template(rawImg, gc_x, gc_y,gc_z, hdc_yaw, hdc_pitch);\n\n % render the raw img\n subplot(3, 3, 1, 'replace');\n imshow(curGrayImg, []);\n title('Raw img');\n axis on\n\n % render the history of visual templates\n subplot(3, 3, [2 3 5 6], 'replace');\n plot(VT_HISTORY, '.r');\n title('Frame vs View Template');\n axis on\n\n % render the resized image of visual templates\n subplot(3, 3, 4, 'replace');\n imshow(SUB_VT_IMG, []);\n title('Resized img');\n axis on\n\n % render the history of visual templates\n subplot(3, 3, 7, 'replace');\n plot(MIN_DIFF_CURR_IMG_VTS, '.');\n title('Min SAD with each template');\n axis on\n\n % render the history of visual templates\n subplot(3, 3, [8 9], 'replace');\n plot(DIFFS_ALL_IMGS_VTS, '.');\n title('Min SAD of each current img');\n axis on\n\n DIFFS_ALL_IMGS_VTS = vt_id;\n\n drawnow; \n end\n\nend", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/04_visual_template/vt_video_main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.15858811971883477}} {"text": "%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by: Giulio Tagliaferro\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\nfunction time = getFileStTime(filename)\n% Return the start time of the file using the standard naming convention\n\n[~,name, ext] = fileparts(filename);\nif strcmpi(ext,'.${YY}p') || ((strcmpi(ext,'.${YY}[n|N]') || ~isempty(regexpi(ext,'\\.\\d\\d[n|N]'))) && isempty(strfind(name, 'CGIM'))) || strcmpi(ext,'.${YY}l') || ~isempty(regexpi(ext,'\\.\\d\\d[p|P]')) || ~isempty(regexp(ext,'\\.\\d\\d[l|L]', 'once')) %#ok\n % name should be : cccwwwwd\n % note: nav file rinex does not have first epoch at the beginning\n % it is too expesivo to look all the file\n if length(name) >= 8\n week = str2double(name(4:7));\n dow = str2double(name(8));\n if ~isnan(week) && ~isnan(dow)\n time = GPS_Time.fromWeekDow(week, dow);\n else\n time = [];\n end\n else\n time = [];\n end\n \nelseif isempty(strfind(lower(ext),lower('eph'))) || isempty(strfind(lower(ext),lower('sp3')))\n % read first 50 lines SP3 headers is 24 (allowing some space for more line comment)\n fid = fopen(filename,'rt');\n if fid > 0\n txt = fread(fid,61*50,'*char')';\n fclose(fid);\n if isempty(txt)\n Core.getLogger.addWarning(sprintf('\"%s\" is empty ', filename));\n time = [];\n else\n % get new line separators\n nl = regexp(txt, '\\n')';\n if nl(end) < numel(txt)\n nl = [nl; numel(txt)];\n end\n lim = [[1; nl(1 : end - 1) + 1] (nl - 1)];\n lim = [lim lim(:,2) - lim(:,1)];\n if lim(end,3) < 3\n lim(end,:) = [];\n end\n % find time line\n idx_epoch = find(txt(lim(:,1)) == '*');\n txt = txt(lim(idx_epoch):end);\n if ~isempty(idx_epoch)\n time = GPS_Time([str2num(txt(4:7)) str2num(txt(9:10)) str2num(txt(12:13)) str2num(txt(15:16)) str2num(txt(18:19)) str2num(txt(21:31))]);\n else\n time = [];\n end\n end\n else\n time = [];\n end\nelseif isempty(strfind(lower(ext),lower('clk')))\n fid = fopen(filename,'rt');\n tline = fgetl(fid);\n i = 0;\n eoh_found = false;\n while ischar(tline) && i < 300 && eoh_found\n eoh_found = strfind(tline,'END OF HEADER');\n tline = fgetl(fid);\n i = i + 1;\n end\n fclose(fid);\n if eoh_found\n tline = fgetl(fid);\n if ischar(tline) && length(tline) > 36\n time = GPS_Time([str2num(tline(9:12)) str2num(tline(14:15)) str2num(tline(17:18)) str2num(tline(20:21)) str2num(tline(24:25)) str2num(tline(26:34))]);\n else\n time = [];\n end\n else\n time = [];\n end\n \nelse\n time = [];\nend\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/getFileStTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.15858811971883477}} {"text": "function planC = importVarianFDF_3D(dirT,optFile)\n% function planC = importVarianFDF_3D(dirT,optFile)\n% Input: directory containing multi-frame FDF file and CERRoptions\n% file or optS structure\n% Output: CERR plan (planC)\n% Example:\n% dirT = 'C:\\Projects\\FDF reader\\Test_data_Joel\\3D-Large';\n% optFile = 'CERROptions.m';\n% planC = importVarianFDF_3D(dirT,optFile);\n%\n% APA, 05/15/2007\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\n\n% Check the format of optFile.\nif ~isstruct(optFile)\n optS = opts4Exe(optFile);\nelse\n optS = optFile;\nend\n\nplanC = initializeCERR;\nindexS = planC{end};\nplanC{indexS.CERROptions} = optS;\nplanC{indexS.indexS} = indexS;\n\n\npathT=[dirT,'/'];\n\n%%%% Import Transverse slices and interpolate\n\n% 1> Read [X,Y,Z,f] from transverse slices\n\n%%%%% Extract Data for Transverse Section\ncontents = dir(fullfile(pathT,'*.fdf'));\n[header, data] = readVarianFDF_3D(pathT, contents(1).name);\nfor i=1:size(data,3)\n H{i}=header; DATA{i}=data(:,:,i);\n %%% Extract info from header\n fbr1=find(header=='{');\n fbr2=find(header=='}');\n MatrixDim(i,:)=str2num(header(fbr1(1)+1:fbr2(1)-1));\n span(i,:)=str2num(header(fbr1(4)+1:fbr2(4)-1));\n offset(i,:)=str2num(header(fbr1(5)+1:fbr2(5)-1));\n sliceCenter(i,:)=str2num(header(fbr1(8)+1:fbr2(8)-1));\n xC(i)=sliceCenter(i,1); yC(i)=sliceCenter(i,2);\n %zC(i)=sliceCenter(i,3);\n roi(i,:)=str2num(header(fbr1(9)+1:fbr2(9)-1));\n orientation(i,:)=str2num(header(fbr1(10)+1:fbr2(10)-1));\nend\nzC = linspace(0,span(1,3),MatrixDim(1,3));\nsizeOfDimension1=MatrixDim(1,1);\nsizeOfDimension2=MatrixDim(1,2);\nsizeOfDimension1U=sizeOfDimension1; sizeOfDimension2U=sizeOfDimension2;\nsizeDim1 = sizeOfDimension1-1;\nsizeDim2 = sizeOfDimension2-1;\nxSpan=span(1,1); ySpan=span(1,2);\nxOffset=sliceCenter(1,1); yOffset=sliceCenter(1,2);\nxOffsetU=xOffset; yOffsetU=yOffset;\ngrid2Units=xSpan/sizeDim2;\ngrid1Units=ySpan/sizeDim1;\nvoxelThickness=zC(2)-zC(1);\n\n% xVals = xOffset - (sizeDim2*grid2Units)/2 : grid2Units : xOffset + (sizeDim2*grid2Units)/2;\n% yVals = yOffset - (sizeDim1*grid1Units)/2 : grid1Units : yOffset + (sizeDim1*grid1Units)/2;\n% zVals = zC;\n% [Xt,Yt] = meshgrid(xVals,yVals);\n% XXt=Xt(:); YYt=Yt(:);\n% XTrans=[]; DD=[]; DDt=[];\n% for i=1:length(zVals)\n% XTrans=[XTrans;\n% XXt, YYt, zVals(i)*XXt.^0];\n% DD1=DATA{i};\n% DD=[DD;\n% DD1(:)];\n% DDt=[DDt;\n% DD1(:)];\n% end\n% \n% %% Reshape Data\n% DDT3=reshape(DDt,[sizeOfDimension1,sizeOfDimension2,length(zVals)]);\n\nDDT3 = data;\n\nfor i=1:length(zC)\n scanInfo(i).grid1Units=grid1Units;\n scanInfo(i).grid2Units=grid2Units;\n scanInfo(i).sizeOfDimension1=sizeOfDimension1U;\n scanInfo(i).sizeOfDimension2=sizeOfDimension2U;\n scanInfo(i).xOffset=xOffsetU;\n scanInfo(i).yOffset=yOffsetU;\n scanInfo(i).voxelThickness=voxelThickness;\n scanInfo(i).zValue=zC(i);\n scanInfo(i).CTOffset=1000;\n scanInfo(i).sliceThickness=[]; \n scanInfo(i).imageType = 'MR Scan';\nend\nplanC{3}(1).scanInfo = scanInfo;\n\nminScanArray = min(DDT3(:));\nmaxScanArray = max(DDT3(:));\nscanArray = (DDT3-minScanArray)/maxScanArray*4095;\nplanC{3}.scanArray = scanArray;\nplanC{3}.scanType = 'MRI';\nplanC{3}.scanUID = createUID('scan');\nplanC = setUniformizedData(planC,optS);\n\n\nreturn\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/varianFDF/importVarianFDF_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.15847991475286055}} {"text": "classdef TuneAGC < adi.common.DebugAttribute & adi.common.RegisterReadWrite \n properties (Nontunable, Hidden)\n CustomAGC = 0;\n \n AttackDelay = 1;\n PeakOverloadWaitTime = 10;\n AGCLockLevel = 10;\n DecStepSizeFullTableCase3 = 3;\n ADCLargeOverloadThresh = 58;\n ADCSmallOverloadThresh = 47;\n DecStepSizeFullTableCase2 = 3;\n DecStepSizeFullTableCase1 = 3;\n LargeLMTOverloadThresh = 35;\n SmallLMTOverloadThresh = 25;\n SettlingDelay = 3;\n EnergyLostThresh = 3;\n LowPowerThresh = 15;\n IncrementGainStep\n FAGCLockLevelGainIncreaseUpperLimit = 7; \n FAGCLPThreshIncrementTime = 3;\n DecPowMeasurementDuration = 16;\n end\n \n properties (Constant, Hidden, Access = private)\n % Register addresses in hexadecimal\n AttackDelay_Reg = '022';\n PeakOverloadWaitTime_Reg = '0FE';\n AGCLockLevel_Reg = '101';\n DecStepSizeFullTableCase3_Reg = '103'; \n ADCSmallOverloadThresh_Reg = '104';\n ADCLargeOverloadThresh_Reg = '105';\n DecStepSizeFullTableCase2_Reg = '106'; \n DecStepSizeFullTableCase1_Reg = '106';\n LargeLMTOverloadThresh_Reg = '108';\n SmallLMTOverloadThresh_Reg = '107';\n SettlingDelay_Reg = '111';\n EnergyLostThresh_Reg = '112';\n LowPowerThresh_Reg = '114';\n IncrementGainStep_Reg = '117';\n FAGCLockLevelGainIncreaseUpperLimit_Reg = '118';\n FAGCLPThreshIncrementTime_Reg = '11B';\n DecPowMeasurementDuration_Reg = '15C';\n \n % Register mask in binary\n AttackDelay_Mask = '11000000';\n PeakOverloadWaitTime_Mask = '11100000';\n AGCLockLevel_Mask = '10000000';\n DecStepSizeFullTableCase3_Mask = '11100011'; \n DecStepSizeFullTableCase2_Mask = '10001111'; \n DecStepSizeFullTableCase1_Mask = '11110000';\n LargeLMTOverloadThresh_Mask = '11000000';\n SmallLMTOverloadThresh_Mask = '11000000';\n SettlingDelay_Mask = '11100000';\n EnergyLostThresh_Mask = '11000000';\n LowPowerThresh_Mask = '10000000';\n IncrementGainStep_Mask = '00011111';\n FAGCLockLevelGainIncreaseUpperLimit_Mask = '11000000';\n DecPowMeasurementDuration_Mask = '11110000';\n \n % Bit-shifts to be applied\n DecStepSizeFullTableCase3_BitShift = 2; \n DecStepSizeFullTableCase2_BitShift = 4; \n IncrementGainStep_BitShift = 5; \n end\n \n methods\n function set.AttackDelay(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',63}, ...\n '', 'AttackDelay'); \n obj.AttackDelay = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.AttackDelay_Reg, obj.AttackDelay_Mask); \n end\n end\n function set.PeakOverloadWaitTime(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',31}, ...\n '', 'PeakOverloadWaitTime'); \n obj.PeakOverloadWaitTime = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.PeakOverloadWaitTime_Reg, obj.PeakOverloadWaitTime_Mask); \n end\n end\n function set.AGCLockLevel(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',127}, ...\n '', 'AGCLockLevel'); \n obj.AGCLockLevel = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.AGCLockLevel_Reg, obj.AGCLockLevel_Mask); \n end\n end \n function set.DecStepSizeFullTableCase3(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',7}, ...\n '', 'DecStepSizeFullTableCase3'); \n obj.DecStepSizeFullTableCase3 = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.DecStepSizeFullTableCase3_Reg, obj.DecStepSizeFullTableCase3_Mask, obj.DecStepSizeFullTableCase3_BitShift); \n end\n end\n function set.ADCLargeOverloadThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',255}, ...\n '', 'ADCLargeOverloadThresh'); \n obj.ADCLargeOverloadThresh = value;\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,gc-adc-large-overload-thresh',value); \n end\n end \n function set.ADCSmallOverloadThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',obj.ADCLargeOverloadThresh}, ...\n '', 'ADCSmallOverloadThresh'); \n obj.ADCSmallOverloadThresh = value;\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,gc-adc-small-overload-thresh',value); \n end\n end\n function set.DecStepSizeFullTableCase2(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',7}, ...\n '', 'DecStepSizeFullTableCase2'); \n obj.DecStepSizeFullTableCase2 = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.DecStepSizeFullTableCase2_Reg, obj.DecStepSizeFullTableCase2_Mask, obj.DecStepSizeFullTableCase2_BitShift); \n end\n end \n function set.DecStepSizeFullTableCase1(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',15}, ...\n '', 'DecStepSizeFullTableCase1'); \n obj.DecStepSizeFullTableCase1 = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.DecStepSizeFullTableCase1_Reg, obj.DecStepSizeFullTableCase1_Mask); \n end\n end \n function set.LargeLMTOverloadThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',63}, ...\n '', 'LargeLMTOverloadThresh'); \n obj.LargeLMTOverloadThresh = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.LargeLMTOverloadThresh_Reg, obj.LargeLMTOverloadThresh_Mask); \n end\n end \n function set.SmallLMTOverloadThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',obj.LargeLMTOverloadThresh}, ...\n '', 'SmallLMTOverloadThresh'); \n obj.SmallLMTOverloadThresh = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.SmallLMTOverloadThresh_Reg, obj.SmallLMTOverloadThresh_Mask); \n end\n end \n function set.SettlingDelay(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',31}, ...\n '', 'SettlingDelay'); \n obj.SettlingDelay = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.SettlingDelay_Reg, obj.SettlingDelay_Mask); \n end\n end \n function set.EnergyLostThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',63}, ...\n '', 'SettlingDelay'); \n obj.EnergyLostThresh = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.EnergyLostThresh_Reg, obj.EnergyLostThresh_Mask); \n end\n end \n function set.LowPowerThresh(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',63}, ...\n '', 'LowPowerThresh'); \n obj.LowPowerThresh = value;\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,gc-low-power-thresh',value); \n end\n end \n function set.IncrementGainStep(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',7}, ...\n '', 'IncrementGainStep'); \n obj.IncrementGainStep = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.IncrementGainStep_Reg, obj.IncrementGainStep_Mask, obj.IncrementGainStep_BitShift); \n end\n end \n function set.FAGCLockLevelGainIncreaseUpperLimit(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',63}, ...\n '', 'FAGCLockLevelGainIncreaseUpperLimit'); \n obj.FAGCLockLevelGainIncreaseUpperLimit = value;\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,fagc-lock-level-gain-increase-upper-limit',value); \n end\n end \n function set.FAGCLPThreshIncrementTime(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',255}, ...\n '', 'FAGCLPThreshIncrementTime'); \n obj.FAGCLPThreshIncrementTime = value;\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,fagc-lp-thresh-increment-time',value); \n end\n end \n function set.DecPowMeasurementDuration(obj, value)\n validateattributes( value, { 'double','single', 'uint32' }, ...\n { 'real', 'nonnegative','scalar', 'finite', 'nonnan', 'nonempty','integer','>=',0,'<=',15}, ...\n '', 'DecPowMeasurementDuration'); \n obj.DecPowMeasurementDuration = value;\n if obj.ConnectedToDevice\n obj.setRegister(value, obj.DecPowMeasurementDuration_Reg, obj.DecPowMeasurementDuration_Mask); \n end\n end \n function WriteDebugAttributes(obj)\n if obj.ConnectedToDevice\n obj.setDebugAttributeLongLong('adi,gc-adc-large-overload-thresh',obj.ADCLargeOverloadThresh); \n obj.setDebugAttributeLongLong('adi,gc-adc-small-overload-thresh',obj.ADCSmallOverloadThresh);\n obj.setDebugAttributeLongLong('adi,gc-low-power-thresh',obj.LowPowerThresh); \n obj.setDebugAttributeLongLong('adi,fagc-lock-level-gain-increase-upper-limit',obj.FAGCLockLevelGainIncreaseUpperLimit); \n obj.setDebugAttributeLongLong('adi,fagc-lp-thresh-increment-time',obj.FAGCLPThreshIncrementTime);\n end\n end\n function WriteToRegisters(obj)\n if obj.ConnectedToDevice\n obj.setRegister(obj.AttackDelay, obj.AttackDelay_Reg, obj.AttackDelay_Mask); \n obj.setRegister(obj.PeakOverloadWaitTime, obj.PeakOverloadWaitTime_Reg, obj.PeakOverloadWaitTime_Mask); \n obj.setRegister(obj.AGCLockLevel, obj.AGCLockLevel_Reg, obj.AGCLockLevel_Mask); \n obj.setRegister(obj.DecStepSizeFullTableCase3, obj.DecStepSizeFullTableCase3_Reg, obj.DecStepSizeFullTableCase3_Mask, obj.DecStepSizeFullTableCase3_BitShift); \n obj.setRegister(obj.DecStepSizeFullTableCase2, obj.DecStepSizeFullTableCase2_Reg, obj.DecStepSizeFullTableCase2_Mask, obj.DecStepSizeFullTableCase2_BitShift); \n obj.setRegister(obj.DecStepSizeFullTableCase1, obj.DecStepSizeFullTableCase1_Reg, obj.DecStepSizeFullTableCase1_Mask); \n obj.setRegister(obj.LargeLMTOverloadThresh, obj.LargeLMTOverloadThresh_Reg, obj.LargeLMTOverloadThresh_Mask); \n obj.setRegister(obj.SmallLMTOverloadThresh, obj.SmallLMTOverloadThresh_Reg, obj.SmallLMTOverloadThresh_Mask); \n obj.setRegister(obj.SettlingDelay, obj.SettlingDelay_Reg, obj.SettlingDelay_Mask); \n obj.setRegister(obj.EnergyLostThresh, obj.EnergyLostThresh_Reg, obj.EnergyLostThresh_Mask); \n obj.setRegister(obj.IncrementGainStep, obj.IncrementGainStep_Reg, obj.IncrementGainStep_Mask, obj.IncrementGainStep_BitShift); \n obj.setRegister(obj.DecPowMeasurementDuration, obj.DecPowMeasurementDuration_Reg, obj.DecPowMeasurementDuration_Mask); \n end\n end\n function value = ReadFromRegister(obj, prop_name)\n if obj.ConnectedToDevice\n switch prop_name\n case 'AttackDelay'\n value = obj.getRegister(obj.AttackDelay_Reg, obj.AttackDelay_Mask); \n case 'PeakOverloadWaitTime'\n value = obj.getRegister(obj.PeakOverloadWaitTime_Reg, obj.PeakOverloadWaitTime_Mask); \n case 'AGCLockLevel'\n value = obj.getRegister(obj.AGCLockLevel_Reg, obj.AGCLockLevel_Mask); \n case 'DecStepSizeFullTableCase3'\n value = obj.getRegister(obj.DecStepSizeFullTableCase3_Reg, obj.DecStepSizeFullTableCase3_Mask, obj.DecStepSizeFullTableCase3_BitShift); \n case 'ADCSmallOverloadThresh'\n value = obj.getRegister(obj.ADCSmallOverloadThresh_Reg); \n case 'ADCLargeOverloadThresh'\n value = obj.getRegister(obj.ADCLargeOverloadThresh_Reg); \n case 'DecStepSizeFullTableCase2'\n value = obj.getRegister(obj.DecStepSizeFullTableCase2_Reg, obj.DecStepSizeFullTableCase2_Mask, obj.DecStepSizeFullTableCase2_BitShift); \n case 'DecStepSizeFullTableCase1'\n value = obj.getRegister(obj.DecStepSizeFullTableCase1_Reg, obj.DecStepSizeFullTableCase1_Mask); \n case 'LargeLMTOverloadThresh'\n value = obj.getRegister(obj.LargeLMTOverloadThresh_Reg, obj.LargeLMTOverloadThresh_Mask); \n case 'SmallLMTOverloadThresh'\n value = obj.getRegister(obj.SmallLMTOverloadThresh_Reg, obj.SmallLMTOverloadThresh_Mask); \n case 'SettlingDelay'\n value = obj.getRegister(obj.SettlingDelay_Reg, obj.SettlingDelay_Mask); \n case 'EnergyLostThresh'\n value = obj.getRegister(obj.EnergyLostThresh_Reg, obj.EnergyLostThresh_Mask); \n case 'LowPowerThresh'\n value = obj.getRegister(obj.LowPowerThresh_Reg, obj.LowPowerThresh_Mask); \n case 'IncrementGainStep'\n value = obj.getRegister(obj.IncrementGainStep_Reg, obj.IncrementGainStep_Mask, obj.IncrementGainStep_BitShift); \n case 'FAGCLockLevelGainIncreaseUpperLimit'\n value = obj.getRegister(obj.FAGCLockLevelGainIncreaseUpperLimit_Reg, obj.FAGCLockLevelGainIncreaseUpperLimit_Mask); \n case 'FAGCLPThreshIncrementTime'\n value = obj.getRegister(obj.FAGCLPThreshIncrementTime_Reg); \n case 'DecPowMeasurementDuration'\n value = obj.getRegister(obj.DecPowMeasurementDuration_Reg, obj.DecPowMeasurementDuration_Mask); \n otherwise\n error('Attempted to read unknown property %s\\n', prop_name);\n end\n end \n end \n end\nend", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/+adi/+AD9361/TuneAGC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1582520074793924}} {"text": "function eval(obj, inputs, derOutputs, stopLayer)\n%EVAL Evaluate the DAGNN\n% EVAL(obj, inputs) evaluates the DaG for the specified input\n% values. `inputs` is a cell array of the type `{'inputName',\n% inputValue, ...}`. This call results in a forward pass through the\n% graph, computing the values of the output variables. These can\n% then be accessed using the `obj.vars(outputIndex)` property of the\n% DaG object. The index of an output can be obtained using the\n% `obj.getOutputIndex(outputName)` call.\n%\n% EVAL(obj, inputs, derOutputs) evaluates the DaG forward and then\n% backward, performing backpropagation. Similar to `inputs`,\n% `derOutputs` is a cell array of the type {'outputName',\n% outputDerValue, ...} of output derivatives.\n%\n% # Understanding backpropagation\n%\n% Only those outputs for which an `outputDerValue` which is\n% non-empty are involved in backpropagation, while the others are\n% ignored. This is useful to attach to the graph auxiliary layers to\n% compute errors or other statistics, without however involving them\n% in backpropagation.\n%\n% Usually one starts backpropagation from scalar outptus,\n% corresponding to loss functions. In this case `outputDerValue` can\n% be interpreted as the weight of that output and is usually set to\n% one. For example: `{'objective', 1}` backpropagates from the\n% `'objective'` output variable with a weight of 1.\n%\n% However, in some cases the DaG may contain more than one such\n% node, for example because one has more than one loss function. In\n% this case `{'objective1', w1, 'objective2', w2, ...}` allows to\n% balance the different objectives.\n%\n% Finally, one can backpropagate from outputs that are *not*\n% scalars. While this is unusual, it is possible by specifying a\n% value of `outputDerValue` that has the same dimensionality as the\n% output; in this case, this value is used as a matrix of weights,\n% or projection.\n%\n% # Factors affecting evaluation\n%\n% There are several factors affecting evaluation:\n%\n% * The *evaluation mode* can be either `normal` or `test`. Layers\n% may behave differently depending on the mode. For example,\n% dropout becomes a pass-through layer in test mode and batch\n% normalization use fixed moments (this usually improves the test\n% performance significantly).\n%\n% * By default, the DaG aggressively conserves memory. This is\n% particularly important on the GPU, where memory is\n% scarce. However, this also means that the values of most\n% variables and of their derivatives are dropped during the\n% computation. For debugging purposes, it may be interesting to\n% observe these variables; in this case you can set the\n% `obj.conserveMemory` property of the DaG to `false`. It is also\n% possible to preserve individual variables by setting the\n% property `obj.vars(v).precious` to `true`.\n\n% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nobj.computingDerivative = nargin > 2 && ~isempty(derOutputs) ;\n\nif ~iscell(inputs), error('INPUTS is not a cell array.') ; end\nif obj.computingDerivative && ~iscell(derOutputs), error('DEROUTPUTS is not a cell array.') ; end\n\nif nargin < 4\n stopLayer = [];\nend\n% -------------------------------------------------------------------------\n% Forward pass\n% -------------------------------------------------------------------------\n\n% set the input values\nv = obj.getVarIndex(inputs(1:2:end)) ;\nif any(isnan(v))\n broken = find(isnan(v)) ;\n% error('No variable of name ''%s'' could be found in the DAG.', inputs{2*broken(1)-1}) ;\nend\n\nfor i = 1:2:numel(inputs)\n v = obj.getVarIndex(inputs{i}) ;\n if ~isnan(v)\n switch obj.device\n case 'cpu', obj.vars(v).value = gather(inputs{i+1}) ;\n case 'gpu', obj.vars(v).value = gpuArray(inputs{i+1}) ;\n end\n end\nend\n\ninputs = [] ;\nobj.numPendingVarRefs = [obj.vars.fanout] ;\nfor l = obj.executionOrder\n time = tic ;\n obj.layers(l).block.forwardAdvanced(obj.layers(l)) ;\n obj.layers(l).forwardTime = toc(time) ;\n \n if stopLayer == l\n break;\n end\nend\n\n\n% -------------------------------------------------------------------------\n% Backward pass\n% -------------------------------------------------------------------------\n\nif ~obj.computingDerivative, return ; end\n\n% conserve memory\nif obj.backpropDepth\nfor l = obj.executionOrder\n [obj.vars(obj.layers(l).inputIndexes).value] = deal([]) ;\n if strcmp(obj.layers(l).name, obj.backpropDepth) \n break;\n end\nend\nend\n\nv = obj.getVarIndex(derOutputs(1:2:end)) ;\n[obj.vars(v).der] = deal(derOutputs{2:2:end}) ;\nderOutputs = [] ;\n\nobj.numPendingVarRefs = zeros(1, numel(obj.vars)) ;\nobj.numPendingParamRefs = zeros(1, numel(obj.params)) ;\nfor l = fliplr(obj.executionOrder)\n time = tic ;\n if strcmp(obj.layers(l).name, obj.backpropDepth) \n [obj.vars.value] = deal([]) ;\n [obj.vars.der] = deal([]) ;\n break;\n end\n obj.layers(l).block.backwardAdvanced(obj.layers(l)) ;\n obj.layers(l).backwardTime = toc(time) ;\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/\u8bc6\u522b\u7b97\u6cd5/DAIN-master/matconvnet/matlab/+dagnn/@DagNN/eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.15825200100913672}} {"text": "function varargout = subsref(varargin)\n%SUBSREF (overloaded)\n\n% Stupid first slice call (supported by MATLAB)\n% x = sdpvar(2);x(1,:,:)\nY = varargin{2};\nif length(Y)==1\n if length(Y.subs) > 2 && isequal(Y.type,'()') && ~( isa(Y(1).subs{1},'constraint') || isa(Y(1).subs{1},'lmi') )\n i = 3;\n ok = 1;\n while ok && (i <= length(Y.subs))\n ok = ok && (isequal(Y.subs{i},1) || isequal(Y.subs{i},':'));\n i = i + 1;\n end\n if ok\n Y.subs = {Y.subs{1:2}};\n else\n error('??? Index exceeds matrix dimensions.');\n end\n end\nend\n\n\nX = varargin{1};\n\ntry\n switch Y(1).type\n case '()'\n if isa(Y(1).subs{1},'constraint') || isa(Y(1).subs{1},'lmi') \n z = Y(1).subs{1};\n for i = 1:length(Y(1).subs)\n z = [z, Y(1).subs{i}];\n end\n % z == 0 => b+Ax == 0 => x = -A\\b\n z = sdpvar(z);\n B = getbase(z);\n A = B(:,2:end);\n b = B(:,1);\n x0 = -A\\b;\n x = recover(getvariables(z));\n varargout{1} = replace(X,x,x0);\n return \n end\n % Check for simple cases to speed things up (yes, ugly but we all want speed don't we!)\n switch size(Y(1).subs,2)\n case 1\n y = subsref1d(X,Y(1).subs{1},Y); \n case 2\n y = subsref2d(X,Y.subs{1},Y(1).subs{2},Y);\n otherwise\n if all( [Y(1).subs{3:end}]==1)\n y = subsref2d(X,Y.subs{1},Y(1).subs{2},Y);\n else\n error('Indexation error.');\n end\n end\n case '{}'\n varargout{nargout} = [];\n \n % it could be the case that we have an extended variable\n % This is a bit tricky, so we do the best we can; assume that\n % we want to replace the internal argument wih the new\n % expression\n OldArgument = recover(depends(X));\n vars = getvariables(X);\n mpt_solution = 1;\n if all(ismembc(vars,yalmip('extvariables')))\n for i = 1:length(X)\n nonlinearModel = yalmip('extstruct',vars);\n if isequal(nonlinearModel{1}.fcn,'pwa_yalmip') | isequal(nonlinearModel{1}.fcn,'pwq_yalmip')\n else\n mpt_solution = 0;\n end\n end\n if mpt_solution\n assign(nonlinearModel{1}.arg{2},Y(1).subs{:});\n XX = value(X);\n varargout{1} = value(X);\n return\n end\n end\n vars = getvariables(X);\n if (length(vars) == 1) & ismembc(vars,yalmip('extvariables'))\n nonlinearModel = yalmip('extstruct',vars);\n OldArgument = [];\n for i = 1:length(nonlinearModel.arg)\n if isa(nonlinearModel.arg{i},'sdpvar')\n OldArgument = [OldArgument; nonlinearModel.arg{i}];\n end\n end\n if isnumeric([Y.subs{:}])\n assign(reshape(OldArgument,[],1),reshape([Y(1).subs{:}],[],1));\n varargout{1} = value(X);\n return\n end\n end\n y = replace(X,OldArgument,[Y(1).subs{:}]);\n if isnumeric(y)\n varargout{1} = y;\n return\n end\n \n case '.'\n switch Y(1).subs\n case {'minimize','maximize'}\n options = [];\n constraints = []; \n objective = varargin{1};\n opsargs = {};\n if length(Y)==2\n if isequal(Y(2).type,'()')\n for i = 1:length(Y(2).subs)\n switch class(Y(2).subs{i})\n case {'lmi','constraint'}\n constraints = [constraints, Y(2).subs{i}];\n case 'struct'\n options = Y(2).subs{i};\n case {'double','char','gem','sgem'}\n opsargs{end+1} = Y(2).subs{i};\n otherwise\n error('Argument to minimize should be constraints or options');\n end\n end\n else\n error(['What do you mean with ' Y(2).type '?']);\n end\n end \n if length(opsargs)>0\n if isempty(options)\n options = sdpsettings(opsargs{:}); \n else\n options = sdpsettings(options,opsargs{:});\n end\n end\n if isequal(Y(1).subs,'minimize')\n sol = solvesdp(constraints,objective,options);\n else\n sol = solvesdp(constraints,-objective,options);\n end\n varargout{1} = varargin{1};\n varargout{2} = sol;\n return\n case 'derivative'\n try\n m = model(varargin{1});\n varargout{1} = m{1}.derivative;\n catch\n varargout{1} = 1;\n end\n return \n otherwise\n error(['Indexation ''' Y.type Y.subs ''' not supported']) ;\n end\n otherwise\n error(['Indexation with ''' Y.type ''' not supported']) ;\n end\ncatch\n error(lasterr)\nend\nif isempty(y.lmi_variables)\n y = full(reshape(y.basis(:,1),y.dim(1),y.dim(2)));\nelse\n % Reset info about conic terms\n y.conicinfo = [0 0];\n y.extra.createTime = definecreationtime;\nend\nvarargout{1} = y;\n\nfunction X = subsref1d(X,ind1,Y)\n\n% Get old and new size\nn = X.dim(1);\nm = X.dim(2);\n\n% Convert to linear indecicies\nif islogical(ind1)\n ind1 = double(find(ind1));\nelseif ischar(ind1)\n X.dim(1) = n*m;\n X.dim(2) = 1;\n return;\nelseif ~isnumeric(ind1)\n X = milpsubsref(X,Y);\n return\nend\n\n% Detect X(scalar)\nif length(ind1) == 1 & ind1 <= n*m\n \n Z = X.basis(ind1,:);\n nnew = 1;\n mnew = 1;\n \nelse\n\n % What would the size be for a double\n dummy = reshape(X.basis(:,1),n,m);\n dummy = dummy(ind1);\n nnew = size(dummy,1);\n mnew = size(dummy,2);\n [nx,mx] = size(X.basis);\n \n if length(ind1) > 1\n try\n % row-based subsref for sparse objects can be very slow and\n % take a lot of memory, transposing a big sparse array as in\n % Z = X.basis.';\n % Z = Z(:,ind1);\n % Z = Z.';\n % can also be quite slow for very large matrices, so we use\n % some custom code\n [ix,jx,sx] = find(X.basis);\n if length(ix) == length(unique(ix))\n % We never have two elements on the same row of X.basis\n [isNnz,loc] = ismember(ind1(:),ix);\n sel = loc(isNnz);\n ix = find(isNnz);\n jx = jx(sel);\n sx = sx(sel);\n Z = sparse(ix,jx,sx,numel(ind1),mx);\n else\n % We can have seveal elements on a given row of X.basis\n if numel(ind1) == length(unique(ind1))\n % Every row of X.basis is selected at most once\n [keep,loc] = ismember(ix,ind1(:));\n ix = loc(keep);\n jx = jx(keep);\n sx = sx(keep);\n Z = sparse(ix,jx,sx,numel(ind1),mx);\n else\n % Complicated case, we use more generica code\n Z = sparse(1:numel(ind1),ind1,1,numel(ind1),size(X,1))*X.basis;\n end\n end\n \n if false\n % For checking purpose\n Z0 = X.basis.';\n Z0 = Z0(:,ind1);\n Z0 = Z0.';\n assert(isequal(Z, Z0));\n end\n catch\n Z = X.basis(ind1,:); \n end\n else\n Z = X.basis(ind1,:);\n end\nend\n\n% Find non-zero basematrices\nnzZ = find(any(Z(:,2:end),1));\nif ~isempty(nzZ)\n X.dim(1) = nnew;\n X.dim(2) = mnew;\n X.lmi_variables = X.lmi_variables(nzZ);\n X.basis = Z(:,[1 1+nzZ]);\nelse\n bas = reshape(X.basis(:,1),n,m);\n X.dim(1) = nnew;\n X.dim(2) = mnew;\n X.lmi_variables = [];\n X.basis = reshape(bas(ind1),nnew*mnew,1);\nend\n\nfunction X = subsref2d(X,ind1,ind2,Y)\n\nif isnumeric(ind1)\nelseif ischar(ind1)\n ind1 = 1:X.dim(1);\nelseif islogical(ind1)\n ind1 = double(find(ind1));\nelseif ~isnumeric(ind1)\n X = milpsubsref(X,Y);\n return\nend\nif isnumeric(ind2)\nelseif ischar(ind2)\n ind2 = 1:X.dim(2);\nelseif islogical(ind2)\n ind2 = double(find(ind2));\nelseif ~isnumeric(ind2) \n X = milpsubsref(X,Y);\n return\nend\n\nn = X.dim(1);\nm = X.dim(2);\nlind2 = length(ind2);\nlind1 = length(ind1);\nif lind2 == 1\n ind1_ext = ind1(:);\nelse\n ind1_ext = kron(ones(lind2,1),ind1(:));\nend\nif lind1 == 1\n ind2_ext = ind2(:);\nelse\n ind2_ext = kron(ind2(:),ones(lind1,1));\nend\n\nif any(ind1 > n) || any(ind2 > m)\n error('Index exceeds matrix dimensions.');\nend\n \nif lind1==1 && lind2==1\n if isequal(X.conicinfo,[-1 0])\n X.basis = [0 1];\n X.lmi_variables = X.lmi_variables(1)+ind1+(ind2-1)*n-1;\n X.dim = [1 1];\n X.conicinfo = [0 0]; \n return\n end\nend\n\nif prod(size(ind1_ext))==0 | prod(size(ind2_ext))==0\n linear_index = [];\nelse\n % Speed-up for some bizarre code with loads of indexing of vector\n if m==1 & ind2_ext==1\n linear_index = ind1_ext;\n elseif length(ind2_ext)==1 && length(ind1_ext)==1\n linear_index = ind1_ext + (ind2_ext-1)*n;\n else\n linear_index = sub2ind([n m],ind1_ext,ind2_ext);\n end\nend\nnnew = length(ind1);\nmnew = length(ind2);\n\n% Put all matrices in vectors and extract sub matrix\nZ = X.basis(linear_index,:);\n% Find non-zero basematrices\n%nzZ = find(any(Z(:,2:end),1));\nnzZ = find(any(Z,1))-1;\nif numel(nzZ)>0\n if nzZ(1)==0\n nzZ = nzZ(2:end);\n end\nend\nif ~isempty(nzZ)\n X.dim(1) = nnew;\n X.dim(2) = mnew;\n X.lmi_variables = X.lmi_variables(nzZ);\n X.basis = Z(:,[1 1+nzZ]);\nelse\n bas = reshape(X.basis(:,1),n,m);\n X.dim(1) = nnew;\n X.dim(2) = mnew;\n X.lmi_variables = [];\n X.basis = reshape(bas(linear_index),nnew*mnew,1);\nend", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/@sdpvar/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1580188185001759}} {"text": "addpath(genpath('D:\\GitHub\\KiloSort2')) % path to kilosort folder\naddpath('D:\\GitHub\\npy-matlab')\n\npathToYourConfigFile = 'D:\\GitHub\\KiloSort2\\configFiles'; % take from Github folder and put it somewhere else (together with the master_file)\nrun(fullfile(pathToYourConfigFile, 'configFileBench384.m'))\n\n% common options for every probe\nops.chanMap = 'D:\\GitHub\\KiloSort2\\configFiles\\neuropixPhase3A_kilosortChanMap.mat';\nops.trange = [0 Inf]; % TIME RANGE IN SECONDS TO PROCESS\n\n % these settings overwrite any settings from config\nops.Th = [10 10]; % threshold on projections (like in Kilosort1)\nops.lam = 40^2; % weighting on the amplitude penalty (like in Kilosort1, but it has to be much larger)\n\nops.ThS = [8 8]; % lower bound on acceptable single spike quality\nops.momentum = [20 400]; % number of samples to average over\nops.minFR = 1/50; % minimum spike rate (Hz)\n\nops.sigmaMask = 30;\n\nops.Nfilt = 1024; % max number of clusters\nops.nfullpasses = 3; % how many forward backward passes to do\nops.nPCs = 3; % how many PCs to project the spikes into\n\nops.NchanTOT = 385;\nops.useRAM = 0;\nops.ccsplit = .99;\n\n% rootZ = 'D:\\DATA\\ALLEN\\mouse366119\\probeC_2018-03-02_15-18-32_SN619041624\\experiment1\\recording1\\continuous\\Neuropix-120.0\\';\n% rootZ = 'H:\\DATA\\Spikes\\Robbins\\ZNP1';\nrootZ = 'H:\\DATA\\Spikes\\WillAllen';\nrootH = 'H:\\DATA\\Spikes\\temp\\';\n\nfs = dir(fullfile(rootZ, '*.bin'));\n\nfname = fs(1).name;\n\nops.fbinary = fullfile(rootZ, fname);\nops.fproc = fullfile(rootH, 'temp_wh2.dat'); % residual from RAM of preprocessed data\n\n\n% preprocess data\nrez = preprocessDataSub(ops);\n\nrez = clusterSingleBatches(rez);\n\n% figure(191);\n% imagesc(rez.ccb(rez.iorig, rez.iorig), [20 100])\n%%\nlearnAndSolve8\n% rez = learnAndSolve8(rez);\n\nrez2 = splitAllClusters(rez);\n\nrezToPhy(rez2, rootZ);\n\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/temp/masterFwBwRobbins.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.2628418489200747, "lm_q1q2_score": 0.15775461428886622}} {"text": "classdef (Abstract, Hidden = true) Base < adi.common.Attribute & ...\n adi.common.DebugAttribute & adi.common.RxTx & ...\n matlabshared.libiio.base & matlab.system.mixin.CustomIcon\n\n %adi.AD9361.Base Class\n % This class contains shared parameters and methods between TX and RX\n % classes\n properties (Nontunable)\n %SamplesPerFrame Samples Per Frame\n % Number of samples per frame, specified as an even positive\n % integer from 2 to 16,777,216. Using values less than 3660 can\n % yield poor performance.\n SamplesPerFrame = 2^15;\n end\n \n properties (Nontunable, Logical)\n %EnableCustomFilter Enable Custom Filter\n % Enable use of custom filter file to set SamplingRate, \n % RFBandwidth, and FIR in datapaths\n EnableCustomFilter = false;\n end\n \n properties (Nontunable)\n %CustomFilterFileName Custom Filter File Name\n % Path to custom filter file created from filter wizard\n CustomFilterFileName = '';\n end\n \n properties (Abstract)\n %CenterFrequency Center Frequency\n % RF center frequency, specified in Hz as a scalar. The\n % default is 2.4e9. This property is tunable.\n CenterFrequency\n %SamplingRate Sampling Rate\n % Baseband sampling rate in Hz, specified as a scalar\n % from 65105 to 61.44e6 samples per second.\n SamplingRate\n %RFBandwidth RF Bandwidth\n % RF Bandwidth of front-end analog filter in Hz, specified as a\n % scalar from 200 kHz to 56 MHz.\n RFBandwidth\n end\n \n properties(Nontunable, Hidden)\n Timeout = Inf;\n kernelBuffersCount = 2;\n dataTypeStr = 'int16';\n phyDevName = 'ad9361-phy';\n iioDevPHY\n end\n \n properties (Hidden, Constant)\n ComplexData = true;\n end\n \n methods\n %% Constructor\n function obj = Base(varargin)\n coder.allowpcode('plain');\n obj = obj@matlabshared.libiio.base(varargin{:});\n end\n % Destructor\n function delete(obj)\n teardownLibad9361(obj);\n delete@adi.common.RxTx(obj);\n end\n % Check SamplesPerFrame\n function set.SamplesPerFrame(obj, value)\n validateattributes( value, { 'double','single' }, ...\n { 'real', 'positive','scalar', 'finite', 'nonnan', 'nonempty','integer','>',0,'<=',2^20}, ...\n '', 'SamplesPerFrame');\n obj.SamplesPerFrame = value;\n end\n % Check EnableCustomFilter\n function set.EnableCustomFilter(obj, value)\n validateattributes( value, { 'logical' }, ...\n { }, ...\n '', 'EnableCustomFilter');\n obj.EnableCustomFilter = value;\n end\n % Check CustomFilterFileName\n function set.CustomFilterFileName(obj, value)\n validateattributes( value, { 'char' }, ...\n { }, ...\n '', 'CustomFilterFileName');\n obj.CustomFilterFileName = value;\n if obj.EnableCustomFilter && obj.ConnectedToDevice %#ok\n writeFilterFile(obj);\n end\n end\n end\n \n %% API Functions\n methods (Hidden, Access = protected)\n \n function icon = getIconImpl(obj)\n icon = sprintf(['AD9361 ',obj.Type]);\n end\n \n function setupLibad9361(obj)\n libName = 'libad9361';\n ad9361wrapperh = 'ad9361-wrapper.h';\n ad9361h = 'ad9361.h';\n fp = fileparts(which(ad9361h));\n loadlibraryArgs = {ad9361wrapperh,'includepath',fp,'addheader',ad9361h};\n if ~libisloaded(libName)\n msgID = 'MATLAB:loadlibrary:StructTypeExists';\n warnStruct = warning('off',msgID);\n [~, ~] = loadlibrary(libName, loadlibraryArgs{:});\n warning(warnStruct);\n end\n obj.iioDevPHY = calllib('libiio', 'iio_context_find_device',obj.iioCtx,'ad9361-phy');\n end\n \n function teardownLibad9361(~)\n libName = 'libad9361';\n if libisloaded(libName)\n unloadlibrary(libName);\n end\n end\n \n function writeFilterFile(obj)\n fir_data_file = obj.CustomFilterFileName;\n fir_data_str = fileread(fir_data_file);\n obj.setAttributeRAW('voltage0','filter_fir_en','0',false);\n obj.setAttributeRAW('voltage0','filter_fir_en','0',true);\n obj.setDeviceAttributeRAW('filter_fir_config',fir_data_str);\n obj.setAttributeRAW('voltage0','filter_fir_en','1',true);\n obj.setAttributeRAW('voltage0','filter_fir_en','1',false);\n end\n \n end\n \n %% External Dependency Methods\n methods (Hidden, Static)\n \n function tf = isSupportedContext(bldCfg)\n tf = matlabshared.libiio.ExternalDependency.isSupportedContext(bldCfg);\n end\n \n function updateBuildInfo(buildInfo, bldCfg)\n % Call the matlabshared.libiio.method first\n matlabshared.libiio.ExternalDependency.updateBuildInfo(buildInfo, bldCfg);\n end\n \n function bName = getDescriptiveName(~)\n bName = 'AD9361';\n end\n \n end\nend\n\n", "meta": {"author": "analogdevicesinc", "repo": "MathWorks_tools", "sha": "5f8df06d4fc2f4832ed9ec8b722fb750b2261f20", "save_path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools", "path": "github-repos/MATLAB/analogdevicesinc-MathWorks_tools/MathWorks_tools-5f8df06d4fc2f4832ed9ec8b722fb750b2261f20/+adi/+AD9361/Base.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.1577546108231512}} {"text": "% IN ORDER TO SIMULATE THE PROGRAM:\n% A) FIRST, LOAD A ROBOT\n% robot = load_robot('abb','irb140');\n% OR\n% robot = load_robot('abb','irb52');\n% or any other robot, the target points may not be reachable,\n% depending on the links' lengths.\n%\n% B) NEXT, LOAD SOME EQUIPMENT.\n% robot.equipment = load_robot('equipment','tables/table_two_areas');\n% \n% \n%\n% The example presents the robot achieving different positions and orientations\n% In addition, the conf values, change accordingly.\n\n\nfunction test_configurations2\n\nglobal TD_tool0 robot\n\n%definition of the end effector.\nTD_tool0=[1,[[0,0,0],[1,0,0,0]],[0,[0,0,0],[1,0,0,0],0,0,0]];\n\n\n\nmain\nend\n\nfunction main\nglobal TD_tool0 robot\n\n\nMoveJ([[217.4,1.57,1072.81]/1000,[0.972982,-0.01947,0.224767,-0.049073],[0,1,-3,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[86.96,1.57,1072.8]/1000,[0.972992,-0.01944,0.224739,-0.049009],[0,0,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[28.15,1.55,1072.8]/1000,[0.973021,-0.019611,0.224611,-0.048949],[1,-2,0,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[14.42,1.55,1072.8]/1000,[0.973015,-0.019655,0.224611,-0.049041],[1,-2,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[0.11,1.57,1072.82]/1000,[0.973031,-0.019796,0.224522,-0.049091],[1,-2,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[-12.28,1.55,1072.81]/1000,[0.973022,-0.019733,0.224521,-0.049298],[1,-2,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[-98.02,1.54,1072.82]/1000,[0.973023,-0.019651,0.22448,-0.049486],[1,-2,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\nMoveJ( [[-231.93,1.54,1072.81]/1000,[0.973047,-0.019566,0.224335,-0.049716],[1,-2,-1,0],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]],'vmax','z50',TD_tool0);\n \n\nend", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/RAPID/programs/simple_examples/test_configurations2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.15749851024159378}} {"text": "function transducer = makeTransducer(kgrid, transducer_properties)\n%MAKETRANSDUCER Create k-Wave ultrasound transducer.\n%\n% DESCRIPTION:\n% makeTransducer creates an object of the kWaveTransducer class which\n% can be substituted for the source or sensor inputs when using\n% kspaceFirstOrder3D. \n%\n% Note: This function will not work with older versions of MATLAB in\n% which custom class definitions are not supported. \n%\n% USAGE:\n% transducer = makeTransducer(kgrid, settings)\n%\n% INPUTS:\n% \n% kgrid - k-Wave grid structure returned by makeGrid\n% settings - input structure used to define the properties of\n% the transducer (see below) \n%\n% The following parameters can be appended as fields to the settings\n% input structure. These parameters are fixed when the transducer is\n% initialised (they cannot be changed without re-creating the\n% transducer). All the settings are optional and are given their\n% default values if not defined. \n%\n% number_elements - total number of transducer elements (default =\n% 128)\n% element_width - width of each element in grid points\n% (default = 1)\n% element_length - length of each element in grid points\n% (default = 10)\n% element_spacing - spacing (kerf width) between the transducer\n% elements in grid points (default = 0)\n% position - position of the corner of the transducer within\n% the grid in grid points (default = [1, 1, 1])\n% radius - radius of curvature of the transducer [m]\n% (currently only inf is supported) (default = inf) \n% input_signal - signal used to drive the ultrasound transducer\n% (where the sampling rate is defined by kgrid.dt\n% or kgrid.t_array) (default = [])\n%\n% The following parameters can also be appended as fields to the\n% settings input structure, and can additionally be modified after\n% the transducer has been initialised.\n% \n% active_elements - transducer elements that are currently active\n% elements (default = all elements)\n% beamforming_delay_offset \n% - beamforming delay offset (used to force\n% beamforming delays to be positive) (default = \n% 'auto') \n% elevation_focus_distance \n% - focus depth in the elevation direction [m]\n% (default = inf) \n% focus_distance - focus distance used to calculate beamforming\n% delays [m] (default = inf) \n% receive_apodization \n% - receive apodization; can be set to any of the\n% window shapes supported by getWin, or given as a\n% vector the same length as number_elements\n% (default = 'Rectangular') \n% sound_speed - sound speed used to calculate beamforming delays\n% [m/s] (default = 1540) \n% steering_angle - steering angle used to calculate beamforming\n% delays [deg] (default = 0)\n% transmit_apodization \n% - transmit apodization; can be set to any of the\n% window shapes supported by getWin, or given as a\n% vector the same length as number_elements \n% (default = 'Rectangular') \n%\n% OUTPUTS:\n%\n% transducer - kWaveTransducer object which can be used to\n% replace the source or sensor inputs of\n% kspaceFirstOrder3D \n% \n% In addition to the input parameters given above (which are also\n% accessible after the transducer has been created), the\n% kWaveTransducer object has a number dependent properties and\n% methods. \n%\n% input_signal - user defined input signal appended and prepended\n% with additional zeros depending on the values of\n% focus_distance, elevation_focus_distance, and\n% steering_angle \n% mask - binary mask of the active transducer elements\n% number_active_elements \n% - current number of active transducer elements \n% transducer_width \n% - total width of the transducer in grid points\n%\n% active_elements_mask \n% - return a binary mask of the active transducer\n% elements (identical to mask) \n% all_elements_mask \n% - return a binary mask of all the transducer\n% elements (both active and inactive) \n% beamforming_delays \n% - return a vector of the beam forming delays (in\n% units of time samples) for each active element\n% based on the focus and steering angle settings \n% combine_sensor_data(sensor_data)\n% - combine the sensor data returned by\n% kspaceFirstOrder3D-OMP and\n% kspaceFirstOrder3D-CUDA to give a single time\n% series per active transducer element (anlogous to\n% the output from the MATLAB code), rather than a\n% time series per grid point \n% delay_mask - return a mask of the active transducer elements,\n% where the mask values contain the beamforming\n% delays (an integer input can also be given to\n% control the beamforming delays used, where 1:\n% both delays, 2: elevation only, 3: azimuth only)\n% elevation_beamforming_delays - return a vector of the elevation\n% beam forming delays (in units of time samples)\n% for each active element based on the elevation\n% focus setting\n% get_receive_apodization \n% - return the receive apodization\n% get_transmit_apodization \n% - return the transmit apodization\n% indexed_active_elements_mask \n% - return a mask of the active transducer elements,\n% where the mask values indicate which transducer\n% element each grid point corresponds to \n% indexed_elements_mask \n% - return a mask of all the transducer elements\n% (both active and inactive), where the mask values\n% indicate which transducer element each grid point\n% corresponds to \n% plot - plot the transducer using voxelPlot\n% properties - print a list of the transducer properties to the\n% command line \n% scan_line(sensor_data)\n% - combine the input sensor data using the current\n% apodization and beamforming setting to generate a\n% single scan line \n% transmit_apodization_mask \n% - return a mask of the active transducer elements,\n% where the mask values contain the apodization\n% weights\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 28th July 2011\n% last update - 4th November 2013\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n%\n% See also makeGrid, kspaceFirstOrder3D, kWaveTransducer\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\ntry\n % create a new instance of the kWaveTransducer class\n transducer = kWaveTransducer(kgrid, transducer_properties);\ncatch ME\n % if user defined classes aren't supported, throw an error \n if strcmp(ME.identifier, 'MATLAB:UndefinedFunction')\n error('The transducer cannot be created because user defined classes are not supported in your version of MATLAB. To use this functionality, please try using a newer MATLAB version.');\n end\n rethrow(ME);\nend\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/makeTransducer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1574339703339076}} {"text": "% Valid ending arguments:\n% - SequenceNumber (0 - 65535)\n% - StateInfo0 (1 byte)\n% - StateInfo1 (1 byte)\n% - SerialNumber (14-16 characters)\n% - Longitude (double)\n% - Latitude (double)\n% - Height (-32768 to 32767)\n% - Altitude (-32768 to 32767)\n% - VelocityNorth (-32768 to 32767)\n% - VelocityEast (-32768 to 32767)\n% - VelocityUp (-32768 to 32767)\n% - Yaw (-32768 to 32767)\n% - PhoneAppGPSTime (milliseconds since Epoch)\n% - PhoneAppLatitude (double)\n% - PhoneAppLongitude (double)\n% - HomeLatitude (double)\n% - HomeLongitude (double)\n% - ProductType (1 byte)\n% - UUID (19 bytes)\n\nfunction [frame] = create_frame_bytes(varargin)\n% MIN_SAMPLE_RATE = 15.36e6;\n% \n% assert(sample_rate >= MIN_SAMPLE_RATE, \"Sample rate must be at least 15.36 MSPS\");\n% assert(round(sample_rate / MIN_SAMPLE_RATE) * MIN_SAMPLE_RATE == sample_rate, ...\n% \"Sample rate must be multiple of %d\", MIN_SAMPLE_RATE);\n\n assert(isempty(varargin) || mod(length(varargin), 2) == 0, ...\n \"Variable argument list must have even number of elements\");\n \n sequence_number = 0;\n state_info = [0, 0];\n serial_number = '0123456789abcd';\n longitude = 0.0;\n latitude = 0.0;\n height = 0;\n altitude = 0;\n velocity_north = 0;\n velocity_east = 0;\n velocity_up = 0;\n yaw = 0;\n phone_app_gps_time = 0;\n phone_app_latitude = 0.0;\n phone_app_longitude = 0.0;\n home_latitude = 0.0;\n home_longitude = 0.0;\n product_type = 0;\n uuid = zeros(1, 19);\n \n\n for idx=1:2:length(varargin)\n key = varargin{idx};\n val = varargin{idx + 1};\n\n switch(key)\n case 'SequenceNumber'\n assert(isnumeric(val), 'Sequence number must be an integer');\n assert(val >= -32768 && val <= 32767, 'Invalid sequence number');\n\n sequence_number = uint16(val);\n case 'StateInfo0'\n assert(isinteger(val), 'StateInfo0 must be an integer');\n assert(val >= 0 && val <= 255, 'Invalid StateInfo0 value');\n\n state_info(1) = uint8(val);\n case 'StateInfo1'\n assert(isinteger(val), 'StateInfo1 must be an integer');\n assert(val >= 0 && val <= 255, 'Invalid StateInfo1 value');\n\n state_info(2) = uint8(val);\n case 'SerialNumber'\n assert(isstring(val) || ischar(val), 'SerialNumber must be a string')\n assert(length(val) >= 14 && length(val) <= 16, ...\n 'SerialNumber length %d is not valid. Must be between 14 and 16 chars', length(val))\n \n serial_number = val;\n case 'Longitude'\n assert(isnumeric(val), 'Longitude must be a number')\n assert(abs(val) <= 180, 'Longitude must be between -180 and 180')\n\n longitude = double(val);\n case 'Latitude'\n assert(isnumeric(val), 'Latitude must be a number')\n assert(abs(val) <= 90, 'Latitude must be between -90 and 90')\n \n latitude = double(val);\n case 'Height'\n assert(isinteger(val), 'Height must be an integer')\n assert(val >= -32768 && val <= 32767, 'Height must be between -32768 and 32767')\n\n height = int16(val);\n case 'Altitude'\n assert(isinteger(val), 'Altitude must be an integer')\n assert(val >= -32768 && val <= 32767, 'Altitude must be between -32768 and 32767')\n\n altitude = int16(val);\n case 'VelocityNorth'\n assert(isinteger(val), 'VelocityNorth must be an integer')\n assert(val >= -32768 && val <= 32767, 'VelocityNorth must be between -32768 and 32767')\n\n velocity_north = int16(val);\n case 'VelocityEast'\n assert(isinteger(val), 'VelocityEast must be an integer')\n assert(val >= -32768 && val <= 32767, 'VelocityEast must be between -32768 and 32767')\n\n velocity_east = int16(val);\n case 'VelocityUp'\n assert(isinteger(val), 'VelocityUp must be an integer')\n assert(val >= -32768 && val <= 32767, 'VelocityUp must be between -32768 and 32767')\n\n velocity_up = int16(val);\n case 'Yaw'\n assert(isinteger(val), 'Yaw must be an integer')\n assert(val >= -32768 && val <= 32767, 'Yaw must be between -32768 and 32767')\n\n yaw = int16(val);\n case 'PhoneAppGPSTime'\n assert(isinteger(val), 'PhoneAppGPSTime must be an integer')\n assert(val >= 0 && val <= (2^64)-1, 'PhoneAppGPSTime must be between 0 and (2^64)-1')\n\n phone_app_gps_time = uint64(val);\n case 'PhoneAppLatitude'\n assert(isnumeric(val), 'PhoneAppLatitude must be a number')\n assert(abs(val) <= 90, 'PhoneAppLatitude must be between -90 and 90')\n \n phone_app_latitude = double(val);\n case 'PhoneAppLongitude'\n assert(isnumeric(val), 'PhoneAppLongitude must be a number')\n assert(abs(val) <= 180, 'PhoneAppLongitude must be between -180 and 180')\n \n phone_app_longitude = double(val);\n case 'HomeLatitude'\n assert(isnumeric(val), 'HomeLatitude must be a number')\n assert(abs(val) <= 90, 'HomeLatitude must be between -90 and 90')\n \n home_latitude = double(val);\n case 'HomeLongitude'\n assert(isnumeric(val), 'HomeLongitude must be a number')\n assert(abs(val) <= 180, 'HomeLongitude must be between -180 and 180')\n \n home_longitude = double(val);\n case 'ProductType'\n assert(isinteger(val), 'ProductType must be an integer')\n assert(val >= 0 && val <= 255, 'ProductType must be between 0 and 255')\n\n product_type = uint8(val);\n case 'UUID'\n assert(isstring(val) || ischar(val), 'UUID must be a string')\n assert(length(val) == 19, 'UUID must be 19 characters long (THIS IS TEMPORARY!!)')\n\n uuid = val;\n otherwise\n error('Invalid key \"%s\"', key);\n end\n end\n\n coord_adj = 10000000 / 57.2957795785523;\n \n % Pack the fields into bytes\n sequence_number_bytes = to_bytes(sequence_number, 2);\n state_info_bytes = state_info;\n serial_number_bytes = [uint8(serial_number) zeros(1, 16 - length(serial_number))];\n longitude_bytes = to_bytes(int32(round(longitude * coord_adj)), 4);\n latitude_bytes = to_bytes(int32(round(latitude * coord_adj)), 4);\n height_bytes = to_bytes(height, 2);\n altitude_bytes = to_bytes(altitude, 2);\n velocity_north_bytes = to_bytes(velocity_north, 2);\n velocity_east_bytes = to_bytes(velocity_east, 2);\n velocity_up_bytes = to_bytes(velocity_up, 2);\n yaw_bytes = to_bytes(yaw, 2);\n phone_app_gps_time_bytes = to_bytes(phone_app_gps_time, 8);\n phone_app_latitude_bytes = to_bytes(int32(round(phone_app_latitude * coord_adj)), 4);\n phone_app_longitude_bytes = to_bytes(int32(round(phone_app_longitude * coord_adj)), 4);\n home_latitude_bytes = to_bytes(int32(round(home_latitude * coord_adj)), 4);\n home_longitude_bytes = to_bytes(int32(round(home_longitude * coord_adj)), 4);\n product_type_bytes = product_type;\n uuid_bytes = uint8(uuid);\n\n version = uint8(2);\n message_type = uint8(16);\n uuid_len = uint8(length(uuid_bytes));\n\n\n frame = [ ...\n message_type, version, sequence_number_bytes, state_info_bytes, serial_number_bytes, longitude_bytes, ...\n latitude_bytes, height_bytes, altitude_bytes, velocity_north_bytes, velocity_east_bytes, velocity_up_bytes, ...\n yaw_bytes, phone_app_gps_time_bytes, phone_app_latitude_bytes, phone_app_longitude_bytes, home_longitude_bytes, ...\n home_latitude_bytes, product_type_bytes, uuid_len, uuid_bytes, uint8(0) ...\n ];\n\n frame = [uint8(length(frame)) frame];\n\n crc_bytes = to_bytes(calculate_crc(frame), 2);\n frame = [frame, crc_bytes];\nend", "meta": {"author": "proto17", "repo": "dji_droneid", "sha": "6ecbd20bdb1babbe2481a3870221553a10cdfe21", "save_path": "github-repos/MATLAB/proto17-dji_droneid", "path": "github-repos/MATLAB/proto17-dji_droneid/dji_droneid-6ecbd20bdb1babbe2481a3870221553a10cdfe21/matlab/updated_scripts/transmit/create_frame_bytes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.1574163636225706}} {"text": "function []=ps_sb_merge()\n%PS_SB_MERGE merge PS and SB pixels\n%\n% Andy Hooper May 2007\n%\nlogit;\n\nps_wd=pwd;\ni=strfind(ps_wd,'INSAR_');\nif isempty(i)\n error('INSAR_* does not appear in current directory path')\nend\n\nsb_wd1=[ps_wd(1:i+13),'/SMALL_BASELINES'];\nsb_wd=[sb_wd1,ps_wd(i+14:end)];\nmerged_wd1=[ps_wd(1:i+13),'/MERGED'];\nmerged_wd=[merged_wd1,ps_wd(i+14:end)];\n\nif ~exist(merged_wd)\n mkdir(merged_wd)\nend\nif ~exist([merged_wd,'/patch_noover.in']) & exist([sb_wd,'/patch_noover.in'])\n aa=['!cp ',sb_wd,'/patch_noover.in ',merged_wd]; \n eval(aa)\nend\nif ~exist([merged_wd1,'/parms.mat'])\n aa=['!cp ',sb_wd1,'/parms.mat ',merged_wd1,'/parms.mat']; \n eval(aa)\nend\n\npsver=2;\nsave([merged_wd,'/psver'],'psver')\n\npsps=load([ps_wd,'/ps2.mat']);\npssb=load([sb_wd,'/ps2.mat']);\n\npssb_ix=zeros(psps.n_ps,1); % points from ps to sb\n\nimax=max([psps.ij(:,2);pssb.ij(:,2)])+1;\njmax=max([psps.ij(:,3);pssb.ij(:,3)])+1;\ngrid_ix=zeros(imax,jmax);\ngrid_ix(pssb.ij(:,2)+1+pssb.ij(:,3)*imax)=[1:pssb.n_ps];\npssb_ix=grid_ix(psps.ij(:,2)+1+psps.ij(:,3)*imax);\n\n\npsu_ix=find(pssb_ix==0); % ps only index\npsnu_ix=find(pssb_ix); % ps non-unique index\nsbnu_ix=pssb_ix(psnu_ix); % sb non-unique index\n\n%%%%%%%%% Some non-adjacent pixels are allocated the same lon/lat by DORIS. %%%%%%%%%\n[dups,I]=setdiff(psps.lonlat(psu_ix,:),pssb.lonlat,'rows');\nfprintf('%d pixels with duplicate lon/lat dropped\\n',length(psu_ix)-length(dups))\npsu_ix=psu_ix(I);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \n\n\nG=zeros(pssb.n_ifg,pssb.n_image);\nfor i=1:pssb.n_ifg\n G(i,pssb.ifgday_ix(i,1))=-1;\n G(i,pssb.ifgday_ix(i,2))=1;\nend\n\npmps=load([ps_wd,'/pm2.mat']);\npmsb=load([sb_wd,'/pm2.mat']);\n\npmps.ph_res_all=[pmps.ph_res(:,1:psps.master_ix-1),pmps.C_ps,pmps.ph_res(:,psps.master_ix:end)]; % add master residual\npmps.ph_res3=exp(j*(G*pmps.ph_res_all')'); % would-be residuals of sb ifgs\npmps.coh_ps2=abs(sum(pmps.ph_res3,2))/pssb.n_ifg; % would-be coherence of sb ifgs\n\npsnu_coh=pmps.coh_ps2(psnu_ix);\npsnu_snr=1./(1./psnu_coh.^2-1);\nsbnu_coh=pmsb.coh_ps(sbnu_ix);\nsbnu_snr=1./(1./sbnu_coh.^2-1);\nps_high_coh_ix=pmps.coh_ps2(psu_ix)>min(pmsb.coh_ps);\npsu_ix=psu_ix(ps_high_coh_ix);\npsu_coh=pmps.coh_ps2(psu_ix);\n\n\nsave([merged_wd,'/merge2'],'psu_ix','psu_coh','psnu_ix','sbnu_ix','psnu_coh','sbnu_coh','G')\n\nps=pssb;\nps.ij=[psps.ij(psu_ix,:);pssb.ij];\nps.lonlat=[psps.lonlat(psu_ix,:);pssb.lonlat];\nll0=(max(ps.lonlat)+min(ps.lonlat))/2;\nxy=llh2local(ps.lonlat',ll0)*1000;\nxy=xy';\nsort_x=sortrows(xy,1);\nsort_y=sortrows(xy,2);\nn_pc=round(size(xy,1)*0.001);\nbl=mean(sort_x(1:n_pc,:)); % bottom left corner\ntr=mean(sort_x(end-n_pc:end,:)); % top right corner\nbr=mean(sort_y(1:n_pc,:)); % bottom right corner\ntl=mean(sort_y(end-n_pc:end,:)); % top left corner\n\nheading=getparm('heading');\ntheta=(180-heading)*pi/180;\nif theta>pi\n theta=theta-2*pi;\nend\n\nrotm=[cos(theta),sin(theta); -sin(theta),cos(theta)];\nxy=xy';\nxynew=rotm*xy; % rotate so that scene axes approx align with x=0 and y=0\nif max(xynew(1,:))-min(xynew(1,:))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": "function output = callfiltersdsp(model)\n\noptions = model.options.filtersd;\n\nmodel = yalmip2nonlinearsolver(model);\n\nif ~model.derivative_available\n disp('Derivate-free call to filterSD not yet implemented')\n error('Derivate-free call to filterSD not yet implemented')\nend\nif model.options.savedebug\n save filtersddebug model\nend\nshowprogress('Calling filterSDSP',model.options.showprogress);\n\ncu = [ repmat(0,length(model.bnonlinineq),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(0,length(model.b),1);\n repmat(0,length(model.beq),1)];\n\ncl = [ repmat(-inf,length(model.bnonlinineq),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(-inf,length(model.b),1);\n repmat(0,length(model.beq),1)];\n\nif isempty(cu)\n Flow = [];\n Fupp = [];\nend\n\n% These are needed to avoid recomputation due to ipopts double call to get\n% f and df, and g and dg\nglobal latest_x_f\nglobal latest_x_g\nglobal latest_df\nglobal latest_f\nglobal latest_G\nglobal latest_g\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_G = [];\nlatest_g = [];\nlatest_x_f = [];\nlatest_x_g = [];\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\nfuncs.objective = @(x)ipopt_callback_f(x,model);\nfuncs.gradient = @(x)ipopt_callback_df(x,model);\nif ~isempty(cu)\n funcs.constraints = @(x)ipopt_callback_g(x,model);\n funcs.jacobian = @(x)ipopt_callback_dg(x,model);\nelse\n funcs.constraints = [];\n funcs.jacobian = [];\nend\n\nlb = model.lb(:)';\nub = model.ub(:)';\n\nif ~isempty(cu)\n nljacstr = jacobiansparsityfromnonlinear(model);\nelse\n nljacstr = [];\nend\n\nif ~model.options.usex0\n model.x0 = (lb+ub)/2;\n model.x0(isinf(ub)) = lb(isinf(ub))+1;\n model.x0(isinf(lb)) = ub(isinf(lb))-1;\n model.x0(isinf(model.x0)) = 0;\nend\n\noptions.display = model.options.verbose;\nsolvertime = tic;\n[xout,fval,exitflag,stats,lambda] = filtersdsp(funcs.objective, funcs.gradient, model.x0, lb, ub, funcs.constraints, funcs.jacobian,nljacstr, cl, cu, options);\nsolvertime = toc(solvertime);\n\n% Duals currently not supported\nlambda = [];\n\nx = RecoverNonlinearSolverSolution(model,xout);\n\nswitch exitflag\n case {0}\n problem = 0;\n case {1}\n problem = 2;\n case {2,3}\n problem = 1;\n case {5}\n problem = 3;\n case {4,9}\n problem = 4;\n case 105\n problem = 16; \n otherwise\n problem = -1;\nend\n\n% Internal format for duals\nD_struc = [];\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n solverinput.model = model;\nelse\n solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n solveroutput.x = xout; \n solveroutput.exitflag = exitflag;\n solveroutput.stats = stats;\nelse\n solveroutput = [];\nend\n\n% Standard interface\noutput = createoutput(x,D_struc,[],problem,'filterSD',solverinput,solveroutput,solvertime);\n\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/YALMIP/solvers/callfiltersdsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15608005076736617}} {"text": "function allen_ccf_2pi(tv,av,st)\n% allen_ccf_2pi(tv,av,st)\n% written by Samuel Picard (samuel.picard@ucl.ac.uk)\n% based on original allen_ccf_npx tool written by Andy Peters (peters.andrew.j@gmail.com)\n%\n% GUI for planning 2pi chronic window implant with the Allen CCF\n% Part of repository: https://github.com/cortex-lab/allenCCF\n% - directions for installing atlas in repository readme\n% - some dependent functions from that repository\n%\n% (optional inputs - if CCF path written in Line 22, loaded automatically)\n% tv, av, st = CCF template volume, annotated volume, structure tree\n% tv = readNPY('template_volume_10um.npy');\n% av = readNPY('annotation_volume_10um_by_index.npy');\n% st = loadStructureTree('structure_tree_safe_2017.csv');\n\n% Initialize gui_data structure\ngui_data = struct;\n\n% Allen CCF-bregma transform (estimated from eyeballing Paxinos->CCF)\n% [AP,DV,ML]\nbregma = [540,0,570];\n\n% If not already loaded in, load in atlas\nif nargin < 3\n allen_atlas_path = 'C:\\Users\\Samuel\\Documents\\GitHub\\allenCCF'; %put path to atlas files here\n if isempty(allen_atlas_path)\n error('Enter path where Allen CCF is stored at Line 26');\n end\n tv = readNPY([allen_atlas_path filesep 'template_volume_10um.npy']); % grey-scale \"background signal intensity\"\n av = readNPY([allen_atlas_path filesep 'annotation_volume_10um_by_index.npy']); % the number at each pixel labels the area, see note below\n st = loadStructureTree([allen_atlas_path filesep 'structure_tree_safe_2017.csv']); % a table of what all the labels mean\nend\n\n% Load the colormap (located in the repository, find by associated fcn)\nallenCCF_path = fileparts(which('allenCCFbregma'));\ncmap_filename = [allenCCF_path filesep 'allen_ccf_colormap_2017.mat'];\nload(cmap_filename);\n\n% Set up the gui\nwindow_atlas_gui = figure('Toolbar','none','Menubar','none','color','w', ...\n 'Name','Atlas-window viewer','Units','normalized','Position',[0.2,0.2,0.7,0.7]);\n\n% Set up the atlas axes\naxes_atlas = subplot(2,2,[1 3]);\n[~, brain_outline] = plotBrainGrid([],axes_atlas);\nhold(axes_atlas,'on');\naxis vis3d equal off manual\nview([-30,25]);\ncaxis([0 300]);\n[ap_max,dv_max,ml_max] = size(tv);\nxlim([-10,ap_max+10])\nylim([-10,ml_max+10])\nzlim([-10,dv_max+10])\n\n% Set up the window area axes\n%top of window\naxes_window_areas = subplot(2,2,2);\naxes_window_areas.ActivePositionProperty = 'position';\nwindow_areas_plot = image(nan(166,166)); %initialized for 5mm window at 30um resolution\naxis off auto\nwindow_areas_text = text(axes_window_areas,zeros(1,100),zeros(1,100),repmat({''}, 1, 100));\nset(axes_window_areas,'FontSize',11,'XLimSpec', 'Tight','YLimSpec', 'Tight');\ncolormap(axes_window_areas,cmap);\ncaxis([1,size(cmap,1)])\n%bottom of window\naxes_window_areas_bottom = subplot(2,2,4);\naxes_window_areas_bottom.ActivePositionProperty = 'position';\nwindow_areas_bottom_plot = image(nan(166,166)); %initialized for 5mm window at 30um resolution\naxis off auto\nwindow_areas_bottom_text = text(axes_window_areas_bottom,zeros(1,100),zeros(1,100),repmat({''}, 1, 100));\nset(axes_window_areas_bottom,'FontSize',11,'XLimSpec', 'Tight','YLimSpec', 'Tight');\ncolormap(axes_window_areas_bottom,cmap);\ncaxis([1,size(cmap,1)])\n\n% Position the axes\nset(axes_atlas,'Position',[-0.15,-0.1,1,1.2]);\nset(axes_window_areas,'Position',[0.7,0.55,0.2,0.34]);\nset(axes_window_areas_bottom,'Position',[0.7,0.1,0.2,0.34]);\n\n% Set the current axes to the atlas (dirty, but some gca requirements)\naxes(axes_atlas);\n\n% Set up the window reference/actual\nwindow_centre = [bregma(1),bregma(3),0];\nwindow_depth = 60; % effective z-range of 2p microscope (in 10 ums)\nwindow_diameter = 500; % diameter in 10 ums\nwindow_vector = [window_centre',[window_centre(1),window_centre(2),window_depth]'];\nwindow_vector_line = line(window_vector(1,:),window_vector(2,:),window_vector(3,:),'linewidth',3,'color','b','linestyle','-');\nwindow_rads = linspace(-pi,pi,100);\nwindow_circle = line(0.5*window_diameter*cos(window_rads)+window_centre(1),...\n 0.5*window_diameter*sin(window_rads)+window_centre(2),...\n zeros(size(window_rads))+window_centre(3),...\n 'linewidth',1.5,'color','r','linestyle','--');\n\n% add titles for window plots\ntitle(axes_window_areas,'Top of window');\ntitle(axes_window_areas_bottom,[sprintf('Bottom (%i ',10*window_depth),'\\mu','m)']);\n\n% Set up the text to display coordinates\nwindow_coordinates_text = uicontrol('Style','text','String','', ...\n 'Units','normalized','Position',[0,0.95,1,0.05], ...\n 'BackgroundColor','w','HorizontalAlignment','left','FontSize',12);\n\n% Store data\ngui_data.tv = tv; % Intensity atlas\ngui_data.av = av; % Annotated atlas\ngui_data.st = st; % Labels table\ngui_data.cmap = cmap; % Atlas colormap\ngui_data.bregma = bregma; % Bregma for external referencing\ngui_data.window_depth = window_depth; % Effective z-depth under window\ngui_data.structure_plot_idx = []; % Plotted structures\ngui_data.window_angle = [0;0]; % window angles in ML/DV\ngui_data.window_centre = window_centre; % Window reference centre on 3D atlas\ngui_data.window_diameter = window_diameter;\ngui_data.ref_centre = window_centre;\n\n%Store handles\ngui_data.handles.cortex_outline = brain_outline;\ngui_data.handles.structure_patch = []; % Plotted structures\ngui_data.handles.axes_atlas = axes_atlas; % Axes with 3D atlas\ngui_data.handles.axes_window_areas = axes_window_areas; % Axes with window areas\ngui_data.handles.axes_window_areas_bottom = axes_window_areas_bottom; % Axes with window areas\ngui_data.handles.slice_plot = surface('EdgeColor','none'); % Slice on 3D atlas\ngui_data.handles.slice_volume = 'tv'; % The volume shown in the slice\ngui_data.handles.window_vector = window_vector_line; % Window centre vector on 3D atlas\ngui_data.handles.window_circle = window_circle; % Window circle on 3D atlas\ngui_data.handles.window_areas_plot = window_areas_plot; % Color-coded window regions\ngui_data.handles.window_areas_bottom_plot = window_areas_bottom_plot; % Color-coded window regions\ngui_data.handles.window_areas_text = window_areas_text; % Labels for window regions\ngui_data.handles.window_areas_bottom_text = window_areas_bottom_text; % Labels for window regions\ngui_data.window_coordinates_text = window_coordinates_text; % Window coordinates text\n\n% Make 3D rotation the default state (toggle on/off with 'r')\nh = rotate3d(axes_atlas);\nh.Enable = 'on';\n% Update the slice whenever a rotation is completed\n%h.ActionPostCallback = @update_slice;\n\n% Set functions for key presses\nhManager = uigetmodemanager(window_atlas_gui);\n[hManager.WindowListenerHandles.Enabled] = deal(false);\nset(window_atlas_gui,'KeyPressFcn',@key_press);\nset(window_atlas_gui,'KeyReleaseFcn',@key_release);\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\n% Display the first slice and update the window position\nupdate_slice(window_atlas_gui);\nupdate_window_coordinates(window_atlas_gui);\n\n% Display controls\ndisplay_controls;\n\nend\n\nfunction key_press(window_atlas_gui,eventdata)\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\nswitch eventdata.Key\n \n case 'uparrow'\n if isempty(eventdata.Modifier)\n % Up: move window anterior\n ap_offset = -10;\n set(gui_data.handles.window_circle,'XData',get(gui_data.handles.window_circle,'XData') + ap_offset);\n set(gui_data.handles.window_vector,'XData',get(gui_data.handles.window_vector,'XData') + ap_offset);\n gui_data.window_centre = gui_data.window_centre + [ap_offset,0,0];\n elseif any(strcmp(eventdata.Modifier,'shift'))\n % Ctrl-up: increase DV angle\n angle_change = [1;0];\n gui_data = update_window_angle(window_atlas_gui,angle_change);\n elseif any(strcmp(eventdata.Modifier,'alt'))\n % Alt-up: raise window\n dv_offset = -10;\n old_window_vector = cell2mat(get(gui_data.handles.window_vector,{'XData','YData','ZData'})');\n old_window_circle = cell2mat(get(gui_data.handles.window_circle,{'XData','YData','ZData'})');\n move_vector = diff(old_window_vector,[],2)./ ...\n norm(diff(old_window_vector,[],2))*dv_offset;\n new_window_vector = bsxfun(@plus,old_window_vector,move_vector);\n new_window_circle = bsxfun(@plus,old_window_circle,move_vector);\n set(gui_data.handles.window_vector,'XData',new_window_vector(1,:), ...\n 'YData',new_window_vector(2,:),'ZData',new_window_vector(3,:));\n set(gui_data.handles.window_circle,'XData',new_window_circle(1,:), ...\n 'YData',new_window_circle(2,:),'ZData',new_window_circle(3,:));\n gui_data.window_centre = gui_data.window_centre + move_vector';\n \n end\n \n case 'downarrow'\n if isempty(eventdata.Modifier)\n % Down: move window posterior\n ap_offset = 10;\n set(gui_data.handles.window_circle,'XData',get(gui_data.handles.window_circle,'XData') + ap_offset);\n set(gui_data.handles.window_vector,'XData',get(gui_data.handles.window_vector,'XData') + ap_offset);\n gui_data.window_centre = gui_data.window_centre + [ap_offset,0,0];\n elseif any(strcmp(eventdata.Modifier,'shift'))\n % Ctrl-down: decrease DV angle\n angle_change = [-1;0];\n gui_data = update_window_angle(window_atlas_gui,angle_change);\n elseif any(strcmp(eventdata.Modifier,'alt'))\n % Alt-down: lower window\n dv_offset = 10;\n old_window_vector = cell2mat(get(gui_data.handles.window_vector,{'XData','YData','ZData'})');\n old_window_circle = cell2mat(get(gui_data.handles.window_circle,{'XData','YData','ZData'})');\n move_vector = diff(old_window_vector,[],2)./ ...\n norm(diff(old_window_vector,[],2))*dv_offset;\n new_window_vector = bsxfun(@plus,old_window_vector,move_vector);\n new_window_circle = bsxfun(@plus,old_window_circle,move_vector);\n set(gui_data.handles.window_vector,'XData',new_window_vector(1,:), ...\n 'YData',new_window_vector(2,:),'ZData',new_window_vector(3,:));\n set(gui_data.handles.window_circle,'XData',new_window_circle(1,:), ...\n 'YData',new_window_circle(2,:),'ZData',new_window_circle(3,:));\n gui_data.window_centre = gui_data.window_centre + move_vector';\n \n end\n \n case 'rightarrow'\n if isempty(eventdata.Modifier)\n % Right: move window right\n ml_offset = 10;\n set(gui_data.handles.window_circle,'YData',get(gui_data.handles.window_circle,'YData') + ml_offset);\n set(gui_data.handles.window_vector,'YData',get(gui_data.handles.window_vector,'YData') + ml_offset);\n gui_data.window_centre = gui_data.window_centre + [0,ml_offset,0];\n elseif any(strcmp(eventdata.Modifier,'shift'))\n % Ctrl-right: increase vertical angle\n angle_change = [0;1];\n gui_data = update_window_angle(window_atlas_gui,angle_change);\n end\n \n case 'leftarrow'\n if isempty(eventdata.Modifier)\n % Left: move window left\n ml_offset = -10;\n set(gui_data.handles.window_circle,'YData',get(gui_data.handles.window_circle,'YData') + ml_offset);\n set(gui_data.handles.window_vector,'YData',get(gui_data.handles.window_vector,'YData') + ml_offset);\n gui_data.window_centre = gui_data.window_centre + [0,ml_offset,0];\n elseif any(strcmp(eventdata.Modifier,'shift'))\n % Ctrl-left: decrease vertical angle\n angle_change = [0;-1];\n gui_data = update_window_angle(window_atlas_gui,angle_change);\n end\n \n case 'c'\n % Bring up controls again\n display_controls;\n \n case 'b'\n % Toggle brain outline visibility\n current_visibility = gui_data.handles.cortex_outline.Visible;\n switch current_visibility; case 'on'; new_visibility = 'off'; case 'off'; new_visibility = 'on'; end;\n set(gui_data.handles.cortex_outline,'Visible',new_visibility);\n \n case 'a'\n % Toggle plotted structure visibility\n if ~isempty(gui_data.structure_plot_idx)\n current_alpha = get(gui_data.handles.structure_patch(1),'FaceAlpha');\n switch current_alpha\n case 0\n new_alpha = 0.2;\n case 0.2\n new_alpha = 1;\n case 1\n new_alpha = 0;\n end\n set(gui_data.handles.structure_patch,'FaceAlpha',new_alpha);\n end\n \n case 's'\n % Toggle slice volume/visibility\n slice_volumes = {'tv','av','none'};\n new_slice_volume = slice_volumes{circshift( ...\n strcmp(gui_data.handles.slice_volume,slice_volumes),[0,1])};\n \n if strcmp(new_slice_volume,'none')\n set(gui_data.handles.slice_plot,'Visible','off');\n else\n set(gui_data.handles.slice_plot,'Visible','on');\n end\n \n gui_data.handles.slice_volume = new_slice_volume;\n guidata(window_atlas_gui, gui_data);\n \n update_slice(window_atlas_gui);\n \n case 'w'\n % Toggle window visibility\n current_visibility = gui_data.handles.window_circle.Visible;\n switch current_visibility; case 'on'; new_visibility = 'off'; case 'off'; new_visibility = 'on'; end;\n set(gui_data.handles.window_circle,'Visible',new_visibility);\n \n case 'm'\n % Set window position manually and find window angle automatically\n set_window_position(window_atlas_gui);\n % Get updated guidata\n gui_data = guidata(window_atlas_gui);\n \n case {'equal','add'}\n % Add structure(s) to display\n slice_spacing = 10;\n \n % Prompt for which structures to show (only structures which are\n % labelled in the slice-spacing downsampled annotated volume)\n \n if ~any(strcmp(eventdata.Modifier,'shift'))\n % (no shift: list in native CCF order)\n \n parsed_structures = unique(reshape(gui_data.av(1:slice_spacing:end, ...\n 1:slice_spacing:end,1:slice_spacing:end),[],1));\n if ~any(strcmp(eventdata.Modifier,'alt'))\n % (no alt: list all)\n plot_structures_parsed = listdlg('PromptString','Select a structure to plot:', ...\n 'ListString',gui_data.st.safe_name(parsed_structures),'ListSize',[520,500]);\n plot_structures = parsed_structures(plot_structures_parsed);\n else\n % (alt: search list)\n structure_search = lower(inputdlg('Search structures'));\n structure_match = find(contains(lower(gui_data.st.safe_name),structure_search));\n list_structures = intersect(parsed_structures,structure_match);\n if isempty(list_structures)\n error('No structure search results')\n end\n \n plot_structures_parsed = listdlg('PromptString','Select a structure to plot:', ...\n 'ListString',gui_data.st.safe_name(list_structures),'ListSize',[520,500]);\n plot_structures = list_structures(plot_structures_parsed);\n end\n \n if ~isempty(plot_structures)\n for curr_plot_structure = reshape(plot_structures,1,[])\n % If this label isn't used, don't plot\n if ~any(reshape(gui_data.av( ...\n 1:slice_spacing:end,1:slice_spacing:end,1:slice_spacing:end),[],1) == curr_plot_structure)\n disp(['\"' gui_data.st.safe_name{curr_plot_structure} '\" is not parsed in the atlas'])\n continue\n end\n \n gui_data.structure_plot_idx(end+1) = curr_plot_structure;\n \n plot_structure_color = hex2dec(reshape(gui_data.st.color_hex_triplet{curr_plot_structure},2,[])')./255;\n structure_3d = isosurface(permute(gui_data.av(1:slice_spacing:end, ...\n 1:slice_spacing:end,1:slice_spacing:end) == curr_plot_structure,[3,1,2]),0);\n \n if isempty(gui_data.handles.structure_patch)\n structure_alpha = 0.2;\n else\n structure_alpha = get(gui_data.handles.structure_patch(1),'FaceAlpha');\n end\n gui_data.handles.structure_patch(end+1) = patch('Vertices',structure_3d.vertices*slice_spacing, ...\n 'Faces',structure_3d.faces, ...\n 'FaceColor',plot_structure_color,'EdgeColor','none','FaceAlpha',structure_alpha);\n end\n end\n \n elseif any(strcmp(eventdata.Modifier,'shift'))\n % (shift: use hierarchy search)\n if ~any(strcmp(eventdata.Modifier,'control'))\n % (no ctrl, choose between all structures)\n plot_structures = hierarchicalSelect(gui_data.st);\n else\n % (ctrl: take pre-defined regions: isocortex, cerebellum, SC & IC)\n plot_structures = [7,13,31,108,115,122,158,221,239,246,253,279,298,340,361,368,374,381,809,813,1016,1017];\n end\n \n if ~isempty(plot_structures) % will be empty if dialog was cancelled\n % get all children of this one\n for plot_structure = plot_structures\n thisID = gui_data.st.id(plot_structure);\n idStr = sprintf('/%d/', thisID);\n theseCh = find(cellfun(@(x)contains(x,idStr), gui_data.st.structure_id_path));\n \n % plot the structure\n slice_spacing = 5;\n plot_structure_color = hex2dec(reshape(gui_data.st.color_hex_triplet{plot_structure},3,[]))./255;\n structure_3d = isosurface(permute(ismember(gui_data.av(1:slice_spacing:end, ...\n 1:slice_spacing:end,1:slice_spacing:end),theseCh),[3,1,2]),0);\n \n if isempty(gui_data.handles.structure_patch)\n structure_alpha = 0.2;\n else\n structure_alpha = get(gui_data.handles.structure_patch(1),'FaceAlpha');\n end\n gui_data.structure_plot_idx(end+1) = plot_structure;\n gui_data.handles.structure_patch(end+1) = patch('Vertices',structure_3d.vertices*slice_spacing, ...\n 'Faces',structure_3d.faces, ...\n 'FaceColor',plot_structure_color,'EdgeColor','none','FaceAlpha',structure_alpha);\n \n end\n \n end\n \n \n end\n \n case {'hyphen','subtract'}\n % Remove structure(s) already plotted\n if ~isempty(gui_data.structure_plot_idx)\n remove_structures = listdlg('PromptString','Select a structure to remove:', ...\n 'ListString',gui_data.st.safe_name(gui_data.structure_plot_idx));\n delete(gui_data.handles.structure_patch(remove_structures))\n gui_data.structure_plot_idx(remove_structures) = [];\n gui_data.handles.structure_patch(remove_structures) = [];\n end\n \n case 'x'\n % Export the window vector coordinates in Allen CCF to the workspace\n window_vector = cell2mat(get(gui_data.handles.window_vector_line,{'XData','YData','ZData'})');\n window_vector_ccf = round(window_vector([1,3,2],:))';\n assignin('base','window_vector_ccf',window_vector_ccf)\n disp('Copied window vector coordinates to workspace');\n \nend\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\nend\n\nfunction key_release(window_atlas_gui,eventdata)\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\nswitch eventdata.Key\n case {'rightarrow','leftarrow','uparrow','downarrow'}\n % Update the window info/slice on arrow release\n update_window_coordinates(window_atlas_gui);\n update_slice(window_atlas_gui);\nend\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\nend\n\n\nfunction update_slice(window_atlas_gui,varargin)\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\n% Only update the slice if it's visible\nif strcmp(gui_data.handles.slice_plot(1).Visible,'on')\n \n offsets = [0,gui_data.window_depth];\n plot_handles = {'window_areas','window_areas_bottom'};\n \n for islice = 1:length(offsets)\n \n % Get current window outline coordinate\n curr_window_circle = cell2mat(get(gui_data.handles.window_circle,{'XData','YData','ZData'})');\n window_vector = cell2mat(get(gui_data.handles.window_vector,{'XData','YData','ZData'})');\n move_vector = diff(window_vector,[],2)./ ...\n norm(diff(window_vector,[],2))*offsets(islice);\n window_circle = bsxfun(@plus,curr_window_circle,move_vector);\n window_centre = gui_data.window_centre + move_vector';\n \n \n % Get two vectors on the window plane\n vlength = size(window_circle,2);\n window_vector_1 = window_circle(:,1)' - window_circle(:,round(0.4*vlength))';\n window_vector_2 = window_circle(:,1)' - window_circle(:,round(0.7*vlength))';\n \n %get the normal vector of the plane\n normal_vector = cross(window_vector_1,window_vector_2);\n \n % Get the plane offset through the window centre\n window_top = window_centre;\n plane_offset = -(normal_vector*window_top');\n \n % Define a plane of points to index\n % (the plane grid is defined based on the which cardinal plan is most\n % orthogonal to the plotted plane. this is janky but it works)\n slice_px_space = 3;\n [~,cam_plane] = max(abs(normal_vector./norm(normal_vector)));\n \n switch cam_plane\n \n case 1\n [plane_y,plane_z] = meshgrid(1:slice_px_space:size(gui_data.tv,3),1:slice_px_space:size(gui_data.tv,2));\n plane_x = ...\n (normal_vector(2)*plane_y+normal_vector(3)*plane_z + plane_offset)/ ...\n -normal_vector(1);\n \n case 2\n [plane_x,plane_z] = meshgrid(1:slice_px_space:size(gui_data.tv,1),1:slice_px_space:size(gui_data.tv,2));\n plane_y = ...\n (normal_vector(1)*plane_x+normal_vector(3)*plane_z + plane_offset)/ ...\n -normal_vector(2);\n \n \n case 3\n [plane_x,plane_y] = meshgrid(1:slice_px_space:size(gui_data.tv,1),1:slice_px_space:size(gui_data.tv,3));\n plane_z = ...\n (normal_vector(1)*plane_x+normal_vector(2)*plane_y + plane_offset)/ ...\n -normal_vector(3);\n \n end\n \n % Get the coordinates on the plane\n x_idx = round(plane_x);\n y_idx = round(plane_y);\n z_idx = round(plane_z);\n \n % make a mask for the window (in the horizontal plane)\n window_mask = uint8(((plane_x-window_centre(1)).^2 + (plane_y-window_centre(2)).^2 + (plane_z-window_centre(3)).^2)<(gui_data.window_diameter/2)^2);\n \n % Find plane coordinates in bounds with the volume and the window\n use_xd = x_idx > 0 & x_idx < size(gui_data.tv,1);\n use_yd = y_idx > 0 & y_idx < size(gui_data.tv,3);\n use_zd = z_idx > 0 & z_idx < size(gui_data.tv,2);\n use_idx = use_xd & use_yd & use_zd & window_mask;\n \n curr_slice_idx = sub2ind(size(gui_data.tv),x_idx(use_idx),z_idx(use_idx),y_idx(use_idx));\n \n % Find plane coordinates that contain brain\n curr_slice_isbrain = false(size(use_idx));\n curr_slice_isbrain(use_idx) = gui_data.av(curr_slice_idx) > 1;\n \n % Index coordinates in bounds + with brain\n grab_pix_idx = sub2ind(size(gui_data.tv),x_idx(curr_slice_isbrain),z_idx(curr_slice_isbrain),y_idx(curr_slice_isbrain));\n \n % Grab pixels from (selected) volume\n curr_slice = nan(size(use_idx));\n switch gui_data.handles.slice_volume\n case 'tv'\n curr_slice(curr_slice_isbrain) = gui_data.tv(grab_pix_idx);\n colormap(gui_data.handles.axes_atlas,'gray');\n caxis([0,255]);\n case 'av'\n curr_slice(curr_slice_isbrain) = gui_data.av(grab_pix_idx);\n colormap(gui_data.handles.axes_atlas,gui_data.cmap);\n caxis([1,size(gui_data.cmap,1)]);\n end\n \n % Update the slice display\n if islice==2 %1 = top, 2 = bottom\n set(gui_data.handles.slice_plot,'XData',plane_x,'YData',plane_y,'ZData',plane_z,'CData',curr_slice);\n end\n \n % Update the title with new depth\n if islice==2\n set(eval(['gui_data.handles.axes_',plot_handles{islice},'.Title']),'String',[sprintf('Bottom (%i ',10*offsets(islice)),'\\mu','m)']);\n end\n \n % Update the window overview\n curr_slice_av = nan(size(use_idx));\n curr_slice_av(curr_slice_isbrain) = gui_data.av(grab_pix_idx);\n x_edges = [find(sum(window_mask,1),1,'first'),find(sum(window_mask,1),1,'last')];\n y_edges = [find(sum(window_mask,2),1,'first'),find(sum(window_mask,2),1,'last')];\n cropped_window = curr_slice_av(y_edges(1):y_edges(2),x_edges(1):x_edges(2))';\n set(eval(['gui_data.handles.',plot_handles{islice},'_plot']),'CData',cropped_window);\n \n %update area labels based on which areas are contained in window\n window_areas = cropped_window;\n unique_areas = unique(window_areas(~isnan(window_areas(:))));\n unique_parent_struct = unique(gui_data.st.parent_structure_id(unique_areas));\n for i_struct = 1:100\n if i_struct<=length(unique_parent_struct)\n areas_in_parent_struct = find(gui_data.st.parent_structure_id==unique_parent_struct(i_struct));\n area_bm = ismember(window_areas,areas_in_parent_struct);\n area_bm_largest = zeros(size(area_bm));\n cc = bwconncomp(area_bm);\n [~,largest_blob] = max(cellfun('length',cc.PixelIdxList));\n area_bm_largest(cc.PixelIdxList{largest_blob}) = 1;\n [area_x,area_y] = find(area_bm_largest==1);\n area_centre = [mean(area_y),mean(area_x)];\n area_string = gui_data.st.acronym{find(gui_data.st.id==unique_parent_struct(i_struct))};\n else\n area_centre = [0,0];\n area_string = '';\n end\n set(eval(['gui_data.handles.',plot_handles{islice},'_text(',num2str(i_struct),')']),...\n 'Position',area_centre,'String',area_string,...\n 'VerticalAlignment','middle','HorizontalAlignment','center');\n end\n end\n\n % Upload gui_data\n guidata(window_atlas_gui, gui_data);\n \nend\n\nend\n\n\nfunction set_window_position(window_atlas_gui,varargin) %this function should place window at tangent plane\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\nprompt_text = { ...\n 'AP position (mm from bregma)', ...\n 'ML position (mm from bregma)', ...\n 'window diameter (mm)', ...\n 'maximum depth (microns)'};\n\nnew_window_position = cellfun(@str2num,inputdlg(prompt_text,'Set window position',1));\n\n% Convert centre position: mm->CCF\nwindow_centre_ccf_coords = round(gui_data.bregma([1,3])' - 100*[new_window_position(1);-new_window_position(2)]);%not sure why we need this sign change...\nwindow_diameter = new_window_position(3)*100;\nwindow_depth = new_window_position(4)/10;\n\n%load surface data or generate it from scratch\nif ~exist('surf_coords','var')\n try\n load('dorsalsurface_nomidline_ccf_coords.mat')\n catch\n %CODE TO GENERATE SURFACE MAP\n surf_coords = nan(size(gui_data.av,1),size(gui_data.av,3));\n for i=1:size(gui_data.av,1)\n for j=1:size(gui_data.av,3)\n idxs = find(squeeze(gui_data.av(i,:,j))>1,1,'first');\n if ~isempty(idxs)\n surf_coords(i,j) = idxs;\n end\n end\n idx_c = round(size(gui_data.av,3)/2);\n [m,idx_m] = min(surf_coords(i,:));\n idx_m_c = idx_m-idx_c;\n surf_coords(i,idx_c-abs(idx_m_c):idx_c+abs(idx_m_c)) = m;\n end\n save('dorsalsurface_nomidline_ccf_coords.mat',surf_coords);\n end\nend\n\n%figure out angle of tangent plane\nsurf_depth_coords = surf_ccf_coords(window_centre_ccf_coords(1),window_centre_ccf_coords(2));\ncentre_surf_ccf_coords = [window_centre_ccf_coords(1); surf_depth_coords; window_centre_ccf_coords(2)];\ncentre_patch = surf_ccf_coords(window_centre_ccf_coords(1)-50:window_centre_ccf_coords(1)+50,window_centre_ccf_coords(2)-50:window_centre_ccf_coords(2)+50);\ncentre_patch_smooth = imgaussfilt(centre_patch,'FilterSize',9);\n[fx,fy] = gradient(centre_patch_smooth,1);\navg_gradient = [-nanmean(fy(:));nanmean(fx(:))];\nwindow_angle_rad = atan(avg_gradient);\nwindow_angle_deg = (window_angle_rad/(2*pi))*360;\n\n%compute new window vector and circle (horizontal)\n%window_diameter = gui_data.window_diameter;\nwindow_rads = linspace(-pi,pi,100);\nwindow_centre = [window_centre_ccf_coords', surf_depth_coords-gui_data.ref_centre(3)];\nwindow_circle = [0.5*window_diameter*cos(window_rads)+window_centre(1);...\n 0.5*window_diameter*sin(window_rads)+window_centre(2);...\n zeros(size(window_rads))+window_centre(3)];\nwindow_vector = [window_centre',(window_centre+[0,0,window_depth])'];\n\n%rotate these by the tangent angle\neul = [0;window_angle_rad]; %[yaw; pitch; roll]\nR = eul2rotm(eul'); %find rotation matrix\nwindow_circle_centred = window_circle - window_centre'; %translate to origin by subtracting its centre coords\nwindow_vector_centred = window_vector - window_centre';\nnew_window_circle_centred = R*window_circle_centred; %rotate around origin\nnew_window_vector_centred = R*window_vector_centred;\nnew_window_circle = new_window_circle_centred + window_centre'; %translate back to its position\nnew_window_vector = new_window_vector_centred + window_centre';\n\n% update gui_data\nset(gui_data.handles.window_circle,'XData',new_window_circle(1,:), ...\n 'YData',new_window_circle(2,:), ...\n 'ZData',new_window_circle(3,:));\nset(gui_data.handles.window_vector,'XData',new_window_vector(1,:), ...\n 'YData',new_window_vector(2,:), ...\n 'ZData',new_window_vector(3,:));\ngui_data.window_angle = window_angle_deg;\ngui_data.window_centre = [window_centre_ccf_coords', surf_depth_coords];\ngui_data.window_diameter = window_diameter;\ngui_data.window_depth = window_depth;\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\n% Update the slice and window coordinates\nupdate_slice(window_atlas_gui);\nupdate_window_coordinates(window_atlas_gui);\n\nend\n\nfunction gui_data = update_window_angle(window_atlas_gui,angle_change)\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\n% Set new angle\nnew_angle = gui_data.window_angle + angle_change;\ngui_data.window_angle = new_angle;\n\n% Get the positions of the window circle and vector\nwindow_circle = cell2mat(get(gui_data.handles.window_circle,{'XData','YData','ZData'})');\nwindow_vector = cell2mat(get(gui_data.handles.window_vector,{'XData','YData','ZData'})');\n\n% Compute the rotation matrix\neul = [0;(angle_change/360)*2*pi];\nR = eul2rotm(eul');\n\n% temporarily translate window position to origin\nwindow_circle_centred = window_circle - gui_data.window_centre';\nwindow_vector_centred = window_vector - gui_data.window_centre';\n\n% rotate the vector around the origin using rotation matrix\nnew_window_circle_centred = R*window_circle_centred;\nnew_window_vector_centred = R*window_vector_centred;\n\n% translate rotated window back to the original centre point\nnew_window_circle = new_window_circle_centred + gui_data.window_centre';\nnew_window_vector = new_window_vector_centred + gui_data.window_centre';\n\n% update gui_data\nset(gui_data.handles.window_circle,'XData',new_window_circle(1,:), ...\n 'YData',new_window_circle(2,:), ...\n 'ZData',new_window_circle(3,:));\nset(gui_data.handles.window_vector,'XData',new_window_vector(1,:), ...\n 'YData',new_window_vector(2,:), ...\n 'ZData',new_window_vector(3,:));\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\nend\n\nfunction update_window_coordinates(window_atlas_gui,varargin)\n\n% Get guidata\ngui_data = guidata(window_atlas_gui);\n\nwindow_bregma_coordinate = round((gui_data.bregma([1,3,2]) - gui_data.window_centre)*10);\n\n% Update the text\nwindow_text = ['Window position: ' ....\n num2str(window_bregma_coordinate(1)) ' AP, ', ...\n num2str(-window_bregma_coordinate(2)) ' ML, ', ...\n num2str(-window_bregma_coordinate(3)) ' DV, ', ...\n num2str(round(gui_data.window_angle(1))) char(176) ' pitch, ' ...\n num2str(round(gui_data.window_angle(2))) char(176) ' roll'];\nset(gui_data.window_coordinates_text,'String',window_text);\n\n% Upload gui_data\nguidata(window_atlas_gui, gui_data);\n\nend\n\n\nfunction display_controls\n\n% Print controls\nCreateStruct.Interpreter = 'tex';\nCreateStruct.WindowStyle = 'non-modal';\nmsgbox( ...\n {'\\fontsize{12}' ...\n '\\bf Window: \\rm' ...\n 'Arrow keys : translate window' ...\n 'Alt/Option up/down : raise/lower window' ...\n 'Shift arrow keys : change window angle' ...\n 'm : set location manually (tangent to surface)', ...\n '\\bf 3D brain areas: \\rm' ...\n ' =/+ : add (list selector)' ...\n ' Alt/Option =/+ : add (search)' ...\n ' Shift =/+ : add (hierarchy selector)' ...\n ' Ctrl Shift =/+ : add all regions on surface' ...\n ' - : remove', ...\n '\\bf Visibility: \\rm' ...\n 's : atlas slice (toggle tv/av/off)' ...\n 'b : brain outline' ...\n 'w : window outline' ...\n 'a : 3D brain areas (toggle transparency)' ...\n '\\bf Other: \\rm' ...\n 'x : export window coordinates to workspace' ...\n 'c : bring up controls box'}, ...\n 'Controls',CreateStruct);\n\nend\n\n\n\n\n\n\n\n", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/Browsing Functions/allen_ccf_2pi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.15605461125960268}} {"text": "%% Example\n% real time control of the KUKA iiwa 7 R 800\n% Moving first joint of the robot, using a sinisoidal function\n% control is executed at joint velocity level\n\n% An example script, it is used to show how to use the different\n% functions of the KUKA Sunrise matlab toolbox\n\n% First run the following script in Matlab\n% Then start the client on the KUKA iiwa controller\n\n% Mohammad SAFEEA, 8th-August-2018\n\nclose all,clear all;clc;\n\nwarning('off')\n\nip='172.31.1.147'; % The IP of the controller\n% start a connection with the server\nglobal t_Kuka;\nt_Kuka=net_establishConnection( ip );\n\nif ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')\n disp('Connection could not be establised, script aborted');\n return;\nend\n \n%% Go to initial position\n\njPos={0,0,0,0,0,0,0};\n\nsetBlueOn(t_Kuka); % turn on blue light\n\nrelVel=0.25;\nmovePTPJointSpace( t_Kuka , jPos, relVel); % move to initial configuration\n\n%% Start direct servo in joint space \nrealTime_startVelControlJoints( t_Kuka );\n\nw=2; % motion constants, frequency rad/sec\nA=pi/6; % motion constants, amplitude of motion\ncounter=0;\njvel={0,0,0,0,0,0,0};\n%% Initiate timing variables\ndt=0;\ntic;\nt0=toc; % calculate initial time\n%% Control loop\ntry \n while(dt<(8*pi/w))\n %% Perform velocity command calculation here\n time=toc;\n dt=time-t0;\n jvel{1}=A*w*sin(w*dt);\n counter=counter+1;\n %% Send joint velocties to robot\n sendJointsVelocities( t_Kuka ,jvel);\n end\n tstart=t0;\n tend=time;\n rate=counter/(tend-tstart);\n %% Stop the direct servo motion\n realTime_stopVelControlJoints( t_Kuka );\n fprintf('\\nTotal execution time is %f: \\n',tend-t0 );\n fprintf('\\nThe rate of command update per second is: \\n');\n disp(rate);\n fprintf('\\n')\n pause(2);\n %% turn off light\n setBlueOff(t_Kuka);\n net_turnOffServer( t_Kuka )\n disp('Direct servo motion completed successfully')\n warning('on')\n return;\ncatch\n % in case of error turn off the server\n net_turnOffServer( t_Kuka );\n disp('Error during execution the direct servo motion')\n fclose(t_Kuka); \n warning('on')\nend\n\n", "meta": {"author": "Modi1987", "repo": "KST-Kuka-Sunrise-Toolbox", "sha": "9299bed2b46058aeb4105d7fbff6d2290ce68bba", "save_path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox", "path": "github-repos/MATLAB/Modi1987-KST-Kuka-Sunrise-Toolbox/KST-Kuka-Sunrise-Toolbox-9299bed2b46058aeb4105d7fbff6d2290ce68bba/Matlab_client/Tutorial_softRealTimeJointsVelControl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.27512973571032984, "lm_q1q2_score": 0.15572852999565143}} {"text": "function header = read_spike6mat_header(filename)\n\n% read_spike6mat_header() - read Matlab files exported from Spike 6\n%\n% Usage:\n% >> header = read_spike6mat_header(filename);\n%\n% Inputs:\n% filename - [string] file name\n%\n% Outputs:\n% header - FILEIO toolbox type structure\n% _______________________________________________________________________\n% Copyright (C) 2008 Institute of Neurology, UCL\n% Vladimir Litvak\n\nif nargin < 1\n help read_spike6mat_header;\n return;\nend;\n\ntry\n vars = struct2cell(load(filename));\ncatch\n ft_error('File not found or wrong format.');\nend\n\nheader = [];\nheader.nChans = length(vars);\nheader.label = {};\nheader.orig = {};\n\nfsample = [];\nonsets = [];\nlengths = [];\nfor i = 1:numel(vars)\n fsample(i) = round(1./vars{i}.interval);\n onsets(i) = 1e-3*round(1e3*vars{i}.times(1));\n lengths(i) = vars{i}.length;\n header.label{i} = vars{i}.title;\n header.orig{i} = rmfield(vars{i}, {'values', 'times'});\nend\n\nif length(unique(fsample))>1 || length(unique(onsets))>1 || length(unique(lengths))>1\n ft_error('Only files with identical channel parameters are supported');\nend\n\nheader.Fs = unique(fsample);\n \nheader.nSamples = unique(lengths);\n\nheader.nSamplesPre = -round(unique(onsets)*header.Fs);\n\nheader.nTrials = 1;\n\nheader.label = header.label(:);\n \n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/external/fieldtrip/fileio/private/read_spike6mat_header.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.15558855864450954}} {"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 res = bf_output_image_mv(BF, S)\n% Computes multivariate test on a number of frequency bands\n% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging\n\n% Gareth Barnes, modified from Vladimir Litvak's example code\n% $Id: bf_output_image_mv.m 7703 2019-11-22 12:06:29Z guillaume $\n\n%--------------------------------------------------------------------------\n\n%% no covariance matrix creation -so need to check bands are within this window\n\nif nargin == 0\n all = cfg_const;\n all.tag = 'all';\n all.name = 'All';\n all.val = {1}; \n \n condlabel = cfg_entry;\n condlabel.tag = 'condlabel';\n condlabel.name = 'Condition label';\n condlabel.strtype = 's';\n condlabel.val = {''};\n \n conditions = cfg_repeat;\n conditions.tag = 'conditions';\n conditions.name = 'Conditions';\n conditions.help = {'Specify the labels of the conditions to be included in the inversion'};\n conditions.num = [1 Inf];\n conditions.values = {condlabel};\n conditions.val = {condlabel};\n \n whatconditions = cfg_choice;\n whatconditions.tag = 'whatconditions';\n whatconditions.name = 'What conditions to include?';\n whatconditions.values = {all, conditions};\n whatconditions.val = {all}; \n \n % design = cfg_const;\n % design.tag = 'design';\n % design.name = 'design';\n % design.help = {'Use default settings for the inversion'};\n % design.val = {1};\n \n design = cfg_files;\n design.tag = 'design';\n design.name = 'design matrix';\n design.filter = 'mat';\n design.num = [1 Inf];\n design.help = {'Select the design matrix'};\n \n \n \n woi = cfg_entry;\n woi.tag = 'woi';\n woi.name = 'Time windows of interest';\n woi.strtype = 'r';\n woi.num = [Inf 2];\n woi.help = {'Time windows (in ms)'};\n \n foi = cfg_entry;\n foi.tag = 'foi';\n foi.name = 'Frequency bands of interest';\n foi.strtype = 'r';\n foi.num = [Inf 2];\n foi.help = {'Freq bands (in Hz)'};\n \n \n datafeatures = cfg_menu;\n datafeatures.tag = 'datafeatures';\n datafeatures.name = 'Features';\n datafeatures.labels =get_data_features;\n datafeatures.values =get_data_features;\n \n datafeatures.help = {'Data features of interest'};\n datafeatures.val =datafeatures.values(end);\n \n contrast = cfg_entry;\n contrast.tag = 'contrast';\n contrast.name = 'contrast';\n contrast.strtype = 'i';\n contrast.num = [1 Inf];\n contrast.val = {1};\n \n result = cfg_menu;\n result.tag = 'result';\n result.name = 'What to output';\n result.help = {'Specify output type'};\n result.labels = {\n 'chi square'\n 'BIC'\n 'r square'\n }';\n result.values = result.labels;\n result.val = {'chi square'};\n \n modality = cfg_menu;\n modality.tag = 'modality';\n modality.name = 'Modality';\n modality.help = {'Specify modality'};\n modality.labels = {\n 'MEG'\n 'MEGPLANAR'\n 'EEG'\n }';\n modality.values = {\n 'MEG'\n 'MEGPLANAR'\n 'EEG'\n }';\n modality.val = {'MEG'};\n \n custom = cfg_branch;\n custom.tag = 'custom';\n custom.name = 'Custom';\n custom.help = {'Define custom settings for the inversion'};\n custom.val = {whatconditions, contrast, woi};\n \n isdesign = cfg_choice;\n isdesign.tag = 'isdesign';\n isdesign.name = 'Design matrix parameters';\n isdesign.help = {'Choose whether to load custom design'};\n isdesign.values = {design, custom};\n isdesign.val = {design};\n \n sametrials = cfg_menu;\n sametrials.tag = 'sametrials';\n sametrials.name = 'Trials same as for filters';\n sametrials.labels = {'yes', 'no'};\n sametrials.values = {true, false};\n sametrials.val = {false};\n sametrials.help = {'Take the same trials as used for filter computation',...\n 'This is useful for bootstrap.'};\n \n image_mv = cfg_branch;\n image_mv.tag = 'image_mv';\n image_mv.name = 'Mv image';\n image_mv.val = { isdesign, datafeatures, foi, result, sametrials, modality};\n \n res = image_mv;\n \n return\nelseif nargin < 2\n error('Two input arguments are required');\nend\n\n\n\n\n\nD = BF.data.D;\n\n\nif isfield(S.isdesign,'custom'),\n %% gui specified conditions and contrast\n \n \n woitmp = S.isdesign.custom.woi;\n \n % DP - The indsample function does not work for matrices, so I have\n % looped through. Otherwise, we are left with only one windows of\n % interest.\n for wi = 1:size(woitmp,1)\n woiind(wi,:)=D.indsample(woitmp(wi,:)/1000);\n woi(wi,:)=D.time(woiind(wi,:)); %% in seconds\n end\n \n duration=unique(woiind(:,2)-woiind(:,1))./D.fsample; %% in sec\n if numel(duration)>1,\n error('both windows need to be the same length');\n end;\n \n % DP - this can result in a tiny bit of residual, presumably due to\n % numerical imprecision. Not sure. Doesn't seem necessary anyway since\n % the number of samples is equal.\n% duration=unique(woi(:,2)-woi(:,1));\n% if numel(duration)>1,\n% error('both windows need to be the same length');\n% end;\n% woi = S.isdesign.custom.woi;\n% woiind=D.indsample(woi/1000);\n% woi=D.time(woiind); %% in seconds\n \n% duration=unique(woiind(:,2)-woiind(:,1))./D.fsample; %% in sec\n% if numel(duration)>1,\n% error('both windows need to be the same length');\n% end;\n \n duration=unique(woi(:,2)-woi(:,1));\n if numel(duration)>1,\n error('both windows need to be the same length');\n end;\n \n %\n whatconditions=S.isdesign.custom.whatconditions;\n \n if isfield(whatconditions, 'all')\n if S.sametrials\n trials{1} = BF.features.trials;\n else\n trials{1} = 1:D.ntrials;\n end\n clabel{1}='all';\n else\n for i = 1:numel(whatconditions.condlabel)\n if isempty(D.indtrial(whatconditions.condlabel{i}, 'GOOD'))\n error('No trials matched the selection.');\n end\n \n clabel{i}=whatconditions.condlabel{i};\n \n if S.sametrials\n trials{i} = BF.features.trials(strmatch(clabel{i}, D.conditions(BF.features.trials)));\n else\n trials{i} = D.indtrial(whatconditions.condlabel{i}, 'GOOD');\n end\n \n \n end\n if isempty(trials)\n error('No trials matched the selection, check the specified condition labels');\n end\n end\n \n \n %%check for number of trials //// added by ANNA 30/04/2013\n for i=1:numel(trials)\n num_trials(i) = length(trials{i});\n end\n \n if min(num_trials)~= max(num_trials)\n warning ('Number of trials are not the same accross conditions- throwing away');\n num_trials\n end\n nt = min(num_trials); % ANNA -throw away the extra trials\n \n col=0;\n X=[];\n Xtrials=[];\n Xstartlatencies=[];\n xlabel=[];\n for j=1:size(woi, 1),\n for i=1:numel(trials)\n col=col+1;\n %nt=numel(trials{i}); % ANNA look above for the warning\n Xtmp=[zeros(size(X,1),1); ones(nt,1)];\n if col>1,\n X=[X;zeros(nt,size(X,2))]; %1)]; ANNA\n end;\n X=[X Xtmp];\n tlist = spm_vec(trials{i}); % ANNA list of trials \n Xtrials=[Xtrials ; tlist(1:nt)]; % ANNA list of trials - this must be a vector\n Xstartlatencies=[Xstartlatencies; ones(nt,1).*woi(j,1)];%% again this has to be a vector\n xlabel=strvcat(xlabel,[clabel{i} ',' num2str(woi(j,1))]);\n end;\n end;\n% % ORIG\n% col=0;\n% X=[];\n% Xtrials=[];\n% Xstartlatencies=[];\n% xlabel=[];\n% for j=1:size(woi, 1),\n% for i=1:numel(trials)\n% col=col+1;\n% nt=numel(trials{i});\n% Xtmp=[zeros(size(X,1),1); ones(nt,1)];\n% if col>1,\n% X=[X;zeros(nt,1)];\n% end;\n% X=[X Xtmp];\n% Xtrials=[Xtrials ;[trials{i}]];\n% Xstartlatencies=[Xstartlatencies; ones(nt,1).*woi(j,1)];\n% xlabel=strvcat(xlabel,[clabel{i} ',' num2str(woi(j,1))]);\n% end;\n% end;\n \n allsamples=[D.indsample(Xstartlatencies); D.indsample(Xstartlatencies+ones(size(Xstartlatencies)).*duration)]';\n contrast=S.isdesign.custom.contrast';\n \n \n \n \n \nelse %% conditions and contrast specified in a file\n \n if ~exist(cell2mat(S.isdesign.design)),\n error('Cannot load design matrix');\n end;\n disp('loading design matrix');\n a=load(cell2mat(S.isdesign.design));\n X=a.design.X; %% design matrix\n contrast=a.design.contrast;\n ntrials=size(X,1);\n if (size(a.design.Xstartlatencies,1)~=ntrials)||(size(a.design.Xtrials,1)~=ntrials)\n error('start latencies and Xtrials and X should have a value per row of the design');\n end;\n \n Xtrials=a.design.Xtrials; %% indices of trials to use\n for j=1:ntrials,\n allsamples(j,1)=D.indsample(a.design.Xstartlatencies(j));\n allsamples(j,2)=D.indsample(a.design.Xstartlatencies(j)+a.design.Xwindowduration);\n end;\n \nend;\n\n\nif size(Xtrials)~=size(Xstartlatencies)\n error('Xtrials and start latencies must be the same length');\nend;\nif size(Xtrials,1)~=size(X,1)\n error('X must have same number of rows as trials and start latencies');\nend;\nif size(contrast,1)~=size(X,2),\n error('contrast needs to match number of columns in design');\nend;\n\n\nFgraph = spm_figure('GetWin','Graphics'); spm_figure('Clear',Fgraph);\n\nsubplot(4,1,1);\nimagesc(X);\ntitle('X');\nset(gca,'Xtick',1:col);\nset(gca,'Xticklabel',xlabel);\nsubplot(4,1,2);\n\nimagesc(contrast);\ntitle('c');\nsubplot(4,1,3);\n\nimagesc(Xtrials);\ntitle('trials');\nsubplot(4,1,4);\n\nimagesc(Xstartlatencies);\ntitle('start latency');\n\nchanind = BF.features.(S.modality).chanind;\nU = BF.features.(S.modality).U;\n\nNchans=size(U,2); %% effective number of channels\n\nnsamples = unique(allsamples(:,2)-allsamples(:,1));\n\nif length(nsamples) > 1\n error('All time windows should be equal lentgh')\nend\n\nalltrials = spm_vec(Xtrials);\nntrials = length(alltrials);\n\n\n%% now identify frequency bands of interest\n\nNbands=size(S.foi,1);\nwindowduration=(nsamples/D.fsample);\ndctfreq = (0:nsamples-1)/2/windowduration; % DCT frequencies (Hz)\ndctT = spm_dctmtx(nsamples,nsamples);\n\nfreqstr=[];\nallfreqind=[];\nfor fband=1:Nbands, %% allows one to break up spectrum and ignore some frequencies\n freqrange=S.foi(fband,:);\n j = find( (dctfreq >= freqrange(1)) & (dctfreq<=freqrange(2)) );\n featureind{fband}=j;\n allfreqind=sort(unique([allfreqind j]));\n freqstr=[freqstr sprintf('%3.1f-%3.1f,',dctfreq(min(j)),dctfreq(max(j)))];\nend; % for fband=1:Nbands\n\nif isempty(allfreqind),\n error('No valid frequency range found');\nend;\n% Tfull = dctT(:,allfreqind); %% A filter for all bands (not necessarily continuous)\n%% end of freq band section\n\nspm('Pointer', 'Watch');drawnow;\nspm_progress_bar('Init', ntrials , 'Computing covariance'); drawnow;\nif ntrials > 100, Ibar = floor(linspace(1, ntrials ,100));\nelse Ibar = 1:ntrials; end\n\n%% load in data and make up simple design matrix\n%ncond=numel(samples); %% number of conditions= columns in design matrix\n%Nt=ntrials*ncond; %% total number of time windows under consideration\n%X=zeros(Nt,ncond);\n\nflatdata=zeros(ntrials*nsamples,Nchans);\n%% want flatdata in form Nchans,Nt*Nsamples\n\n%count=0;\nfor i = 1:ntrials\n %for j = 1:numel(samples)\n % count=count+1;\n % X(count,j)=1;\n Y = U'*squeeze(D(chanind, allsamples(i,1):allsamples(i,2)-1, alltrials(i)));\n Y = detrend(Y'); %% detrend and throw away low freq drift\n flatdata((i-1)*nsamples+1:i*nsamples,:) =Y;\n \n %end\n if ismember(i, Ibar)\n spm_progress_bar('Set', i); drawnow;\n end\nend\n\nspm_progress_bar('Clear');\n\nW = BF.inverse.(S.modality).W;\nnvert = numel(W);\nS.regressout=[]; %% turn off for now\nregressout=S.regressout;\n\n\n%% set up the data features\nweights=-1; %% set up flag\nYfull=get_data_features(flatdata,nsamples,ntrials,weights,dctT,S.datafeatures,featureind,regressout); %% set up data structures\n\n\n\nspm('Pointer', 'Watch');drawnow;\nspm_progress_bar('Init', nvert, 'Scanning grid points'); drawnow;\nif nvert > 100, Ibar = floor(linspace(1, nvert,100));\nelse Ibar = 1:nvert; end\n\noutval = nan(1, nvert);\n\n\nfor i = 1:nvert\n \n if ~isnan(W{i})\n \n w = W{i};\n \n %% returns columns of a matrix with rows as different observations\n [Yfull,vedata]=get_data_features(flatdata,nsamples,ntrials,w,dctT,S.datafeatures,featureind,regressout); %% extract the data features\n \n Yfull=Yfull-repmat(mean(Yfull),size(Yfull,1),1); %% remove dc level from each column/feature\n Yfull=Yfull./repmat(std(Yfull),size(Yfull,1),1); %% normalize features to have unit variance by default\n [chival,BIC,cva] = output_image_mv_cva(X,Yfull,contrast); %% run the multivariate test\n \n \n switch S.result\n case 'chi square'\n resultstr='chisq';\n outval(i) = chival(1);\n case 'r square'\n outval(i) = cva.ccorr.^2;\n resultstr='rsq';\n case 'BIC'\n outval(i)=BIC(1);\n resultstr='BIC';\n end;\n \n end\n \n if ismember(i, Ibar)\n spm_progress_bar('Set', i); drawnow;\n end\nend\n\nspm_progress_bar('Clear');\n\n\nimage(1).val = outval;\n\nimage(1).label = ['mv' resultstr S.datafeatures freqstr spm_file(D.fname, 'basename')];\n\n\nres = image;", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/bf_output_image_mv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.15558317682942682}} {"text": "function sFileOut = out_fopen_bst(OutputFile, sFileIn, ChannelMat, EpochSize)\n% OUT_FOPEN_BST: Saves the header of a new empty Brainstorm binary file.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2014-2019; Martin Cousineau, 2018\n\n% Get file comment\n[fPath, fBase, fExt] = bst_fileparts(OutputFile);\n\n% Create a new header structure\nsFileOut = sFileIn;\nsFileOut.filename = OutputFile;\nsFileOut.condition = '';\nsFileOut.format = 'BST-BIN';\nsFileOut.byteorder = 'l';\nsFileOut.comment = fBase;\nsFileOut.header = struct();\nsFileOut.header.device = sFileOut.device;\nsFileOut.header.sfreq = sFileOut.prop.sfreq;\nsFileOut.header.starttime = sFileOut.prop.times(1);\nsFileOut.header.navg = sFileOut.prop.nAvg;\n% sFileOut.header.version = 51; % April 2019\nsFileOut.header.version = 52; % March 2023\nsFileOut.header.nsamples = round((sFileOut.prop.times(2) - sFileOut.prop.times(1)) .* sFileOut.prop.sfreq) + 1;\nsFileOut.header.epochsize = EpochSize;\nsFileOut.header.nchannels = length(ChannelMat.Channel);\n% Force the destination compensation level\nsFileOut.prop.currCtfComp = sFileOut.prop.destCtfComp; \nsFileOut.header.ctfcomp = sFileOut.prop.destCtfComp;\n% Open file\nfid = fopen(OutputFile, 'w+', sFileOut.byteorder);\nif (fid == -1)\n error(['Could not open output file: \"' OutputFile '\".']);\nend\n\n% ===== FORMAT HEADER =====\nfwrite(fid, 'BSTBIN', 'char'); % CHAR(6) : Format\nfwrite(fid, sFileOut.header.version, 'uint8'); % UINT8(1) : Version of the format\nfwrite(fid, str_zeros(sFileOut.header.device, 40), 'char'); % CHAR(40) : Device used for recording\nfwrite(fid, sFileOut.header.sfreq, 'float32'); % UINT32(1) : Sampling frequency\nfwrite(fid, sFileOut.header.starttime, 'float32'); % FLOAT32(1) : Start time\nfwrite(fid, sFileOut.header.navg, 'uint32'); % UINT32(1) : Number of files averaged\nif ~isempty(sFileOut.header.ctfcomp)\n fwrite(fid, sFileOut.header.ctfcomp, 'uint8'); % UINT8(1) : CTF compensation status (0,1,2,3)\nelse\n fwrite(fid, 0, 'uint8');\nend\nfwrite(fid, sFileOut.header.nsamples, 'uint32'); % UINT32(1) : Total number of samples\nfwrite(fid, sFileOut.header.epochsize, 'uint32'); % UINT32(1) : Number of samples per epoch\nfwrite(fid, sFileOut.header.nchannels, 'uint32'); % UINT32(1) : Number of channels\n\n% ===== CHANNEL LOCATIONS =====\nfwrite(fid, str_zeros(ChannelMat.Comment, 40), 'char'); % CHAR(40) : Channel file comment\nfor i = 1:length(ChannelMat.Channel)\n fwrite(fid, str_zeros(ChannelMat.Channel(i).Name, 20), 'char'); % CHAR(20) : Channel name\n fwrite(fid, str_zeros(ChannelMat.Channel(i).Type, 20), 'char'); % CHAR(20) : Channel type\n fwrite(fid, str_zeros(ChannelMat.Channel(i).Comment, 40), 'char'); % CHAR(40) : Channel comment\n % Loc\n fwrite(fid, size(ChannelMat.Channel(i).Loc, 2), 'uint8'); % UINT8(1) : Number of location points\n if ~isempty(ChannelMat.Channel(i).Loc)\n fwrite(fid, ChannelMat.Channel(i).Loc, 'float32'); % FLOAT32(N) : Locations [3xN]\n end\n % Orient\n fwrite(fid, size(ChannelMat.Channel(i).Orient, 2), 'uint8'); % UINT8(1) : Number of orientations points\n if ~isempty(ChannelMat.Channel(i).Orient)\n fwrite(fid, ChannelMat.Channel(i).Orient, 'float32'); % FLOAT32(N) : Orientations [3xN]\n end\n % Weight\n fwrite(fid, length(ChannelMat.Channel(i).Weight), 'uint8'); % UINT8(1) : Number of weights\n if ~isempty(ChannelMat.Channel(i).Weight)\n fwrite(fid, ChannelMat.Channel(i).Weight, 'float32'); % FLOAT32(N) : Weights [1xN]\n end\n % Channel flag\n fwrite(fid, sFileIn.channelflag(i), 'int8'); % INT8(1) : Channel flag\nend\n\n% ===== CTF =====\n% CTF compensation matrix\nfwrite(fid, size(ChannelMat.MegRefCoef), 'uint32'); % UINT32(2) : Dimensions of the MegRefCoef matrix\nfwrite(fid, ChannelMat.MegRefCoef, 'float32'); % FLOAT32(N) : MegRefCoef matrix\n\n% ===== SSP PROJECTORS =====\nfwrite(fid, length(ChannelMat.Projector), 'uint32'); % UINT32(1) : Number of projectors\nfor i = 1:length(ChannelMat.Projector)\n fwrite(fid, str_zeros(ChannelMat.Projector(i).Comment, 40), 'char'); % CHAR(40) : Projector comment\n fwrite(fid, size(ChannelMat.Projector(i).Components), 'uint32'); % UINT32(2) : Dimensions of the Components matrix\n fwrite(fid, ChannelMat.Projector(i).Components, 'float32'); % FLOAT32(N) : Components matrix\n fwrite(fid, size(ChannelMat.Projector(i).CompMask), 'uint32'); % UINT32(2) : Dimensions of the CompMask matrix\n fwrite(fid, ChannelMat.Projector(i).CompMask, 'float32'); % FLOAT32(N) : CompMask matrix\n fwrite(fid, size(ChannelMat.Projector(i).SingVal), 'uint32'); % UINT32(2) : Dimensions of the SingVal matrix\n if ~isempty(ChannelMat.Projector(i).SingVal)\n fwrite(fid, ChannelMat.Projector(i).SingVal, 'float32'); % FLOAT32(N) : SingVal matrix\n end\n fwrite(fid, ChannelMat.Projector(i).Status, 'int8'); % INT8(1) : Status\nend\n\n% ===== HEAD POINTS =====\nif ~isempty(ChannelMat.HeadPoints)\n fwrite(fid, length(ChannelMat.HeadPoints.Label), 'uint32'); % UINT32(1) : Number of head points\n for i = 1:length(ChannelMat.HeadPoints.Label)\n fwrite(fid, ChannelMat.HeadPoints.Loc(:,i), 'float32'); % FLOAT32(3) : (X,Y,Z) positions in meters\n fwrite(fid, str_zeros(ChannelMat.HeadPoints.Label{i}, 10), 'char'); % CHAR(10) : Point label\n fwrite(fid, str_zeros(ChannelMat.HeadPoints.Type{i}, 10), 'char'); % CHAR(10) : Point type\n end\nelse\n fwrite(fid, 0, 'uint32');\nend\n\n% ===== FIDUCIALS =====\n% Write fiducials positions (SCS)\nif isfield(ChannelMat, 'SCS') && ~isempty(ChannelMat.SCS) ...\n&& isfield(ChannelMat.SCS, 'NAS') && (length(ChannelMat.SCS.NAS) == 3) ...\n&& isfield(ChannelMat.SCS, 'LPA') && (length(ChannelMat.SCS.LPA) == 3) ...\n&& isfield(ChannelMat.SCS, 'RPA') && (length(ChannelMat.SCS.RPA) == 3) ...\n&& isfield(ChannelMat.SCS, 'R') && isequal(size(ChannelMat.SCS.R), [3,3]) ...\n&& isfield(ChannelMat.SCS, 'T') && (length(ChannelMat.SCS.T) == 3) ...\n&& isfield(ChannelMat.SCS, 'Origin') && (length(ChannelMat.SCS.Origin) == 3)\n fwrite(fid, 1, 'int8'); % INT8(1) : Are the fiducials saved in the file?\n fwrite(fid, ChannelMat.SCS.NAS, 'float32'); % FLOAT32(3) : NAS (X,Y,Z) positions in meters\n fwrite(fid, ChannelMat.SCS.LPA, 'float32'); % FLOAT32(3) : LPA (X,Y,Z) positions in meters\n fwrite(fid, ChannelMat.SCS.RPA, 'float32'); % FLOAT32(3) : RPA (X,Y,Z) positions in meters\n fwrite(fid, ChannelMat.SCS.R, 'float32'); % FLOAT32(9) : Rotation matrix [3x3] \n fwrite(fid, ChannelMat.SCS.T, 'float32'); % FLOAT32(3) : Translation vector [3x1]\n fwrite(fid, ChannelMat.SCS.Origin, 'float32'); % FLOAT32(3) : Origin (X,Y,Z) positions in meters\nelse\n fwrite(fid, 0, 'int8'); % INT8(1) : Are the fiducials saved in the file?\nend\n\n% ===== EVENTS =====\nfwrite(fid, length(sFileOut.events), 'uint32'); % UINT32(1) : Number of event categories\nfor iEvt = 1:length(sFileOut.events)\n isExtended = (size(sFileOut.events(iEvt).times,1) == 2);\n evtLabel = sFileOut.events(iEvt).label;\n labelLength = length(evtLabel);\n nOcc = size(sFileOut.events(iEvt).times,2);\n fwrite(fid, labelLength, 'uint8'); % UINT8(1) : Length of event name (1 to 255)\n fwrite(fid, str_zeros(evtLabel, labelLength), 'char'); % CHAR(??) : Event name\n fwrite(fid, sFileOut.events(iEvt).color, 'float32'); % FLOAT32(3) : Event color\n fwrite(fid, isExtended, 'int8'); % INT8(1) : Event type (0=regular, 1=extended)\n fwrite(fid, nOcc, 'uint32'); % UINT32(1) : Number of occurrences\n % If there are event occurrences\n if ~isempty(sFileOut.events(iEvt).times)\n % Write latencies\n fwrite(fid, sFileOut.events(iEvt).times, 'float32'); % FLOAT32(2*N) : Time in seconds\n % Write list of channels associated to each event\n isChannels = ~isempty(sFileOut.events(iEvt).channels);\n fwrite(fid, uint8(isChannels), 'uint8'); % UINT8(1) : 1 if channels list is present, 0 otherwise\n if isChannels\n for iOcc = 1:nOcc\n nChannels = length(sFileOut.events(iEvt).channels{iOcc});\n fwrite(fid, nChannels, 'uint16'); % UINT16(1) : Number of channels associated to this event\n for iChan = 1:nChannels\n chLabel = sFileOut.events(iEvt).channels{iOcc}{iChan};\n labelLength = length(chLabel);\n fwrite(fid, labelLength, 'uint8'); % UINT8(1) : Length of channel name (1 to 255)\n fwrite(fid, str_zeros(chLabel, labelLength), 'char'); % CHAR(??) : Channel name\n end\n end\n end\n % Read list of notes associated to each event\n isNotes = ~isempty(sFileOut.events(iEvt).notes);\n fwrite(fid, uint8(isNotes), 'uint8'); % UINT8(1) : 1 if notes list is present, 0 otherwise\n if isNotes\n for iOcc = 1:nOcc\n noteLabel = sFileOut.events(iEvt).notes{iOcc};\n labelLength = length(noteLabel);\n fwrite(fid, labelLength, 'uint16'); % UINT16(1) : Length of note text\n fwrite(fid, str_zeros(noteLabel, labelLength), 'char'); % CHAR(??) : Note text\n end\n end\n end\nend\n\n% Save total header size (to allow fast skipping when reading)\nsFileOut.header.hdrsize = ftell(fid);\n% Close file\nfclose(fid);\n\nend\n\n\n%% ===== HELPER FUNCTIONS =====\nfunction sout = str_zeros(sin, N)\n sout = char(zeros(1,N));\n if (length(sin) <= N)\n sout(1:length(sin)) = sin;\n else\n sout = sin(1:N);\n end\nend\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_fopen_bst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.15558317490355741}} {"text": "function undersamplingRINEX(filenameIN, filenameOUT, base, step, delta, wait_dlg)\n\n% SYNTAX:\n% undersamplingRINEX(filenameIN, filenameOUT, base, step, delta, wait_dlg);\n%\n% INPUT:\n% filenameIN = input RINEX observation file\n% filenameOUT = output RINEX observation file\n% base = base timing (e.g. if first epoch should be 13 4 5 11 35 1, then base = 1) [sec]\n% step = new sampling rate [sec]\n% delta = original sampling rate [sec]\n% wait_dlg = optional handler to waitbar figure (optional)\n%\n% OUTPUT:\n%\n%\n% DESCRIPTION:\n% Undersamples a RINEX observation file.\n\n%--- * --. --- --. .--. ... * ---------------------------------------------\n% ___ ___ ___\n% __ _ ___ / __| _ | __|\n% / _` / _ \\ (_ | _|__ \\\n% \\__, \\___/\\___|_| |___/\n% |___/ v 1.0RC1\n%\n%--------------------------------------------------------------------------\n% Copyright (C) 2021 Geomatics Research & Development srl (GReD)\n% Written by:\n% Contributors: ...\n% A list of all the historical goGPS contributors is in CREDITS.nfo\n%--------------------------------------------------------------------------\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n%--------------------------------------------------------------------------\n% 01100111 01101111 01000111 01010000 01010011\n%--------------------------------------------------------------------------\n\n%default values\nif (nargin < 3)\n base = 0;\nend\n\nif (nargin < 4)\n step = 30;\nend\n\nif (nargin < 5)\n delta = 1;\nend\n\n% ------------------------------------------\n% header copy and paste\n% ------------------------------------------\n\nfidIN = fopen(filenameIN,'rt');\nfidOUT = fopen(filenameOUT,'wt');\n\nline = fgets(fidIN);\nwhile (isempty(strfind(line,'END OF HEADER')))\n fprintf(fidOUT,'%s',line);\n line = fgets(fidIN);\n if (~isempty(strfind(line,'INTERVAL')))\n line = sprintf('%10.3f INTERVAL \\n', step);\n end\nend\nfprintf(fidOUT,line);\n\n% fclose(fidIN);\n% fclose(fidOUT);\n\n% ------------------------------------------\n% undersampling\n% ------------------------------------------\n\nwhile (feof(fidIN) == 0)\n\n % time (seconds) extraction\n\tsec = roundmod(str2num(line(17:27)),delta);\n\t%fprintf('%d\\n',sec); % debugging\n\n\tif (mod(sec-base,step) == 0) % if it is a header message\n\t\tfprintf(fidOUT,'%s',line);\n\t\tline = fgets(fidIN);\n\t\t%fprintf('%s',line); % debugging\n\t\twhile (feof(fidIN) == 0) & ...\n\t\t ((line(1) ~= ' ') | (line(2) == ' ') | ...\n\t\t (line(3) == ' ') | (line(4) ~= ' '))\n\t\t\tfprintf(fidOUT,'%s',line);\n\t\t\tline = fgets(fidIN);\n\t\t\t%fprintf('%s',line); % debugging\n end\n if (feof(fidIN) == 1) && ~isempty(line)\n fprintf(fidOUT,'%s',line);\n end\n\telse % if it is a data message\n\t\tline = fgets(fidIN);\n\t\t%fprintf('%s',line); % debugging\n\t\twhile (feof(fidIN) == 0) & ...\n\t\t ((line(1) ~= ' ') | (line(2) == ' ') | ...\n\t\t (line(3) == ' ') | (line(4) ~= ' '))\n\t\t\tline = fgets(fidIN);\n\t\t\t%fprintf('%s',line); % debugging\n\t\tend\n\tend\nend\n\nfclose(fidIN); % input file closure\nfclose(fidOUT); % output file closure\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/undersamplingRINEX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2942149845400438, "lm_q1q2_score": 0.15514442277382898}} {"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}} {"text": "% [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K)\n% GETADA3 Compute ADA(i,j) = (D(d^2)*A.t(:,i))' *A.t(:,j),\n% and exploit sparsity as much as possible.\n% absd - length m output vector, containing\n% absd(i) = abs((D(d^2)*A.t(:,i))' *abs(A.t(:,i)).\n% Hence, diag(ADA)./absd gives a measure of cancelation (in [0,1]).\n%\n% ******************** INTERNAL FUNCTION OF SEDUMI ********************\n%\n% See also sedumi, getada1, getada2\n\n\nfunction [ADA,absd] = getada3(ADA, A,Ajc1,Aord, udsqr,K) %#ok\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\ndisp('The SeDuMi binaries are not installed.')\ndisp('In Matlab, launch \"install_sedumi\" in the folder you put the SeDuMi files.')\ndisp('For more information see the file Install.txt.')\nerror(' ')", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sedumi/getada3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.1549439968351581}} {"text": "function [state, y] = ft_preproc_online_downsample_apply(state, x)\n\n% FT_PREPROC_ONLINE_DOWNSAMPLE_APPLY passes a signal through the online downsampler\n% and returns the downsampler state and the downsampled signal. The state keeps track\n% of the number of samples to be skipped in the next call.\n%\n% Use as\n% [state, dat] = ft_preproc_online_downsample_apply(state, x)\n% where\n% dat = Nchan x Ntime\n% state = downsampler state, see FT_PREPROC_ONLINE_DOWNSAMPLE_INIT\n%\n% See also PREPROC\n\n% Copyright (C) 2010, Stefan Klanke\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\nN = size(x,2);\n\n% to get number K of sample we can write out, subtract the skipped samples,\n% and then add maximum possible number of skip samples for next time (=state.factor-1)\nK = floor((N - state.numSkip + state.factor-1)/state.factor);\n\nstartIdx = 1+state.numSkip;\nendIdx = 1+state.numSkip + (K-1)*state.factor;\n\ny = x(:,startIdx:state.factor:endIdx);\nstate.numSkip = state.factor-1-(N-endIdx); % for next time\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/preproc/ft_preproc_online_downsample_apply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15454197458740657}} {"text": "% ------------------------------------------------------------------------\n% Run Allen Atlas Browser\n% ------------------------------------------------------------------------\n\n\n%% ENTER FILE LOCATION AND PROBE-SAVE-NAME\n\n\n% directory of histology\nprocessed_images_folder = 'C:\\Drive\\Histology\\brainX\\processed'; \n\n% name the saved probe points, to avoid overwriting another set of probes going in the same folder\nprobe_save_name_suffix = ''; \n\n% directory of reference atlas files\nannotation_volume_location = 'C:\\Drive\\Histology\\annotation_volume_10um_by_index.npy';\nstructure_tree_location = 'C:\\Drive\\Histology\\structure_tree_safe_2017.csv';\ntemplate_volume_location = 'C:\\Drive\\Histology\\template_volume_10um.npy';\n\n% plane to view ('coronal', 'sagittal', 'transverse')\nplane = 'coronal';\n\n\n%% GET PROBE TRAJECTORY POINTS\n\n% load the reference brain and region annotations\nif ~exist('av','var') || ~exist('st','var') || ~exist('tv','var')\n disp('loading reference atlas...')\n av = readNPY(annotation_volume_location);\n st = loadStructureTree(structure_tree_location);\n tv = readNPY(template_volume_location);\nend\n\n% select the plane for the viewer\nif strcmp(plane,'coronal')\n av_plot = av;\n tv_plot = tv;\nelseif strcmp(plane,'sagittal')\n av_plot = permute(av,[3 2 1]);\n tv_plot = permute(tv,[3 2 1]);\nelseif strcmp(plane,'transverse')\n av_plot = permute(av,[2 3 1]);\n tv_plot = permute(tv,[2 3 1]);\nend\n\n% create Atlas viewer figure\nf = figure('Name','Atlas Viewer'); \n\n% show histology in Slice Viewer\ntry; figure(slice_figure_browser); title('');\ncatch; slice_figure_browser = figure('Name','Slice Viewer'); end\nreference_size = size(tv_plot);\nsliceBrowser(slice_figure_browser, processed_images_folder, f, reference_size);\n\n\n% % use application in Atlas Transform Viewer\n% % use this function if you have a processed_images_folder with appropriately processed .tif histology images\nf = AtlasTransformBrowser(f, tv_plot, av_plot, st, slice_figure_browser, processed_images_folder, probe_save_name_suffix, plane);\n\n\n% use the simpler version, which does not interface with processed slice images\n% just run these two lines instead of the previous 5 lines of code\n% \n% save_location = processed_images_folder;\n% f = allenAtlasBrowser(f, tv_plot, av_plot, st, save_location, probe_save_name_suffix, plane);\n\n", "meta": {"author": "cortex-lab", "repo": "allenCCF", "sha": "0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0", "save_path": "github-repos/MATLAB/cortex-lab-allenCCF", "path": "github-repos/MATLAB/cortex-lab-allenCCF/allenCCF-0bbff55fc906fd3f023da81ce1d0e4b8726d4fd0/SHARP-Track/Navigate_Atlas_and_Register_Slices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.1544858606672575}} {"text": "\n% Author: Guosheng Lin (guosheng.lin@gmail.com)\n\n% perform segmentation prediction on user provided images.\n% specify the location of your images, e.g., using the following \n% folder which contains serveral example images:\n% ds_config.img_data_dir='../datasets/custom_data';\n\n\nfunction demo_refinenet_test_example_eyth()\n folders = {'vid4','vid6','vid9'};\n\n for i = 1:length(folders)\n rng('shuffle');\n\n addpath('./my_utils');\n dir_matConvNet='../libs/matconvnet/matlab';\n run(fullfile(dir_matConvNet, 'vl_setupnn.m'));\n\n\n run_config=[];\n ds_config=[];\n\n run_config.use_gpu=true;\n % run_config.use_gpu=false;\n run_config.gpu_idx=1;\n\n\n\n % result dir:\n result_name=[char(folders(i))]\n \n result_dir=fullfile('../cache_data', 'eyth_on_eyth_val/val_1', result_name);\n\n\n % the folder that contains testing images:\n ds_config.img_data_dir=strcat('../datasets/eyth/JPEGImages/test/',char(folders(i)));\n \n\n % using a trained model which is trained on VOC 2012\n % run_config.trained_model_path='../model_trained/refinenet_res101_voc2012.mat';\n % ds_config.class_info=gen_class_info_voc();\n\n\n % using the object parsing model\n run_config.trained_model_path='../model_trained/refinenet_res101_eyth.mat';\n ds_config.class_info=gen_class_info_ego();\n\n\n % for voc trained model, control the size of input images\n run_config.input_img_short_edge_min=450;\n run_config.input_img_short_edge_max=600;\n\n % set the input image scales, useful for multi-scale evaluation\n % e.g. using multiple scale settings (1.0 0.8 0.6) and average the resulting score maps.\n run_config.input_img_scale=1.0;\n\n\n run_config.gen_net_opts_fn=@gen_net_opts_model_type1;\n\n\n run_config.run_evaonly=true;\n ds_config.use_custom_data=true;\n ds_config.use_dummy_gt=true;\n run_config.use_dummy_gt=ds_config.use_dummy_gt;\n\n\n ds_config.ds_name='tmp_data';\n run_config.root_cache_dir=result_dir;\n mkdir_notexist(run_config.root_cache_dir);\n\n run_config.model_name=result_name;\n\n diary_dir=run_config.root_cache_dir;\n mkdir_notexist(diary_dir);\n diary(fullfile(diary_dir, 'output.txt'));\n diary on\n\n\n run_dir_name=fileparts(mfilename('fullpath'));\n [~, run_dir_name]=fileparts(run_dir_name);\n run_config.run_dir_name=run_dir_name;\n run_config.run_file_name=mfilename();\n\n ds_info=gen_dataset_info(ds_config);\n my_diary_flush();\n\n train_opts=run_config.gen_net_opts_fn(run_config, ds_info.class_info);\n\n\n imdb=my_gen_imdb(train_opts, ds_info);\n\n data_norm_info=[];\n data_norm_info.image_mean=128;\n\n imdb.ref.data_norm_info=data_norm_info;\n\n if run_config.use_gpu\n gpu_num=gpuDeviceCount;\n if gpu_num>=1\n gpuDevice(run_config.gpu_idx);\n else\n error('no gpu found!');\n end\n end\n\n [net_config, net_exp_info]=prepare_running_model(train_opts);\n\n my_net_tool(train_opts, imdb, net_config, net_exp_info);\n\n\n fprintf('\\n\\n--------------------------------------------------\\n\\n');\n disp('results are saved in:');\n disp(run_config.root_cache_dir);\n\n\n my_diary_flush();\n diary off\n\n end\nend\n\n\n", "meta": {"author": "aurooj", "repo": "Hand-Segmentation-in-the-Wild", "sha": "2a8dc04394d51bdfcc93d2db6509297127645b1a", "save_path": "github-repos/MATLAB/aurooj-Hand-Segmentation-in-the-Wild", "path": "github-repos/MATLAB/aurooj-Hand-Segmentation-in-the-Wild/Hand-Segmentation-in-the-Wild-2a8dc04394d51bdfcc93d2db6509297127645b1a/refinenet_files/demo_refinenet_test_example_eyth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.15448585737341863}} {"text": "function Calls = Automerge_Callback(Calls1,Calls2,AudioFile)\n%% Merges two detection files into one\n\nCalls=[Calls1; Calls2];\n\n% Audio info\naudio_info = audioinfo(AudioFile);\n\n%% Merge overlapping boxes\nCalls = merge_boxes(Calls.Box, Calls.Score, Calls.Type, audio_info, 1, 0, 0);\n", "meta": {"author": "DrCoffey", "repo": "DeepSqueak", "sha": "c62f2c7bb86a9d77ae177248abe7d234857edf53", "save_path": "github-repos/MATLAB/DrCoffey-DeepSqueak", "path": "github-repos/MATLAB/DrCoffey-DeepSqueak/DeepSqueak-c62f2c7bb86a9d77ae177248abe7d234857edf53/Functions/Automerge_Callback.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.15399810987024487}} {"text": "classdef Stitcher < handle\n %STITCHER High level image stitcher\n %\n % It's possible to use this class without being aware of the entire\n % stitching pipeline. However, to be able to achieve higher stitching\n % stability and quality of the final images at least being familiar with\n % the theory is recommended.\n %\n % ![image](https://docs.opencv.org/3.3.1/StitchingPipeline.jpg)\n %\n % This figure illustrates the stitching module pipeline implemented in the\n % cv.Stitcher class. Using that class it's possible to configure/remove\n % some steps, i.e. adjust the stitching pipeline according to the\n % particular needs.\n %\n % The implemented stitching pipeline is very similar to the one proposed\n % in [BL07].\n %\n % # Camera models\n % There are currently 2 camera models implemented in stitching pipeline.\n %\n % - *Homography model* expecting perspective transformations between\n % images implemented in `BestOf2NearestMatcher`,\n % `HomographyBasedEstimator`, `BundleAdjusterReproj`, and\n % `BundleAdjusterRay`.\n % - *Affine model* expecting affine transformation with 6 DOF or 4 DOF\n % implemented in `AffineBestOf2NearestMatcher`, `AffineBasedEstimator`,\n % `BundleAdjusterAffine`, `BundleAdjusterAffinePartial`, and\n % `AffineWarper`.\n %\n % Homography model is useful for creating photo panoramas captured by\n % camera, while affine-based model can be used to stitch scans and object\n % captured by specialized devices. Use cv.Stitcher.Stitcher to get\n % preconfigured pipeline for one of those models.\n %\n % Note: Certain detailed settings of cv.Stitcher might not make sense.\n % Especially you should not mix classes implementing affine model and\n % classes implementing Homography model, as they work with different\n % transformations.\n %\n % ## Example\n % * A basic example on image stitching can be found in the\n % `stitching_demo.m` sample\n % * A detailed example on image stitching can be found in the\n % `stitching_detailed_demo.m` sample.\n %\n % ## References\n % [BL07]:\n % > Matthew Brown and David G Lowe.\n % > \"Automatic panoramic image stitching using invariant features\".\n % > International journal of computer vision, 74(1):59-73, 2007.\n %\n % See also: cv.Stitcher.Stitcher\n %\n\n properties (SetAccess = private)\n % Object ID\n id\n end\n\n properties (Dependent)\n % Registration resolution. default 0.6\n RegistrationResol\n % Seam estimation resolution. default 1\n SeamEstimationResol\n % Compositing resolution. default 'Orig'\n CompositingResol\n % Panorama confidence threshold. default 1\n PanoConfidenceThresh\n % Whether it should try to make panorama more horizontal (or vertical).\n % default true\n WaveCorrection\n % Correction kind. default 'Horiz'\n WaveCorrectKind\n end\n\n methods\n function this = Stitcher(varargin)\n %STITCHER Creates a Stitcher configured in one of the stitching modes\n %\n % obj = cv.Stitcher()\n % obj = cv.Stitcher('OptionName',optionValue, ...)\n %\n % ## Options\n % * __Mode__ Scenario for stitcher operation. This is usually\n % determined by source of images to stitch and their\n % transformation. Default parameters will be chosen for\n % operation in given scenario. Default 'Panorama'. One of:\n % * __Panorama__ Mode for creating photo panoramas. Expects\n % images under perspective transformation and projects\n % resulting pano to sphere. See also `BestOf2NearestMatcher`,\n % `SphericalWarper`.\n % * __Scans__ Mode for composing scans. Expects images under\n % affine transformation does not compensate exposure by\n % default. See also `AffineBestOf2NearestMatcher`,\n % `AffineWarper`\n % * __TryUseGPU__ Flag indicating whether GPU should be used\n % whenever it's possible. default false\n %\n % See also: cv.Stitcher.stitch\n %\n this.id = Stitcher_(0, 'new', varargin{:});\n end\n\n function delete(this)\n %DELETE Destructor\n %\n % obj.delete()\n %\n % See also: cv.Stitcher\n %\n if isempty(this.id), return; end\n Stitcher_(this.id, 'delete');\n end\n end\n\n methods\n function pano = stitch(this, images, varargin)\n %STITCH Tries to stitch the given images\n %\n % pano = obj.stitch(images)\n % pano = obj.stitch(images, rois)\n % [pano, status] = obj.stitch(...)\n %\n % ## Input\n % * __images__ Input cell-array of images.\n % * __rois__ Optional region of interest rectangles, a cell-array\n % of cell-arrays of 4-elements vectors `{{[x,y,w,h], ...}, ...}`\n % or `{[x,y,w,h; ...], ...}`.\n %\n % ## Output\n % * __pano__ Final pano.\n % * __status__ optional output status code. If not requested, the\n % function throws an error if the operation fails. A string one\n % of:\n % * __OK__\n % * **ERR_NEED_MORE_IMGS**\n % * **ERR_HOMOGRAPHY_EST_FAIL**\n % * **ERR_CAMERA_PARAMS_ADJUST_FAIL**\n %\n % The function throws an error if the stitch function returns a\n % non-OK status code.\n %\n % See also: cv.Stitcher.estimateTransform,\n % cv.Stitcher.composePanorama\n %\n pano = Stitcher_(this.id, 'stitch', images, varargin{:});\n end\n\n function estimateTransform(this, images, varargin)\n %ESTIMATETRANSFORM Estimate transformation\n %\n % obj.estimateTransform(images)\n % obj.estimateTransform(images, rois)\n % status = obj.estimateTransform(...)\n %\n % ## Input\n % * __images__ Input cell-array of images.\n % * __rois__ Optional region of interest rectangles, a cell-array\n % of cell-arrays of 4-elements vectors `{{[x,y,w,h], ...}, ...}`\n % or `{[x,y,w,h; ...], ...}`.\n %\n % ## Output\n % * __status__ optional output status code. If not requested, the\n % function throws an error if the operation fails. A string one\n % of:\n % * __OK__\n % * **ERR_NEED_MORE_IMGS**\n % * **ERR_HOMOGRAPHY_EST_FAIL**\n % * **ERR_CAMERA_PARAMS_ADJUST_FAIL**\n %\n % This function tries to match the given images and to estimate\n % rotations of each camera.\n %\n % Note: Use the function only if you're aware of the stitching\n % pipeline, otherwise use cv.Stitcher.stitch.\n %\n % See also: cv.Stitcher.composePanorama\n %\n Stitcher_(this.id, 'estimateTransform', images, varargin{:});\n end\n\n function pano = composePanorama(this, varargin)\n %COMPOSEPANORAMA Compose panorama\n %\n % pano = obj.composePanorama()\n % pano = obj.composePanorama(images)\n % [pano, status] = obj.composePanorama(...)\n %\n % ## Input\n % * __images__ Input cell-array of images.\n %\n % ## Output\n % * __pano__ Final pano.\n % * __status__ optional output status code. If not requested, the\n % function throws an error if the operation fails. A string one\n % of:\n % * __OK__\n % * **ERR_NEED_MORE_IMGS**\n % * **ERR_HOMOGRAPHY_EST_FAIL**\n % * **ERR_CAMERA_PARAMS_ADJUST_FAIL**\n %\n % This function tries to compose the given images (or images\n % stored internally from the other function calls) into the final\n % `pano` under the assumption that the image transformations were\n % estimated before.\n %\n % Note: Use the function only if you're aware of the stitching\n % pipeline, otherwise use cv.Stitcher.stitch.\n %\n % See also: cv.Stitcher.estimateTransform\n %\n pano = Stitcher_(this.id, 'composePanorama', varargin{:});\n end\n\n function indices = component(this)\n %COMPONENT Image indices\n %\n % indices = obj.component()\n %\n % ## Output\n % * __indices__ Vector of integer indices (0-based).\n %\n % See also: cv.Stitcher.cameras, cv.Stitcher.workScale\n %\n indices = Stitcher_(this.id, 'component');\n end\n\n function params = cameras(this)\n %CAMERAS Estimates camera parameters\n %\n % params = obj.cameras()\n %\n % ## Output\n % * __params__ Describes camera parameters, a struct-array with\n % the following fields:\n % * __aspect__ Aspect ratio.\n % * __focal__ Focal length.\n % * __ppx__ Principal point X.\n % * __ppy__ Principal point Y.\n % * __R__ 3x3 camera rotation matrix.\n % * __t__ 3x1 camera translation vector.\n % * __K__ 3x3 camera intrinsic parameters.\n %\n % Note: Translation is assumed to be zero during the whole\n % stitching pipeline.\n %\n % See also: cv.Stitcher.component, cv.Stitcher.workScale\n %\n params = Stitcher_(this.id, 'cameras');\n end\n\n function wscale = workScale(this)\n %WORKSCALE Work scale\n %\n % wscale = obj.workScale()\n %\n % ## Output\n % * __wscale__ scalar double value.\n %\n % See also: cv.Stitcher.cameras, cv.Stitcher.component\n %\n wscale = Stitcher_(this.id, 'workScale');\n end\n end\n\n methods\n function mask = getMatchingMask(this)\n %GETMATCHINGMASK\n %\n % mask = obj.getMatchingMask()\n %\n % ## Output\n % * __mask__\n %\n % See also: cv.Stitcher.setMatchingMask\n %\n mask = Stitcher_(this.id, 'getMatchingMask');\n end\n\n function setMatchingMask(this, mask)\n %SETMATCHINGMASK\n %\n % obj.setMatchingMask(mask)\n %\n % ## Input\n % * __mask__\n %\n % See also: cv.Stitcher.getMatchingMask\n %\n Stitcher_(this.id, 'setMatchingMask', mask);\n end\n\n function value = getFeaturesFinder(this)\n %GETFEATURESFINDER Get the features finder\n %\n % value = obj.getFeaturesFinder()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setFeaturesFinder\n %\n value = Stitcher_(this.id, 'getFeaturesFinder');\n end\n\n function setFeaturesFinder(this, finderType, varargin)\n %SETFEATURESFINDER Set the features finder\n %\n % obj.setFeaturesFinder(finderType)\n % obj.setFeaturesFinder(finderType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __finderType__ Feature finder type. One of:\n % * __OrbFeaturesFinder__ ORB features finder. See cv.ORB\n % * __AKAZEFeaturesFinder__ AKAZE features finder. See cv.AKAZE\n % * __SurfFeaturesFinder__ SURF features finder. See cv.SURF\n % (requires `xfeatures2d` module)\n % * __SurfFeaturesFinderGpu__ (requires CUDA and `xfeatures2d`\n % module)\n %\n % ## Options\n % The following are options for the various finders:\n %\n % ### `OrbFeaturesFinder`\n % * __GridSize__ default [3,1]\n % * __NFeatures__ default 1500\n % * __ScaleFactor__ default 1.3\n % * __NLevels__ default 5\n %\n % ### `AKAZEFeaturesFinder`\n % * __DescriptorType__ default 'MLDB'\n % * __DescriptorSize__ default 0\n % * __DescriptorChannels__ default 3\n % * __Threshold__ default 0.001\n % * __NOctaves__ default 4\n % * __NOctaveLayers__ default 4\n % * __Diffusivity__ default `PM_G2`\n %\n % ### `SurfFeaturesFinder`\n % * __HessThresh__ default 300.0\n % * __NumOctaves__ default 3\n % * __NumLayers__ default 4\n % * __NumOctaveDescr__ default 3\n % * __NumLayersDesc__ default 4\n %\n % The class uses `OrbFeaturesFinder` by default or\n % `SurfFeaturesFinder` if `xfeatures2d` module is available.\n %\n % See also: cv.Stitcher.getFeaturesFinder, cv.FeaturesMatcher\n %\n Stitcher_(this.id, 'setFeaturesFinder', finderType, varargin{:});\n end\n\n function value = getFeaturesMatcher(this)\n %GETFEATURESMATCHER Get the features matcher\n %\n % value = obj.getFeaturesMatcher()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setFeaturesMatcher\n %\n value = Stitcher_(this.id, 'getFeaturesMatcher');\n end\n\n function setFeaturesMatcher(this, matcherType, varargin)\n %SETFEATURESMATCHER Set the features matcher\n %\n % obj.setFeaturesMatcher(matcherType)\n % obj.setFeaturesMatcher(matcherType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __matcherType__ Feature matcher type. One of:\n % * __BestOf2NearestMatcher__ A \"best of 2 nearest\" matcher.\n % Features matcher which finds two best matches for each\n % feature and leaves the best one only if the ratio between\n % descriptor distances is greater than the threshold\n % `MatchConf`.\n % * __BestOf2NearestRangeMatcher__\n % * __AffineBestOf2NearestMatcher__ A \"best of 2 nearest\"\n % matcher that expects affine trasformation between images.\n % Features matcher similar to `BestOf2NearestMatcher` which\n % finds two best matches for each feature and leaves the best\n % one only if the ratio between descriptor distances is\n % greater than the threshold `MatchConf`. Unlike\n % `BestOf2NearestMatcher` this matcher uses affine\n % transformation (affine trasformation estimate will be placed\n % in `matches_info`).\n %\n % ## Options\n % The following are options accepted by all matchers:\n %\n % * __TryUseGPU__ Should try to use GPU or not. default false\n % * __MatchConf__ Match distances ration threshold. default 0.3\n % * __NumMatchesThresh1__ Minimum number of matches required for\n % the 2D projective transform estimation used in the inliers\n % classification step. default 6\n % * __NumMatchesThresh2__ Minimum number of matches required for\n % the 2D projective transform re-estimation on inliers.\n % default 6\n %\n % The following are options for the various algorithms:\n %\n % ### `BestOf2NearestRangeMatcher`\n % * __RangeWidth__ default 5\n %\n % ### `AffineBestOf2NearestMatcher`\n % * __FullAffine__ whether to use full affine transformation with\n % 6 degress of freedom or reduced transformation with 4 degrees\n % of freedom using only rotation, translation and uniform\n % scaling. default false\n %\n % The class uses `BestOf2NearestMatcher` by default.\n %\n % See also: cv.Stitcher.getFeaturesMatcher, cv.FeaturesMatcher\n %\n Stitcher_(this.id, 'setFeaturesMatcher', matcherType, varargin{:});\n end\n\n %{\n function value = getEstimator(this)\n %GETESTIMATOR Get the estimator\n %\n % value = obj.getEstimator()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setEstimator\n %\n value = Stitcher_(this.id, 'getEstimator');\n end\n\n function setEstimator(this, estimatorType, varargin)\n %SETESTIMATOR Set the estimator\n %\n % obj.setEstimator(estimatorType)\n % obj.setEstimator(estimatorType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __estimatorType__ Estimator type. One of:\n % * __HomographyBasedEstimator__ Homography based rotation\n % estimator.\n % * __AffineBasedEstimator__ Affine transformation based\n % estimator. This estimator uses pairwise transformations\n % estimated by matcher to estimate final transformation for\n % each camera.\n %\n % The following are options for the various algorithms:\n %\n % ### `HomographyBasedEstimator`\n % * __IsFocalsEstimated__ default false\n %\n % See also: cv.Stitcher.getEstimator. cv.Estimator\n %\n Stitcher_(this.id, 'setEstimator', estimatorType, varargin{:});\n end\n %}\n\n function value = getBundleAdjuster(this)\n %GETBUNDLEADJUSTER Get the bundle adjuster\n %\n % value = obj.getBundleAdjuster()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setBundleAdjuster\n %\n value = Stitcher_(this.id, 'getBundleAdjuster');\n end\n\n function setBundleAdjuster(this, adjusterType, varargin)\n %SETBUNDLEADJUSTER Set the bundle adjuster\n %\n % obj.setBundleAdjuster(adjusterType)\n % obj.setBundleAdjuster(adjusterType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __adjusterType__ camera parameters refinement method. One of:\n % * __NoBundleAdjuster__ Stub bundle adjuster that does nothing.\n % * __BundleAdjusterRay__ Implementation of the camera\n % parameters refinement algorithm which minimizes sum of the\n % distances between the rays passing through the camera center\n % and a feature. It can estimate focal length. It ignores the\n % refinement mask for now.\n % * __BundleAdjusterReproj__ Implementation of the camera\n % parameters refinement algorithm which minimizes sum of the\n % reprojection error squares. It can estimate focal length,\n % aspect ratio, principal point. You can affect only on them\n % via the refinement mask.\n % * __BundleAdjusterAffine__ Bundle adjuster that expects affine\n % transformation represented in homogeneous coordinates in R\n % for each camera param. Implements camera parameters\n % refinement algorithm which minimizes sum of the reprojection\n % error squares. It estimates all transformation parameters.\n % Refinement mask is ignored. See also\n % cv.AffineBasedEstimator, `AffineBestOf2NearestMatcher`.\n % * __BundleAdjusterAffinePartial__ Bundle adjuster that expects\n % affine transformation with 4 DOF represented in homogeneous\n % coordinates in R for each camera param. Implements camera\n % parameters refinement algorithm which minimizes sum of the\n % reprojection error squares. It estimates all transformation\n % parameters. Refinement mask is ignored.\n %\n % ## Options\n % The following are options accepted by all adjusters:\n %\n % * __ConfThresh__ default 1\n % * __RefinementMask__ default `eye(3)`\n % * __TermCriteria__ default\n % `struct('type','Count+EPS', 'maxCount',1000, 'epsilon',eps)`\n %\n % The class uses `BundleAdjusterRay` by default.\n %\n % See also: cv.Stitcher.getBundleAdjuster, cv.BundleAdjuster\n %\n Stitcher_(this.id, 'setBundleAdjuster', adjusterType, varargin{:});\n end\n\n function value = getWarper(this)\n %GETWARPER Get the warper\n %\n % value = obj.getWarper()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setWarper\n %\n value = Stitcher_(this.id, 'getWarper');\n end\n\n function setWarper(this, warperType, varargin)\n %SETWARPER Set the image warper\n %\n % obj.setWarper(warperType)\n % obj.setWarper(warperType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __warperType__ image warper factory class type, used to create\n % the rotation-based warper. One of:\n % * __PlaneWarper__ Plane warper factory class. Warper that maps\n % an image onto the `z = 1` plane.\n % * __PlaneWarperGpu__ (requires CUDA)\n % * __AffineWarper__ Affine warper factory class. Affine warper\n % that uses rotations and translations. Uses affine\n % transformation in homogeneous coordinates to represent both\n % rotation and translation in camera rotation matrix.\n % * __CylindricalWarper__ Cylindrical warper factory class.\n % Warper that maps an image onto the `x*x + z*z = 1` cylinder.\n % * __CylindricalWarperGpu__ (requires CUDA)\n % * __SphericalWarper__ Warper that maps an image onto the unit\n % sphere located at the origin. Projects image onto unit\n % sphere with origin at [0,0,0] and radius `scale`, measured\n % in pixels. A 360 panorama would therefore have a resulting\n % width of `2*scale*pi` pixels. Poles are located at [0,-1,0]\n % and [0,1,0] points.\n % * __SphericalWarperGpu__ (requires CUDA)\n % * __FisheyeWarper__\n % * __StereographicWarper__\n % * __CompressedRectilinearWarper__\n % * __CompressedRectilinearPortraitWarper__\n % * __PaniniWarper__\n % * __PaniniPortraitWarper__\n % * __MercatorWarper__\n % * __TransverseMercatorWarper__\n %\n % ## Options\n % The following are options for the various warpers:\n %\n % ### `CompressedRectilinearWarper`, `CompressedRectilinearPortraitWarper`, `PaniniWarper`, `PaniniPortraitWarper`\n % * __A__ default 1\n % * __B__ default 1\n %\n % The class uses `SphericalWarper` by default.\n %\n % See also: cv.Stitcher.getWarper, cv.RotationWarper\n %\n Stitcher_(this.id, 'setWarper', warperType, varargin{:});\n end\n\n function value = getExposureCompensator(this)\n %GETEXPOSURECOMPENSATOR Get the exposire compensator\n %\n % value = obj.getExposureCompensator()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setExposureCompensator\n %\n value = Stitcher_(this.id, 'getExposureCompensator');\n end\n\n function setExposureCompensator(this, compensatorType, varargin)\n %SETEXPOSURECOMPENSATOR Set the exposure compensator\n %\n % obj.setExposureCompensator(compensatorType)\n % obj.setExposureCompensator(compensatorType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __compensatorType__ exposure compensator type. One of:\n % * __NoExposureCompensator__ Stub exposure compensator which\n % does nothing.\n % * __GainCompensator__ Exposure compensator which tries to\n % remove exposure related artifacts by adjusting image\n % intensities, see [BL07] and [WJ10] for details.\n % * __BlocksGainCompensator__ Exposure compensator which tries\n % to remove exposure related artifacts by adjusting image\n % block intensities, see [UES01] for details.\n %\n % ## Options\n % The following are options for the various compensators:\n %\n % ### `BlocksGainCompensator`\n % * __Width__ Block width. default 32\n % * __Heigth__ Block height. default 32\n %\n % The class uses `BlocksGainCompensator` by default.\n %\n % ## References\n % [BL07]:\n % > Matthew Brown and David G Lowe.\n % > \"Automatic panoramic image stitching using invariant features\".\n % > International journal of computer vision, 74(1):59-73, 2007.\n %\n % [WJ10]:\n % > Wei Xu and Jane Mulligan. \"Performance evaluation of color\n % > correction approaches for automatic multi-view image and video\n % > stitching\". In Computer Vision and Pattern Recognition (CVPR),\n % > 2010 IEEE Conference on, pages 263-270. IEEE, 2010.\n %\n % [UES01]:\n % > Matthew Uyttendaele, Ashley Eden, and R Skeliski.\n % > \"Eliminating ghosting and exposure artifacts in image mosaics\".\n % > In Computer Vision and Pattern Recognition, 2001. CVPR 2001.\n % > Proceedings of the 2001 IEEE Computer Society Conference on,\n % > volume 2, pages II-509. IEEE, 2001.\n %\n % See also: cv.Stitcher.getExposureCompensator,\n % cv.ExposureCompensator\n %\n Stitcher_(this.id, 'setExposureCompensator', compensatorType, varargin{:});\n end\n\n function value = getSeamFinder(this)\n %GETSEAMFINDER Get the seam finder\n %\n % value = obj.getSeamFinder()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setSeamFinder\n %\n value = Stitcher_(this.id, 'getSeamFinder');\n end\n\n function setSeamFinder(this, seamType, varargin)\n %SETSEAMFINDER Set the seam finder\n %\n % obj.setSeamFinder(seamType)\n % obj.setSeamFinder(seamType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __seamType__ seam estimator type. One of:\n % * __NoSeamFinder__ Stub seam estimator which does nothing.\n % * __VoronoiSeamFinder__ Voronoi diagram-based pairwise seam\n % estimator.\n % * __DpSeamFinder__\n % * __GraphCutSeamFinder__ Minimum graph cut-based seam\n % estimator. See details in [V03].\n % * __GraphCutSeamFinderGpu__ (requires CUDA)\n %\n % ## Options\n % The following are options for the various seam finders:\n %\n % ### `DpSeamFinder`\n % * __CostFunction__ default 'Color'. One of:\n % * __Color__\n % * __ColorGrad__\n %\n % ### `GraphCutSeamFinder`\n % * __CostType__ default 'ColorGrad'. One of:\n % * __Color__\n % * __ColorGrad__\n % * __TerminalCost__ default 10000.0\n % * __BadRegionPenaly__ default 1000.0\n %\n % The class uses `GraphCutSeamFinder` by default.\n %\n % ## References\n % [V03]:\n % > Vivek Kwatra, Arno Schodl, Irfan Essa, Greg Turk, and Aaron\n % > Bobick. \"Graphcut textures: image and video synthesis using\n % > graph cuts\". In ACM Transactions on Graphics (ToG), volume 22,\n % > pages 277-286. ACM, 2003.\n %\n % See also: cv.Stitcher.getSeamFinder, cv.SeamFinder\n %\n Stitcher_(this.id, 'setSeamFinder', seamType, varargin{:});\n end\n\n function value = getBlender(this)\n %GETBLENDER Get the blender\n %\n % value = obj.getBlender()\n %\n % ## Output\n % * __value__ output scalar struct.\n %\n % See also: cv.Stitcher.setBlender\n %\n value = Stitcher_(this.id, 'getBlender');\n end\n\n function setBlender(this, blenderType, varargin)\n %SETBLENDER Set the blender\n %\n % obj.setBlender(blenderType)\n % obj.setBlender(blenderType, 'OptionName',optionValue, ...)\n %\n % ## Input\n % * __blenderType__ image blender type. One of:\n % * __NoBlender__ Simple blender which puts one image over\n % another.\n % * __FeatherBlender__ Simple blender which mixes images at its\n % borders.\n % * __MultiBandBlender__ Blender which uses multi-band blending\n % algorithm (see [BA83]).\n %\n % ## Options\n % The following are options for the various blenders:\n %\n % ### `FeatherBlender`\n % * __Sharpness__ default 0.02\n %\n % ### `MultiBandBlender`\n % * __TryGPU__ default false\n % * __NumBands__ default 5\n % * __WeightType__ One of:\n % * __single__ (default)\n % * __int16__\n %\n % The class uses `MultiBandBlender` by default.\n %\n % ## References\n % [BA83]:\n % > Peter J Burt and Edward H Adelson.\n % > \"A multiresolution spline with application to image mosaics\".\n % > ACM Transactions on Graphics (TOG), 2(4):217-236, 1983.\n %\n % See also: cv.Stitcher.getBlender, cv.Blender\n %\n Stitcher_(this.id, 'setBlender', blenderType, varargin{:});\n end\n end\n\n %% Getters/Setters\n methods\n function value = get.RegistrationResol(this)\n value = Stitcher_(this.id, 'get', 'RegistrationResol');\n end\n function set.RegistrationResol(this, value)\n Stitcher_(this.id, 'set', 'RegistrationResol', value);\n end\n\n function value = get.SeamEstimationResol(this)\n value = Stitcher_(this.id, 'get', 'SeamEstimationResol');\n end\n function set.SeamEstimationResol(this, value)\n Stitcher_(this.id, 'set', 'SeamEstimationResol', value);\n end\n\n function value = get.CompositingResol(this)\n value = Stitcher_(this.id, 'get', 'CompositingResol');\n end\n function set.CompositingResol(this, value)\n Stitcher_(this.id, 'set', 'CompositingResol', value);\n end\n\n function value = get.PanoConfidenceThresh(this)\n value = Stitcher_(this.id, 'get', 'PanoConfidenceThresh');\n end\n function set.PanoConfidenceThresh(this, value)\n Stitcher_(this.id, 'set', 'PanoConfidenceThresh', value);\n end\n\n function value = get.WaveCorrection(this)\n value = Stitcher_(this.id, 'get', 'WaveCorrection');\n end\n function set.WaveCorrection(this, value)\n Stitcher_(this.id, 'set', 'WaveCorrection', value);\n end\n\n function value = get.WaveCorrectKind(this)\n value = Stitcher_(this.id, 'get', 'WaveCorrectKind');\n end\n function set.WaveCorrectKind(this, value)\n Stitcher_(this.id, 'set', 'WaveCorrectKind', value);\n end\n end\n\nend\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/Stitcher.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.15389651294982415}} {"text": "function output = callfiltersdsp(model)\n\noptions = model.options.filtersd;\n\nmodel = yalmip2nonlinearsolver(model);\n\nif ~model.derivative_available\n disp('Derivate-free call to filterSD not yet implemented')\n error('Derivate-free call to filterSD not yet implemented')\nend\nif model.options.savedebug\n save filtersddebug model\nend\nshowprogress('Calling filterSDSP',model.options.showprogress);\n\ncu = [ repmat(0,length(model.bnonlinineq),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(0,length(model.b),1);\n repmat(0,length(model.beq),1)];\n\ncl = [ repmat(-inf,length(model.bnonlinineq),1);\n repmat(0,length(model.bnonlineq),1);\n repmat(-inf,length(model.b),1);\n repmat(0,length(model.beq),1)];\n\nif isempty(cu)\n Flow = [];\n Fupp = [];\nend\n\n% These are needed to avoid recomputation due to ipopts double call to get\n% f and df, and g and dg\nglobal latest_x_f\nglobal latest_x_g\nglobal latest_df\nglobal latest_f\nglobal latest_G\nglobal latest_g\nglobal latest_xevaled\nglobal latest_x_xevaled\nlatest_G = [];\nlatest_g = [];\nlatest_x_f = [];\nlatest_x_g = [];\nlatest_xevaled = [];\nlatest_x_xevaled = [];\n\nfuncs.objective = @(x)ipopt_callback_f(x,model);\nfuncs.gradient = @(x)ipopt_callback_df(x,model);\nif ~isempty(cu)\n funcs.constraints = @(x)ipopt_callback_g(x,model);\n funcs.jacobian = @(x)ipopt_callback_dg(x,model);\nelse\n funcs.constraints = [];\n funcs.jacobian = [];\nend\n\nlb = model.lb(:)';\nub = model.ub(:)';\n\nif ~isempty(cu)\n nljacstr = jacobiansparsityfromnonlinear(model);\nelse\n nljacstr = [];\nend\n\nif ~model.options.warmstart\n model.x0 = (lb+ub)/2;\n model.x0(isinf(ub)) = lb(isinf(ub))+1;\n model.x0(isinf(lb)) = ub(isinf(lb))-1;\n model.x0(isinf(model.x0)) = 0;\nend\n\noptions.display = model.options.verbose;\nsolvertime = tic;\n[xout,fval,exitflag,stats,lambda] = filtersdsp(funcs.objective, funcs.gradient, model.x0, lb, ub, funcs.constraints, funcs.jacobian,nljacstr, cl, cu, options);\nsolvertime = toc(solvertime);\n\n% Duals currently not supported\nlambda = [];\n\nx = RecoverNonlinearSolverSolution(model,xout);\n\nswitch exitflag\n case {0}\n problem = 0;\n case {1}\n problem = 2;\n case {2,3}\n problem = 1;\n case {5}\n problem = 3;\n case {4,9}\n problem = 4;\n case 105\n problem = 16; \n otherwise\n problem = -1;\nend\n\n% Internal format for duals\nD_struc = [];\n\n% Save all data sent to solver?\nif model.options.savesolverinput\n solverinput.model = model;\nelse\n solverinput = [];\nend\n\n% Save all data from the solver?\nif model.options.savesolveroutput\n solveroutput.x = xout; \n solveroutput.exitflag = exitflag;\n solveroutput.stats = stats;\nelse\n solveroutput = [];\nend\n\n% Standard interface\noutput = createOutputStructure(x,D_struc,[],problem,'filterSD',solverinput,solveroutput,solvertime);\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/solvers/callfiltersdsp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.15389650653560064}} {"text": "function [img_files, pos, target_sz, ground_truth, video_path] = load_video_info(base_path, video)\n%LOAD_VIDEO_INFO\n% Loads all the relevant information for the video in the given path:\n% the list of image files (cell array of strings), initial position\n% (1x2), target size (1x2), the ground truth information for precision\n% calculations (Nx2, for N frames), and the path where the images are\n% located. The ordering of coordinates and sizes is always [y, x].\n%\n% Joao F. Henriques, 2014\n% http://www.isr.uc.pt/~henriques/\n\n\n\t%see if there's a suffix, specifying one of multiple targets, for\n\t%example the dot and number in 'Jogging.1' or 'Jogging.2'.\n\tif numel(video) >= 2 && video(end-1) == '.' && ~isnan(str2double(video(end))),\n\t\tsuffix = video(end-1:end); %remember the suffix\n\t\tvideo = video(1:end-2); %remove it from the video name\n\telse\n\t\tsuffix = '';\n\tend\n\n\t%full path to the video's files\n\tif base_path(end) ~= '/' && base_path(end) ~= '\\',\n\t\tbase_path(end+1) = '/';\n\tend\n\tvideo_path = [base_path video '/'];\n\n\t%try to load ground truth from text file (Benchmark's format)\n\tfilename = [video_path 'groundtruth_rect' suffix '.txt'];\n\tf = fopen(filename);\n\tassert(f ~= -1, ['No initial position or ground truth to load (\"' filename '\").'])\n\t\n\t%the format is [x, y, width, height]\n\ttry\n\t\tground_truth = textscan(f, '%f,%f,%f,%f', 'ReturnOnError',false); \n\tcatch %#ok, try different format (no commas)\n\t\tfrewind(f);\n\t\tground_truth = textscan(f, '%f %f %f %f'); \n\tend\n\tground_truth = cat(2, ground_truth{:});\n\tfclose(f);\n\t\n\t%set initial position and size\n\ttarget_sz = [ground_truth(1,4), ground_truth(1,3)];\n\tpos = [ground_truth(1,2), ground_truth(1,1)] + floor(target_sz/2);\n\t\n\n\t\n\t\n\t%from now on, work in the subfolder where all the images are\n\tvideo_path = [video_path 'img/'];\n\t\n\t%for these sequences, we must limit ourselves to a range of frames.\n\t%for all others, we just load all png/jpg files in the folder.\n\tframes = {'David', 300, 465; %770\n\t\t\t 'Football1', 1, 74;\n\t\t\t 'Freeman3', 1, 460;\n\t\t\t 'Freeman4', 1, 283};\n\t\n\tidx = find(strcmpi(video, frames(:,1)));\n\t\n\tif isempty(idx),\n\t\t%general case, just list all images\n\t\timg_files = dir([video_path '*.png']);\n\t\tif isempty(img_files),\n\t\t\timg_files = dir([video_path '*.jpg']);\n\t\t\tassert(~isempty(img_files), 'No image files to load.')\n\t\tend\n\t\timg_files = sort({img_files.name});\n target_sz = [ground_truth(1,4), ground_truth(1,3)];\n\t pos = [ground_truth(1,2), ground_truth(1,1)] + floor(target_sz/2);\n else\n \n target_sz = [ground_truth(frames{idx, 2},4), ground_truth(frames{idx, 2},3)];\n pos = [ground_truth(frames{idx, 2},2), ground_truth(frames{idx, 2},1)] + floor(target_sz/2);\n\t\t%list specified frames. try png first, then jpg.\n\t\tif exist(sprintf('%s%04i.png', video_path, frames{idx,2}), 'file'),\n\t\t\timg_files = num2str((frames{idx,2} : frames{idx,3})', '%04i.png');\n\t\t\t\n\t\telseif exist(sprintf('%s%04i.jpg', video_path, frames{idx,2}), 'file'),\n\t\t\timg_files = num2str((frames{idx,2} : frames{idx,3})', '%04i.jpg');\n\t\t\t\n\t\telse\n\t\t\terror('No image files to load.')\n\t\tend\n\t\t\n\t\timg_files = cellstr(img_files);\n end\n \n \tif size(ground_truth,1) == 1,\n\t\t%we have ground truth for the first frame only (initial position)\n\t\tground_truth = [];\n\telse\n\t\t%store positions instead of boxes\n\t\tground_truth = ground_truth(:,[2,1]) + ground_truth(:,[4,3]) / 2;\n\tend\n\t\nend\n\n", "meta": {"author": "scott89", "repo": "KCF", "sha": "012d6b3401d3871001e6fd8a5722ab3c2e0843ad", "save_path": "github-repos/MATLAB/scott89-KCF", "path": "github-repos/MATLAB/scott89-KCF/KCF-012d6b3401d3871001e6fd8a5722ab3c2e0843ad/load_video_info.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30074556640652333, "lm_q1q2_score": 0.1538965001213772}} {"text": "function obj = Q_pTop_func_new(in1,in2,in3)\ncoefs_tq1_11 = in2(31);\ncoefs_tq2_11 = in2(32);\ncoefs_tq3_11 = in2(33);\ncoef_Jacob1_qt_syms11 = in3(41);\ncoef_Jacob1_qt_syms12 = in3(45);\ncoef_Jacob1_qt_syms13 = in3(49);\ncoef_Jacob1_qt_syms14 = in3(53);\ncoef_Jacob1_qt_syms21 = in3(81);\ncoef_Jacob1_qt_syms22 = in3(85);\ncoef_Jacob1_qt_syms23 = in3(89);\ncoef_Jacob1_qt_syms24 = in3(93);\ncoef_Jacob1_qt_syms28 = in3(109);\ncoef_Jacob1_qt_syms29 = in3(113);\ncoef_Jacob1_qt_syms30 = in3(117);\ncoef_Jacob1_qt_syms31 = in3(121);\ncoef_Jacob1_qt_syms33 = in3(129);\ncoef_Jacob1_qt_syms34 = in3(133);\ncoef_Jacob1_qt_syms35 = in3(137);\ncoef_Jacob1_qt_syms36 = in3(141);\ncoef_Jacob2_qt_syms11 = in3(42);\ncoef_Jacob2_qt_syms12 = in3(46);\ncoef_Jacob2_qt_syms13 = in3(50);\ncoef_Jacob2_qt_syms14 = in3(54);\ncoef_Jacob2_qt_syms21 = in3(82);\ncoef_Jacob2_qt_syms22 = in3(86);\ncoef_Jacob2_qt_syms23 = in3(90);\ncoef_Jacob2_qt_syms24 = in3(94);\ncoef_Jacob2_qt_syms28 = in3(110);\ncoef_Jacob2_qt_syms29 = in3(114);\ncoef_Jacob2_qt_syms30 = in3(118);\ncoef_Jacob2_qt_syms31 = in3(122);\ncoef_Jacob2_qt_syms33 = in3(130);\ncoef_Jacob2_qt_syms34 = in3(134);\ncoef_Jacob2_qt_syms35 = in3(138);\ncoef_Jacob2_qt_syms36 = in3(142);\ncoef_Jacob3_qt_syms11 = in3(43);\ncoef_Jacob3_qt_syms12 = in3(47);\ncoef_Jacob3_qt_syms13 = in3(51);\ncoef_Jacob3_qt_syms14 = in3(55);\ncoef_Jacob3_qt_syms21 = in3(83);\ncoef_Jacob3_qt_syms22 = in3(87);\ncoef_Jacob3_qt_syms23 = in3(91);\ncoef_Jacob3_qt_syms24 = in3(95);\ncoef_Jacob3_qt_syms28 = in3(111);\ncoef_Jacob3_qt_syms29 = in3(115);\ncoef_Jacob3_qt_syms30 = in3(119);\ncoef_Jacob3_qt_syms31 = in3(123);\ncoef_Jacob3_qt_syms33 = in3(131);\ncoef_Jacob3_qt_syms34 = in3(135);\ncoef_Jacob3_qt_syms35 = in3(139);\ncoef_Jacob3_qt_syms36 = in3(143);\ncoef_Jacob4_qt_syms11 = in3(44);\ncoef_Jacob4_qt_syms12 = in3(48);\ncoef_Jacob4_qt_syms13 = in3(52);\ncoef_Jacob4_qt_syms14 = in3(56);\ncoef_Jacob4_qt_syms21 = in3(84);\ncoef_Jacob4_qt_syms22 = in3(88);\ncoef_Jacob4_qt_syms23 = in3(92);\ncoef_Jacob4_qt_syms24 = in3(96);\ncoef_Jacob4_qt_syms28 = in3(112);\ncoef_Jacob4_qt_syms29 = in3(116);\ncoef_Jacob4_qt_syms30 = in3(120);\ncoef_Jacob4_qt_syms31 = in3(124);\ncoef_Jacob4_qt_syms33 = in3(132);\ncoef_Jacob4_qt_syms34 = in3(136);\ncoef_Jacob4_qt_syms35 = in3(140);\ncoef_Jacob4_qt_syms36 = in3(144);\npinvG1_1 = in1(1);\npinvG1_2 = in1(4);\npinvG1_3 = in1(7);\npinvG2_1 = in1(2);\npinvG2_2 = in1(5);\npinvG2_3 = in1(8);\npinvG3_1 = in1(3);\npinvG3_2 = in1(6);\npinvG3_3 = in1(9);\nobj = reshape([coef_Jacob1_qt_syms14+coefs_tq1_11.*coef_Jacob1_qt_syms11.*pinvG1_1+coefs_tq1_11.*coef_Jacob1_qt_syms12.*pinvG2_1+coefs_tq1_11.*coef_Jacob1_qt_syms13.*pinvG3_1+coefs_tq2_11.*coef_Jacob1_qt_syms11.*pinvG1_2+coefs_tq2_11.*coef_Jacob1_qt_syms12.*pinvG2_2+coefs_tq2_11.*coef_Jacob1_qt_syms13.*pinvG3_2+coefs_tq3_11.*coef_Jacob1_qt_syms11.*pinvG1_3+coefs_tq3_11.*coef_Jacob1_qt_syms12.*pinvG2_3+coefs_tq3_11.*coef_Jacob1_qt_syms13.*pinvG3_3,coef_Jacob2_qt_syms14+coefs_tq1_11.*coef_Jacob2_qt_syms11.*pinvG1_1+coefs_tq1_11.*coef_Jacob2_qt_syms12.*pinvG2_1+coefs_tq1_11.*coef_Jacob2_qt_syms13.*pinvG3_1+coefs_tq2_11.*coef_Jacob2_qt_syms11.*pinvG1_2+coefs_tq2_11.*coef_Jacob2_qt_syms12.*pinvG2_2+coefs_tq2_11.*coef_Jacob2_qt_syms13.*pinvG3_2+coefs_tq3_11.*coef_Jacob2_qt_syms11.*pinvG1_3+coefs_tq3_11.*coef_Jacob2_qt_syms12.*pinvG2_3+coefs_tq3_11.*coef_Jacob2_qt_syms13.*pinvG3_3,coef_Jacob3_qt_syms14+coefs_tq1_11.*coef_Jacob3_qt_syms11.*pinvG1_1+coefs_tq1_11.*coef_Jacob3_qt_syms12.*pinvG2_1+coefs_tq1_11.*coef_Jacob3_qt_syms13.*pinvG3_1+coefs_tq2_11.*coef_Jacob3_qt_syms11.*pinvG1_2+coefs_tq2_11.*coef_Jacob3_qt_syms12.*pinvG2_2+coefs_tq2_11.*coef_Jacob3_qt_syms13.*pinvG3_2+coefs_tq3_11.*coef_Jacob3_qt_syms11.*pinvG1_3+coefs_tq3_11.*coef_Jacob3_qt_syms12.*pinvG2_3+coefs_tq3_11.*coef_Jacob3_qt_syms13.*pinvG3_3,coef_Jacob4_qt_syms14+coefs_tq1_11.*coef_Jacob4_qt_syms11.*pinvG1_1+coefs_tq1_11.*coef_Jacob4_qt_syms12.*pinvG2_1+coefs_tq1_11.*coef_Jacob4_qt_syms13.*pinvG3_1+coefs_tq2_11.*coef_Jacob4_qt_syms11.*pinvG1_2+coefs_tq2_11.*coef_Jacob4_qt_syms12.*pinvG2_2+coefs_tq2_11.*coef_Jacob4_qt_syms13.*pinvG3_2+coefs_tq3_11.*coef_Jacob4_qt_syms11.*pinvG1_3+coefs_tq3_11.*coef_Jacob4_qt_syms12.*pinvG2_3+coefs_tq3_11.*coef_Jacob4_qt_syms13.*pinvG3_3,coef_Jacob1_qt_syms24+coefs_tq1_11.*coef_Jacob1_qt_syms21.*pinvG1_1+coefs_tq1_11.*coef_Jacob1_qt_syms22.*pinvG2_1+coefs_tq1_11.*coef_Jacob1_qt_syms23.*pinvG3_1+coefs_tq2_11.*coef_Jacob1_qt_syms21.*pinvG1_2+coefs_tq2_11.*coef_Jacob1_qt_syms22.*pinvG2_2+coefs_tq2_11.*coef_Jacob1_qt_syms23.*pinvG3_2+coefs_tq3_11.*coef_Jacob1_qt_syms21.*pinvG1_3+coefs_tq3_11.*coef_Jacob1_qt_syms22.*pinvG2_3+coefs_tq3_11.*coef_Jacob1_qt_syms23.*pinvG3_3,coef_Jacob2_qt_syms24+coefs_tq1_11.*coef_Jacob2_qt_syms21.*pinvG1_1+coefs_tq1_11.*coef_Jacob2_qt_syms22.*pinvG2_1+coefs_tq1_11.*coef_Jacob2_qt_syms23.*pinvG3_1+coefs_tq2_11.*coef_Jacob2_qt_syms21.*pinvG1_2+coefs_tq2_11.*coef_Jacob2_qt_syms22.*pinvG2_2+coefs_tq2_11.*coef_Jacob2_qt_syms23.*pinvG3_2+coefs_tq3_11.*coef_Jacob2_qt_syms21.*pinvG1_3+coefs_tq3_11.*coef_Jacob2_qt_syms22.*pinvG2_3+coefs_tq3_11.*coef_Jacob2_qt_syms23.*pinvG3_3,coef_Jacob3_qt_syms24+coefs_tq1_11.*coef_Jacob3_qt_syms21.*pinvG1_1+coefs_tq1_11.*coef_Jacob3_qt_syms22.*pinvG2_1+coefs_tq1_11.*coef_Jacob3_qt_syms23.*pinvG3_1+coefs_tq2_11.*coef_Jacob3_qt_syms21.*pinvG1_2+coefs_tq2_11.*coef_Jacob3_qt_syms22.*pinvG2_2+coefs_tq2_11.*coef_Jacob3_qt_syms23.*pinvG3_2+coefs_tq3_11.*coef_Jacob3_qt_syms21.*pinvG1_3+coefs_tq3_11.*coef_Jacob3_qt_syms22.*pinvG2_3+coefs_tq3_11.*coef_Jacob3_qt_syms23.*pinvG3_3,coef_Jacob4_qt_syms24+coefs_tq1_11.*coef_Jacob4_qt_syms21.*pinvG1_1+coefs_tq1_11.*coef_Jacob4_qt_syms22.*pinvG2_1+coefs_tq1_11.*coef_Jacob4_qt_syms23.*pinvG3_1+coefs_tq2_11.*coef_Jacob4_qt_syms21.*pinvG1_2+coefs_tq2_11.*coef_Jacob4_qt_syms22.*pinvG2_2+coefs_tq2_11.*coef_Jacob4_qt_syms23.*pinvG3_2+coefs_tq3_11.*coef_Jacob4_qt_syms21.*pinvG1_3+coefs_tq3_11.*coef_Jacob4_qt_syms22.*pinvG2_3+coefs_tq3_11.*coef_Jacob4_qt_syms23.*pinvG3_3,coef_Jacob1_qt_syms31+coefs_tq1_11.*coef_Jacob1_qt_syms28.*pinvG1_1+coefs_tq1_11.*coef_Jacob1_qt_syms29.*pinvG2_1+coefs_tq1_11.*coef_Jacob1_qt_syms30.*pinvG3_1+coefs_tq2_11.*coef_Jacob1_qt_syms28.*pinvG1_2+coefs_tq2_11.*coef_Jacob1_qt_syms29.*pinvG2_2+coefs_tq2_11.*coef_Jacob1_qt_syms30.*pinvG3_2+coefs_tq3_11.*coef_Jacob1_qt_syms28.*pinvG1_3+coefs_tq3_11.*coef_Jacob1_qt_syms29.*pinvG2_3+coefs_tq3_11.*coef_Jacob1_qt_syms30.*pinvG3_3,coef_Jacob2_qt_syms31+coefs_tq1_11.*coef_Jacob2_qt_syms28.*pinvG1_1+coefs_tq1_11.*coef_Jacob2_qt_syms29.*pinvG2_1+coefs_tq1_11.*coef_Jacob2_qt_syms30.*pinvG3_1+coefs_tq2_11.*coef_Jacob2_qt_syms28.*pinvG1_2+coefs_tq2_11.*coef_Jacob2_qt_syms29.*pinvG2_2+coefs_tq2_11.*coef_Jacob2_qt_syms30.*pinvG3_2+coefs_tq3_11.*coef_Jacob2_qt_syms28.*pinvG1_3+coefs_tq3_11.*coef_Jacob2_qt_syms29.*pinvG2_3+coefs_tq3_11.*coef_Jacob2_qt_syms30.*pinvG3_3,coef_Jacob3_qt_syms31+coefs_tq1_11.*coef_Jacob3_qt_syms28.*pinvG1_1+coefs_tq1_11.*coef_Jacob3_qt_syms29.*pinvG2_1+coefs_tq1_11.*coef_Jacob3_qt_syms30.*pinvG3_1+coefs_tq2_11.*coef_Jacob3_qt_syms28.*pinvG1_2+coefs_tq2_11.*coef_Jacob3_qt_syms29.*pinvG2_2+coefs_tq2_11.*coef_Jacob3_qt_syms30.*pinvG3_2+coefs_tq3_11.*coef_Jacob3_qt_syms28.*pinvG1_3+coefs_tq3_11.*coef_Jacob3_qt_syms29.*pinvG2_3+coefs_tq3_11.*coef_Jacob3_qt_syms30.*pinvG3_3,coef_Jacob4_qt_syms31+coefs_tq1_11.*coef_Jacob4_qt_syms28.*pinvG1_1+coefs_tq1_11.*coef_Jacob4_qt_syms29.*pinvG2_1+coefs_tq1_11.*coef_Jacob4_qt_syms30.*pinvG3_1+coefs_tq2_11.*coef_Jacob4_qt_syms28.*pinvG1_2+coefs_tq2_11.*coef_Jacob4_qt_syms29.*pinvG2_2+coefs_tq2_11.*coef_Jacob4_qt_syms30.*pinvG3_2+coefs_tq3_11.*coef_Jacob4_qt_syms28.*pinvG1_3+coefs_tq3_11.*coef_Jacob4_qt_syms29.*pinvG2_3+coefs_tq3_11.*coef_Jacob4_qt_syms30.*pinvG3_3,coef_Jacob1_qt_syms36+coefs_tq1_11.*coef_Jacob1_qt_syms33.*pinvG1_1+coefs_tq1_11.*coef_Jacob1_qt_syms34.*pinvG2_1+coefs_tq1_11.*coef_Jacob1_qt_syms35.*pinvG3_1+coefs_tq2_11.*coef_Jacob1_qt_syms33.*pinvG1_2+coefs_tq2_11.*coef_Jacob1_qt_syms34.*pinvG2_2+coefs_tq2_11.*coef_Jacob1_qt_syms35.*pinvG3_2+coefs_tq3_11.*coef_Jacob1_qt_syms33.*pinvG1_3+coefs_tq3_11.*coef_Jacob1_qt_syms34.*pinvG2_3+coefs_tq3_11.*coef_Jacob1_qt_syms35.*pinvG3_3,coef_Jacob2_qt_syms36+coefs_tq1_11.*coef_Jacob2_qt_syms33.*pinvG1_1+coefs_tq1_11.*coef_Jacob2_qt_syms34.*pinvG2_1+coefs_tq1_11.*coef_Jacob2_qt_syms35.*pinvG3_1+coefs_tq2_11.*coef_Jacob2_qt_syms33.*pinvG1_2+coefs_tq2_11.*coef_Jacob2_qt_syms34.*pinvG2_2+coefs_tq2_11.*coef_Jacob2_qt_syms35.*pinvG3_2+coefs_tq3_11.*coef_Jacob2_qt_syms33.*pinvG1_3+coefs_tq3_11.*coef_Jacob2_qt_syms34.*pinvG2_3+coefs_tq3_11.*coef_Jacob2_qt_syms35.*pinvG3_3,coef_Jacob3_qt_syms36+coefs_tq1_11.*coef_Jacob3_qt_syms33.*pinvG1_1+coefs_tq1_11.*coef_Jacob3_qt_syms34.*pinvG2_1+coefs_tq1_11.*coef_Jacob3_qt_syms35.*pinvG3_1+coefs_tq2_11.*coef_Jacob3_qt_syms33.*pinvG1_2+coefs_tq2_11.*coef_Jacob3_qt_syms34.*pinvG2_2+coefs_tq2_11.*coef_Jacob3_qt_syms35.*pinvG3_2+coefs_tq3_11.*coef_Jacob3_qt_syms33.*pinvG1_3+coefs_tq3_11.*coef_Jacob3_qt_syms34.*pinvG2_3+coefs_tq3_11.*coef_Jacob3_qt_syms35.*pinvG3_3,coef_Jacob4_qt_syms36+coefs_tq1_11.*coef_Jacob4_qt_syms33.*pinvG1_1+coefs_tq1_11.*coef_Jacob4_qt_syms34.*pinvG2_1+coefs_tq1_11.*coef_Jacob4_qt_syms35.*pinvG3_1+coefs_tq2_11.*coef_Jacob4_qt_syms33.*pinvG1_2+coefs_tq2_11.*coef_Jacob4_qt_syms34.*pinvG2_2+coefs_tq2_11.*coef_Jacob4_qt_syms35.*pinvG3_2+coefs_tq3_11.*coef_Jacob4_qt_syms33.*pinvG1_3+coefs_tq3_11.*coef_Jacob4_qt_syms34.*pinvG2_3+coefs_tq3_11.*coef_Jacob4_qt_syms35.*pinvG3_3],[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/Q_pTop_func_new.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.1533816945533521}} {"text": "function [modelUpdated,modelPruned,Ex_Rxns] = pruneModel(model,minGrowth, biomassRxn)\n% This function prunes a model to its most compact subnetwork given some model\n% constraints and a minimal growth rate by identifying and removing all blocked reactions.\n%\n% USAGE:\n%\n% [modelUpdated, modelPruned, Ex_Rxns] = pruneModel(model, minGrowth, biomassRxn)\n%\n% INPUTS:\n% model: model structure\n% minGrowth: minimal Growth rate to be set on biomass reaction\n% biomassRxn: biomass reaction name (default: 'biomass_reaction2')\n%\n% OUTPUTS:\n% modelUpdated: same as input model but constraints on blocked reactions\n% are set to be 0\n% modelPruned: pruned model, where all blocked reactions are removed\n% (attention this seems to cause issues with GPRs)\n% Ex_Rxns: List of exchange reactions in pruned model\n%\n% .. Authors: - Ines Thiele, 02/2014\n% - Modified by Loic Marx, December 2018\n\nif ~exist('biomassRxn','var')\n biomassRxn = checkObjective(model);\n biomassRxn = biomassRxn{1};\nend\n\nmodelUpdated = model;\nmodelForPruning = model;\nmodelForPruning.lb(modelForPruning.lb < 0) = -1000;\nmodelForPruning.ub(modelForPruning.ub < 0) = 0; % in case uptake is enforced\nmodelForPruning.ub(modelForPruning.ub > 0) = 1000;\nmodelForPruning.lb(modelForPruning.lb > 0) = 0; % in case secretion is enforced\n%set back biomass constraint\nmodelForPruning.lb(find(ismember(modelForPruning.rxns,biomassRxn)))=minGrowth;\nepsilon =getCobraSolverParams('LP', 'feasTol')*100;\n[modelForPruningPruned, BlockedRxns] = identifyBlockedRxns(modelForPruning,epsilon);\ncnt =1;\nfor t=1:length(modelForPruningPruned.rxns)\n if strfind(modelForPruningPruned.rxns{t}, 'EX_')\n Ex_Rxns(cnt,1) =modelForPruningPruned.rxns(t); %make exchange reaction list\n cnt=cnt+1;\n end\nend\n\nmodelUpdated.lb(ismember(model.rxns,BlockedRxns.allRxns))=0;\nmodelUpdated.ub(ismember(model.rxns,BlockedRxns.allRxns))=0;\n\nRxnsInModelMin = setdiff(model.rxns,BlockedRxns.allRxns); % all reactions that are not blocked\nmodelPruned = extractSubNetwork(model,RxnsInModelMin);\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/dataIntegration/metabotools/pruneModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.27202455109402257, "lm_q1q2_score": 0.1529258102890676}} {"text": "function [y,fs,h]=readcnx(filename,mode)\n%READCNX Read a .CNX format sound file [Y,FS,H]=(FILENAME)\n%\n% Inputs:\n% filename : character string containing filename (default extension .cnx)\n% mode: 't' = trim leading and trailing silences\n% 'h' = read header only\n% 'd' Look in data directory: voicebox('dir_data')\n%\n% Outputs:\n% y : column vector containing waveform\n% fs : sample frequency\n% h : parameter array:\n% h(1) = number of samples in file\n% h(2) = status: 0=good, 1=bad\n% h(3) = start sample number\n% h(4) = ending sample number\n% h(5) = speaker identification number\n% h(6) = speaker age group\n% h(7) = speaker sex: 0=male, 1=female\n% h(8) = ascii character\n% h(9) = repetition number\n%\n% This is the format of the BT Connex-S1 alphabet database\n% Note: the decoding is not particularly robust and assumes\n% that all headers contain the same sequence of fields\n\n%\t Copyright (C) Mike Brookes 1998\n% Version: $Id: readcnx.m,v 1.4 2007/05/04 07:01:39 dmb Exp $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nix=[17 71; 18 0; 19 0; 10 0; 12 0; 13 77; 15 -1; 16 0; ];\n\nif nargin<2 mode='0'; end \nif any(mode=='d')\n filename=fullfile(voicebox('dir_data'),filename);\nend\nfid=fopen(filename,'rb','l');\nif fid == -1\n fn=[filename,'.cnx'];\n fid=fopen(fn,'rb','l');\n if fid ~= -1 filename=fn; end\nend\nif fid == -1 error(sprintf('Can''t open %s for input',filename)); end\n[hdr,n]=fread(fid,512,'uchar');\nif n ~= 512 error(sprintf('Can''t read header from connex file %s',filename)); end\ndel=find(hdr(5:end)=='|')';\nfs=sscanf(char(hdr(17:del(1)+3)),'%f');\nh=zeros(size(ix,1),1);\nfor i=1:length(h)\n e=find(hdr(del(ix(i)-1)+5:del(ix(i))+3)=='=');\n if ix(i,2)\n h(i)=hdr(del(ix(i)-1)+e+5);\n if ix(i,2)>0\n h(i)=1-(h(i)==ix(i,2));\n end\n else\n h(i)=sscanf(char(hdr(del(ix(i)-1)+e+5:del(ix(i))+3)),'%d');\n end\nend\nif any(mode =='h')\n y=[];\nelseif any(mode =='t')\n fseek(fid,2*h(2),0);\n [y,n]=fread(fid,h(3)-h(2)+1,'short');\n if n ~= h(3)-h(2)+1 error(sprintf('Error reading data from connex file %s',filename)); end\nelse\n y=fread(fid,inf,'short');\nend\nfseek(fid,0,1);\nh=[ftell(fid)/2-256; h];\nfclose(fid);\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/\u7b2c 19 \u7ae0 \u57fa\u4e8e\u8bed\u97f3\u8bc6\u522b\u7684\u4fe1\u53f7\u706f\u56fe\u50cf\u6a21\u62df\u63a7\u5236\u6280\u672f/voicebox/readcnx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.2658804614657029, "lm_q1q2_score": 0.15252987970638282}} {"text": "%Esto es el PURPOSE de la FUNCION que es sumar a + b\nfunction [ c ] = funct1( a,b )\n%FUNCT1 Summary of this function goes here\n% Detailed explanation goes here\n% Esta funcion suma a + b\nc=a+b;\nt=0:0.001:1;\nplot(sin(t));\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31572-automatische-dokumentation-matlab-quellcodes-automatic-documentation-matlab-source-codes/proyecto/funct1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363242, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15230530652800037}} {"text": "function varargout = process_timefreq( varargin )\n% PROCESS_TIMEFREQ: Computes the time frequency decomposition of any signal in the database.\n% \n% USAGE: sProcess = process_timefreq('GetDescription')\n% sInput = process_timefreq('Run', sProcess, sInput)\n% TFmask = process_timefreq('GetEdgeEffectMask', Time, Freqs, tfOptions)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2010-2017\n\neval(macro_method);\nend\n\n\n%% ===== GET DESCRIPTION =====\nfunction sProcess = GetDescription() %#ok\n % Description the process\n sProcess.Comment = 'Time-frequency (Morlet wavelets)';\n sProcess.Category = 'Custom';\n sProcess.SubGroup = 'Frequency';\n sProcess.Index = 505;\n sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/TimeFrequency#Morlet_wavelets';\n % Definition of the input accepted by this process\n sProcess.InputTypes = {'data', 'results', 'matrix'};\n sProcess.OutputTypes = {'timefreq', 'timefreq', 'timefreq'};\n sProcess.nInputs = 1;\n sProcess.nMinFiles = 1;\n % Options: Sensor types\n sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): ';\n sProcess.options.sensortypes.Type = 'text';\n sProcess.options.sensortypes.Value = 'MEG, EEG';\n sProcess.options.sensortypes.InputTypes = {'data'};\n sProcess.options.sensortypes.Group = 'input';\n % Options: Scouts\n sProcess.options.clusters.Comment = '';\n sProcess.options.clusters.Type = 'scout_confirm';\n sProcess.options.clusters.Value = {};\n sProcess.options.clusters.InputTypes = {'results'};\n sProcess.options.clusters.Group = 'input';\n % Options: Scout function\n sProcess.options.scoutfunc.Comment = {'Mean', 'Max', 'PCA', 'Std', 'All', 'Scout function:'};\n sProcess.options.scoutfunc.Type = 'radio_line';\n sProcess.options.scoutfunc.Value = 1;\n sProcess.options.scoutfunc.InputTypes = {'results'};\n sProcess.options.scoutfunc.Group = 'input';\n % Options: Time-freq\n sProcess.options.edit.Comment = {'panel_timefreq_options', 'Morlet wavelet options: '};\n sProcess.options.edit.Type = 'editpref';\n sProcess.options.edit.Value = [];\n % Options: Normalize\n sProcess.options.normalize2020.Comment = 'Spectral flattening: Multiply output power values by frequency';\n sProcess.options.normalize2020.Type = 'checkbox';\n sProcess.options.normalize2020.Value = 0; \n % Old normalize option, for backwards compatibility.\n sProcess.options.normalize.Comment = {'None: Save non-standardized time-frequency maps', '1/f compensation: Multiply output values by frequency'; ...\n 'none', 'multiply'};\n sProcess.options.normalize.Type = 'radio_label';\n sProcess.options.normalize.Value = 'none';\n sProcess.options.normalize.Hidden = 1;\nend\n\n\n%% ===== FORMAT COMMENT =====\nfunction Comment = FormatComment(sProcess) %#ok\n Comment = sProcess.Comment;\nend\n\n\n%% ===== RUN =====\nfunction OutputFiles = Run(sProcess, sInputs) %#ok\n % Initialize returned values\n OutputFiles = {};\n % Extract method name from the process name\n switch (func2str(sProcess.Function))\n case 'process_timefreq', strProcess = 'morlet';\n case 'process_hilbert', strProcess = 'hilbert';\n case 'process_fft', strProcess = 'fft';\n case 'process_psd', strProcess = 'psd';\n case 'process_sprint', strProcess = 'sprint';\n case 'process_ft_mtmconvol', strProcess = 'mtmconvol';\n otherwise, error('Unsupported process.');\n end\n % Get editable options (Edit... button)\n if isfield(sProcess.options, 'edit')\n tfOPTIONS = sProcess.options.edit.Value;\n % If user did not edit values: get default values\n if isempty(tfOPTIONS)\n [bstPanelNew, panelName] = panel_timefreq_options('CreatePanel', sProcess, sInputs);\n jPanel = gui_show(bstPanelNew, 'JavaWindow', panelName, 0, 0, 0); \n drawnow;\n tfOPTIONS = panel_timefreq_options('GetPanelContents');\n gui_hide(panelName);\n end\n % Else: get default options\n else\n tfOPTIONS = bst_timefreq();\n tfOPTIONS.Method = strProcess;\n switch tfOPTIONS.Method\n case 'fft', tfOPTIONS.Comment = 'FFT';\n case 'psd', tfOPTIONS.Comment = 'PSD';\n case 'sprint', tfOPTIONS.Comment = 'SPRiNT';\n case 'morlet', tfOPTIONS.Comment = 'Wavelet';\n case 'hilbert', tfOPTIONS.Comment = 'Hilbert';\n case 'mtmconvol', tfOPTIONS.Comment = 'Multitaper';\n end\n end\n \n % Add other options\n tfOPTIONS.Method = strProcess;\n if isfield(sProcess.options, 'sensortypes')\n tfOPTIONS.SensorTypes = sProcess.options.sensortypes.Value;\n else\n tfOPTIONS.SensorTypes = [];\n end\n if isfield(sProcess.options, 'mirror') && ~isempty(sProcess.options.mirror) && ~isempty(sProcess.options.mirror.Value)\n tfOPTIONS.isMirror = sProcess.options.mirror.Value;\n else\n tfOPTIONS.isMirror = 0;\n end\n if isfield(sProcess.options, 'clusters') && ~isempty(sProcess.options.clusters) && ~isempty(sProcess.options.clusters.Value)\n tfOPTIONS.Clusters = sProcess.options.clusters.Value;\n else\n tfOPTIONS.Clusters = [];\n end\n % Override scouts function\n if isfield(sProcess.options, 'scoutfunc') && isfield(sProcess.options.scoutfunc, 'Value') && ~isempty(sProcess.options.scoutfunc.Value)\n switch lower(sProcess.options.scoutfunc.Value)\n case {1, 'mean'}, tfOPTIONS.ScoutFunc = 'mean';\n case {2, 'max'}, tfOPTIONS.ScoutFunc = 'max';\n case {3, 'pca'}, tfOPTIONS.ScoutFunc = 'pca';\n case {4, 'std'}, tfOPTIONS.ScoutFunc = 'std';\n case {5, 'all'}, tfOPTIONS.ScoutFunc = 'all';\n otherwise, bst_report('Error', sProcess, [], 'Invalid scout function.'); return;\n end\n else\n tfOPTIONS.ScoutFunc = [];\n end\n % If a time window was specified\n if isfield(sProcess.options, 'timewindow') && ~isempty(sProcess.options.timewindow) && ~isempty(sProcess.options.timewindow.Value) && iscell(sProcess.options.timewindow.Value)\n tfOPTIONS.TimeWindow = sProcess.options.timewindow.Value{1};\n elseif ~isfield(tfOPTIONS, 'TimeWindow')\n tfOPTIONS.TimeWindow = [];\n end\n % If a window length was specified (PSD)\n if isfield(sProcess.options, 'win_length') && ~isempty(sProcess.options.win_length) && ~isempty(sProcess.options.win_length.Value) && iscell(sProcess.options.win_length.Value)\n tfOPTIONS.WinLength = sProcess.options.win_length.Value{1};\n tfOPTIONS.WinOverlap = sProcess.options.win_overlap.Value{1};\n end\n if isfield(sProcess.options, 'win_std') && ~isempty(sProcess.options.win_std) && ~isempty(sProcess.options.win_std.Value)\n tfOPTIONS.WinStd = sProcess.options.win_std.Value;\n if tfOPTIONS.WinStd\n tfOPTIONS.Comment = [tfOPTIONS.Comment ' std'];\n end\n end\n % If units specified (PSD)\n if isfield(sProcess.options, 'units') && ~isempty(sProcess.options.units) && ~isempty(sProcess.options.units.Value)\n tfOPTIONS.PowerUnits = sProcess.options.units.Value;\n end \n % Multitaper options\n if isfield(sProcess.options, 'mt_taper') && ~isempty(sProcess.options.mt_taper) && ~isempty(sProcess.options.mt_taper.Value)\n if iscell(sProcess.options.mt_taper.Value)\n tfOPTIONS.ft_mtmconvol.taper = sProcess.options.mt_taper.Value{1};\n else\n tfOPTIONS.ft_mtmconvol.taper = sProcess.options.mt_taper.Value;\n end\n end\n if isfield(sProcess.options, 'mt_frequencies') && ~isempty(sProcess.options.mt_frequencies) && ~isempty(sProcess.options.mt_frequencies.Value)\n tfOPTIONS.ft_mtmconvol.frequencies = eval(sProcess.options.mt_frequencies.Value);\n % Add frequencies to comment\n tfOPTIONS.Comment = [tfOPTIONS.Comment, ' ', sProcess.options.mt_frequencies.Value, 'Hz'];\n end\n if isfield(sProcess.options, 'mt_freqmod') && ~isempty(sProcess.options.mt_freqmod) && ~isempty(sProcess.options.mt_freqmod.Value)\n tfOPTIONS.ft_mtmconvol.freqmod = sProcess.options.mt_freqmod.Value{1};\n end\n if isfield(sProcess.options, 'mt_timeres') && ~isempty(sProcess.options.mt_timeres) && ~isempty(sProcess.options.mt_timeres.Value)\n tfOPTIONS.ft_mtmconvol.timeres = sProcess.options.mt_timeres.Value{1};\n end\n if isfield(sProcess.options, 'mt_timestep') && ~isempty(sProcess.options.mt_timestep) && ~isempty(sProcess.options.mt_timestep.Value)\n tfOPTIONS.ft_mtmconvol.timestep = sProcess.options.mt_timestep.Value{1};\n end\n if isfield(sProcess.options, 'measure') && ~isempty(sProcess.options.measure) && ~isempty(sProcess.options.measure.Value)\n tfOPTIONS.Measure = sProcess.options.measure.Value;\n % Add measure to comment\n if strcmpi(tfOPTIONS.Measure, 'none')\n strMeasure = 'complex';\n else\n strMeasure = tfOPTIONS.Measure;\n end\n tfOPTIONS.Comment = [tfOPTIONS.Comment, ' ', strMeasure];\n end\n % if process is SPRiNT\n if isfield(sProcess.options, 'fooof')\n tfOPTIONS.SPRiNTopts = sProcess.options;\n end\n % Output\n if isfield(sProcess.options, 'avgoutput') && ~isempty(sProcess.options.avgoutput) && ~isempty(sProcess.options.avgoutput.Value)\n if sProcess.options.avgoutput.Value\n tfOPTIONS.Output = 'average';\n else\n tfOPTIONS.Output = 'all';\n end\n end\n % Frequency normalization\n if isfield(sProcess.options, 'normalize2020') && ~isempty(sProcess.options.normalize2020) \n if isequal(sProcess.options.normalize2020.Value, 1)\n tfOPTIONS.NormalizeFunc = 'multiply2020';\n elseif ischar(sProcess.options.normalize2020.Value)\n tfOPTIONS.NormalizeFunc = sProcess.options.normalize2020.Value;\n end\n elseif isfield(sProcess.options, 'normalize') && ~isempty(sProcess.options.normalize) \n if isequal(sProcess.options.normalize.Value, 1)\n tfOPTIONS.NormalizeFunc = 'multiply';\n elseif ischar(sProcess.options.normalize.Value)\n tfOPTIONS.NormalizeFunc = sProcess.options.normalize.Value;\n end\n else\n tfOPTIONS.NormalizeFunc = 'none';\n end\n \n % === EXTRACT CLUSTER/SCOUTS ===\n if ~isempty(tfOPTIONS.Clusters)\n % If cluster function should be applied AFTER time-freq: get all time series\n if strcmpi(tfOPTIONS.ClusterFuncTime, 'after')\n ExtractScoutFunc = 'all';\n else\n ExtractScoutFunc = tfOPTIONS.ScoutFunc;\n end\n AddRowComment = ~isempty(tfOPTIONS.ScoutFunc) && strcmpi(tfOPTIONS.ScoutFunc, 'all');\n % Flip sign only for results\n isflip = strcmpi(sInputs(1).FileType, 'results');\n % Call process\n ClustMat = bst_process('CallProcess', 'process_extract_scout', sInputs, [], ...\n 'timewindow', tfOPTIONS.TimeWindow, ...\n 'scouts', tfOPTIONS.Clusters, ...\n 'scoutfunc', ExtractScoutFunc, ... % If ScoutFunc is not defined, use the scout function available in each scout\n 'isflip', isflip, ...\n 'isnorm', 0, ...\n 'concatenate', 0, ...\n 'save', 0, ...\n 'addrowcomment', AddRowComment, ...\n 'addfilecomment', 0, ...\n 'progressbar', 0);\n if isempty(ClustMat)\n bst_report('Error', sProcess, sInputs, 'Cannot access clusters/scouts time series.');\n return;\n end\n % Get data to process\n DataToProcess = {ClustMat.Value};\n tfOPTIONS.TimeVector = ClustMat(1).Time;\n tfOPTIONS.ListFiles = {sInputs.FileName};\n tfOPTIONS.nComponents = [ClustMat.nComponents];\n tfOPTIONS.RowNames = {};\n tfOPTIONS.SurfaceFile = {ClustMat.SurfaceFile};\n for iFile = 1:length(ClustMat)\n tfOPTIONS.RowNames{iFile} = ClustMat(iFile).Description;\n end\n clear ClustMat;\n % === DATA FILES ===\n else\n DataToProcess = {sInputs.FileName};\n tfOPTIONS.TimeVector = in_bst(sInputs(1).FileName, 'Time');\n end\n\n % === OUTPUT STUDY ===\n if strcmpi(tfOPTIONS.Output, 'average')\n % Get output study\n [sStudy, iStudy, Comment] = bst_process('GetOutputStudy', sProcess, sInputs);\n % If no valid output study can be found\n if isempty(iStudy)\n return;\n end\n % Save all outputs from bst_timefreq in target Study\n tfOPTIONS.iTargetStudy = iStudy;\n else\n tfOPTIONS.iTargetStudy = [];\n end\n \n % === START COMPUTATION ===\n [OutputFiles, Messages, isError] = bst_timefreq(DataToProcess, tfOPTIONS);\n if ~isempty(Messages)\n if isError\n bst_report('Error', sProcess, sInputs, Messages);\n elseif isempty(OutputFiles)\n bst_report('Warning', sProcess, sInputs, Messages);\n else\n bst_report('Info', sProcess, sInputs, Messages);\n disp(['BST> process_timefreq: ' Messages]);\n end\n end\nend\n\n\n%% ===== GET EDGE EFFECT MASK =====\nfunction TFmask = GetEdgeEffectMask(Time, Freqs, tfOptions) %#ok\n % Get time vector\n if ~iscell(Time)\n t = Time;\n else\n t = mean(cell2mat(Time(:,2:3)), 2)';\n end\n % Get frequency vector\n if ~iscell(Freqs)\n f = Freqs;\n else\n FreqBands = process_tf_bands('GetBounds', Freqs);\n f = mean(FreqBands, 2)';\n end\n \n % Morlet wavelets\n if isfield(tfOptions, 'Method') && strcmpi(tfOptions.Method, 'morlet') && isfield(tfOptions, 'MorletFc') && isfield(tfOptions, 'MorletFwhmTc')\n FWHM_t = tfOptions.MorletFwhmTc * tfOptions.MorletFc ./ f;\n TF_timeres = repmat(FWHM_t' ./ 2, [1,length(t)]);\n TFmask = (bst_bsxfun(@minus, t - t(1), TF_timeres) > 0);\n TFmask = (TFmask & bst_flip(TFmask, 2));\n \n % Hilbert transform\n elseif isfield(tfOptions, 'Method') && strcmpi(tfOptions.Method, 'hilbert')\n if iscell(Time)\n disp('BST> Edge effects map for Hilbert process is not available yet when time bands are selected.');\n TFmask = [];\n else\n % Sampling frequency\n sfreq = 1 ./ (t(2) - t(1));\n % Compute the transients for each bandpass filter\n TFmask = zeros(size(Freqs,1), length(t));\n for i = 1:size(Freqs,1)\n % Compute the filter specifications\n [tmp, FiltSpec] = process_bandpass('Compute', [], sfreq, FreqBands(i,1), FreqBands(i,2), 'bst-hfilter-2019');\n % Only the values outside of the transients are valid\n TFmask(i,(t - t(1) > FiltSpec.transient) & (t(end) - t > FiltSpec.transient)) = 1;\n end\n end\n else\n TFmask = [];\n end\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/process/functions/process_timefreq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15230530330972575}} {"text": "function coast = ma_createNBodyCoast(name, coastType, coastToValue, revs, refBody, vars, soiSkipIds, lineColor, lineStyle, lineWidth, massLoss, forceModel, maxPropTime)\n%ma_createNBodyCoast Summary of this function goes here\n% Detailed explanation goes here\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % Valid coast type strings:\n % goto_ut - goes to a specific Universal Time\n % goto_dt - goes to a specific delta-time from the input state\n % goto_tru - goes to a specific true anomaly\n % goto_apo - goes to the next apogee\n % goto_peri - goes to the next perigee\n % goto_asc_node - goes to ascending node\n % goto_desc_node - goes to the descending node (asc node + pi)\n % goto_soi_trans - goes to the next SOI transition\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n coast = struct();\n coast.name = name;\n coast.type = 'NBodyCoast';\n coast.coastType = coastType;\n coast.coastToValue = coastToValue;\n coast.revs = revs;\n coast.refBody = refBody;\n coast.id = rand(1);\n coast.vars = vars;\n coast.soiSkipIds = soiSkipIds;\n coast.forceModel = forceModel;\n coast.lineColor = lineColor;\n coast.lineStyle = lineStyle;\n coast.lineWidth = lineWidth;\n coast.massloss = massLoss;\n coast.maxPropTime = maxPropTime;\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/events/create_events/ma_createNBodyCoast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15154754982967136}} {"text": "function [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric)\n%%DECODEAISPOSREPORTS2MAT Given a matrix of Automatic Identification\n% System (AIS) messages (or a cell array of AIS messages)\n% given as National Marine Electronics Association (NMEA)\n% formatted ASCII text messages, extract position reports\n% of message types 1, 2, 3, 18, 19, and 27, storing the\n% information related to ship location, identity, course,\n% and time in different rows of a matrix, where each\n% column corresponds to a different report. If a cell\n% array is passed, then the matrices for decoding each\n% cell array are placed into corresponding cells on\n% return. It is also possible to decode timestamps (or\n% another integer number) appended as a final field on the\n% messages. The manipulation of matrices rather than\n% structures is significantly faster in Matlab, which is\n% why one might prefer this function to decodeAISString\n% when only simple position reports are needed.\n% \n%INPUTS: NMEAStrings A character string containing one or more Automatic\n% Identification System (AIS) messages given as National\n% Marine Electronics Association (NMEA) formatted ASCII\n% text. Each message is on its own line. Invalid messages\n% and messages that are not of types 1, 2, 3, 18, 19, and\n% 27 are skipped.\n% convert2Metric If true, all distance units in the result are converted\n% to meters, all speed units are converted to meters per\n% second, and all angles are converted to radians North of\n% East (the mathematical definition) and angular rates are\n% converted to radians per second North of East, all\n% rather than using typical nautical units. The default if\n% omitted is true.\n% \n%decodedMsgs A 14XN matrix of the N successfully decoded position reports.\n% The 14 fields that are decoded are stored in the matrix as:\n% 1) The maritime mobile service identity (MMSI)\n% number of the transmitter that can be used to\n% identify targets (A 30-bit integer value).\n% 2) Navigation status. An integer indicating what the\n% ship is doing/ whether it is moving. Possible\n% valid values are:\n% *0 = under way using engine\n% *1 = at anchor\n% *2 = not under command,\n% *3 = restricted maneuverability\n% *4 = constrained by her draught\n% *5 = moored\n% *6 = aground\n% *7 = engaged in fishing\n% *8 = under way sailing\n% *9 = reserved for future amendment of\n% navigational status for ships carrying DG, HS,\n% or MP, or IMO hazard or pollutant category C,\n% high speed craft (HSC).\n% *10 = reserved for future amendment of\n% navigational status for ships carrying\n% dangerous goods (DG), harmful substances (HS)\n% or marine pollutants (MP), or IMO hazard or\n% pollutant category A, wing in ground (WIG).\n% *11 = power- driven vessel towing astern\n% (regional use)\n% *12 = power-driven vessel pushing ahead or towing\n% alongside (regional use)\n% *13 = reserved for future use,\n% *14 = AIS-SART (active), MOB-AIS, EPIRB-AIS\n% 3) Turn rate. This is limited to +/- 708 degrees per\n% minute (about +/- .2059 radians per second when\n% using metric units).\n% 4) Speed over ground in knots up to 102.2 knots, or\n% 52.6 meters per second when using metric units.\n% 5) Position accuracy flag. Possible values are:\n% 1=high (accuracy beter than 10m)\n% 0=low (accuracy worse than 10 meters)\n% 6) Latitude (WGS-84) in degrees North or radians\n% North when using the metric units option.\n% 7) Longitude (WGS 84) in degrees East or radians\n% East when using the metric units option.\n% 8) Course over ground (heading) in degrees East of\n% North or radians North of East when using the\n% metric units option.\n% 9) True heading in degrees East of North or radians\n% North of East when using the metric units option.\n% 10) The second number within the universal\n% coordinated time (UTC) minute when the ship's\n% transmitter sent the position report. NOTE that\n% if this is 61 or greater, than this means that the \n% the positioning system is broken or in dead\n% reckoning mode, so the return is likely to be\n% inaccurate. Also, the standard does not properly\n% account for 61 second minutes when a leapsecond\n% is added, so it is not clear what will happen\n% with leapseconds. This field is not used by\n% message 27. Rather, there is no timestamp and a\n% position latency indicator is used to indicate\n% the extend of the delay of the true time of the\n% position from the broadcast time.\n% 11) Special manoeuvre indicator. This can be\n% 1 = not engaged in special manoeuvre\n% 2 = engaged in special manoeuvre\n% 12) The ID of the message that provided the above\n% information. This can be\n% 1 Class A position report, scheduled.\n% 2 Class A position report, assigned.\n% 3 Class A position report, when interrogated.\n% 18 Standard class B equipment position report.\n% 19 Extended class B equipment position report.\n% 27 Long-range automatic identification system\n% broadcast message.\n% 13) A number indicating how many times the message\n% has been repeated. This ranged from 0 to 3. 3\n% also indicates that the message should not be\n% repeated anymore.\n% 14) Position latency. This is only used with message\n% 27. This is 0 or 1. 0 means the position latency\n% is less than five seconds, one means it is more.\n% epochTimes If this parameter is requested, then the final\n% numbers after the checklsum (separated by a comma)\n% are assumed to either be an integer epoch time, or\n% anything with a comma separating an integer epoch\n% time at the end. Thus, this tries to decode the\n% epoch time associated with the message. Note that in\n% multi-part messages (message 19 can have multiple\n% parts), the epoch time used is that of the LAST\n% received part in the sequence. If no time can be\n% decoded, then\n%\n%This function relies on libais from \n%https://github.com/schwehr/libais\n%The library probably does not work on big-endian processors (Intel\n%processors are little-endian).\n%\n%The algorithm can be compiled for use in Matlab using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);\n%or\n%[decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);\n%if timestamps are available\n%\n%The algorithm is run in Matlab using the command format\n%decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);\n%or\n%[decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings,convert2Metric);\n%if timestamps are available\n%\n%Example 1:, Decoding a single valid ID=1 string.\n% NMEAStrings='!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23';\n% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,false)\n%The decoded message should be:\n% decodedMsgs=[227006760;%MMSI\n% 0;%Navigation status (underway)\n% NaN;%Not used\n% 0;%Turn rate\n% 0;%Speed over ground\n% 49.475578308105469;%North latitude\n% 0.131380006670952;%East longitude\n% 36.700000762939453;%Heading East of North\n% NaN;%Not used\n% 14;%Seconds within minute when message sent.\n% NaN;%Not used.\n% 1;%Class A position report, scheduled.\n% 0;%has not ben rebroadcast.\n% NaN];%Not used.\n%\n%Example 2: Decoding multiple messages, one valid string of each type of\n%message. It is most likely that this would arise from reading the\n%messages in from a file, because adding newline characters to strings has\n%to be done using the \\n newline character to separate the string in\n%sprintf rather than just typing them. The AIS19 string consists of two\n%parts that are joined.\n% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23\\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C\\n!AIVDM,1,1,,B,34hoV<5000Jw95`GWokbFTuf0000,0*6C\\n!SAVDM,1,1,4,B,B5NU=J000=l0BD6l590EkwuUoP06,0*61\\n!AIVDM,2,1,7,B,C5NMbDQl0NNJC7VNuCP8=5EikdUet,0*6B');\n% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings,false)\n%One will observe that 6 messages are correctly decoded, of types 1, 2, 3,\n%18, 19, and 27.\n%\n%Example 3: Decoding multiple messages, some of them of the wrong type.\n%When messages of the wrong type are used, then they are askipped. Here,\n%two correct messages are read in as well as one incorrect message in\n%between them. The \"incorrect\" message is of type 26 (not a position report) and is thus ignored.\n%Below are four strings, but only two of them contain AIS position reports\n% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23\\n!AIVDM,1,1,,A,H44cj<0DdvlHhuB222222222220,2*46\\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C');\n% decodedMsgs=decodeAISPosReports2Mat(NMEAStrings)\n%The results are in metric units.\n%\n%Example 4: Consider the case where the messages contain some numbers\n%after the checksum, which make up the timestamps of the messages.\n%This is the same as the previous example, but with fake timestamps\n%appended.\n% NMEAStrings=sprintf('!AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23,1241827197\\n!AIVDM,1,1,,A,H44cj<0DdvlHhuB222222222220,2*46,1241827198\\n!AIVDM,1,1,,B,284;UGTdP4301>3L;B@Wk3TnU@A1,0*7C,1241827199');\n% [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings)\n%The results are in metric units.\n%\n%Example 5: Some receivers will append aditional information before the\n%timestamp. As long as the timestamp is the last thing in the message,\n%then we can still recover it.\n% NMEAStrings='!AIVDM,1,1,,A,100WhdhP0nJRdiFFHFvm??v00L12,0*13,raishub,1342569600';\n% [decodedMsgs,epochTimes]=decodeAISPosReports2Mat(NMEAStrings)\n%The results are in metric units.\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nerror('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Transponders/decodeAISPosReports2Mat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.265880478916874, "lm_q1q2_score": 0.15151269587004657}} {"text": "clear all;clc;\n% close all; \noutputDir = GetOutputDataDir;\n\n%% Init load\nhfig = figure;\nInitializeAppData(hfig);\nResetDisplayParams(hfig);\n\n%% params\nisStimLockRanking = 0; % init\nisMotorRanking = 0; % init\n\nfor caseflag = 5\n switch caseflag\n case 1 % seeds\n stimrange = [];\n M_clus_range = {[11,2],[12,1]};\n M_clus_name = {'motorseed2','ABN'};\n M_fishrange = {[1:3,5:18],[1:12,14:18]};\n n_reg = length(M_clus_name);\n \n case 2 % testing\n stimrange = [];\n M_clus_range = {[11,2],[11,3],[11,4]};\n M_clus_name = {'motorseed_v2','motorseed_LRmanual','motorseed_Fwmanual'};\n M_fishrange = {[5:13],[5:13],[5:13]};\n n_reg = length(M_clus_name);\n\n case 3 % conserved clusters\n stimrange = 1;\n M_clus_range = {[10,1]};\n M_clus_name = {'conservedclus_SLranked'};\n M_fishrange = {1:18};\n n_reg = length(M_clus_name);\n isStimLockRanking = 1;\n \n case 4 % all Auto0.7 clusters\n stimrange = [];\n M_clus_range = {[6,1]};\n M_clus_name = {'A0.7_def_stimlockrank'};\n M_fishrange = {1:18};\n n_reg = length(M_clus_name);\n isStimLockRanking = 1;\n \n case 5 % all Auto0.7 clusters\n stimrange = [];\n M_clus_range = {[6,1]};\n M_clus_name = {'A0.7_def_motorrank'};\n M_fishrange = {[1:3,5:18]};\n n_reg = length(M_clus_name);\n isStimLockRanking = 0;\n isMotorRanking = 1;\n \n case 6 % HBO stripes\n stimrange = 2;\n M_clus_range = {[10,4]};\n M_clus_name = {'HBO_anat'};\n% M_clus_name = {'HBO_OMR_stimlockrank'};\n M_fishrange = {[1:3,5:18]};%{8:18};%{1:18};%\n n_reg = length(M_clus_name);\n isStimLockRanking = 0;%1;\n isMotorRanking = 0;\n \n P_stimscore = zeros(18,4);\n \n case 7 % sparse network\n stimrange = 2;\n M_clus_range = {[12,2]};\n M_clus_name = {'sparse_nw'};\n % M_clus_name = {'HBO_OMR_stimlockrank'};\n M_fishrange = {[1:8]};%{8:18};%{1:18};%\n n_reg = length(M_clus_name);\n \n% case 6 % HBO stripes\n% stimrange = 1;\n% M_clus_range = {[10,4]};\n% M_clus_name = {'HBO_PT_stimlockrank'};\n% M_fishrange = {1:18};%{1:18};%{[1:3,5:18]};\n% n_reg = length(M_clus_name);\n% isStimLockRanking = 1;\n% \n% P_stimscore = zeros(18,4);\n% \n% case 3 % Looming\n% stimrange = 5;\n% M_stimmotorflag = [1,0]; % 1 for stim and 0 for motor\n% M_reg_name = {'Loom_LR','Loom_SwimLR'};\n% M_reg_range = {[11,12],[1,3]};\n% M_fishrange = {[9:15,17:18],[9:15,17:18]};\n% n_reg = length(M_reg_name);\n% \n% case 4 % Dark Flash (black-white)\n% stimrange = 3;\n% M_stimmotorflag = [1,0]; % 1 for stim and 0 for motor\n% M_reg_name = {'DF_BW','DF_SwimLR'};\n% M_reg_range = {[1,4],[1,3]};\n% M_fishrange = {[12:15,17:18],[12:15,17:18]};\n% n_reg = length(M_reg_name);\n end\n \n M_fishrange_im = M_fishrange;\n \n %% Load fish\n range_fish = 1:18;\n IM_full = cell(n_reg,max(range_fish));\n %%\n for i_fish = range_fish\n %% load fish\n if ismember(i_fish,cell2mat(M_fishrange))\n ClusterIDs = [1,1];\n if isempty(stimrange)\n LoadSingleFishDefault(i_fish,hfig,ClusterIDs);\n else\n LoadSingleFishDefault(i_fish,hfig,ClusterIDs,stimrange);\n end\n % [cIX_load,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs);\n end\n \n %% load clusters\n for i_set = 1:n_reg\n range_set = M_fishrange{i_set};\n if ismember(i_fish,range_set)\n ClusterIDs = M_clus_range{i_set};%[12,1];% GetClusterIDs('all');\n [cIX,gIX] = LoadCluster_Direct(i_fish,ClusterIDs(1),ClusterIDs(2));\n \n % override:\n if caseflag==7\n gIX = ones(size(cIX)); \n end\n% if caseflag==6\n% [cIX1,gIX1] = LoadCluster_Direct(i_fish,10,2);\n% [cIX2,gIX2] = LoadCluster_Direct(i_fish,10,3);\n% cIX = [cIX1;cIX2];\n% gIX = [gIX1;5-gIX2];\n \n% absIX = getappdata(hfig,'absIX');\n% name = 'HBO_4stripes';\n% clusgroupID = 10;\n% clusIDoverride = 4;\n% SaveCluster_Direct(cIX,gIX,absIX,i_fish,name,clusgroupID,clusIDoverride);\n% end\n \n if isempty(cIX)\n M_fishrange_im{i_set} = setdiff(M_fishrange_im{i_set} ,i_fish);\n continue;\n end\n \n %% [option: ranking]\n if caseflag>=3\n if isStimLockRanking\n M = UpdateIndices_Manual(hfig,cIX,gIX);\n C = FindClustermeans(gIX,M);\n [~,~,H] = GetTrialAvrLongTrace(hfig,C);\n [gIX,rankscore] = SortGroupIXbyScore(H,gIX);\n \n if caseflag==6\n P_stimscore(i_fish,:) = H;\n end\n elseif isMotorRanking\n M = UpdateIndices_Manual(hfig,cIX,gIX);\n C = FindClustermeans(gIX,M);\n numU = max(gIX);\n [gIX,rankscore] = RankByMotorReg_Direct(hfig,gIX,numU,C,1); \n end\n end\n \n %% make figure\n \n if caseflag==3 || caseflag==4 || caseflag==6\n setappdata(hfig,'clrmap_name','hsv_new');\n% elseif caseflag==6\n% setappdata(hfig,'clrmap_name','jet');\n else\n setappdata(hfig,'clrmap_name','hsv_old');\n end\n \n I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX);\n [h,im_full] = DrawCellsOnAnat(I);\n \n %% save figure\n close(h);\n IM_full{i_set,i_fish} = im_full;\n end\n end\n end\n \n% if caseflag==6\n% % save VAR\n% SaveVARtoMat(hfig);\n% end\n \n %% save as tiff stack\n for i_set = 1:n_reg\n range_im = M_fishrange_im{i_set};\n tiffdir = fullfile(outputDir,[M_clus_name{i_set},'_allfish.tiff']);\n IM = IM_full(i_set,range_im);\n \n SaveImToTiffStack(IM,tiffdir);\n end\n \n %% [for later] plot from tiff stack\n isPlotfromtiffstack = 0;\n \n if isPlotfromtiffstack\n IM_full = cell(n_reg,18);\n for i_set = 1:n_reg\n %% get tiff-stack path\n tiffdir = fullfile(outputDir,[M_clus_name{i_set},'_allfish.tiff']);\n \n %% load\n \n for i_fish = 1:18\n im = double(imread(tiffdir,i_fish))./255;\n IM_full{i_set,i_fish} = im(317:1236,1:621,:);\n end\n end\n end\n \n %% save average tiff image\n for i_set = 1:n_reg;\n range_im = M_fishrange_im{i_set};%[1:3,5:7];%[1:3,5:18];\n cellarray = IM_full(i_set,range_im);\n \n % adjust params for visualization\n k_scale = 0.5;\n k_contrast = 1;% 1.2;\n \n [h_anat,im_avr] = AverageAnatPlot(cellarray,k_contrast,k_scale);\n \n tiffdir = fullfile(outputDir,[M_clus_name{i_set},'_avr.tiff']);\n imwrite(im_avr, tiffdir, 'compression','none','writemode','overwrite');\n end\n \nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/Clustering/Batch_multifish_anatplot_from_VAR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.1512455614619536}} {"text": "function ph = atlasUndoPhase(atlasParams, ph)\n%\n% ph = atlasUndoPhase(atlasParams, ph)\n%\n% Purpose:\n% Convert the atlas phase data by shifting their phase and scaling the\n% phase range. The amount of shifting and scaling is stored in the\n% phaseShift/phaseScale fields. I am not sure why this code is used at\n% all. I think we should be using shiftPhase instead and this is left\n% over from version 1.0. I am trying to get rid of it -- BW \n%\n% HISTORY:\n% 2003.08.29 RFD (bob@white.stanford.edu) got tired of duplicating this\n% code, so here's a simple function.\n\nwarning('atlasUndoPhase is obsolete.')\n\n% Checking.\nif(length(atlasParams) ~= length(ph) | length(atlasParams(1).phaseShift) ~= size(ph{1},3))\n warning('atlasParams and ph should have the same number of scans and slices!');\nend\n\n% Create a scaled and shifted version of the atlas parameters.\nfor(scan=1:length(atlasParams))\n for(slice=1:length(atlasParams(scan).phaseShift))\n ph{scan}(:,:,slice) = mod((squeeze(ph{scan}(:,:,slice)) ...\n - atlasParams(scan).phaseShift(slice)) / atlasParams(scan).phaseScale(slice), 2*pi);\n end\nend\n\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/Atlas/atlasUndoPhase.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.15119254720903685}} {"text": "function out = rdivide( dividend, divisor )\n%RDIVIDE for nested cells\n%\n% (c) Thomas Kuestner \n% ---------------------------------------------------------------------\n\n% determine input types\ninType = {class(dividend), class(divisor)};\nif(strcmp(inType{1},'TRAFO') && strcmp(inType{2},'TRAFO'))\n [outA, idx] = flattenCellMatrix(dividend.data);\n [outB, idxB] = flattenCellMatrix(divisor.data); \n meta = dividend.meta;\n meta_b = divisor.meta;\n clear 'dividend' 'divisor'\n \n % idx must be consistent\n if(~isempty(idx) && ~isempty(idxB) && ~all(cellfun(@(x,y) isequal(x,y), idx, idxB)))\n error('TRAFO::rdivide: Nested cells must have the same size');\n end\n if(iscell(meta) && iscell(meta_b))\n if(~isempty(meta) && ~isempty(meta_b))\n if(iscell(meta{1}) && iscell(meta_b{1}))\n if(~all(cellfun(@(x,y) isequal(x,y), flattenCellMatrix(meta), flattenCellMatrix(meta_b))))\n error('TRAFO::rdivide: Unequal reconstruction information');\n end\n else\n if(~all(cellfun(@(x,y) isequal(x,y), meta, meta_b)))\n error('TRAFO::rdivide: Unequal reconstruction information');\n end\n end\n end\n else \n if ~isequal(meta, meta_b)\n error('TRAFO::rdivide: Unequal reconstruction information');\n end\n end\n out = cellfun(@(x,y) x./y, outA, outB, 'UniformOutput', false);\n\nelseif(strcmp(inType{1},'TRAFO')) % assume divisor is double/uint/int\n [out, idx] = flattenCellMatrix(dividend.data);\n meta = dividend.meta;\n clear 'dividend'\n \n out = cellfun(@(x) x./divisor, out, 'UniformOutput', false);\n \nelseif(strcmp(inType{2},'TRAFO'))\n [out, idx] = flattenCellMatrix(divisor.data);\n meta = divisor.meta;\n clear 'divisor'\n \n out = cellfun(@(x) dividend./x, out, 'UniformOutput', false);\n \nelse\n error('TRAFO::rdivide: Impossible constellation!');\nend\n\nout = reconFlatCellMatrix(out,idx);\nout = TRAFO(out,meta); % return TRAFO object again without modifying input\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@TRAFO/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15105876295844725}} {"text": "clc;\nclose all;\nclear;\n\nmDir = fileparts(mfilename('fullpath'));\ncd(mDir);\naddpath(genpath('../'));\n\n%% Params:\n\nexp = 'ALL_4_SEGS'; % Select which configuration to use: 'JUST_LAB_SEG', 'ALL_4_SEGS'\ncalcInLog=false; %false (for linear vus), true (for logarithmic vus)\n\n%Change these paths:\noriginalVOCDirectory = TOFILL; %Top directory of VOC 2007 dataset\nparsedVOCDir = TOFILL; %Directory where parsed VOC07 will be stored\n\n%VOC params:\n\nimgListDir= 'complete_test_set.txt'; %File with ids of the 4952 images of the test set\n\nparams.includeBoxesWithClasses={'aeroplane', 'bicycle','boat','bottle','bus','chair','diningtable','horse','motorbike','person','pottedplant','sofa','train','tvmonitor'};\nparams.omitImagesWithClasses={'bird','car','cat','cow','dog','sheep'};\nparams.considerDifficult=true;\n\nnMaximumWindows = 10000;\nevalParams.nWindows = unique(round(logspace(0, log10(nMaximumWindows), 100)));\nevalParams.ious = 0 : 0.05 : 1;\n\nif(strcmp(exp, 'ALL_4_SEGS'))\n configFile = '../config/rp_4segs.mat'; \n proposalsDir = [mDir '/tmp_prop_dir'];\nelseif(strcmp(exp, 'JUST_LAB_SEG'))\n configFile = '../config/rp.mat';\n proposalsDir = [mDir '/tmp_prop_dir_lab'];\nelse\n assert(false);\nend\nresultDirs={proposalsDir};\n\n\n%% Parse VOC2007 data:\n\nAdaptVOC2007Data(originalVOCDirectory,imgListDir,parsedVOCDir,params);\n\n%% Compute proposals and individual detection rates:\n\nComputeProposals(parsedVOCDir, proposalsDir, configFile, evalParams);\n\n%% Aggregate detection rates:\n\nAggregateDRs(proposalsDir, parsedVOCDir, evalParams);\n\n%% Compute Volume Under Surface:\n\nnWindowsRange=[0 10000];\niouRange=[0.5 1];\n\nnResults=numel(resultDirs);\ndrs=[];\nfor k=1:nResults\n data=load([resultDirs{k} '/aggregated_drs/drs.mat']);\n \n [cropped,legendStr]=CropEvaluations({data}, nWindowsRange, iouRange,{''});\n \n data=cropped{1};\n \n if(exist('ious','var'))\n assert( all(ious==data.ious));\n else\n ious=data.ious;\n nIous=length(ious);\n end\n \n if(exist('nWindows','var'))\n assert(all(nWindows==data.nWindows));\n else\n nWindows=data.nWindows;\n nnWindows=length(nWindows);\n end\n \n assert( ~exist('iNWindows','var') && ~exist('iIous','var'));\n \n drs=cat(3,drs,data.drs);\nend\n\nif(calcInLog)\n nWindows=log10(nWindows);\nend\n\nmaxDrs=max(drs,[],3);\nvolumes=[];\nmaxVolume=trapz(ious, trapz(nWindows, maxDrs));\nfor k=1:nResults\n assert(all(all(maxDrs>=drs(:,:,k))));\n volumes=[ volumes, trapz(ious, trapz(nWindows, drs(:,:,k)))];\nend\n\n%Worse point computation\nworsePoint=[];\nfor k=1:nResults\n worsePoint=[worsePoint, -max(max(maxDrs-drs(:,:,k)))];\nend\n\nperVolumes = volumes./((nWindows(end)-nWindows(1))*(ious(end)-ious(1)));\n\nassert(all(perVolumes)>=0 && all(perVolumes)<=1);\n\nvolumeRatios=volumes/maxVolume;\n[~, ids]=sort(volumeRatios,'descend');\n\nvolumeRatios=volumeRatios(ids);\nworsePoint=worsePoint(ids);\nperVolumes=perVolumes(ids);\nassert(issorted(flipdim(perVolumes,2)));\nfor k=1:nResults\n fName=resultDirs{ids(k)};\n if(fName(end)=='/')\n fName=fName(1:(end-1));\n end\n [~,name,~]=fileparts(fName);\n disp('############################################################################');\n disp([ 'Volume Under Surface (VUS):' num2str(perVolumes(k))]);\nend\n\n%% Display DR curve:\n\nselIou = 0.5;\nsemilogx(data.nWindows, data.drs(:, find(data.ious==selIou)), 'LineWidth', 3, 'Color', 'r');\nylim([0, 1]);\nylabel('Detection Rate');\nxlabel('Number of proposals')\naxis square;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Cloud-CV", "repo": "object-proposals", "sha": "597a89520bc1b0b261420d7627b8c36439a24c7a", "save_path": "github-repos/MATLAB/Cloud-CV-object-proposals", "path": "github-repos/MATLAB/Cloud-CV-object-proposals/object-proposals-597a89520bc1b0b261420d7627b8c36439a24c7a/randomizedPrims/rp-master/evaluation/evalVOC2007.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.24220562325537978, "lm_q1q2_score": 0.15076315026487203}} {"text": "% ----------------------------------------------------------------------------\n% function hfssAssignMaster(fid, Name, ObjName, iUStart, iUEnd, Units, \n% [ReverseV])\n% \n% Description :\n% -------------\n% Creates the necessary VB Script to assign a Master Boundary to a given Object.\n%\n% Parameters :\n% ------------\n% fid - file identifier of the HFSS script file.\n% Name - name of the master boundary (appears under 'Boundaries' in HFSS).\n% ObjName - name of the (sheet-like) object to which the master boundary is to \n% be assigned.\n% iUStart - (vector) starting point of the U vector. Specify as\n% [x, y, z].\n% iUEnd - (vector) ending point of the U vector. Specify as\n% [x, y, z].\n% Units - specify as 'meter', 'in', 'cm' (defined in HFSS).\n% [ReverseV] - (boolean, optional) reverses vector V (defaults to \n% true if the U vector points +y, and to false elsewise)\n% Example :\n% ---------\n% fid = fopen('myantenna.vbs', 'wt');\n% ... \n% hfssAssignMaster(fid, 'Master', 'Sheet', [-width/2, 0, 0], ...\n%\t [width/2, 0, 0], 'meter', false);\n%\n% ----------------------------------------------------------------------------\n\n% ----------------------------------------------------------------------------\n% CHANGELOG\n%\n% 20-May-2013: *Initial release.\n% ----------------------------------------------------------------------------\n\n% ----------------------------------------------------------------------------\n% Written by Pablo Alcon Garcia\n% pabloalcongarcia@gmail.com / palcon@tsc.uniovi.es\n% 20 May 2013\n% ----------------------------------------------------------------------------\nfunction hfssAssignMaster(fid, Name, ObjName, iUStart, iUEnd, Units, ReverseV)\n\n% arguments processor.\nif (nargin < 6)\n\terror('Insufficient # of arguments !');\nelseif (nargin < 7)\n if iUEnd(2)~=iUStart(2)\n ReverseV = true;\n else\n ReverseV = false;\n end\nend\n\nif ReverseV\n ReverseV = 'true';\nelse\n ReverseV = 'false';\nend\n\n% Preamble.\nfprintf(fid, '\\n');\nfprintf(fid, 'Set oModule = oDesign.GetModule(\"BoundarySetup\")\\n');\n\n% Parameters\nfprintf(fid, 'oModule.AssignMaster _\\n');\nfprintf(fid, 'Array(\"NAME:%s\", _\\n', Name);\nfprintf(fid, '\\t\"Objects:=\", Array(\"%s\"), _\\n', ObjName);\nfprintf(fid, '\\tArray(\"NAME:CoordSysVector\", \"Origin:=\", _\\n');\nfprintf(fid, '\\t\\tArray(\"%f%s\", \"%f%s\", \"%f%s\"), _\\n', ...\n iUStart(1), Units, iUStart(2), Units, iUStart(3), Units);\nfprintf(fid, '\\t\\t\"UPos:=\", Array(\"%f%s\", \"%f%s\", \"%f%s\") _\\n', ...\n iUEnd(1), Units, iUEnd(2), Units, iUEnd(3), Units);\nfprintf(fid, '\\t\\t), _\\n');\nfprintf(fid, '\\t\"ReverseV:=\", %s _\\n',ReverseV);\nfprintf(fid, '\\t)\\n');\n", "meta": {"author": "yuip", "repo": "hfss-api", "sha": "93ac0700830f473f1438f335a7fa964383b07abb", "save_path": "github-repos/MATLAB/yuip-hfss-api", "path": "github-repos/MATLAB/yuip-hfss-api/hfss-api-93ac0700830f473f1438f335a7fa964383b07abb/boundary/hfssAssignMaster.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.1505546802748307}}