{"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 % \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