{"text": "function organizeRFexperiments_OldMitaineWithAerts(pathWORK,pathExperimentTextures,pathRF)\n\n% IMPORTANT! CETTE FONCTION DOIT ABSOLUMENT ETRE AUTOMATISEE!!!\n\nstartpath = pwd;\n\ncd(pathWORK)\nload('clinical')\nload('subTypes')\n\n% LOADING VARIABLES\ncd(pathExperimentTextures)\nload('permTrain'), load('permTest')\ntrainText = load('training'); trainText = struct2cell(trainText); trainText = trainText{1};\ntestText = load('testing'); testText = struct2cell(testText); testText = testText{1};\nPT_loco = load('testResultsModels_PET_Locoregional'); PT_loco = struct2cell(PT_loco); PT_loco = PT_loco{1};\nCT_loco = load('testResultsModels_CT_Locoregional'); CT_loco = struct2cell(CT_loco); CT_loco = CT_loco{1};\nPT_distant = load('testResultsModels_PET_Distant'); PT_distant = struct2cell(PT_distant); PT_distant = PT_distant{1};\nCT_distant = load('testResultsModels_CT_Distant'); CT_distant = struct2cell(CT_distant); CT_distant = CT_distant{1};\nPT_death = load('testResultsModels_PET_Death'); PT_death = struct2cell(PT_death); PT_death = PT_death{1};\nCT_death = load('testResultsModels_CT_Death'); CT_death = struct2cell(CT_death); CT_death = CT_death{1};\n\n\n% ORGANIZING OUTCOMES\ntraining.outcomes.Locoregional = trainText.Locoregional.outcome;\ntraining.outcomes.Distant = trainText.Distant.outcome;\ntraining.outcomes.Death = trainText.Death.outcome;\ntesting.outcomes.Locoregional = testText.Locoregional.outcome;\ntesting.outcomes.Distant = testText.Distant.outcome;\ntesting.outcomes.Death = testText.Death.outcome;\ntraining.timeToEvents.Locoregional = trainText.Locoregional.timeToEvent;\ntraining.timeToEvents.Distant = trainText.Distant.timeToEvent;\ntraining.timeToEvents.Death = trainText.Death.timeToEvent;\ntesting.timeToEvents.Locoregional = testText.Locoregional.timeToEvent;\ntesting.timeToEvents.Distant = testText.Distant.timeToEvent;\ntesting.timeToEvents.Death = testText.Death.timeToEvent;\n\n\n% ORGANIZING CLINICAL DATA\nage_train = [clinical.HGJ.Age;clinical.CHUS.Age]; age_test = [clinical.HMR.Age;clinical.CHUM.Age];\nsubType_train = [subTypes.HGJ;subTypes.CHUS]; subType_test = [subTypes.HMR;subTypes.CHUM];\ntStage_train = [clinical.HGJ.T_stage;clinical.CHUS.T_stage]; tStage_test = [clinical.HMR.T_stage;clinical.CHUM.T_stage];\nnStage_train = [clinical.HGJ.N_stage;clinical.CHUS.N_stage]; nStage_test = [clinical.HMR.N_stage;clinical.CHUM.N_stage];\ntnmStage_train = [clinical.HGJ.TNM_stage;clinical.CHUS.TNM_stage]; tnmStage_test = [clinical.HMR.TNM_stage;clinical.CHUM.TNM_stage];\nage_train = age_train(permTrain); age_test = age_test(permTest);\nsubType_train = subType_train(permTrain); subType_test = subType_test(permTest);\ntStage_train = tStage_train(permTrain); tStage_test = tStage_test(permTest);\nnStage_train = nStage_train(permTrain); nStage_test = nStage_test(permTest);\ntnmStage_train = tnmStage_train(permTrain); tnmStage_test = tnmStage_test(permTest); \n\nAge = age_train; SubType = subType_train; T_Stage = tStage_train; N_Stage = nStage_train; TNM_Stage = tnmStage_train;\ntraining.clinical.table = table(Age,SubType,T_Stage,N_Stage,TNM_Stage);\ntraining.clinical.categories = [0,1,1,1,1];\nAge = age_test; SubType = subType_test; T_Stage = tStage_test; N_Stage = nStage_test; TNM_Stage = tnmStage_test;\ntesting.clinical.table = table(Age,SubType,T_Stage,N_Stage,TNM_Stage);\ntesting.clinical.categories = [0,1,1,1,1];\n\n\n\n% ORGANIZING TEXTURES (change names if necessary)\n\n% For Locoregional\nPET_GLV = PT_loco.trainData.data(:,1); PET_GLN = PT_loco.trainData.data(:,2); PET_LGRE = PT_loco.trainData.data(:,3);\ntraining.textures.Locoregional.PET = table(PET_GLV,PET_GLN,PET_LGRE);\nPET_GLV = PT_loco.testData.data(:,1); PET_GLN = PT_loco.testData.data(:,2); PET_LGRE = PT_loco.testData.data(:,3);\ntesting.textures.Locoregional.PET = table(PET_GLV,PET_GLN,PET_LGRE);\n\nCT_LGZE = CT_loco.trainData.data(:,1); CT_Correlation = CT_loco.trainData.data(:,2); CT_Busyness = CT_loco.trainData.data(:,3);\ntraining.textures.Locoregional.CT = table(CT_LGZE,CT_Correlation,CT_Busyness);\nCT_LGZE = CT_loco.testData.data(:,1); CT_Correlation= CT_loco.testData.data(:,2); CT_Busyness = CT_loco.testData.data(:,3);\ntesting.textures.Locoregional.CT = table(CT_LGZE,CT_Correlation,CT_Busyness);\n\nPET_GLV = PT_loco.trainData.data(:,1); PET_GLN = PT_loco.trainData.data(:,2); PET_LGRE = PT_loco.trainData.data(:,3);\nCT_LGZE = CT_loco.trainData.data(:,1); CT_Correlation = CT_loco.trainData.data(:,2); CT_Busyness = CT_loco.trainData.data(:,3);\ntraining.textures.Locoregional.PETCT = table(PET_GLV,PET_GLN,PET_LGRE,CT_LGZE,CT_Correlation,CT_Busyness);\nPET_GLV = PT_loco.testData.data(:,1); PET_GLN = PT_loco.testData.data(:,2); PET_LGRE = PT_loco.testData.data(:,3);\nCT_LGZE = CT_loco.testData.data(:,1); CT_Correlation= CT_loco.testData.data(:,2); CT_Busyness = CT_loco.testData.data(:,3);\ntesting.textures.Locoregional.PETCT = table(PET_GLV,PET_GLN,PET_LGRE,CT_LGZE,CT_Correlation,CT_Busyness);\n\n\n% For Distant\nPT_SRHGE = PT_distant.trainData.data(:,1); PT_SUVmax = PT_distant.trainData.data(:,2); PT_ZSV = PT_distant.trainData.data(:,3);\ntraining.textures.Distant.PET = table(PT_SRHGE,PT_SUVmax,PT_ZSV);\nPT_SRHGE = PT_distant.testData.data(:,1); PT_SUVmax = PT_distant.testData.data(:,2); PT_ZSV = PT_distant.testData.data(:,3);\ntesting.textures.Distant.PET = table(PT_SRHGE,PT_SUVmax,PT_ZSV);\n\nCT_LRHGE = CT_distant.trainData.data(:,1); CT_ZSV = CT_distant.trainData.data(:,2); CT_ZSN = CT_distant.trainData.data(:,3);\ntraining.textures.Distant.CT = table(CT_LRHGE,CT_ZSV,CT_ZSN);\nCT_LRHGE = CT_distant.testData.data(:,1); CT_ZSV = CT_distant.testData.data(:,2); CT_ZSN = CT_distant.testData.data(:,3);\ntesting.textures.Distant.CT = table(CT_LRHGE,CT_ZSV,CT_ZSN);\n\nPT_SRHGE = PT_distant.trainData.data(:,1); PT_SUVmax = PT_distant.trainData.data(:,2); PT_ZSV = PT_distant.trainData.data(:,3);\nCT_LRHGE = CT_distant.trainData.data(:,1); CT_ZSV = CT_distant.trainData.data(:,2); CT_ZSN = CT_distant.trainData.data(:,3);\ntraining.textures.Distant.PETCT = table(PT_SRHGE,PT_SUVmax,PT_ZSV,CT_LRHGE,CT_ZSV,CT_ZSN);\nPT_SRHGE = PT_distant.testData.data(:,1); PT_SUVmax = PT_distant.testData.data(:,2); PT_ZSV = PT_distant.testData.data(:,3);\nCT_LRHGE = CT_distant.testData.data(:,1); CT_ZSV = CT_distant.testData.data(:,2); CT_ZSN = CT_distant.testData.data(:,3);\ntesting.textures.Distant.PETCT = table(PT_SRHGE,PT_SUVmax,PT_ZSV,CT_LRHGE,CT_ZSV,CT_ZSN);\n\n\n% For Death\nPT_SZLGE = PT_death.trainData.data(:,1); PT_LGZE = PT_death.trainData.data(:,2); PT_Contrast = PT_death.trainData.data(:,3);\ntraining.textures.Death.PET = table(PT_SZLGE,PT_LGZE,PT_Contrast);\nPT_SZLGE = PT_death.testData.data(:,1); PT_LGZE = PT_death.testData.data(:,2); PT_Contrast = PT_death.testData.data(:,3);\ntesting.textures.Death.PET = table(PT_SZLGE,PT_LGZE,PT_Contrast);\n\nCT_GLN = CT_death.trainData.data(:,1); CT_SZE = CT_death.trainData.data(:,2); CT_Energy = CT_death.trainData.data(:,3);\ntraining.textures.Death.CT = table(CT_GLN,CT_SZE,CT_Energy);\nCT_GLN = CT_death.testData.data(:,1); CT_SZE = CT_death.testData.data(:,2); CT_Energy = CT_death.testData.data(:,3);\ntesting.textures.Death.CT = table(CT_GLN,CT_SZE,CT_Energy);\n\nPT_SZLGE = PT_death.trainData.data(:,1); PT_LGZE = PT_death.trainData.data(:,2); PT_Contrast = PT_death.trainData.data(:,3);\nCT_GLN = CT_death.trainData.data(:,1); CT_SZE = CT_death.trainData.data(:,2); CT_Energy = CT_death.trainData.data(:,3);\ntraining.textures.Death.PETCT = table(PT_SZLGE,PT_LGZE,PT_Contrast,CT_GLN,CT_SZE,CT_Energy);\nPT_SZLGE = PT_death.testData.data(:,1); PT_LGZE = PT_death.testData.data(:,2); PT_Contrast = PT_death.testData.data(:,3);\nCT_GLN = CT_death.testData.data(:,1); CT_SZE = CT_death.testData.data(:,2); CT_Energy = CT_death.testData.data(:,3);\ntesting.textures.Death.PETCT = table(PT_SZLGE,PT_LGZE,PT_Contrast,CT_GLN,CT_SZE,CT_Energy);\n\n\n% For Death (Aerts signature)\nPT_death = load('testResultsAerts_PET_Death'); PT_death = struct2cell(PT_death); PT_death = PT_death{1};\nCT_death = load('testResultsAerts_CT_Death'); CT_death = struct2cell(CT_death); CT_death = CT_death{1};\n\nPT_Energy = PT_death.trainData.data(:,1); PT_Compactness = PT_death.trainData.data(:,2); PT_GLN = PT_death.trainData.data(:,3); PT_GLN_HLH = PT_death.trainData.data(:,4);\ntraining.textures.DeathSign.PET = table(PT_Energy,PT_Compactness,PT_GLN,PT_GLN_HLH);\nPT_Energy = PT_death.testData.data(:,1); PT_Compactness = PT_death.testData.data(:,2); PT_GLN = PT_death.testData.data(:,3); PT_GLN_HLH = PT_death.testData.data(:,4);\ntesting.textures.DeathSign.PET = table(PT_Energy,PT_Compactness,PT_GLN,PT_GLN_HLH);\n\nCT_Energy = CT_death.trainData.data(:,1); CT_Compactness = CT_death.trainData.data(:,2); CT_GLN = CT_death.trainData.data(:,3); CT_GLN_HLH = CT_death.trainData.data(:,4);\ntraining.textures.DeathSign.CT = table(CT_Energy,CT_Compactness,CT_GLN,CT_GLN_HLH);\nCT_Energy = CT_death.testData.data(:,1); CT_Compactness = CT_death.testData.data(:,2); CT_GLN = CT_death.testData.data(:,3); CT_GLN_HLH = CT_death.testData.data(:,4);\ntesting.textures.DeathSign.CT = table(CT_Energy,CT_Compactness,CT_GLN,CT_GLN_HLH);\n\nPT_Energy = PT_death.trainData.data(:,1); PT_Compactness = PT_death.trainData.data(:,2); PT_GLN = PT_death.trainData.data(:,3); PT_GLN_HLH = PT_death.trainData.data(:,4);\nCT_Energy = CT_death.trainData.data(:,1); CT_Compactness = CT_death.trainData.data(:,2); CT_GLN = CT_death.trainData.data(:,3); CT_GLN_HLH = CT_death.trainData.data(:,4);\ntraining.textures.DeathSign.PETCT = table(PT_Energy,PT_Compactness,PT_GLN,PT_GLN_HLH,CT_Energy,CT_Compactness,CT_GLN,CT_GLN_HLH);\nPT_Energy = PT_death.testData.data(:,1); PT_Compactness = PT_death.testData.data(:,2); PT_GLN = PT_death.testData.data(:,3); PT_GLN_HLH = PT_death.testData.data(:,4);\nCT_Energy = CT_death.testData.data(:,1); CT_Compactness = CT_death.testData.data(:,2); CT_GLN = CT_death.testData.data(:,3); CT_GLN_HLH = CT_death.testData.data(:,4);\ntesting.textures.DeathSign.PETCT = table(PT_Energy,PT_Compactness,PT_GLN,PT_GLN_HLH,CT_Energy,CT_Compactness,CT_GLN,CT_GLN_HLH);\n\n% SAVING ORGANIZED DATA\ncd(pathRF)\nsave('training','training'), save('testing','testing')\nsave('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/organizeRFexperiments_OldMitaineWithAerts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.14989694276388382}}
{"text": "% SPM5 UPDATE 17/12/06\n% UPDATE 27/01/05\n% Sets the default values for the FieldMap toolbox\n%\n% FORMAT pm_defaults_Allegra_eFoV\n%_______________________________________________________________________\n%\n% This file is intended for use with the Siemens fieldmap sequence\n% on the Allegra scanner at the FIL and the new EPI sequence with\n% extended  FOV, and PE blips=-1:\n% nw_mepi_v3d_efov, nw_mepi_v3d_Amy,\n% nw_mepi_v3d_Hippoc, nw_mepi_v3d_OFC_Amy.\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Chloe Hutton and Jesper Andersson\n% $Id: pm_defaults_Allegra_eFoV.m 5015 2012-10-24 13:40:07Z guillaume $\n\nglobal pm_def;\n\n% Defaults for creating field map. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.INPUT_DATA_FORMAT = 'PM';      % 'RI' = load two real and \n                                      % imaginary image pairs\n                                      % 'PM' = load one or two\n                                      % phase and magnitude image\n                                      % pairs.\npm_def.SHORT_ECHO_TIME = 10.0;        % Short echo time in ms for Allegra\npm_def.LONG_ECHO_TIME = 12.46;        % Long echo time in ms for Allegra\npm_def.MASKBRAIN = 1;                 % Do brain masking (1 or 0,\n                      % 0 for EPI fieldmaps)\n\n% Defaults for unwrapping options. (See pm_make_fieldmap.m and \n%                                   FieldMap.man for more info.)\n%=======================================================================\npm_def.UNWRAPPING_METHOD = 'Mark3D';  % Unwrapping options are:\n                                      % 'Huttonish', 'Mark3D' or 'Mark2D'\npm_def.FWHM = 10;                     % FWHM of Gaussian filter used to \n                                      % implement weighted smoothing of\n                                      % unwrapped maps.\npm_def.PAD = 0;                       % Size of padding kernel if required.\npm_def.WS = 1;                        % Weighted or normal smoothing.\n\n% Flags for brain extraction\n%=======================================================================\npm_def.MFLAGS.TEMPLATE = fullfile(spm('Dir'),'toolbox','FieldMap','T1.nii');\npm_def.MFLAGS.FWHM = 5;     % In mm\npm_def.MFLAGS.NERODE = 2;   % In voxels\npm_def.MFLAGS.NDILATE = 4;  % In voxels\npm_def.MFLAGS.THRESH = 0.5;\npm_def.MFLAGS.REG = 0.02;   % A larger value helps segmentation to converge\npm_def.MFLAGS.GRAPHICS = 0; % A larger value helps segmentation to converge\n\n% Defaults for converting field map to voxel displacement map.\n%=======================================================================\npm_def.EPI_BASED_FIELDMAPS = 0;         % EPI=1, other=0.\npm_def.K_SPACE_TRAVERSAL_BLIP_DIR = -1; % +ve k-space = 1, -ve = -1.\npm_def.TOTAL_EPI_READOUT_TIME = 23.76;   % Allegra EPI RO time (330E-6*72)\n\n% Defaults for Unwarping.\n%=======================================================================\npm_def.DO_JACOBIAN_MODULATION = 0;    % Do jacobian modulation to adjust \n                                      % for compression or stretching\n                                      % No = 0, Yes = 1\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/FieldMap/FIL/pm_defaults_Allegra_eFoV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.28776782797747225, "lm_q1q2_score": 0.14950152240613884}}
{"text": "function blockwrite(f)\n%BLOCKWRITE  Append block to an existing file\n%   Usage: blockwrite(f);\n%\n%   Input parameters:\n%      f    : Block stream input.\n%\n%   Function appends *f* to a existing file. The file must have been\n%   explicitly defined as the 'outfile' parameter of |block| prior\n%   calling this function. If not, the function does nothing.\n%\n%   The function expect exactly the same format of *f* as is returned by\n%   |blockread|.\n%\n%   See also: block\n\n% Authors: Bjoern Ohl, Zdenek Prusa\n\ncomplainif_notenoughargs(nargin,1,'BLOCKWRITE');\n\nfilestruct = block_interface('getOutFile');\n\nif isempty(filestruct)\n   % Do nothing if the file was not setup in block.\n   return;\n   %error('%s: Output file was not specified in block function.',...\n   %      upper(mfilename));\nend\n\nfilename = filestruct.filename;\n\n\n% Reformat f if necessary\nf = comp_sigreshape_pre(f,'BLOCKPLAY',0);\n\n[L, W] = size(f);\n\nWread = filestruct.Nchan;\n\nif Wread ~= W\n    error(['%s: %s was initialized to work with %i channels but', ...\n           ' only %i provided. '],upper(mfilename),filename,Wread,W);\nend\n\n\nif W>2\n    error('%s: Cannot work with more than 2 channels.',upper(mfilename));\nend\n\n\n% prepare data depending on mono/stereo:\nif W == 2           % stereo\n  f = f.';\n  f = f(:);\nend\n\n\n% flength = dlength + 36;\n% We need to read one field from the header and\n% update two.\nfid = fopen(filename,'r+');\n\nfseek(fid,40,-1);\ndataLenInBytes = fread(fid,1,'uint32');\ndataLenInBytes = dataLenInBytes + filestruct.alignment*L;\nfileLenInBytes = dataLenInBytes + 36;\n\ntry\n    if fseek(fid,4,-1) ~= 0\n        error('d');\n    end\n    if fwrite(fid,fileLenInBytes,'uint32')<=0\n        error('d');\n    end\n\n    if fseek(fid,40,-1)~=0\n         error('d');\n    end\n    if fwrite(fid,dataLenInBytes,'uint32') <=0\n         error('d');\n    end\ncatch\n    % We have to check whether the header was modified properly.\n    error(['%s: An error has ocurred when modifying header of the ',...\n          ' wav file. The file might be unreadable. Consider',...\n          ' starting over.'],upper(mfilename));\n\nend\nfclose(fid);\n\n% And now we can append the actual data\nfid = fopen(filename,'a');\n%write data into file (amplified by 2^15 to suit int16-range (from -2^15 to +2^15):\n\nmaxval = 1-(1/2^16);\nminval = -1;\n\n% Allow clipping since it is hard to do some sensible normalization.\nf(f >= maxval)  = maxval;\nf(f <= minval)  = minval;\n\n\n% clipping check:\n%if (max(tempvec) >= maxval) || (min(tempvec) <= minval)\n    %We have no way how to find out how to properly normalize in blocks\n    %warning('Clipping! Audio data limited to [-1, +1)');\n%end\n\nfwrite(fid, f*2^15, 'int16');\nfclose(fid);    %close file\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/blockproc/blockwrite.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.29098087851200094, "lm_q1q2_score": 0.14889974718599636}}
{"text": "clear all; close all; clc\n%%\nM_dir = GetFishDirectories();\ndata_masterdir = GetNestedDataDir();\nsave_masterdir = GetCurrentDataDir();\n%%\ntiffname = 'C:\\Janelia2015\\Elavl3-H2BRFP_6dpf_MeanImageOf10Fish.tif';\ninfo = imfinfo(tiffname,'tiff');\nnPlanes = length(info);\ns1 = info(1).Height;\ns2 = info(1).Width;\nanat_stack_norm = zeros(s1,s2,nPlanes);\nfor i=1:nPlanes,\n    anat_stack_norm(:,:,i) = imread(tiffname,i);\nend\n%%\n% im = max(anat_stack_norm,[],3);\n% out=imNormalize99(im);\n% anat_yx_norm = repmat(out,[1 1 3]);\n% \n% % y-z view\n% im = squeeze(max(anat_stack_norm,[],2));\n% out=imNormalize99(im);\n% anat_yz_norm = repmat(out,[1 1 3]);\n% \n% % x-z view\n% im = squeeze(max(anat_stack_norm,[],1));\n% out=imNormalize99(im);\n% out = flipud(out'); %%%% empirically necessary...\n% anat_zx_norm = repmat(out,[1 1 3]);\n%%\nrange_fish = 2:11;\n\nfor i_fish = range_fish,\n    tic\n    disp(['i_fish = ', num2str(i_fish)]);\n   \n    data_dir = fullfile(data_masterdir,['subject_' num2str(i_fish)]);\n%     save_dir = fullfile(save_masterdir,['subject_' num2str(i_fish)]);\n    \n    load(fullfile(data_dir,'OptionalInfo.mat'));\n%     load(fullfile(save_dir,'data.mat'));\n%     absIX = data.absIX;\n%     absIX = (1:data.numcell_full)';\n    \n%     filename = fullfile(save_dir,'TimeSeries.h5');\n%     h5create(filename,'/absIX',size(absIX));\n%     h5write(filename,'/absIX',absIX);\n\n%     CellXYZ = data.CellXYZ;\n%     CellXYZ_ref = data.CellXYZ_ref;\n%     \n%     load(fullfile(save_dir,'data.mat'));\n%     \n%     data.CellXYZ = CellXYZ;\n%     data.CellXYZ_ref = CellXYZ_ref;\n    \n%%\nfilename = fullfile('C:\\Janelia2015\\norm cell coord',['F' num2str(i_fish) '_XYZ_norm.txt']);\ndelimiter = ' ';\nformatSpec = '%f%f%f%s%[^\\n\\r]';\nfileID = fopen(filename,'r');\ndataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'EmptyValue' ,NaN, 'ReturnOnError', false);\nfclose(fileID);\n\nVarName1 = dataArray{:, 1};\nVarName2 = dataArray{:, 2};\nVarName3 = dataArray{:, 3};\nFAILED = dataArray{:, 4};\n\ntemp = zeros(length(FAILED),1);\nfor i = 1:length(FAILED),\n    temp(i) = length(FAILED{i});\nend\nIX_inval_norm = find(temp~=0);\n    \nY = round(VarName1/0.798);\nX = round(VarName2/0.798);\nZ = round(VarName3/2);\nCellXYZ_norm = horzcat(X,Y,Z);\n\n    %%\n\n    save(fullfile(data_dir,'OptionalInfo.mat'),'Behavior_raw','CellXYZ_norm','IX_inval','numcell_full','IX_inval_norm');%,'anat_stack_norm'\n\n    toc\nend\n\n%%\nrange_fish = 2:11;\nfor i_fish = range_fish,\n    %% load data\n    disp(['load fish ' num2str(i_fish) '...']);\n    save_dir = fullfile(save_masterdir,['subject_' num2str(i_fish)]);\n    load(fullfile(save_dir,'data_full.mat'),'data'); % struct with many fields\n    %%\n    data_full = data;\n    names = fieldnames(data_full); % cell of strings\n    for i = 1:length(names),\n        eval([names{i} ' = data_full.' names{i} ';']);\n    end\n    \n    data_dir = fullfile(data_masterdir,['subject_' num2str(i_fish)]);\n    load(fullfile(data_dir,'OptionalInfo.mat'));\n\n    %%\n    data = [];\n    names = {'periods','timelists_names','stimuluskey_raw','CellXYZ','anat_stack','fpsec',...\n        'Behavior_raw','numcell_full','CellXYZ_norm','IX_inval_norm','IX_inval_anat',...\n        'anat_yx','anat_yz','anat_zx',...\n        'timelists','stim_full','stimAvr','Behavior_full','BehaviorAvr'};\n%         'absIX'};\n    if length(timelists_names)>1, % M_stimset(i_fish) > 1,\n        names = [names,{'stimset'}];\n    end\n    \n    for i = 1:length(names), % use loop to save variables into fields of 'data'\n        eval(['data.',names{i},'=', names{i},';']);\n    end\n    \n    save(fullfile(save_dir,'data_full.mat'),'data');\nend\n%%\nfilename = fullfile(save_dir,'TimeSeries.h5');\nfileattrib(filename,'+w');\nh5writeatt(filename,'/','absIX',absIX);\nh5disp(filename);\n\n%%\n% srcFile = fullfile(matlabroot,'toolbox','matlab','demos','example.h5');\ncopyfile(filename,'myfile.h5','f');\nfileattrib('myfile.h5','+w');\nh5writeatt('myfile.h5','/','creation_date',datestr(now));\n\nh5writeatt('myfile.h5','/','absIX',absIX(1:10));\n\n%%\nfilename = fullfile(save_dir,'TimeSeries_full.h5');\n%%\ntic\nCellResp = h5read(filename,'/CellResp');\nCellRespZ = h5read(filename,'/CellRespZ');\nCellRespAvr = h5read(filename,'/CellRespAvr');\nCellRespAvrZ = h5read(filename,'/CellRespAvrZ');\ntoc\n%%\ntic\nCellResp_ = CellResp(absIX,:);\nCellRespZ_ = CellRespZ(absIX,:);\nCellRespAvr_ = CellRespAvr(absIX,:);\nCellRespAvrZ_ = CellRespAvrZ(absIX,:);\ntoc\n\n%%\nabsIX = (1:data.numcell_full)';\n\nfilename = fullfile(save_dir,'TimeSeries_full.h5');\nh5create(filename,'/CellResp',size(CellResp),'Datatype','single','ChunkSize',[1000 100]);\nh5write(filename,'/CellResp',CellResp);\n\nh5create(filename,'/CellRespZ',size(CellRespZ),'Datatype','single','ChunkSize',[1000 100]);\nh5write(filename,'/CellRespZ',CellRespZ);\n\nh5create(filename,'/CellRespAvr',size(CellRespAvr),'Datatype','single','ChunkSize',[1000 100]);\nh5write(filename,'/CellRespAvr',CellRespAvr);\n\nh5create(filename,'/CellRespAvrZ',size(CellRespAvrZ),'Datatype','single','ChunkSize',[1000 100]);\nh5write(filename,'/CellRespAvrZ',CellRespAvrZ);\n\nh5create(filename,'/absIX',size(absIX));\nh5write(filename,'/absIX',absIX);\n\n%% need to delete 'absIX' from data_full.mat\n\n", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/old code/temp_correction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.14889974403968267}}
{"text": "function [eventLog] = ma_executeCoast_nBody_goto_soi_trans(initialState, eventNum, forceModel, soiSkipIds, massLoss, maxPropTime, events, celBodyData)\n%ma_executeCoast_nBody_goto_soi_trans Summary of this function goes here\n%   Detailed explanation goes here\n\n    eventLog = ma_executeCoast_nBody_goto_dt(maxPropTime, initialState, eventNum, forceModel, true, soiSkipIds, massLoss, maxPropTime, events, false, celBodyData);\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/ksptot_ma/propagation/nbody_coast/ma_executeCoast_nBody_goto_soi_trans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.14889476665949358}}
{"text": "function ir = compensate_headphone(ir,conf)\n%COMPENSATE_HEADPHONE applies a headphone compensation to an impulse response\n%\n%   Usage: ir = compensate_headphone(ir,conf)\n%\n%   Input parameters:\n%       ir      - Impulse response to which the compensation should be applied\n%       conf    - configuration struct (see SFS_config)\n%\n%   Output:\n%       ir      - Impulse response which is compensated for the given headphone\n%\n%   COMPENSATE_HEADPHONE(ir,conf) applies a headphone compensation to the\n%   given impulse response. Which headphone compensation it should use is\n%   mentioned in the conf struct. The compensation filter can be a one-channel\n%   (same filter for left and right) or two-channel signal (1st signal: left,\n%   2nd signal: right) with signals stored as columns in a matrix.\n%   The compensation is only applied, if the conf.ir.usehcomp value is not false.\n%\n%   See also: ir_wfs, ir_point_source, 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 = 2;\nnargmax = 2;\nnarginchk(nargmin,nargmax);\nisargmatrix(ir);\nisargstruct(conf);\n\n\n%% ===== Configuration ===================================================\nusehcomp = conf.ir.usehcomp;\n\n\n%% ===== Computation =====================================================\nif(usehcomp)\n    lenir = size(ir,1);\n    % Read headphone compensation filter\n    hcomp = audioread(conf.ir.hcompfile);\n    % Check if the IR has the right length for the filter\n    if lenir<length(hcomp)\n        warning(['The length of the used IR is shorter than the headphone ', ...\n            'compensation filter.']);\n    end\n    % Apply filter\n    ir = convolution(hcomp,ir);\n    ir = fix_length(ir,lenir);\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_binaural_synthesis/compensate_headphone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2720245628973633, "lm_q1q2_score": 0.1476721473180283}}
{"text": "function [c, r, t, cpulse, acq_codes] = tapas_physio_read_physlogfiles_philips(log_files, cardiac_modality)\n% reads out physiological time series and timing vector depending on the\n% MR scanner vendor and the modality of peripheral cardiac monitoring (ECG\n% or pulse oximetry)\n%\n%   [c, r, t, cpulse] = tapas_physio_read_physlogfiles_philips(logfile, vendor, cardiac_modality)\n%\n% IN\n%   log_files                   tapas.log_files; see also tapas_physio_new\n%           .respiratory\n%           .cardiac\n%           .sampling_interval\n%           .relative_start_acquisition\n%   cardiac_modality    \n%                       'ecg1_filtered'     filtered 1st ECG channel signal\n%                                           (Default)\n%                       'ecg2_filtered'     filteered 2nd ECG channel\n%                                           (sometimes less gradient artifacts)\n%                       'ecg1_raw'          raw 1st ECG channel\n%                       'ecg2_raw'          raw 2nd ECG channel\n%                       'OXY'/'PPU'         pulse plethysmographic unit\n%                                           (PPU) signal\n%\n%                       Note: for ECG, append '_wifi'\n%                       for adjusted sampling rate in\n%                       wireless Ingenia Scanners\n%                       \n%\n% OUT\n%   c                   cardiac time series (ECG or pulse oximetry)\n%   r                   respiratory time series\n%   t                   vector of time points (in seconds)\n%   cpulse              time events of R-wave peak in cardiac time series (seconds)\n%   acq_codes           slice/volume start events marked by number <> 0\n%                       for time points in t\n%                       10/20 = scan start/end; \n%                       1 = ECG pulse; 2 = OXY max; 4 = Resp trigger; \n%                       8 = scan volume trigger\n%\n% EXAMPLE\n%   [ons_secs.cpulse, ons_secs.rpulse, ons_secs.t, ons_secs.c] =\n%   tapas_physio_read_physlogfiles(logfile, vendor, cardiac_modality);\n%\n%   See also tapas_physio_main_create_regressors\n\n% Author: Lars Kasper\n% Created: 2013-02-16\n% Copyright (C) 2013, Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\n%% read out values\nhasCardiac  = ~isempty(log_files.cardiac);\nhasResp     = ~isempty(log_files.respiration);\n\nif hasCardiac\n    logfile = log_files.cardiac;\nelse\n    logfile = log_files.respiration;\nend\n\nif hasCardiac || hasResp\n    y = tapas_physio_read_physlogfiles_philips_matrix(logfile);\n    acq_codes   = y(:,10);\nelse\n    y = [];\n    acq_codes = [];\nend\n\nNsamples    = size(y,1);\n\ndt          = log_files.sampling_interval;\n\n%default: 500 Hz sampling frequency\nisWifi      = regexpi(cardiac_modality, '_wifi');\n\nif isWifi\n    cardiac_modality = regexprep(cardiac_modality, '_wifi', '', 'ignorecase');\nend\n\nif isempty(dt)\n    if isWifi\n        dt = 1/496;\n    else\n        dt = 2e-3;\n    end\nend\n\nt= -log_files.relative_start_acquisition + ((0:(Nsamples-1))*dt)';\n\n\n\n% column 3 = ECG, 5 = PPU, 6 = resp,\n% 10 = scanner signal: 10/20 = scan start/end; 1 = ECG pulse; 2 = OXY max; 8 = scan event TODO: what is 3 and 9???\n% columns 7,8,9: Grad-strengh x,y,z\n\ncpulse = find(acq_codes==1);\nif ~isempty(cpulse)\n    cpulse = t(cpulse);\nend;\n\nif hasResp\n    r = y(:,6);\nelse\n    r = [];\nend\n\n\nif hasCardiac\n    \n    useDefaultEcgModality = strcmpi(cardiac_modality, 'ecg');\n    \n    if useDefaultEcgModality\n        cardiacModalityArray = ...\n            {'ecg1_filtered', 'ecg2_filtered', 'ecg1_raw', 'ecg2_raw', 'ppu'};\n    else\n        cardiacModalityArray = {cardiac_modality};\n    end\n    \n    hasValidCardiacReadout = false;\n    iModality = 0;\n    \n    % cycle through modalities until non-zero cardiac column found\n    while ~hasValidCardiacReadout\n        iModality = iModality + 1;\n        cardiac_modality = cardiacModalityArray{iModality};\n        switch lower(cardiac_modality)\n            case {'ecg_raw', 'ecg1_raw'}\n                c = y(:,1);\n            case {'ecg2_raw'}\n                c = y(:,2);\n            case {'ecg1', 'ecg_filtered', 'ecg1_filtered'}\n                c = y(:,3);\n            case { 'ecg2', 'ecg2_filtered'}\n                c = y(:,4);\n            case {'oxy','oxyge', 'ppu'}\n                c = y(:,5);\n        end\n        \n        hasValidCardiacReadout = any(c);\n        \n    end\nelse\n    c = [];\n    cpulse = [];\nend\n\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/readin/tapas_physio_read_physlogfiles_philips.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.25982564369245537, "lm_q1q2_score": 0.14706613024918777}}
{"text": "function [phd_trimmed, cphd_nb, meta] = ExtractChipPhaseHistory(cphd_filename,SRP_new,img_support_size,channel)\n% EXTRACTCHIPPHASEHISTORY extracts user-specified area from phase history\n%   data = ExtractChipPhaseHistory(cphd_filename,img_offset,img_width,channel)\n%   filters the input phase history to produce a reduced size phase history\n%   that supports full resolution imaging of a user specified image chip\n%   (slant plane rectangular area of dimensions IMG_SUPPORT_SIZE centered\n%   on SRP_NEW.)\n%\n%   Separable 1-D range and 1-D azimuth processing, range first, azimuth\n%   second, because of memory constraints.\n%\n% ASSUMPTIONS:\n%   1) Assumes a spotlight collect, since it is assumed all points on the\n%   ground are equally illuminated by all pulses.\n%   2) Assumes a (nearly) monostatic collect.\n%   3) This code assumes that the full phase history might not fit into\n%   memory, but that the range trimmed phase history must be able to fit\n%   into memory.\n%   4) Also currently assumes that all pulses have common bandwidths and\n%   frequency sampling.  If this is not the case, things become messy.\n%   Azimuth filtering becomes difficult/impossible for pulses with\n%   arbitrarily different frequency content.  Furthermore, its not clear\n%   what the Fx0/F_SS of the resulting decimated pulses would be.\n%\n% INPUTS:\n%   cphd_filename    : string : input phase history file\n%   SRP_new          : [1x3]  : ECEF coordinates of new scene reference\n%                               point.\n%   img_support_size : If scalar, this is the radius of a sphere around the\n%                      SRP to extract.\n%                      If [1x2], this is the image chip extent in meters\n%                      [azimuth_extent range_extent]  (in the slant plane).\n%   channel          : scalar : Channel in the phase history file to chip.\n%                               (Default = 1).\n%\n% OUTPUTS:\n%   phd_trimmed : Phase history trimmed as requested with pulses in columns\n%   cphd_nb     : CPHD formatted per pulse narrowband data for phd_trimmed\n%   meta        : SICD-like meta structure\n%\n% Dan Hack, AFIT/ENG, 09AUG11\n% Tim Cox, NRL, 19JUL12 - Modifications to bring to CPHD \"X\" format.\n% Wade Schwartzkopf, NGA/IDT, 01DEC12 - Documentation and code clean up.\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n%%%%%%%%%%%%%%%%%%\n% Constants      %\n%%%%%%%%%%%%%%%%%%\nc = 299792458; % Speed of light (m/s)\n% Algorithm parameters\nshow_waitbar = true;\npBlockSize = 2000;\nverification_pulse = 0; % Pulse number (or set to zero for no verification plots)\n\n%%%%%%%%%%%%%%%%%%\n% Pre-processing %\n%%%%%%%%%%%%%%%%%%\n\n% Default input parameters\nif ~exist('channel','var')\n    channel = 1; % Default\nend\n% Get the narrowband data  \nreader_obj = open_ph_reader(cphd_filename);\nmeta = reader_obj.get_meta();\nN = double(meta.Data.Channel(channel).NumVectors);\nM = double(meta.Data.Channel(channel).NumSamples);  % num_samples per pulse\n[ignore, all_nb] = reader_obj.read_cphd(1:N,[],1);\nall_nb.ARP = (all_nb.TxPos + all_nb.RcvPos)/2; % Aperture reference position (nearly monostatic assumption)\n% This function assumes spotlight data.\nif isfield(meta, 'CollectionInfo') && isfield(meta.CollectionInfo, 'RadarMode') && ...\n        isfield(meta.CollectionInfo.RadarMode, 'ModeType') && ...\n        ~strcmpi(meta.CollectionInfo.RadarMode.ModeType,'SPOTLIGHT')\n    error('EXTRACTCHIPPHASEHISTORY:NON_SPOTLIGHT_DATA',...\n        'ExtractChipPhaseHistory function requires spotlight data.');\nend\n% Determine some collection parameters\n[resolution, extent, delta_azimuth, total_azimuth] = pulse_info_to_resolution_extent(...\n    all_nb.ARP([1 end],:) - all_nb.SRPPos([1 end],:), ... % Line-of-sight vector between ARP and SRP\n    max(all_nb.SC0  + (all_nb.SCSS * (M-1))),... % Highest frequency sample (which has the least azimuth extent, so most conservative)\n    max(all_nb.SCSS),... % Largest sample spacing (which has the least range extent)-- although we don't use it here\n    [],... % This parameter should be bandwidth, but we don't need it here, since we aren't using resolution.\n    N);\n\n%%%%%%%%%%%%%%%%%%%%%%%\n% 1:  Range Windowing %\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% Slice out the required range bins from each pulse.\n\n% First we determine how much range distance we need to cut out of each\n% pulse.  \nif isscalar(img_support_size) % A sphere around the SRP, the easiest.\n    image_span_distance = img_support_size;\nelseif numel(img_support_size)==2\n    % Extracting range/azimuth oriented rectangle in the slant plane of\n    % dimensions img_support_size ([azimuth, range]).\n    %\n    % In theory, since the geometry (and potentially frequency content) of\n    % each pulse varies, each pulse could require a (potentially\n    % drammatically) different set of range bins to exactly span our slant\n    % plane rectangle. For the selected range bins to cover all corners of\n    % the slant plane rectangle, including geometry and range curvature\n    % contraints, the required distance span around the SRP for a single\n    % pulse is:\n    %    image_span_distance = 2*(sqrt(...\n    %         (SRP_range*cos(theta) + (img_support_size(2)/2)).^2 + ...\n    %         (SRP_range*abs(sin(theta)) + (img_support_size(1)/2)).^2) - ...\n    %         SRP_range)\n    % where\n    %    theta is the angle of a given pulse off of the reference range\n    %       direction for which our range/azimuth slant plane rectangle is\n    %       defined.\n    %    SRP_range is the distance from the ARP to SRP.\n    %\n    % Although the above equation may be exact per pulse, this distance\n    % likely equates to a different number of range bins for each pulse,\n    % and in MATLAB we prefer to work with rectangular arrays.  So for the\n    % purposes of simplifying the computation, we pick the minimum distance\n    % that spans our slant plane rectangle for all pulses.  This is not\n    % optimum from the standpoint of the minimum amount of information\n    % required to describe the requested image area, but it is required to\n    % keep the computations tractable in MATLAB.\n    % For simplicity, we only need to evaluate the above\n    % image_span_distance equation with the pulse geometries at the ends of\n    % the collect (when the theta angle, and thus the require range, is the\n    % greatest) and with the minimum range to SRP for all pulses (since\n    % that is when range curvature is at its greatest).\n    min_SRP_range = min(sqrt(sum((all_nb.ARP - all_nb.SRPPos).^2,2)));\n    image_span_distance = 2*(sqrt(...\n        (min_SRP_range*cos(total_azimuth/2) + (img_support_size(2)/2)).^2 + ...\n        (min_SRP_range*sin(total_azimuth/2) + (img_support_size(1)/2)).^2) - ...\n        min_SRP_range);\n    % Do we need some small amount of buffer on top of this?\nelse % For other areas (or volumes), this computation would have to change.\n    error('EXTRACTCHIPPHASEHISTORY:UNRECOGNIZED_IMG_SUPPORT_SIZE',...\n        'Unrecognized IMG_SUPPORT_SIZE format.');\nend\n\n% Determine range parameters\nrange_extent = c/(2*max(all_nb.SCSS));  % range profile extent (for pulse with the least extent)\nrc_vec = fft_bin_pos_vec(M) * range_extent;  % Distance of each range bin from SRP\nrc_ndx = find(abs(rc_vec) <= image_span_distance/2);  % range extraction indices\n% These indices extract at least the range width needed to cover the\n% requested area for all pulses.\n\n% Allocate storage.  We assume this entire array of range-trimmed phase\n% history can fit into memory.\nM_new = length(rc_ndx); % Number of frequency samples after decimating\nphd_trimmed_rangeonly = zeros(M_new,N);\n\n% This is a vectorized implementation in which a block of pulses is\n% processed on each iteration.  We process in blocks because it is likely\n% that the entire untrimmed phase history cannot fit into memory.\n%\n% This loop processes all pulses in the phase history file because we\n% assume a spotlight collect where all pulses equally affect our new\n% reference point.  For non-spotlight collects, we should limit this loop\n% to only pulses for which our new reference point fall in their beam.\n% This would further reduce computation.\n\nif show_waitbar\n  wb = waitbar(0); tic\nend\n\nNumBlocks = ceil(N/pBlockSize); % Determine number of blocks.\nfor pbDx = 1:NumBlocks\n    % Calculate pulse indices for this block\n    pDx = ( ((pbDx-1)*pBlockSize+1):min(pbDx*pBlockSize,N) );\n    \n    % Read all samples from a block of pulses\n    ph = reader_obj.read_cphd(pDx, 1:M, channel);\n    \n    % Calculate differential ranges (difference of range to current SRP and\n    % range to desired SRP)\n    delR = sqrt(sum((all_nb.ARP(pDx,:).' - repmat(SRP_new(:),[1 numel(pDx)])).^2)) - ...\n           sqrt(sum((all_nb.ARP(pDx,:).' - all_nb.SRPPos(pDx,:).').^2));\n        \n    % Calculate frequency vector for each pulse: Fx0+Fx_SS*(0:M-1)\n    f_orig = bsxfun(@plus,all_nb.SC0(pDx).',(0:M-1).'*all_nb.SCSS(pDx).');\n    k_orig = 2*pi*f_orig/c;\n\n    % Adjust phase reference (re-mocomp to new scene reference point)\n    % This is currently just a linear shift based on difference in range\n    % between the old and new reference points.  This is the 99% solution.\n    % Might be some other higher-order components like tropospheric\n    % adjustment.\n    ph = ph.*exp(1i*2*bsxfun(@times,k_orig,delR));\n    \n    % Form range profile (IFFT)\n    rc = ifft(ph,[],1);\n    \n    % Apply range gate and convert back to spatial freq domain\n    phd_trimmed_rangeonly(:,pDx) = fft(rc(rc_ndx,:),[],1);\n\n    % Generate plot comparisons for data from a single pulse\n    if (verification_pulse ~= 0) && any(pDx == verification_pulse)\n        % Recompute so we are using Fx_SS of this specific pulse, not max(Fx_SS)\n        range_extent_orig = c/(2*all_nb.SCSS(verification_pulse));\n        rc_vec_orig = fft_bin_pos_vec(M) * range_extent_orig;\n        % Compute extent and range profile of trimmed pulse\n        range_extent_new = c/(2*all_nb.SCSS(verification_pulse)*M/M_new);\n        rc_vec_new = fft_bin_pos_vec(M_new) * range_extent_new;\n        rc_new = ifft(phd_trimmed_rangeonly(:,verification_pulse));\n        % Compare pre- and post- trimming\n        figure;\n        plot(fftshift(rc_vec_orig), fftshift(abs(rc(:,pDx==verification_pulse))), 'b', ...\n            fftshift(rc_vec_new), fftshift(abs(rc_new)), 'r');\n        set(gca,'xlim',[min(rc_vec) max(rc_vec)]);\n        legend({'Original' 'Windowed'});\n        xlabel('Range (m)'); ylabel('Magnitude');\n        title(['Range Profile Comparison, Pulse ' num2str(verification_pulse)]);\n    end\n    \n    if show_waitbar\n        % Determine remaining execution time and display\n        t_sofar = toc;\n        t_est = (t_sofar*NumBlocks/pbDx)-t_sofar;\n        wb_message=sprintf('Range Filtering, Time remaining: %s',datestr(datenum(0,0,0,0,0,t_est),13));\n        waitbar(pbDx/NumBlocks,wb,wb_message);\n    end\n    \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 2:  Azimuth (Doppler) Windowing %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Due to re-mocomping to new reference point in the range processing step,\n% the desired scene center is already at zero Doppler.\n%\n% Range filtering is exact.  Azimuth filtering (as implemented below) is\n% approximate:\n%\n% 1) Pulses might not have uniform angular sampling. Since the FFT (and\n% most filters) assume uniform sampling, this could be a point of concern.\n% For now we assume that spacing is \"close enough\" to uniform, and that any\n% distortions from the FFTing of non-uniform data will be somewhat undone\n% with the inverse transform.  Also when we interpolate to new ARP\n% positions later, we will retain this non-uniformity by interpolating with\n% reference to pulse number rather than time.\n% 2) Since we are filtering (at least roughly) across frequency sample\n% here, there are some \"polar formatting\" approximations going on here.\n%\n% Note that if pulses have signficantly different Fx0 and/or Fx_SS, this\n% step probably doesn't make any sense.\n\nif show_waitbar\n    waitbar(0,wb,'Azimuth Filtering');\nend\n\n% Azimuth profile vector\nac_vec = fft_bin_pos_vec(N)*extent(2); % extent(2) is azimuth extent\n\n% Azimuth extraction indices\nac_ndx = find(abs(ac_vec) <= 1.1 * img_support_size(1)/2); % 10% extra buffer since our filtering is inexact \n\n% Number of azimuth frequency samples after decimating\nN_new = length(ac_ndx);  \n\nif show_waitbar\n    waitbar(0.33,wb,'Azimuth Filtering');\nend\n\n% Azimuth compression (IFFT)\nac = ifft(phd_trimmed_rangeonly,[],2);\n\nif show_waitbar\n    waitbar(0.66,wb,'Azimuth Filtering');\nend\n\n% Window and azimuth uncompress (FFT)\nphd_trimmed = fft(ac(:,ac_ndx),[],2);\n\nif show_waitbar\n    waitbar(1,wb,'Azimuth Filtering');\n    pause(0.25);\n    close(wb);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%\n% Form pulse metadata %\n%%%%%%%%%%%%%%%%%%%%%%%\n\n% Generate output data structure.  Generic structure that reflects CPHD\n% format metadata.\n\n% Interpolate aperture reference position (ARP) -- assuming that\n% interpolating the original trajectory in time will maintain phase\n% coherency with respect to decimated pulses.\nARP_interp = interp1(1:N,all_nb.ARP,linspace(1,N,N_new),'spline');\n% Time is really irrelevant in CPHD, but we compute it anyway.\ntime_ref = (all_nb.TxTime + all_nb.RcvTime)/2; % Monostatic approximation\ntime_interp = interp1(1:N,time_ref,linspace(1,N,N_new).','spline');\n\ncphd_nb.TxTime = time_interp;\ncphd_nb.TxPos = ARP_interp;\ncphd_nb.RcvTime = time_interp;\ncphd_nb.RcvPos = ARP_interp;\ncphd_nb.SRPPos = repmat(SRP_new(:).',[N_new 1]);\n% Interpolation along Fx probably isn't valid if Fx values jitter.\ncphd_nb.SC0 = interp1(1:N,all_nb.SC0,linspace(1,N,N_new).','spline');\ncphd_nb.SCSS = interp1(1:N,all_nb.SCSS*(M/M_new),linspace(1,N,N_new).','spline');\ncphd_nb.FX1 = interp1(1:N,all_nb.FX1,linspace(1,N,N_new).','spline');\ncphd_nb.FX2 = interp1(1:N,all_nb.FX2,linspace(1,N,N_new).','spline');\n\nend\n\n% Compute a vector of the positions of the bins in an FFT'd vector.\n% Output is in normalized units (1 is Nyquist).  Need to multiply by extent\n% to convert to real units like meters (or Hz).\nfunction bin_pos_norm = fft_bin_pos_vec(Nfft)\n    bin_pos_norm = (0:(Nfft-1))/Nfft; % Normalized units (no sampling frequency used)\n    ind_to_flip = (floor((Nfft-1)/2)+2):Nfft; % These positions are 0.5 or above.  Should be negative units.\n    bin_pos_norm(ind_to_flip) = bin_pos_norm(ind_to_flip) - 1;\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Processing/IFP/ExtractChipPhaseHistory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.25091277568224823, "lm_q1q2_score": 0.14680935465601988}}
{"text": "function events = in_events_nicolet(sFile, EventFile)\n% IN_EVENTS_NICOLET: Open a text file with events exported from the Nicolet viewer.\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\n% Open and read file\nfid = fopen(EventFile,'r');\n% Markers list\nMarkers = {};\nisMarkerSection = 0;\n% Read file line by line\nwhile 1\n    % Read one line\n    newLine = fgetl(fid);\n    if ~ischar(newLine)\n        break;\n    end\n    % Lines to skip\n    if isempty(newLine)\n        continue;\n    elseif ~isempty(strfind(newLine, 'Name')) && ~isempty(strfind(newLine, 'Time')) && ~isempty(strfind(newLine, 'Duration'))\n        isMarkerSection = 1;\n        continue\n    elseif ~isempty(strfind(newLine, 'Exam Start')) || (nnz(newLine == 9) >= 2)    % Lines with tabs = events\n        isMarkerSection = 1;\n    elseif ~isMarkerSection\n        continue;\n    end\n    % Split with tabs (ASCII #9): Name, Time, Duration\n    splitLine = str_split(newLine, char(9), 0);\n    if (length(splitLine) ~= 3) || any(cellfun(@isempty, splitLine))\n        continue;\n    end\n    % Get the time and duration\n    try\n        vecStart = datevec(splitLine{2}, 'HH:MM:SS');\n        tStart = vecStart(4)*3600 + vecStart(5)*60 + vecStart(6);\n        vecDuration = datevec(splitLine{3}, 'MM:SS');\n        tDuration = vecDuration(5)*60 + vecDuration(6);\n    catch\n        continue;\n    end\n    % Add markers entry: {name, type, start, length}\n    Markers(end+1,:) = {splitLine{1}, tStart, tDuration};\nend\n% Close file\nfclose(fid);\n\n% List of events\nif isempty(Markers)\n    uniqueEvt = [];\nelse\n    uniqueEvt = unique(Markers(:,1)');\nend\n% Initialize returned structure\nevents = repmat(db_template('event'), [1, length(uniqueEvt)]);\n% Create events list\nfor iEvt = 1:length(uniqueEvt)\n    % Find all the occurrences of event #iEvt\n    iMrk = find(strcmpi(Markers(:,1)', uniqueEvt{iEvt}));\n    % Add event structure\n    events(iEvt).label   = uniqueEvt{iEvt};\n    events(iEvt).epochs  = ones(1, length(iMrk));   \n    times = [Markers{iMrk,2}];\n    if any([Markers{iMrk,3}] > 0)\n        times(2,:) = [Markers{iMrk,2}] + [Markers{iMrk,3}];\n    end\n    events(iEvt).times      = round(times .* sFile.prop.sfreq) ./ sFile.prop.sfreq;\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_nicolet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.14673305531091804}}
{"text": "function [sourcemodel, cfg] = ft_prepare_leadfield(cfg, data)\n\n% FT_PREPARE_LEADFIELD computes the forward model for many dipole locations\n% on a regular 2D or 3D sourcemodel and stores it for efficient inverse modelling\n%\n% Use as\n%   [sourcemodel] = ft_prepare_leadfield(cfg, data)\n%\n% It is necessary to input the data on which you want to perform the inverse\n% computations, since that data generally contain the gradiometer information and\n% information about the channels that should be included in the forward model\n% computation. The data structure can be either obtained from FT_PREPROCESSING,\n% FT_FREQANALYSIS or FT_TIMELOCKANALYSIS. If the data is empty, all channels will be\n% included in the forward model.\n%\n% The configuration should contain\n%   cfg.channel            = Nx1 cell-array with selection of channels (default = 'all'),\n%                            see FT_CHANNELSELECTION for details\n%\n% The positions of the sources can be specified as a regular 3-D\n% sourcemodel that is aligned with the axes of the head coordinate system\n%   cfg.xgrid      = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.ygrid      = vector (e.g. -20:1:20) or 'auto' (default = 'auto')\n%   cfg.zgrid      = vector (e.g.   0:1:20) or 'auto' (default = 'auto')\n%   cfg.resolution = number (e.g. 1 cm) for automatic sourcemodel generation\n%\n% Alternatively the position of a few sources at locations of interest can\n% be specified, for example obtained from an anatomical or functional MRI\n%   cfg.sourcemodel.pos        = N*3 matrix with position of each source\n%   cfg.sourcemodel.inside     = N*1 vector with boolean value whether sourcemodel point is inside brain (optional)\n%   cfg.sourcemodel.dim        = [Nx Ny Nz] vector with dimensions in case of 3-D sourcemodel (optional)\n%\n% The volume conduction model of the head should be specified as\n%   cfg.headmodel     = structure with volume conduction model, see FT_PREPARE_HEADMODEL\n%\n% The EEG or MEG sensor positions can be present in the data or can be specified as\n%   cfg.elec          = structure with electrode positions or filename, see FT_READ_SENS\n%   cfg.grad          = structure with gradiometer definition or filename, see FT_READ_SENS\n%\n% Optionally, you can modify the leadfields by reducing the rank (i.e. remove the\n% weakest orientation), or by normalizing each column.\n%   cfg.reducerank      = 'no', or number (default = 3 for EEG, 2 for MEG)\n%   cfg.backproject     = 'yes' or 'no',  determines when reducerank is applied whether the\n%                         lower rank leadfield is projected back onto the original linear\n%                         subspace, or not (default = 'yes')\n%   cfg.normalize       = 'yes' or 'no' (default = 'no')\n%   cfg.normalizeparam  = depth normalization parameter (default = 0.5)\n%   cfg.weight          = number or Nx1 vector, weight for each dipole position to compensate\n%                         for the size of the corresponding patch (default = 1)\n%\n% Depending on the type of headmodel, some additional options may be\n% specified.\n%\n% For OPENMEEG based headmodels:\n%   cfg.openmeeg.batchsize    = scalar (default 1e4), number of dipoles\n%                               for which the leadfield is computed in a\n%                               single call to the low-level code. Trades off\n%                               memory efficiency for speed.\n%   cfg.openmeeg.dsm          = 'no'/'yes', reuse existing DSM if provided\n%   cfg.openmeeg.keepdsm      = 'no'/'yes', option to retain DSM (no by default)\n%   cfg.openmeeg.nonadaptive  = 'no'/'yes'\n%\n% For SINGLESHELL based headmodels:\n%   cfg.singleshell.batchsize = scalar or 'all' (default 1), number of dipoles\n%                               for which the leadfield is computed in a\n%                               single call to the low-level code. Trades off\n%                               memory efficiency for speed.\n%\n% To facilitate data-handling and distributed computing you can use\n%   cfg.inputfile   =  ...\n% If you specify this option the input data will be read from a *.mat\n% file on disk. This mat files should contain only a single variable named 'data',\n% corresponding to the input structure.\n%\n% See also FT_SOURCEANALYSIS, FT_DIPOLEFITTING, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL\n\n% Undocumented local options:\n% cfg.feedback\n% cfg.sel50p      = 'no' (default) or 'yes'\n% cfg.lbex        = 'no' (default) or a number that corresponds with the radius\n% cfg.mollify     = 'no' (default) or a number that corresponds with the FWHM\n\n% Copyright (C) 2004-2013, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n%    FieldTrip is free software: you can redistribute it and/or modify\n%    it under the terms of the GNU General Public License as published by\n%    the Free Software Foundation, either version 3 of the License, or\n%    (at your option) any later version.\n%\n%    FieldTrip is distributed in the hope that it will be useful,\n%    but WITHOUT ANY WARRANTY; without even the implied warranty of\n%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n%    GNU General Public License for more details.\n%\n%    You should have received a copy of the GNU General Public License\n%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.\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% the data can be passed as input arguments or can be read from disk\nhasdata = exist('data', 'var');\n\nif ~hasdata\n  % the data variable will be passed to the prepare_headmodel function below\n  % where it would be used for channel selection\n  data = [];\nelse\n  % check if the input data is valid for this function\n  data = ft_checkdata(data);\nend\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden',  {'channels'}); % prevent accidental typos, see issue 1729\ncfg = ft_checkconfig(cfg, 'renamed',    {'hdmfile',   'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'vol',       'headmodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'grid',      'sourcemodel'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'om',        'openmeeg'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'elecfile',  'elec'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'gradfile',  'grad'});\ncfg = ft_checkconfig(cfg, 'renamed',    {'optofile',  'opto'});\ncfg = ft_checkconfig(cfg, 'deprecated', {'patchindx', 'patchsize'});\n\n% set the defaults\ncfg.lbex           = ft_getopt(cfg, 'lbex',      'no');\ncfg.sel50p         = ft_getopt(cfg, 'sel50p',    'no');\ncfg.feedback       = ft_getopt(cfg, 'feedback',  'text');\ncfg.mollify        = ft_getopt(cfg, 'mollify',   'no');\ncfg.patchsvd       = ft_getopt(cfg, 'patchsvd',  'no');\n\ncfg = ft_checkconfig(cfg, 'renamed', {'tightgrid',   'tight'});  % this is moved to cfg.sourcemodel.tight by the subsequent createsubcfg\ncfg = ft_checkconfig(cfg, 'renamed', {'sourceunits', 'unit'});   % this is moved to cfg.sourcemodel.unit by the subsequent createsubcfg\n\n% put the low-level options pertaining to the sourcemodel in their own field\ncfg = ft_checkconfig(cfg, 'createsubcfg', {'sourcemodel'});\n% move some fields from cfg.sourcemodel back to the top-level configuration\ncfg = ft_checkconfig(cfg, 'createtopcfg', {'sourcemodel'});\n\n% this code expects the inside to be represented as a logical array\ncfg.sourcemodel = ft_checkconfig(cfg.sourcemodel, 'renamed',  {'pnt' 'pos'});\ncfg = ft_checkconfig(cfg, 'inside2logical', 'yes');\n\nif strcmp(cfg.sel50p, 'yes') && strcmp(cfg.lbex, 'yes')\n  ft_error('subspace projection with either lbex or sel50p is mutually exclusive');\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% collect and preprocess the electrodes/gradiometer and head model\n[headmodel, sens, cfg] = prepare_headmodel(cfg, data);\n\n% construct the sourcemodel for which the leadfield will be computed\ntmpcfg           = keepfields(cfg, {'sourcemodel', 'mri', 'headshape', 'symmetry', 'smooth', 'threshold', 'spheremesh', 'inwardshift', 'xgrid' 'ygrid', 'zgrid', 'resolution', 'tight', 'warpmni', 'template', 'showcallinfo', 'trackcallinfo', 'trackusage', 'trackdatainfo', 'trackmeminfo', 'tracktimeinfo', 'checksize'});\ntmpcfg.headmodel = headmodel;\nif ft_senstype(sens, 'eeg')\n  tmpcfg.elec = sens;\nelseif ft_senstype(sens, 'meg')\n  tmpcfg.grad = sens;\nend\nsourcemodel = ft_prepare_sourcemodel(tmpcfg);\n\n% find the indices of all sourcemodel points that are inside the brain\ninsideindx = find(sourcemodel.inside);\n\n% check whether units are equal (NOTE: this was previously not required,\n% this check can be removed if the underlying bug is resolved. See\n% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387\nif ~isfield(headmodel, 'unit') || ~isfield(sourcemodel, 'unit') || ~isfield(sens, 'unit')\n  ft_warning('cannot determine the units of all geometric objects required for leadfield computation (headmodel, sourcemodel, sensor configuration). THIS CAN LEAD TO WRONG RESULTS! (refer to http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387)');\nelse\n  if ~strcmp(headmodel.unit, sourcemodel.unit) || ~strcmp(sourcemodel.unit, sens.unit)\n    ft_error('geometric objects (headmodel, sourcemodel, sensor configuration) are not expressed in the same units (this used to be allowed, and will be again in the future, but for now there is a bug which prevents a correct leadfield from being computed; see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2387)');\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% construct the low-level options for the leadfield computation as key-value pairs, these are passed to FT_COMPUTE_LEADFIELD\nleadfieldopt = {};\nleadfieldopt = ft_setopt(leadfieldopt, 'reducerank',     ft_getopt(cfg, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject',    ft_getopt(cfg, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize',      ft_getopt(cfg, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(cfg, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight',         ft_getopt(cfg, 'weight'));\n\nif ft_headmodeltype(headmodel, 'openmeeg')\n  \n  ft_hastoolbox('openmeeg', 1);  % add to path (if not yet on path)\n  \n  cfg.openmeeg = ft_getopt(cfg, 'openmeeg', []);\n  batchsize    = ft_getopt(cfg.openmeeg, 'batchsize', 1e4);  % number of voxels per DSM batch; set to e.g. 1000 if not much RAM available\n  keepdsm      = ft_getopt(cfg.openmeeg, 'keepdsm', 'no');   % retain DSM\n  \n  leadfieldopt = ft_setopt(leadfieldopt, 'dsm',         ft_getopt(cfg.openmeeg, 'dsm')); % reuse existing DSM if provided\n  leadfieldopt = ft_setopt(leadfieldopt, 'nonadaptive', ft_getopt(cfg.openmeeg, 'nonadaptive', 'no'));\n  \n  % repeated system calls to the openmeeg executable makes it rather slow, calling it once is much more efficient\n  fprintf('calculating leadfield for %d positions at a time, this may take a while...\\n', batchsize);\n  \n  % a dsm in the input cfg currently assumes that the 'content' of the dsm matches\n  % exactly the positions that were passed in sourcemodel.pos. This is not guaranteed\n  % of course. If anything, it would make sense to represent the dsm in the input\n  % sourcemodel, so that the pos, and dsm are bound together. Still no guarantee, but\n  % better than nothing. This means that the cfg.openmeeg.dsm option should be\n  % deprecated\n  \n  ndip       = length(insideindx);\n  numchunks  = ceil(ndip/batchsize);\n  dippos     = sourcemodel.pos(insideindx,:);\n  \n  if(numchunks > 1)\n    if istrue(keepdsm)\n      ft_warning('Keeping DSM output not supported when the computation is split into batches')\n    end\n    keepdsm = false;\n  end\n  \n  % DSM computation is computationally intensive: As it can be reused with same voxel\n  % sourcemodel (i.e. if voxels are defined in MRI coordinates rather than MEG\n  % coordinates), optionally save result. Dense voxel grids may require several\n  % gigabytes of RAM, so optionally split into smaller batches\n  dsm = ft_getopt(leadfieldopt, 'dsm');\n  if istrue(keepdsm) && ~isempty(dsm)\n    % dsm needs to be computed outside ft_compute_leadfield, because it needs to be passed on in the output\n    dsm          = ft_sysmat_openmeeg(dippos, headmodel, sens, ft_getopt(leadfieldopt, 'nonadaptive'));\n    leadfieldopt = ft_setopt(leadfieldopt, 'dsm', dsm);\n  end\n  \n  sourcemodel.leadfield = cell(size(sourcemodel.pos,1),1);\n  ft_progress('init', cfg.feedback, 'computing leadfield');\n  for k = 1:numchunks\n    ft_progress(k/numchunks, 'computing leadfield %d/%d\\n', k, numchunks);\n    diprange = (((k-1)*batchsize + 1):(min(k*batchsize,ndip)));\n    tmp      = ft_compute_leadfield(dippos(diprange,:), sens, headmodel, leadfieldopt{:});\n    % distribute the columns of the leadfield matrix over the individual dipole positions\n    % avoid using the options reducerank and backproject, see https://github.com/fieldtrip/fieldtrip/issues/1410#issuecomment-646994620\n    [m, n] = size(tmp);\n    sourcemodel.leadfield(insideindx(diprange)) = mat2cell(tmp, m, repmat(n/numel(diprange), 1, numel(diprange)));\n  end\n  ft_progress('close');\n  \n  if istrue(keepdsm)\n    % retain DSM in cfg if desired -> FIXME this should not be kept in\n    % the cfg. If anything, it is sourcemodel specific, so it should be\n    % retained in the output sourcemodel\n    cfg.openmeeg.dsm = dsm;\n  end\n  \nelseif ft_headmodeltype(headmodel, 'singleshell')\n  cfg.singleshell = ft_getopt(cfg, 'singleshell', []);\n  batchsize       = ft_getopt(cfg.singleshell, 'batchsize', 1);\n  if ischar(batchsize) && strcmp(batchsize, 'all')\n    batchsize = length(insideindx);\n  end\n  \n  dippos     = sourcemodel.pos(insideindx,:);\n  ndip       = length(insideindx);\n  numchunks  = ceil(ndip/batchsize);\n  \n  sourcemodel.leadfield = cell(size(sourcemodel.pos,1),1);\n  ft_progress('init', cfg.feedback, 'computing leadfield');\n  for k = 1:numchunks\n    ft_progress(k/numchunks, 'computing leadfield %d/%d\\n', k, numchunks);\n    diprange = (((k-1)*batchsize + 1):(min(k*batchsize,ndip)));\n    tmp      = ft_compute_leadfield(dippos(diprange,:), sens, headmodel, leadfieldopt{:});\n    % distribute the columns of the leadfield matrix over the individual dipole positions\n    % avoid using the options reducerank and backproject, see https://github.com/fieldtrip/fieldtrip/issues/1410#issuecomment-646994620\n    [m, n] = size(tmp);\n    sourcemodel.leadfield(insideindx(diprange)) = mat2cell(tmp, m, repmat(n/numel(diprange), 1, numel(diprange)));\n  end\n  ft_progress('close');\n  \nelseif ft_headmodeltype(headmodel, 'duneuro')\n%   ft_hastoolbox('duneuro', 1); %does not look necessary here? check\n  % repeated system calls to the duneuro executable makes it rather slow\n  % calling it once for all dipoles is much more efficient\n  \n  % find the indices of all grid points that are inside the brain\n  insideindx = find(sourcemodel.inside);\n  \n  ft_progress('init', cfg.feedback, 'computing leadfield');\n  % compute the leadfield on all grid positions inside the brain\n  lf = ft_compute_leadfield(sourcemodel.pos(insideindx,:), sens, headmodel, 'reducerank', cfg.reducerank, 'normalize', cfg.normalize, 'normalizeparam', cfg.normalizeparam, 'backproject', cfg.backproject);\n  lf = mat2cell(lf, size(lf,1), repmat(3,1,size(lf,2)/3));\n  sourcemodel.leadfield(sourcemodel.inside) = lf;\n  for i=1:length(insideindx)\n    thisindx = insideindx(i);\n    if isfield(cfg, 'grid') && isfield(cfg.grid, 'mom')\n      % multiply with the normalized dipole moment to get the leadfield in the desired orientation\n      sourcemodel.leadfield{thisindx} = sourcemodel.leadfield{thisindx} * sourcemodel.mom(:,thisindx);\n    end\n  end % for all grid locations inside the brain\n\nelseif ft_headmodeltype(headmodel, 'interpolate')\n\n  lf = ft_compute_leadfield(sourcemodel.pos(insideindx,:), sens, headmodel, leadfieldopt{:});\n  sourcemodel.leadfield(insideindx) = mat2cell(lf, 3, 3.*ones(1,numel(insideindx)));\n  \nelse\n  ft_progress('init', cfg.feedback, 'computing leadfield');\n  for i=1:length(insideindx)\n    % compute the leadfield on all sourcemodel positions inside the brain\n    ft_progress(i/length(insideindx), 'computing leadfield %d/%d\\n', i, length(insideindx));\n    thisindx = insideindx(i);\n    sourcemodel.leadfield{thisindx} = ft_compute_leadfield(sourcemodel.pos(thisindx,:), sens, headmodel, leadfieldopt{:});\n  end % for all sourcemodel locations inside the brain\n  ft_progress('close');\nend\n\nif isfield(cfg, 'sourcemodel') && isfield(cfg.sourcemodel, 'mom')\n  for i=1:length(insideindx)\n    % multiply with the normalized dipole moment to get the leadfield in the desired orientation\n    % FIXME mom and ori seem to be mixed up here, see https://github.com/fieldtrip/fieldtrip/issues/1399\n    thisindx = insideindx(i);\n    sourcemodel.leadfield{thisindx} = sourcemodel.leadfield{thisindx} * sourcemodel.mom(:,thisindx);\n  end\nend\n\n% represent the leadfield for positions outside the brain as empty array\nsourcemodel.leadfield(~sourcemodel.inside) = {[]};\n\n% add the label of the channels\nsourcemodel.label           = sens.label;\nsourcemodel.leadfielddimord = '{pos}_chan_ori';\n\n% mollify the leadfields\nif ~isequal(cfg.mollify, 'no')\n  sourcemodel = mollify(cfg, sourcemodel);\nend\n\n% combine leadfields in patches and do an SVD on them\nif ~isequal(cfg.patchsvd, 'no')\n  sourcemodel = patchsvd(cfg, sourcemodel);\nend\n\n% compute the 50 percent channel selection subspace projection\nif ~isequal(cfg.sel50p, 'no')\n  sourcemodel = sel50p(cfg, sourcemodel, sens);\nend\n\n% compute the local basis function expansion (LBEX) subspace projection\nif ~isequal(cfg.lbex, 'no')\n  sourcemodel = lbex(cfg, sourcemodel);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous   data\nft_postamble provenance sourcemodel\nft_postamble history    sourcemodel\nft_postamble savevar    sourcemodel\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_prepare_leadfield.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14672940092792267}}
{"text": "%function StateEditorProBeta(baseName, inputData, supressGUI, makePortable)\n% SIMPLE USAGE (NO INPUT VARIABLES, if run from dir with .xml and .eeg/lfp):\n% Add StateEditor to your Matlab path. Within Matlab navigate to a folder\n% containing '.xml' and '.eeg' (or '.lfp') files. Type in the name of this \n% .m file and press enter (StateEditor will get the relevant baseName from \n% the name of the first available '.xml' file in the folder). The StateEditor\n% loading GUI will guide you through channel selection and processing. Once \n% the TheStateEditor GUI loads, press 'H' for further information on using \n% StateEditor.\n% \n% THE '.eegstates.mat' FILE: When it first runs on a new folder\n% StateEditor creates a 'baseName.eegstates.mat' file. This file contains\n% your channel selection as well as the (whitened) spectrograms. Subsequent\n% runs on this folder will automatically load and use the selections found\n% in the '.eegstates.mat' file, substantially speeding up the loading\n% process. In order to view different channels you must first delete or\n% rename this file. Note that in order to save space StateEditor does not\n% save the lfp channels selected in the 'eegstates.mat' file unless the\n% 'makePortable' input variable is set to 1.\n% \n% SAVING AND LOADING STATE EDITOR WORK: Pressing 'S' allows you to save\n% your StateEditor work. The default output file name is:\n% 'baseName-states.mat'. By default this file contains a structure with 3\n% fields: \n%    'states' - the state vector is of length N, where N is the number\n%               of seconds\tbins in your spectrogram \n%               (N = round((length(eeg)/eegFS) - 1). It has a value between\n%               0 and 5 for each bin (0 = 'no state', 1 = 'awake', 2 = \n%               'Light/Drowzy', 3 = 'NREM', 4 = 'Intermediate', 5 = 'REM').\n%   'events' -  a N by 2 matrix where the first column are event type ID's \n%               (1 through max of 10 types) and the 2nd column are the \n%               event times in seconds (in arbitrary precision). \n%   'transitions' - a Nx3 matrix of exact state transition times. 1st \n%                   collumn: state number, 2nd collumn: state start time \n%                   (in seconds), 3rd column: \tend time (in seconds). The \n%                   transition matrix is a higher resolution complement to\n%                   the state vector for those who wish to choose their\n%                   states with a resolution greater than 1Hz. In order to \n%                   load states or events into StateEditor save a structure \n%                   formatted as specified above.\n% \n% LOADING VARIABLES DIRECTLY FROM MATLAB: The structure 'inputData' allows\n% for loading directly from existing matlab variables (NOTE: the details\n% below are only relevant to those that do not have access to .lfp/.eeg\n% files or wish to bypass the StateEditor loading GUI) It must contain the\n% following (case-sensitive) fields: \n%       'rawEeg': this is a cell array of size N where N is the number of \n%               eeg channels to load (maximum of 3). Each cell of 'rawEeg' \n%               must be a vector 1 eeg channel of length n where n is the\n%               number of samples 'Chs': 1xN matrix of channel numbers \n%               where N is the number of lfp channels to load \n%               (for instance inputData.Chs = [20, 39])\n%       'eegFS': lfp sampling frequency (default: 1250 Hz)\n%       'Chs': List of channel numbers corresponding to rawEeg\n%       'nChs': number of input channels in rawEeeg\n%       'MotionType':\n%           Must be one of the following (case-sensitive) strings:\n%           -'none'\n%           -'Whl' \n%           -'Channels (accelerometer)' \n%           -'Channels (MEG)' \n%           -'File'\n%       'motion': a 1xN vector of movement data to be displayed in the \n%           motion panel. N is the number of second bins in the spectrogram\n%           of the lfp channels and has the value: \n%               round((length(rawEeg{1}/eegFS) - 1). \n%   NOTE: to use a pre-processed motion signal, set the 'MotionType' to 'none' and\n% pass the actual motion signal in the field 'motion' as described above.\n% Conversely, if you wish to pass a motion signal to be processed (for\n% instance, accelerometer or MEG channel(s), pass these channels in through\n% the field 'MotionSignal' (which must be yxn vector or matrix (where y is\n% the number of motionsignal channels, and n is the number of samples in\n% eegFS samples/second)) and set the 'MotionType' to the desired processing\n% type.\n% \n% \n% SUPRESSING THE GUI LOADER AND THE STATE EDITOR GUI: \n% If you wish to bypass the StateEditor GUI loader use the 'inputData' \n% structure to pass StateEditor the variables: 'Chs' and 'MotionType'. If \n% applicable also  select the motion signal channels through the variable \n% 'mChs'. Note that StateEditor must still be called from the folder in \n% which the relevant '.xml' and '.eeg/.lfp' files are stored. In order to \n% suppress the StateEditor GUI, set the supressGUI variable to 1. This can \n% be useful for those wishing to pre-create the '.eegstates.mat' file as \n% part of their data pre-processing.\n%\n% Dependency: Does require LoadXml.m from XmlTree\n% http://www.artefact.tk/software/matlab/xml/\n%\n%created by Andres Grosmark at Gyuri Buzsaki's lab, 12/2012.\n%Improvements by Brendon Watson, DLevenstein\n%Many subfunctions, mostly from Anton Sirota, but also from Adrien Peyrache\n%and others have been included as subfunctions of this script to reduce\n%dependency issues.\n%\n\n\n\nfunction TheStateEditor(baseName, inputData, supressGUI, makePortable)\n\n%% get baseName if doesn't exist, save\n\nif exist('inputData', 'var');\n    if ~isempty(inputData);\n        fields = fieldnames(inputData);\n        for i = 1:length(fields)\n            eval([fields{i} ' = inputData.', fields{i}, ';']);\n        end\n    end\nend\n\nif exist('Chs', 'var') & exist('rawEeg', 'var') & exist('MotionType', 'var') & ~exist('nCh', 'var')\n    nCh = max(Chs);\nend\n\nif ~exist('eegFS', 'var')\n        eegFS = 1250;%this is dangerous, creates some problems I'll try to fix below, BW\nend\nLoadFromPortable = 0;\nif ~exist('baseName','var')\n    baseName = [];\nend\nif isempty(baseName)\n    xmlBase = dir('*xml');\n    if length(xmlBase) == 0\n%         if FileExistsIn('*.eegstates.mat')\n%             d = dir('*.eegstates.mat');\n%             StateInfo = load(d(1).name);\n%             StateInfo = StateInfo.StateInfo;\n%             \n%             if ~isfield(StateInfo, 'rawEeg')\n%                 warndlg({['Only ''.eegstates.mat'' file containing '],\n%                     ['the eeg/lfp signals can be loaded without'],\n%                     ['an ''.xml'' file present.']});\n%                 return;\n%             else\n%                 d = dir('*eegstates.mat');\n%                 baseName = d(1).name(1:(end - 14));\n%                 LoadFromPortable = 1;\n%             end\n%         else\n%             \n%             warndlg('No ''*xml'' file found. Quitting now. Bye bye.');\n%             return\n%             \n%         end\n    else\n        xmlBase = xmlBase(1);\n        choice = questdlg(['No basename entered, use ', xmlBase.name(1:(end - 4)), ' as file basename?'],'No Basename','Yes','Cancel','Yes');\n        if strmatch(choice,'Cancel')\n            return\n        elseif strmatch(choice,'Yes')\n            baseName = xmlBase.name(1:(end - 4));\n        end\n    end\nend\n\n\nif FileExistsIn([baseName, '.eegstates.mat']);\n    StateInfo = load([baseName, '.eegstates.mat']);\n    StateInfo = StateInfo.StateInfo;\n    if isfield(StateInfo, 'rawEeg')\n        LoadFromPortable = 1;\n    end\nend\nsuffix = [];\n\n\n%         if FileExistsIn('*.eegstates.mat')\n%             d = dir('*.eegstates.mat');\n%             StateInfo = load(d(1).name);\n%             StateInfo = StateInfo.StateInfo;\n%             \n%             if ~isfield(StateInfo, 'rawEeg')\n%                 warndlg({['Only ''.eegstates.mat'' file containing '],\n%                     ['the eeg/lfp signals can be loaded without'],\n%                     ['an ''.xml'' file present.']});\n%                 return;\n%             else\n%                 d = dir('*eegstates.mat');\n%                 baseName = d(1).name(1:(end - 14));\n%                 LoadFromPortable = 1;\n%             end\n%         else\n%             \n%             warndlg('No ''*xml'' file found. Quitting now. Bye bye.');\n%             return\n%             \n%         end\n\n\n\n\n\n\n\nif ~exist('supressGUI', 'var')\n    supressGUI = 0;\nend\n\nif exist('Chs', 'var') & exist('MotionType', 'var')\n    supressLoadGUI = 1;\nelse\n    supressLoadGUI = 0;\nend\n\nif ~exist('makePortable', 'var')\n    makePortable = 0;\nend\n\nif ~exist('spikeInfo', 'var')\n    spikeInfo = 0;\nend\n\n\n%These parameters are passed through all functions\nFO.downsampleGoal = 312.5;% display Hz goal, to save memory... will calculate downsample factor to match (ie 4 if 1250hz lfp file)\nFO.eegAlreadyDownsampled = 0; %will have been downsampled if saved by user as raw\nFO.baseName = baseName;  %Includes basePath\nFO.basePath = fileparts(baseName);\nif isempty(FO.basePath)\n    FO.basePath = pwd;     %basePath is assumed to be pwd... \nend\nFO.eegDisplaySeconds = 2; %show 2 seconds of eeg\nFO.maxFreq = 40; %default starting frequency extent\nFO.hanningW = 10; %default hanning smoothing window\nFO.EegUpdateBoolean = logical(0);\nFO.stateAxisToggleModeBool = logical(1);\n\n%FO.lax - handle for state label axes\n%FO.ilab - handle for state label plot\n%FO.sax{1:nCh} - handles for the spectrogram axes\n%FO.iSpec{1:nCh} - handles for the spectrogram objects\n%FO.max - handle for motion axes\n%FO.Mplot - handle for motion plot\n%FO.eax{1:nCh} - handles for eeg axes\n%FO.Eplot{1:nCh} - handles for eeg plots\n%FO.sMiddline{1:nCh} - handles for spectrogram center of view line objects\n%FO.mMidline - handle for motion center of view line object\n%FO.eMidline{1:nCh} - handle for eeg center of view line objects\n\n\n%% account for possibility that some lft files are .eeg and some are .lft\nif ~(exist('rawEeg', 'var') & exist('Chs', 'var') & exist('nCh', 'var') & exist('MotionType', 'var'))\n    if LoadFromPortable == 0\n        if FileExistsIn([baseName,'.eeg'])\n            suffix = '.eeg';\n        else\n            if FileExistsIn([baseName,'.lfp'])\n                suffix = '.lfp';\n            else\n% %                 try \n% %                     basepath = cd;\n% %                     eeglfppath = findsessioneeglfpfile(baseName,basepath);\n% %                 catch\n%                     disp(['Error: ', baseName, '.eeg or .lfp not found.'])\n%                     disp(['Quitting now. Bye bye.']);\n%                     return\n% %                 end\n            end\n        end\n        \n        if ~FileExistsIn([baseName, '.xml'])\n            disp(['Error: ', baseName, '.xml not found.'])\n            disp(['Quitting now. Bye bye.']);\n            return;\n        end\n    end\nend\n\n\n%% check for prior processing\nstates = [];\nif FileExistsIn([baseName,'.eegstates.mat'])\n    if ~exist('StateInfo','var')\n        StateInfo = load([baseName,'.eegstates.mat']);\n        StateInfo = StateInfo.StateInfo;\n    end\n    eegloaded = 0;\n\n    if isfield(StateInfo, 'rawEeg')%if made portable, take from StateInfo\n        rawEeg = StateInfo.rawEeg;\n        eegloaded = 1;\n    elseif FileExistsIn([baseName,'.RawEEG.eegstates.mat'])%if raw eeg saved by user (separate file)\n        load(fullfile(FO.basePath,[FO.baseName, '.RawEEG.eegstates.mat']))\n        %check if channels are right\n        schan = StateInfo.Chs(:);\n        echan = RawEegData.channels(:);\n        if length(echan) == length(schan)\n            if sum(abs(echan-schan)) == 0\n                rawEeg = RawEegData.data;\n                for eix = 1:length(rawEeg)\n                    rawEeg{eix} = double(rawEeg{eix});\n                end\n                eegloaded = 1;\n                FO.eegAlreadyDownsampled = 1;\n            end\n        end\n        clear RawEegData schan echan\n    end\n    \n    if ~eegloaded %load from .lfp/eeg if not loaded in above if/elseif\n        if ~exist('rawEeg', 'var')\n            rawEeg = {};\n            if isfield(StateInfo,'eegFS')\n                eegFS = StateInfo.eegFS;%this was missing and caused probs with default 1250Hz assumption if data not at 1250hz\n            else %allows compatibility with old files...\n                eegFS = 1250;\n                StateInfo.eegFS = eegFS;%...should fix them too\n            end\n            Chs = StateInfo.Chs;\n            nCh = StateInfo.nCh;\n            disp([baseName, '.eegstates.mat loaded']);\n            disp(['Using channel(s): ', int2str(Chs)]);\n            \n            disp('Retrieving eeg channel(s)...');\n            rawEeg = {};\n            eeg = [];\n            try\n                for i = 1:length(Chs)\n                    e = LoadChanArch(baseName, Chs(i));\n                    eeg = [eeg; e];\n                    e = [];\n                end\n            catch\n                disp('No eeg in your eegstates.mat. Loading from .lfp/.eeg file...');\n                try %first try bz_getLFP\n                    eeg = bz_GetLFP(Chs,'basepath',FO.basePath,'noPrompts',true);\n                    eeg = single(eeg.data)';\n                catch\n                    try\n                        % try Anton's LoadBinary\n                        eeg = LoadBinary([baseName, suffix], Chs+1, nCh, [], 'int16', 'single');\n                    catch\n                        %Otherwise try to use Micheal Zugaro\n                        eeg = LoadBinaryIn([baseName, suffix], 'channels', Chs+1, 'nChannels', nCh)';\n                        eeg = single(eeg);\n                    end\n                end\n                \n            end\n            \n            for i = 1:length(Chs)\n                rawEeg{i} = eeg(i, :);\n            end\n            disp('Done.');\n        end\n    end\n\nelse\n    StateInfo = [];\n    info1 = bz_getSessionInfo(FO.basePath,'noPrompts',true);\n    eegFS = info1.lfpSampleRate;\n\n    if ~exist('nCh', 'var')\n%             info1 = LoadXmlIn([baseName, '.xml']);\n            nCh = info1.nChannels;\n    end\n    if supressLoadGUI == 0\n        \n        global answer1\n        answer1 = 0;\n        \n        if exist([baseName '.SleepScoreLFP.LFP.mat'],'file')\n            load([baseName '.SleepScoreLFP.LFP.mat'])\n            defaultchans = ([SleepScoreLFP.SWchanID SleepScoreLFP.THchanID]);\n            if length(defaultchans)<2\n                defaultchans = num2str(defaultchans);\n            elseif length(defaultchans)>=2\n                dcout = num2str(defaultchans(1));\n                for chanidx = 2\n                    dcout = strcat(dcout,',',num2str(defaultchans(chanidx)));\n                end\n                defaultchans = dcout;\n            end\n        else\n            defaultchans = '';\n        end\n        \n        inputFig = figure('Position', [280   453   550   250], 'MenuBar', 'none', 'numbertitle', 'off', 'name', [baseName, ' channel selection']);\n        warning('off', 'MATLAB:hg:default_child_strategy:IllegalPermutation')\n        annotation('textbox',  'Position', [0.02, 0.87, 0.9, 0.07], 'string', ['\\bf\\fontsize{10}Please choose up to 3 eeg channels (base 0, nCh = ', int2str(nCh), '):'], 'EdgeColor', 'none');\n        Channels1 = uicontrol('style', 'edit', 'FontSize', 10, 'Units', 'Normalized', 'Position', [0.37, 0.75, 0.45, 0.08],'String',defaultchans);\n        set(Channels1, 'HorizontalAlignment', 'left');\n        \n        \n        annotation('textbox',  'Position', [0.02, 0.65, 0.9, 0.07], 'string', ['\\bf\\fontsize{10}Choose a motion signal to use:'], 'EdgeColor', 'none');\n        mOptions = {'.EMGFromLFP.LFP.mat';'Load From .whl file (head tracking)';'Load from eeg ch(s) (accelerometer/motion pad)';'Load from eeg ch(s) (MEG)';'Load from .mat file vector';'Load from TimeValue Pair .mat';'None'};\n        mInput = uicontrol('style', 'popupmenu', 'string', mOptions );\n        set(mInput, 'Units', 'normalized', 'Position', [0.37, 0.5, 0.62, 0.1]);\n        \n        annotation('textbox',  'Position', [0.02, 0.405, 0.9, 0.07], 'string', ['\\bf\\fontsize{10}Choose motion signal channel(s) (if applicable):'], 'EdgeColor', 'none');\n        \n        mChannels1 = uicontrol('style', 'edit', 'FontSize', 10, 'Units', 'Normalized', 'Position', [0.37, 0.295, 0.45, 0.08]);\n        set(mChannels1, 'HorizontalAlignment', 'left');\n        \n        proceed1 = uicontrol('style', 'pushbutton', 'string', 'Go!', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 1;');\n        set(proceed1, 'Units', 'normalized', 'Position', [0.4, 0.05, 0.25, 0.12], 'FontSize', 12);\n        \n        cancel1 = uicontrol('style', 'pushbutton', 'string', 'Cancel', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 0;');\n        set(cancel1, 'Units', 'normalized', 'Position', [0.7, 0.05, 0.25, 0.12], 'FontSize', 12);\n        \n        uiwait(inputFig);\n        Chs = get(Channels1, 'string');\n        mIn = mOptions{get(mInput, 'Value')};\n        mChs = get(mChannels1, 'string');\n        \n       \n        clf(inputFig);\n        close(inputFig);\n        if answer1 == 0;\n            return;\n        end\n    end\n    if ischar(Chs)\n        Chs = str2num(Chs);\n    end\n%     if exist('MotionType', 'var') & ~exist('mIn', 'var')\n%         switch MotionType\n%             case 'none'\n%                 mIn = 1;\n%             case  'Whl'\n%                 mIn = 2;\n%             case 'Channels (accelerometer)'\n%                 mIn = 3;\n%             case 'Channels (MEG)'\n%                 mIn = 4';\n%             case 'File'\n%                 mIn = 5;\n%         end\n%     end\n    \n    \n    if ~iscell(Chs)\n        if sum(Chs >= 0 & Chs <= nCh) ~= length(Chs) | isempty(Chs)\n            b = msgbox('Error: Incorrect channel selection. Quiting now. Bye bye.');\n            uiwait(b);\n            return;\n        end\n    end\n    \n    \n    if ~exist('rawEeg', 'var')\n        weeg = {};\n        fspec = {};\n        \n        disp(['Loading eeg channels: ', int2str(Chs)]);\n        try %first try bz_getLFP\n            eeg1 = bz_GetLFP(Chs,'basepath',FO.basePath,'noPrompts',true);\n            eeg1 = single(eeg1.data)';\n        catch\n            try\n                % try Anton's LoadBinary\n                eeg1 = LoadBinary([baseName, suffix], Chs+1, nCh, [], 'int16', 'single');\n            catch\n                %Otherwise try to use Micheal Zugaro\n                eeg1 = LoadBinaryIn([baseName, suffix], 'channels', Chs+1, 'nChannels', nCh)';\n                eeg1 = single(eeg1);\n            end\n        end\n        disp('Done.');\n        for i = 1:length(Chs)\n            \n            rawEeg{i} =eeg1(i, :);\n            if iscell(Chs)\n                disp(['Whitening and computing spectrogram for channel ', Chs{i},'. This will all be over in a minute.']);\n            else\n                disp(['Whitening and computing spectrogram for channel ', int2str(Chs(i)),'. This will all be over in a minute.']);\n            end\n            try\n                fspec{i} = LoadSpecArch(baseName, [], Chs(i), 1, 0, 3072, [0 200], 1, []);\n            catch\n                fspec{i} =[];\n                \n                weeg{i} =  WhitenSignalIn(rawEeg{i},eegFS*2000,1);\n                [fspec{i}.spec, fspec{i}.fo, fspec{i}.to] = mtchglongIn(weeg{i}, 3072, eegFS, eegFS, 0, [], [], [], [0 200]);\n                fspec{i}.spec = single(fspec{i}.spec);\n                fspec{i}.info.Ch = Chs(i);\n                fspec{i}.info.FileInfo.name = [baseName, suffix];\n            end\n            disp('Done.');\n            \n        end\n    else\n        for i = 1:length(Chs)\n            \n            \n            if iscell(Chs)\n                disp(['Whitening and computing spectrogram for channel ', Chs{i}, '. This will all be over in a minute.']);\n            else\n                 disp(['Whitening and computing spectrogram for channel ', int2str(Chs(i)),'. This will all be over in a minute.']);\n            end\n            try\n                fspec{i} = LoadSpecArch(baseName, [], Chs(i), 1, 0, 3072, [0 200], 1, []);\n            catch\n                fspec{i} =[];\n                weeg{i} =  WhitenSignalIn(rawEeg{i}, eegFS*2000,1);\n                [fspec{i}.spec, fspec{i}.fo, fspec{i}.to] = mtchglongIn(weeg{i}, 3072, eegFS, eegFS, 0, [], [], [], [0 200]);\n                fspec{i}.spec = single(fspec{i}.spec);\n                fspec{i}.info.Ch = Chs(i);\n                fspec{i}.info.FileInfo.name = [baseName, suffix];\n            end\n            disp('Done.');\n            \n        end\n        \n    end\n    \n    \n    if ~exist('mChs', 'var')\n        mChs = [];\n    end\n    \n    if ~exist('motion', 'var')\n        if ~isempty(mChs) & ischar(mChs)\n            mChs = str2num(mChs);\n        end\n        \n        \n        if strcmp(mIn,'Load from eeg ch(s) (accelerometer/motion pad)')\n        %         if mIn == 3\n            if ischar(mChs)\n                mChs  = str2num(mChs);\n            end\n            if (sum(mChs > 0 & mChs <= nCh) ~= length(mChs)) | isempty(mChs)\n                b = msgbox('Error: Incorrect motion channel selection. Quiting now. Bye bye.');\n                uiwait(b);\n                return;\n            end\n        end\n       \n        \n        MotionType = [];\n        switch(mIn)\n            case '.EMGFromLFP.LFP.mat'\n                motion = [];\n                MotionType = 'EMGFromLFP';\n                if exist([baseName,'.EMGFromLFP.LFP.mat'],'file')\n                    tpath = [baseName,'.EMGFromLFP.LFP.mat'];\n                else\n                    [name, path] = uigetfile('*.mat', 'EMG: Choose a file with time:val pairs:');\n                    tpath = fullfile(path,name);\n                end\n                load(tpath)%should now have the EMG variable with fields \n                \n                tos = fspec{1}.to;\n                times = EMGFromLFP.timestamps;\n                vals = EMGFromLFP.data;\n                motion = ResampleTolerant_IN(vals,length(tos),length(times));\n            case 'None'\n                motion = [];\n                MotionType = 'none';\n            case 'Load From .whl file (head tracking)'\n                disp('Loading and preprocessing motion data from .whl file...');\n                motion = LoadFromWhl(baseName, fspec{1}.to);\n                if sum(isnan(motion)) ~= 0\n                    disp(['Note that ', num2str(mean(isnan(motion))*100), '% of the motion values are NaNs']);\n                    disp('Proceeding...');\n                end\n                MotionType = 'Whl';\n                mChs = [];\n                disp('Done.');\n            case 'Load from eeg ch(s) (accelerometer/motion pad)'\n                disp(['Loading and preprocessing motion data from channel(s) ', int2str(mChs), '...']);\n                if exist('motionSignal', 'var')\n                    meeg = motionSignal;\n                else\n                    try\n                        %First try Anton's LoadBinary\n                        meeg = LoadBinary([baseName, suffix], mChs+1, nCh, [], 'int16', 'single');\n                    catch\n                        %Otherwise try to use Micheal Zugaro\n                        meeg = LoadBinaryIn([baseName, suffix], 'channels', mChs+1, 'nChannels', nCh)';\n                        meeg = single(meeg);\n                    end\n                end\n                meeg = abs(zscore(meeg')');\n                meeg = sum(meeg, 1);\n                forder = 500;\n                forder = ceil(forder/2)*2;\n                EEGSR = eegFS;\n                lowband = 0.1;\n                highband = 1;\n                firfiltb = fir1(forder,[lowband/EEGSR*2,highband/EEGSR*2]);\n                meeg = filter2(firfiltb,  meeg);\n                motion = mean(reshape(meeg(1:(length(meeg) - mod(length(meeg), eegFS))), eegFS, []), 1);\n                if length(motion) == (length(fspec{1}.to) + 1)\n                    motion = motion(1:(end - 1));\n                end\n                MotionType = 'Channels (accelerometer)';\n                disp('Done.');\n            case 'Load from eeg ch(s) (MEG)'\n                disp(['Loading and preprocessing meg data from channel(s) ', int2str(mChs), '...']);\n                if exist('motionSignal', 'var')\n                    meeg = motionSignal;\n                else\n                    try\n                        %First try Anton's LoadBinary\n                        meeg = LoadBinary([baseName, suffix], mChs+1, nCh, [], 'int16', 'single');\n                    catch\n                        %Otherwise try to use Micheal Zugaro\n                        meeg = LoadBinaryIn([baseName, suffix], 'channels', mChs+1, 'nChannels', nCh)';\n                        meeg = single(meeg);\n                    end\n                end\n                meeg = zscore(meeg')';\n                meeg = sum(meeg, 1);\n                forder = 500;\n                forder = ceil(forder/2)*2;\n                EEGSR = eegFS;\n                lowband = 100;\n                highband = 600;\n                firfiltb = fir1(forder,[lowband/EEGSR*2,highband/EEGSR*2]);\n                meeg = filter2(firfiltb,  meeg);\n                meeg = zscore(meeg).^2;\n                lowband = 0.1;\n                highband = 1;\n                firfiltb = fir1(forder,[lowband/EEGSR*2,highband/EEGSR*2]);\n                meeg = filter2(firfiltb,  meeg);\n                motion = mean(reshape(meeg(1:(length(meeg) - mod(length(meeg), eegFS))), eegFS, []), 1);\n                if length(motion) == (length(fspec{1}.to) + 1)\n                    motion = motion(1:(end - 1));\n                end\n                MotionType = 'Channels (MEG)';\n                disp('Done.');\n                \n            case 'Load from TimeValue Pair .mat'\n                MotionType = 'TimeVal';\n                varname = [];\n%                 b = msgbox(['Note: Motion vector must be 1xn where n is the number of time bins in seconds (n = ', int2str(length(fspec{1}.to)), ')']);\n%                 uiwait(b);\n                [name, path] = uigetfile('*.mat', 'Choose a file with time:val pairs:');\n                matobj = matfile(fullfile(path,name));\n                w = whos(matobj);\n                if length(w)>1\n                    for a = 1:length(w)\n                        n{a} = w(a).name;\n                    end\n                    varname = listdlg('ListString',n,'SelectionMode','Single','Name','Variable choice','PromptString','Choose variable to load');\n                    varname = n{varname};\n                end\n                \n                tos = fspec{1}.to;\n                if isempty(varname);\n                    motion = LoadTimeStampValuePairs(tos,fullfile(path,name));\n                else\n                    motion = LoadTimeStampValuePairs(tos,fullfile(path,name),varname);\n                end\n                \n            case 'Load from .mat file vector'\n                MotionType = 'File';\n                b = msgbox(['Note: Motion vector must be 1xn where n is the number of time bins in seconds (n = ', int2str(length(fspec{1}.to)), ')']);\n                uiwait(b);\n                [name, path] = uigetfile('*mat', 'Choose a motion vector to load:');\n                motion = load([path, name]);\n                if isstruct(motion)\n                    f1 = fieldnames(motion);\n                    motion = motion.(f1{1});\n                end                    \n                \n                mChs = name;\n        end\n        \n    end\n    if ~exist('nCh', 'var')\n        nCh = length(Chs);\n    end\n    StateInfo.nCh = nCh;\n    StateInfo.Chs = Chs;\n    StateInfo.mChs = mChs;\n    StateInfo.MotionType = MotionType;\n    StateInfo.fspec = fspec;\n    StateInfo.motion = motion;\n    StateInfo.eegFS = eegFS;\n%     if makePortable == 1\n%         StateInfo.rawEeg = rawEeg;\n%     end\n    \n    disp(['Saving ', baseName, '.eegstates.mat...']);\n    try\n        save([baseName, '.eegstates.mat'], 'StateInfo');\n    catch\n        warndlg(['Failed to save ' , baseName, '.eegstates.mat']);\n    end\nend\n\n%Load Previous state tagging in SleepState.states.mat\nthispath = FO.basePath;\ntimevector = StateInfo.fspec{1}.to;\nstates = bz_LoadStates_StateEditorWrapper_In(thispath,timevector);\n\nif eegFS>FO.downsampleGoal\n    FO.downsample = round(eegFS/FO.downsampleGoal);\nelse\n    FO.downsample = 1;\nend\n\ndisp('So far so good. Now, loading StateEditor GUI. This is going to be great!');\n\nif supressGUI == 1\n    return;\nelse\n    StateEditorSetup(StateInfo.fspec, StateInfo.motion, states, rawEeg, FO, eegFS);\nend\n% \n% if exist([baseName,'-states.mat'],'file')\n%     LoadStatesAutoNoMsgs\n% end\n\n\nend\n\n\nfunction StateEditorSetup(f, MP, States, rawEeg, FO, eegFS)\n\nif ~iscell(f)\n    a = f; e = rawEeg;\n    f = {}; rawEeg = {};\n    f{1} = a; rawEeg{1} = e;\n    a = []; e =[];\nend\nnCh = length(f);\nFO.nCh = nCh;\n\nChs =[];\nfor i = 1:length(f)\n    Chs = [Chs; f{i}.info.Ch];\nend\nFO.Chs = Chs;\n\nif isempty(States)\n    States = zeros(1, length(f{1}.to));\nend\n\nfor i = 1:nCh\n    if FO.eegAlreadyDownsampled\n        FO.eeg{i} = rawEeg{i};\n    else\n        FO.eeg{i} = rawEeg{i}(1:FO.downsample:end);\n    %     FO.eeg{i} = (eeg{i}(1:FO.downsample:end)/2150)/1000;%why was this division?? To convert to volts in some old system?  \n    end\nend\n\nFO.clickPoint = [];\nFO.startLine = {};\nFO.States = States;\nFO.stateHistory = {};\nFO.stateHistoryNum = 0;\nFO.newStates = {};\nFO.currAction = 'Browse';\nFO.eegFS = eegFS;\n\n\nFO.overlayLines = {};\n\nposvar = get(0,'Screensize');\nposvar(1) = 20;\nposvar(2) = 20;\nposvar(3) = posvar(3)-100;\nposvar(4) = posvar(4)-100;\nFO.fig = figure('KeyReleaseFcn', {@DefKey}, 'Position', posvar);\nset(FO.fig, 'numbertitle', 'off', 'name', ['States: ', FO.baseName]);\nset(FO.fig,'WindowButtonDownFcn', {@MouseClick}, 'WindowButtonUpFcn', {@unMouseClick}, 'Units', 'normalized');\nset(FO.fig, 'WindowButtonMotionFcn', {@Nothing}, 'WindowScrollWheelFcn', {@MouseScroll});\nset(FO.fig, 'CloseRequestFcn', {@CloseDialog});\nset(FO.fig, 'Tag', 'StateEditorMaster');\nFO.madeChanges = 0;\nFO.startLocation = [];\n\n%%%%%%%%%%%%%%Axes Positions%%%%%%%%%%%%%%%%%%\npositions = [];\nswitch nCh\n    case 1\n        position.lax = [0.0500    0.940    0.8000    0.0500];\n        position.sax{1} = [0.0500    0.3100    0.8000    0.6200];\n        position.MP = [0.0500    0.170    0.8000    0.1000];\n        position.eax{1} = [0.0500    0.04    0.8000    0.1000];\n        position.eegCh{1} =   [0.8100    0.0350    0.1000    0.1000];\n        \n        a = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        if iscell(FO.Chs)\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch ', FO.Chs{1}], 'Position', [-0.0050    0.7800    0.1000    0.1000]);\n        else\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(1))], 'Position', [-0.0050    0.7800    0.1000    0.1000]);\n        end\n%         annotation('textarrow',[0.02 0.02],[0.14 0.14],'string','\\fontsize{10} EEG (m.V.)', ...\n%             'HeadStyle','none','LineStyle', 'none', 'TextRotation',90);\n        \n        position.eegWidth = [0.05, 0.0350, 0.1, 0.1];\n    case 2\n        position.lax = [0.0500    0.940    0.8000    0.0500];\n        position.sax{1} = [0.05         0.62          0.8         0.31];\n        position.sax{2} = [0.05         0.3          0.8         0.31];\n        position.MP = [0.05         0.195          0.8          0.07];\n        position.eax{1} =  [0.05         0.105         0.8          0.06];\n        position.eax{2} =  [0.05         0.04          0.8          0.06];\n        position.eegCh{1} =    [0.81, 0.069, 0.1, 0.1];\n        position.eegCh{2} = [0.81, 0.004, 0.1, 0.1];\n        position.eegWidth = [0.05, 0.069, 0.1, 0.1];\n        a = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        if iscell(FO.Chs)\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch ', FO.Chs{1}], 'Position', [-0.005, 0.79, 0.1, 0.1]);\n        else\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(1))], 'Position', [-0.005, 0.79, 0.1, 0.1]);\n        end\n        \n        a = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        \n        if iscell(FO.Chs)\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', FO.Chs{2}], 'Position', [-0.005, 0.49, 0.1, 0.1]);\n        else\n            set(a, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(2))], 'Position', [-0.005, 0.49, 0.1, 0.1]);\n        end\n        annotation('textarrow',[0.02 0.02],[0.14 0.14],'string','\\fontsize{10} EEG (m.V.)', ...\n            'HeadStyle','none','LineStyle', 'none', 'TextRotation',90);\n    case 3\n        position.lax = [0.0500    0.945    0.8000    0.0475];\n        position.sax{1} = [0.0500    0.730    0.8000    0.21];\n        position.sax{2} = [0.0500    0.515    0.8000    0.21];\n        position.sax{3} = [0.0500    0.3100    0.8000    0.20];\n        position.MP = [0.05        0.23          0.8         0.07];\n        position.eax{1} = [0.05         0.15          0.8          0.05];\n        position.eax{2} = [0.05         0.095          0.8          0.05];\n        position.eax{3} = [0.05         0.04          0.8          0.05];\n        position.eegWidth = [0.05, 0.105, 0.1, 0.1];\n        \n        position.eegCh{1} =   [0.8100    0.095    0.1000    0.1000];\n        position.eegCh{2} = [0.8100    0.0400    0.100    0.1000];\n        position.eegCh{3} = [0.8100    -0.015    0.1000    0.1000];\n        a1 = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        a2 = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        a3 = annotation('textbox', 'Units', 'Normalized', 'EdgeColor', 'none');\n        \n        if iscell(FO.Chs)\n            set(a1, 'String', ['\\bf\\color{black}\\fontsize{11}Ch',FO.Chs{1}], 'Position', [-0.0050    0.8200    0.1000    0.1000]);\n            set(a2, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', FO.Chs{2}], 'Position', [-0.0050    0.6150    0.1000    0.1000]);\n            set(a3, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', FO.Chs{3}], 'Position', [-0.0050    0.410    0.1000    0.1000]);\n        else\n            set(a1, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(1))], 'Position', [-0.0050    0.8200    0.1000    0.1000]);\n            set(a2, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(2))], 'Position', [-0.0050    0.6150    0.1000    0.1000]);\n            set(a3, 'String', ['\\bf\\color{black}\\fontsize{11}Ch', int2str(FO.Chs(3))], 'Position', [-0.0050    0.410    0.1000    0.1000]);\n        end\n        %         annotation('textarrow',[0.02 0.02],[0.14 0.14],'string','\\fontsize{10} EEG (m.V.)', ...\n        %             'HeadStyle','none','LineStyle', 'none', 'TextRotation',90);\nend\nFO.xplotLims = [0.0500, 0.85];\n\nyplotLims = [];\nyplotLFPLims = [];\nfor i = 1:FO.nCh\n    yplotLims = [yplotLims; position.sax{i}(2), position.sax{i}(2) + position.sax{i}(4)];\n    yplotLFPLims = [yplotLFPLims; position.eax{i}(2), position.eax{i}(2) + position.eegCh{i}(4)];\n    \nend\nyplotLims = [yplotLims; position.lax(2), position.lax(2) + position.lax(4)];\nyplotLims = [yplotLims; position.MP(2), position.MP(2) + position.MP(4)];\nFO.yplotLims = yplotLims;\nFO.yplotLFPLims = [yplotLFPLims];\n\ncolors = {};\nFO.resolution = 0.5;\nf1 = round(sum(f{1}.fo >= 2 & f{1}.fo <= 4)/(2./FO.resolution));\nspec = {};\nfor I = 1:FO.nCh\n    fo = [];\n    s = [];\n    for i = 1:f1:(size(f{I}.spec, 2) - f1)\n        s = [s, mean(f{I}.spec(:, i:(i + f1 - 1), :), 2)];\n        fo = [fo; mean(f{I}.fo(i:(i + f1 - 1)))];\n    end\n    spec{I} = s;\nend\n\nfor i = 1:length(f)\n    n = prctile(reshape(f{i}.spec, 1, []), [1, 99]);\n    f{i}.spec(f{i}.spec < n(1)) = n(1);\n    f{i}.spec(f{i}.spec > n(2)) = n(2);\nend\n\nFO.unsmoothedSpec = spec;\nFO.originalFO = f{1}.fo;\n\n\nfor i = 1:nCh\n    FO.spec{i} = log10(convWithIn(spec{i}, hanning(FO.hanningW)));\nend\n\n\nFO.fo = fo;\nFO.to = f{1}.to;\nFO.lims = [min(FO.to), max(FO.to)];\n\nif nCh > 1\n    min1 = min(min(FO.spec{1}(:, FO.fo <= FO.maxFreq)));\n    max1 = max(max(FO.spec{1}(:, FO.fo <= FO.maxFreq)));\n    for i = 2:nCh\n        min2 = min(min(FO.spec{i}(:, FO.fo <= FO.maxFreq)));\n        FO.spec{i} = FO.spec{i} - min2;\n        max2 = max(max(FO.spec{i}(:, FO.fo <= FO.maxFreq)));\n        FO.spec{i} = FO.spec{i}./max2;\n        FO.spec{i} = FO.spec{i}.*(max1 - min1);\n        FO.spec{i} = FO.spec{i} + min1;\n    end\nend\n\ncolors.states{1} = reshape([0, 0, 0], [1, 1, 3])/255;%black/wake\ncolors.states{2} = reshape([255, 236, 79], [1, 1, 3])/255;%yellow/drowzy\ncolors.states{3} = reshape([6, 113, 148], [1, 1, 3])/255;%blue/NREM\ncolors.states{4} = reshape([19, 166, 50], [1, 1, 3])/255;%green/Intermediate\ncolors.states{5} = reshape([207, 46, 49], [1, 1, 3])/255;%red/REM\n\ncolors.white = reshape([1, 1, 1], [1, 1, 3]);\ncolors.grey = reshape([206, 206, 206], [1, 1, 3])/255;\ncolors.orange = reshape([238, 113, 25], [1, 1, 3])/255;\nFO.colors = colors;\n\nrows{1} = 1;\nrows{2} = 2;\nrows{3} = 3;\nrows{4} = 4;\nrows{5} = 5;\n\nFO.rows = rows;\nFO.SM = ones(length(rows), length(States), 3); %SM holds the color matrix for the states plot\n\n\nfor I = 1:5 %sets up the states plot\n    f = find(States == I);\n    FO.SM(rows{I}, f, :) = repmat(colors.states{I}, [1, length(f), 1]);\nend\n\n\n\n\nFO.lax = axes('Position', position.lax);\n\nFO.ilab = image(FO.to, 1:(size(FO.SM, 1)), FO.SM);\nylabel('State');\nset(FO.ilab, 'HitTest', 'off');\nset(FO.lax, 'YTick', [1, 2, 3, 4, 5], 'YTickLabel', (1:5), 'XTick', []);\nFO.zoomL = zoom;\nsetAxesZoomMotion(FO.zoomL, FO.lax, 'horizontal');\n\nFO.panL = pan;\nsetAxesPanMotion(FO.panL, FO.lax, 'horizontal');\n\n\n\n\nfor i = 1:nCh\n    FO.sax{i} = axes('Position', position.sax{i});\n    FO.iSpec{i} = imagesc(FO.to, FO.fo(FO.fo <= FO.maxFreq), FO.spec{i}(:, FO.fo <= FO.maxFreq)');\n    colormap('jet');\n    ylabel('Freq. (Hz)');\n    set(FO.iSpec{i}, 'HitTest', 'off');\n    set(FO.sax{i}, 'YDir', 'normal');\n    FO.zoomS = zoom;\n    setAxesZoomMotion(FO.zoomS, FO.sax{i}, 'horizontal');\n    set(FO.zoomS, 'ActionPostCallback', {@ZoomButton});\n    %set(FO.zoomS, 'Enable', 'on');\n    FO.panS = pan;\n    setAxesPanMotion(FO.panS, FO.sax{i}, 'horizontal');\n    \n    hold on;\n    p = get(FO.sax{i}, 'Position');\n    %    FO.sMidline{i} = annotation('line', [p(1) + p(3)/2, p(1) + p(3)/2], [p(2), p(2) + p(4)], 'LineStyle', '--', 'Color', 'w');\n    FO.sMidline{i} = annotation('line', [0, 0], [p(2), p(2) + p(4)], 'LineStyle', '--', 'Color', 'w');\n    set(FO.sMidline{i}, 'Position', [p(1) + p(3)/2, p(2), 0, p(4)]);\n    \n%     if i ~= nCh\n        set(FO.sax{i}, 'XTick', [],'xticklabels',[]);\n%     end\n%     if i == 3\n%         set(FO.sax{i}, 'XTick', [],'xticklabels',[]);\n%     end\nend\n\n\n\nMP(~isnan(MP)) = zscore(MP(~isnan(MP)));\nFO.max = axes('Position', position.MP);\nif ~isempty(MP)\n    FO.Mplot = plot(FO.to, MP, '-k');\n    ylabel('Motion (z.s.)');\n    set(FO.Mplot, 'HitTest', 'off');\n    ylim([prctile(MP(~isnan(MP)), 1), prctile(MP(~isnan(MP)), 99)]);\n    FO.zoomM = zoom;\n    setAxesZoomMotion(FO.zoomM, FO.max, 'horizontal');\n    FO.panM = pan;\n    setAxesPanMotion(FO.panM, FO.max, 'horizontal');\n    yl = get(FO.max, 'YLim');\n    xl = get(FO.max, 'XLim');\n    \nend\n\n\n\np = get(FO.max, 'Position');\nFO.mMidline = annotation('line', [p(1) + p(3)/2, p(1) + p(3)/2], [p(2), p(2) + p(4)], 'LineStyle', '--', 'Color', 'k');\n\n\nfor i = 1:nCh\n    eegX = (1:length(FO.eeg{i}))/(FO.eegFS/FO.downsample);\n    FO.eax{i} = axes('Position', position.eax{i});\n    \n    FO.Eplot{i} = plot(eegX(eegX >= 0 & eegX <= 120), FO.eeg{i}(eegX >= 0 & eegX <= 120), 'y');\n    set(FO.eax{i}, 'Color', [0 0 0], 'XColor', 'b');\n    %   FO.Eplot{i} = plot(eegX, FO.eeg{i});\n    ylabel('Eeg');\n    l1 = [min(get(FO.Eplot{i}, 'YData')), max(get(FO.Eplot{i}, 'YData'))];\n    ylim(l1);\n    FO.zoomE = zoom;\n    setAxesZoomMotion(FO.zoomE, FO.eax{i}, 'horizontal');\n    FO.panE = pan;\n    setAxesPanMotion(FO.panE, FO.eax{i}, 'horizontal');\n    p = get(FO.eax{i}, 'Position');\n    FO.eMidline{i} = annotation('line', [p(1) + p(3)/2, p(1) + p(3)/2], [p(2), p(2) + p(4)], 'LineStyle', '--', 'Color', 'w');\n    FO.lineParent = get(FO.eMidline{i}, 'Parent');\n    %set(FO.lineParent, 'HandleVisibility', 'on');\n    if i ~= nCh\n        set(FO.eax{i}, 'XTickLabel', []);\n    end\n    \n    if ~FO.EegUpdateBoolean\n        set(FO.Eplot{i}, 'XData', [], 'YData', []);\n    end\nend\n\nswitch nCh\n    case 1\n        linkaxes([FO.lax, FO.sax{1}, FO.max, FO.lax], 'x');\n    case 2\n        linkaxes([FO.sax{1}, FO.sax{2}, FO.max, FO.lax], 'x');\n        linkaxes([FO.eax{1}, FO.eax{2}], 'x');\n    case 3\n        linkaxes([FO.sax{1}, FO.sax{2}, FO.sax{3}, FO.max, FO.lax], 'x');\n        linkaxes([FO.eax{1}, FO.eax{2}, FO.eax{3}], 'x');\nend\n\n\n\n%%%%% Right panel display/buttons\n\n%Toggle for selectable states\nFO.stateAxisActiveCheckbox = uicontrol('style', 'checkbox', 'String', 'Clickable State Display',...\n    'value',FO.stateAxisToggleModeBool ,'Units', 'normalized', 'Position',  [0.855, 0.965, 0.1, 0.02]);\nset(FO.stateAxisActiveCheckbox, 'Callback', {@ToggleStateAxisActive});\n\n%status/action display (upper right)\nFO.actionDisp = annotation('textbox', 'Units', 'normalized', 'Position', [0.85, 0.86, 0.135, 0.105], 'EdgeColor', 'none');\n\n% Notificaton to press h for help\na = annotation('textbox', 'Position', [0.85          0.81          0.15         0.05], 'EdgeColor', 'none');\nset(a, 'String', {'\\fontsize{14}!Press \\bf''h'' for help!';...\n                    '\\fontsize{14}!Press \\bf''c'' to cancel'});\n\n\n% Apparently unused - BW 2018\n% FO.startLocDisp = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.7, 0.135, 0.1], 'EdgeColor', 'none');\n\n%Guide regarding states/colors\nFO.infoDisp = annotation('textbox', 'Position', [0.855, 0.7, 0.135, 0.1], 'EdgeColor', 'none');\ninfo = {};\ninfo{end + 1} = ['\\color[rgb]{', num2str(colors.states{1}), '}1: Wake'];\ninfo{end + 1} = ['\\color[rgb]{', num2str(colors.states{2}), '}2: Drowzy/Light'];\ninfo{end + 1} = ['\\color[rgb]{', num2str(colors.states{3}), '}3: NREM'];\ninfo{end + 1} = ['\\color[rgb]{', num2str(colors.states{4}), '}4: Intermediate'];\ninfo{end + 1} = ['\\color[rgb]{', num2str(colors.states{5}), '}5: REM'];\n\nset(FO.infoDisp, 'FontSize', 10, 'String', info);\n\n%last click indicator\nFO.lastClickDisp = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.68, 0.135, 0.03], 'EdgeColor', 'none');\n\n%Go To Second Command and label\na = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.62, 0.135, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'Go To Second:');\nFO.gotosecondbox = uicontrol('Style', 'edit', 'Units', 'normalized', 'Position', [0.88, 0.605, 0.06, 0.025]);\nset(FO.gotosecondbox, 'Callback', @goToSecond);\n\n% Window length command and labe\na = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.57, 0.135, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'Window Length (sec)');\nFO.xlimbox = uicontrol('Style', 'edit', 'Units', 'normalized', 'Position', [0.88, 0.55, 0.06, 0.025]);\nset(FO.xlimbox, 'Callback', {@changeXlim}, 'String', int2str(round(diff(FO.lims))));\n\n%Smoothing windows settings stuff\nWoptions =  [0, 5, 10, 15, 20, 30, 45, 60];\nFO.Woptions = Woptions;\noptString = [];\nfor I = 1:length(Woptions)\n    optString = [optString, int2str(Woptions(I)),' secs|'];\nend\noptString = optString(1:(end - 1));\nhanL = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.515, 0.135, 0.03], 'EdgeColor', 'none','String', 'Smoothing Window:');\nFO.hanningWDisp = uicontrol('style', 'popup', 'Units', 'normalized', 'Position', [0.88, 0.505, 0.08, 0.01]);\nset(FO.hanningWDisp, 'String', optString, 'CallBack', {@ChangeSmoothingWindow}, 'Value', find(Woptions == FO.hanningW));\n\n%Overlay stuff\nOoptions = ['none|(5-10Hz)/(0.5-4Hz)|From SleepScoreMaster|Choose from file'];\na = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.46, 0.1355, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'Overlay Display:');\nFO.overlayDisp = uicontrol('style', 'popup', 'Units', 'normalized', 'Position', [0.8800    0.45    0.0800    0.01]);\nset(FO.overlayDisp, 'String', Ooptions, 'CallBack', {@OverlayDisplay}, 'Value', 1);\n\n%Event stuff\nEoptions = ['none|1 (0 events)|2 (0 events)|3 (0 events)|4 (0 events)|5 (0 events)|6 (0 events)|7 (0 events)|8 (0 events)|9 (0 events)|10 (0 events)'];\na = annotation('textbox', 'Units', 'normalized', 'Position', [0.855, 0.403, 0.1355, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'Event #:');\nFO.eventDisp = uicontrol('style', 'popup', 'Units', 'normalized', 'Position', [0.8800    0.397    0.0800    0.01]);\nset(FO.eventDisp, 'String', Eoptions, 'CallBack', {@EventNumber}, 'Value', 2);\nFO.eventNum = 1;\n\n% EEG stuff\n%Set width of eeg display \na = annotation('textbox', 'Units', 'normalized', 'Position', [0.87, 0.225, 0.135, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'EEG Display Width (sec):');\nFO.eegDisplayWidthBox = uicontrol('Style', 'edit', 'Units', 'normalized', 'Position', [0.88, 0.21, 0.06, 0.025]);\nset(FO.eegDisplayWidthBox,'String',num2str(FO.eegDisplaySeconds))\nset(FO.eegDisplayWidthBox, 'Callback', {@changeEEGDisplaySeconds});\n\n%Toggle for whether or not to update eeg when clicking\nFO.updateEegOnClickCheckbox = uicontrol('style', 'checkbox', 'String', 'Update EEG on Click', 'Units', 'normalized', 'Position',  [0.87, 0.185, 0.1, 0.02]);\nset(FO.updateEegOnClickCheckbox, 'Callback', {@ToggleUpdateEeg});\n\n%Save raw eeg for offline use\nFO.saveEEGButton = uicontrol('style', 'pushbutton', 'String', 'Export Raw EEG', 'Units', 'normalized', 'Position',  [0.87, 0.152, 0.1, 0.03]);\nset(FO.saveEEGButton, 'Callback', {@saveRawEEG});\n\n\n\n% Buttons to scroll full screen widths\na = annotation('textbox', 'Units', 'normalized', 'Position', [0.87, 0.078, 0.2, 0.03], 'EdgeColor', 'none');\nset(a, 'String', 'Scroll:');\nFO.leftScreenOver = uicontrol('style', 'pushbutton', 'String', '<', 'Units', 'normalized', 'Position',  [0.898, 0.08, 0.038, 0.03]);\nset(FO.leftScreenOver, 'Callback', {@leftScreenOver});\nFO.rightScreenOver = uicontrol('style', 'pushbutton', 'String', '>', 'Units', 'normalized', 'Position',  [0.938, 0.08, 0.038, 0.03]);\nset(FO.rightScreenOver, 'Callback', {@rightScreenOver});\n\n%Undo/Redo state buttons\nFO.undoButton = uicontrol('style', 'pushbutton', 'String', 'Undo State', 'Units', 'normalized', 'Position',  [0.87, 0.05, 0.1, 0.03]);\nset(FO.undoButton, 'Callback', {@undoChange});\nFO.redoButton = uicontrol('style', 'pushbutton', 'String', 'Redo State', 'Units', 'normalized', 'Position',  [0.87, 0.02, 0.1, 0.03]);\nset(FO.redoButton, 'Callback', {@redoChange});\n\n%???\nfor i = 1:length(FO.Chs)\n    a = annotation('textbox', 'Units', 'Normalized');\n    if iscell(FO.Chs)\n        set(a, 'String', ['\\bf\\color{red}\\fontsize{10}C', FO.Chs{i}], 'Position', position.eegCh{i}, 'EdgeColor', 'none');        \n    else\n        set(a, 'String', ['\\bf\\color{red}\\fontsize{10}C', int2str(FO.Chs(i))], 'Position', position.eegCh{i}, 'EdgeColor', 'none');\n    end\nend\nFO.eegWidthDisp = annotation('textbox', 'Units', 'Normalized');\nset(FO.eegWidthDisp, 'String', ['\\bf\\color{red}\\fontsize{11}', num2str(FO.eegDisplaySeconds), ' sec'], 'Position', position.eegWidth, 'EdgeColor', 'none');\n\n%%%% Other stuff?\n\n%set(FO.actionDisplay, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Browse'});\n\nFO.Events = [];\nFO.CurrEventLines = {};\nFO.Transitions = [];\nFO.TransHistoryTracker = [];\nFO.saxYLim = [min(FO.fo), max(FO.fo)];\nFO.mpYLim = get(FO.max, 'YLim');\na = [];\nfor i = 1:length(nCh)\n    a = [a; min(FO.eeg{i}), max(FO.eeg{i})];\nend\nFO.eegYLim = [min(a(:, 1)), max(a(:, 2))];\n\n\n%% BW speeding things up... didn't change anything above to be safe\nsetappdata(FO.fig,'unsmoothedSpec',FO.unsmoothedSpec)\nsetappdata(FO.fig,'spec',FO.spec)\nsetappdata(FO.fig,'eeg',FO.eeg)\n\nFO = rmfield(FO,'spec');\nFO = rmfield(FO,'unsmoothedSpec');%access only when needed using appdata now\nFO = rmfield(FO,'eeg');%access only when needed using appdata now\n% FO = rmfield(FO,'eegX');%recalculate on the fly using:   eegX = (1:length(FO.eeg{i}))/(FO.eegFS/FO.downsample);\n%%\nguidata(FO.fig, FO); \n\n\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO);\nend\nFO = UpdateGUI(FO);\nset(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n% set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\nset(FO.sax{1}, 'XLim', FO.lims);\n\n%set(FO.eax{end},'xticklabel',num2str(get(FO.eax{end},'xtick')'));\n\n\n\nend\n\n\nfunction DefKey(fig, e)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \nFO = guidata(fig);\n\nswitch e.Key\n    case 'uparrow'\n        if strcmpi(FO.currAction, 'FreqResize')\n            ResizeFreqY(1);\n            obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        else\n            for i = 1:FO.nCh\n                v = caxis(gca); caxis(gca, v - 0.1);\n            end\n        end\n    case 'downarrow'\n        if strcmpi(FO.currAction, 'FreqResize')\n            ResizeFreqY(-1);\n            obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        else\n            for i = 1:FO.nCh\n                v = caxis(gca); caxis(gca, v + 0.1);\n            end\n        end\n    case 'z'\n        if strcmpi(FO.currAction, 'Browse');\n            for i = 1:FO.nCh\n                axes(FO.sax{i});\n            end\n            %zoom;\n            FO.currAction = 'Zoom';\n            \n        else\n            for i = 1:FO.nCh\n                axes(FO.sax{i});\n                \n            end\n            \n            if isempty(FO.startLocation)\n                FO.currAction = 'Browse';\n            else\n                FO.currAction = 'Add';\n            end\n        end\n    case 'rightarrow'\n        l = get(FO.sax{1}, 'XLim');\n        l = l + 0.15*diff(l);\n        if l(1) < FO.lims(1)\n            l(1) = FO.lims(1);\n        end\n        if l(2) > FO.lims(2)\n            l(2) = FO.lims(2);\n        end\n        set(FO.sax{1}, 'XLim', l);\n%         guidata(FO.fig, FO); \n        if FO.EegUpdateBoolean\n            FO = updateEEG(FO);\n        end\n%         obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        % updateMidline([]);\n    case 'leftarrow'\n        l = get(FO.sax{1}, 'XLim');\n        l = l - 0.15*diff(l);\n        if l(1) < FO.lims(1)\n            l(1) = FO.lims(1);\n        end\n        if l(2) > FO.lims(2)\n            l(2) = FO.lims(2);\n        end\n        set(FO.sax{1}, 'XLim', l);\n%         guidata(FO.fig, FO); \n        if FO.EegUpdateBoolean\n            FO = updateEEG(FO,nextE);\n        end        \n%         obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        %    updateMidline([]);\n    case '1'\n        FO.currentState = 1;\n        FO.currAction = 'Add';\n        FO.stateAxisToggleModeBool = logical(0);\n        \n        set(FO.fig,'Pointer','arrow');\n        FO.zoomState = 0;\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 1']);\n    case '2'\n        FO.currentState = 2;\n        FO.currAction = 'Add';\n        FO.stateAxisToggleModeBool = logical(0);\n        \n        set(FO.fig,'Pointer','arrow');\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 2']);\n    case '3'\n        FO.currentState = 3;\n        FO.currAction = 'Add';\n        FO.stateAxisToggleModeBool = logical(0);\n        \n        set(FO.fig,'Pointer','arrow');\n        FO.zoomState = 0;\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 3']);\n    case '4'\n        FO.currentState = 4;\n        FO.currAction = 'Add';\n        FO.stateAxisToggleModeBool = logical(0);\n        \n        set(FO.fig,'Pointer','arrow');\n        FO.zoomState = 0;\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 4']);\n    case '5'\n        FO.currentState = 5;\n        FO.currAction = 'Add';\n        FO.stateAxisToggleModeBool = logical(0);\n        \n        set(FO.fig,'Pointer','arrow');\n        FO.zoomState = 0;\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 5']);\n    case '0'\n        FO.currentState = 0;\n        FO.currAction = 'Add';\n        \n        set(FO.fig,'Pointer','arrow');\n        FO.zoomState = 0;\n        set(FO.fig, 'Name', ['States: ', FO.baseName, ' - Add State 0']);\n    case 'e'\n        FO.currentState = 0;\n        if strcmp(FO.currAction, 'AddEvent')\n            if isempty(FO.startLocation)\n                FO.currAction = 'Browse';\n            else\n                FO.currAction = 'Add';\n            end\n            \n        else\n            if length(FO.eventNum) == 1\n                FO.currAction = 'AddEvent';\n                set(gcf, 'Pointer', 'crosshair');\n            else\n                warndlg('No event # selected');\n            end\n        end\n        FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n    case 'd'\n        if strcmp(FO.currAction, 'DeleteEvent')\n            if isempty(FO.startLocation)\n                FO.currAction = 'Browse';\n            else\n                FO.currAction = 'Add';\n            end\n        else\n            if ~isempty(FO.Events)\n                if sum(FO.Events(:, 1) == FO.eventNum) > 0\n                    skullCursor;\n                    FO.currAction = 'DeleteEvent';\n                else\n                    warndlg('There are currently no events displayed for you to delete');\n                end\n            else\n                warndlg('There are currently no events displayed for you to delete');\n            end\n        end\n        FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n\n    case {'c', 'escape'}\n        FO.currAction = 'Browse';\n        if ~isempty(FO.startLine)\n            for i = 1:length(FO.startLine)\n                delete(FO.startLine{i});\n            end\n            FO.startLine = {};\n            \n        end\n        FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n    case 'a'\n        FO = ViewAutoScoreThresholds(gcf);\n    case 'f'\n        if strcmpi(FO.currAction, 'FreqResize')\n            FO.currAction = 'Browse';\n        else\n            FO.currAction = 'FreqResize';\n        end\n    case 'u'\n        undoChange;\n        obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n    case 'r'\n        set(FO.sax{1}, 'XLim', FO.lims);\n    case 's'\n        saveStates;\n        obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n    case 'l'\n        LoadStates;\n        obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n        FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n    case 'n'\n        nextEvent;\n    case 'p'\n        previousEvent;\n    case 'hyphen'\n        f = find(histc(FO.eegDisplaySeconds, [0, 0.26, 2.1, 5.1, 15.1, 30.1,  60.1]) == 1);\n        switch f\n            case 1\n                delta = 0;\n            case 2\n                delta = 0.25;\n            case 3\n                delta = 0.5;\n            case 4\n                delta = 1;\n            case 5\n                delta = 2.5;\n            case 6\n                delta = 5;\n        end\n        \n        \n        FO.eegDisplaySeconds = FO.eegDisplaySeconds - delta;\n        guidata(FO.fig, FO); \n        if FO.EegUpdateBoolean\n            FO = updateEEG(FO,mean(get(FO.eax{1}, 'XLim')));\n        end\n        FO = UpdateGUI(FO);\n        return;\n        \n    case 'equal'\n        f = find(histc(FO.eegDisplaySeconds, [0, 0.24, 1.99, 4.99, 14.99, 29.9,  60]) == 1);\n        switch f\n            case 2\n                delta = 0.25;\n            case 3\n                delta = 0.5;\n            case 4\n                delta = 1;\n            case 5\n                delta = 2.5;\n            case 6\n                delta = 5;\n            case 7\n                delta = 0;\n        end \n        \n        FO.eegDisplaySeconds = FO.eegDisplaySeconds + delta;\n        guidata(FO.fig, FO); \n        \n        if FO.EegUpdateBoolean\n            FO = updateEEG(FO,mean(get(FO.eax{1}, 'XLim')));\n        end\n        FO = UpdateGUI(FO);;\n        return;\n        \n    case 'h'\n        helpFig = figure('Position', [300    50   520   750], 'MenuBar', 'none');\n        a = annotation('textbox', 'Units', 'normalized');\n        set(a, 'Position', [0.025 0.05 0.95 0.95], 'EdgeColor', 'none');\n        set(a, 'String', {'\\fontsize{14}\\bfWelcome to StateEditor!\\fontsize{10}\\rm'...\n            ' '...\n            '''\\bfSingle-Click\\rm''-- Center view on click point'...\n            ' ',...\n            '''\\bfClick-and-Hold\\rm''-- Drag currently visible ''xlim'' extent(applied to either spectral'...\n            '        or lfp windows depending on mouse position).'...\n            ' '...\n            '''\\bfScroll-Wheel\\rm''-- Zoom in or out (applied to either spectral or lfp windows depending'...\n            '        on click position).'...\n            ' '...\n            '''\\bfLeftArrow\\rm''-- Move view left'...\n            '''\\bfRightArrow\\rm''-- Move view right'...\n            ' '...\n            '''\\bfUpArrow\\rm''-- Increase color limits'...\n            '''\\bfDownArrow\\rm''-- Decrease color limits'...\n            ' '...\n            '\\bf''1'', ''2'', ''3'', ''4'' or ''5''\\rm',...\n            '       Add State - First click adds first bound, second click adds second bound.'...\n            '       Press ''\\bfC'' \\rmto cancel addition.'...\n            ' '...\n            '\\bf''0''\\rm--Delete state labels (add state 0)'...\n            ' '...\n            '''\\bfZ''\\rm-- Toggle Zoom ON/OFF',...\n            '       Left click zoom in. Right click zoom out. Hold and drag to select zoom area.'...\n            '       Double left click: fast zoom in. Double right click: reset full X extent.'... \n            ' '...\n            '''\\bfR''\\rm-- Reset X limits to full extent',...\n            ' '...\n            '''\\bfF\\rm''-- Toggle frequency edit mode. ''UpArrow''- Increase Freq. extent'...\n            '       ''DownArrow''- Decrease Freq. extent'...\n            ' '...\n            '''\\bf- or =\\rm''-- Increase/decrease the extent of LFP display(s).'...\n            ' '...\n            '''\\bfE\\rm''-- Add event (the number is determined by the Event # list on the right'...\n            '       panel.'...\n            ' '...\n            '''\\bfD\\rm''-- Delete event from currently selected event number.'...\n            ' '...\n            '''\\bfN or P\\rm''-- View next/Previous event (of currently selected event #)'...\n            ' '...\n            '''\\bfS''\\rm-- Save state vector/events/transitions to file',...\n            ' '...\n            '''\\bfL''\\rm-- Load state vector/events/transitions from file',...\n            ' '...\n            '''\\bfA''\\rm-- Autoscoring parameters: View and manipulate',...\n            ' '...\n            'Also note the editable fields and lists on the right hand panel!'\n                \n            });\n        uiwait(helpFig);\n        obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \nend\nguidata(FO.fig, FO);\nFO = UpdateGUI(FO);\nend\n\n\n\nfunction FO = updateEEG(FO,varargin)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n% try\n    eeg = getappdata(FO.fig,'eeg');\n    eegX = (1:length(eeg{1}))/(FO.eegFS/FO.downsample);\n% catch\n%     eeg = FO.eeg;\n%     eegX = FO\n% end\n\nif isempty(varargin)\n    pos = mean(get(FO.sax{1}, 'XLim'));\nelse\n    pos = varargin{1};\nend\nlow = pos - FO.eegDisplaySeconds/2;\nhigh = pos + FO.eegDisplaySeconds/2;\nif low < FO.lims(1)\n    high = high + (FO.lims(1) + low);\n    low = FO.lims(1);\nelse\n    if high > FO.lims(2)\n        low = low + (FO.lims(2) - high);\n        high = FO.lims(2);\n    end\nend\n\nlowMargin = low - 60;\nhighMargin = high + 60;\nfor i = 1:FO.nCh\n    set(FO.Eplot{i}, 'XData', eegX(eegX >= lowMargin & eegX <= highMargin), 'YData', eeg{i}(eegX >= lowMargin & eegX <= highMargin));\n    l1 = [min(eeg{i}(eegX >= low & eegX <= high)), max(eeg{i}(eegX >= low & eegX <= high))];\n    set(FO.eax{i}, 'YLim', l1);\n    set(FO.eax{i}, 'XLim', [pos - FO.eegDisplaySeconds/2, pos + FO.eegDisplaySeconds/2]);\nend\n\n% set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n% set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\nset(FO.eax{end},'xticklabel',num2str(get(FO.eax{end},'xtick')'));\n\nlims1 = get(FO.sax{1}, 'XLim');\nperc = (pos - lims1(1))/diff(lims1);\nnewL = (diff(FO.xplotLims)*perc) + FO.xplotLims(1);\n\nfor i = 1:length(FO.sMidline)\n    set(FO.sMidline{i}, 'X', [newL, newL]);\nend\nset(FO.mMidline, 'X', [newL, newL]);\n\n\nh = get(gcf, 'Children');\ntry\n    h = [FO.lineParent; h(h ~= FO.lineParent)];\n    warning('off', 'MATLAB:hg:default_child_strategy:IllegalPermutation')\n    set(gcf, 'Children', h);\ncatch\nend\nset(FO.eegDisplayWidthBox,'String',FO.eegDisplaySeconds);%update display\n\n\n\n% for i = 1:FO.nCh\n%     set(FO.Eplot{i}, 'XData', eegX(eegX >= low & eegX <= high));\n%     set(FO.Eplot{i}, 'YData', eeg{i}(eegX >= low & eegX <= high));\n%     l1 = [min(eeg{i}(eegX >= low & eegX <= high)), max(eeg{i}(eegX >= low & eegX <= high))];\n%     set(FO.eax{i}, 'YLim', l1);\n%     set(FO.eax{i}, 'XLim', [pos - FO.eegDisplaySeconds/2, pos + FO.eegDisplaySeconds/2]);\n% end\n\n% guidata(FO.fig, FO); \nend\n\n\nfunction MouseClick(obj, ev)\nst = dbstack;%make sure not overloading thestateeditor\nif length(st)>1\n    for idx = 2:length(st)\n        if strmatch (st(idx).file,'TheStateEditor.m')%if state editor is already running\n            disp('You clicked while TheStateEditor was still running, click later')\n            return\n        end\n    end\nend\n\n% obj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj); \nglobal isClicking\npersistent chk lastButton\n\nif ~strcmpi(get(FO.fig, 'SelectionType'), 'open')\n    lastButton = get(FO.fig, 'SelectionType');\nend\n% updateEegToClick = 1;\nisClicking = 1;\n\nclickType = [];\nholdC = get(FO.fig, 'CurrentPoint');\nif isempty(chk)\n    chk = 1;\n    pause(0.25);\n    if chk == 1\n        if isClicking == 0\n            \n            clickType = 'Single';\n            \n        else\n            clickType = 'Hold';\n        end\n        \n        chk = [];\n    end\nelse\n    chk = [];\n    clickType = 'Double';\nend\nif strcmpi(clickType, 'Double')\n    return;\nend\n\nif isempty(clickType)\n    clickType = 'Double';\nend\n\n\nc = get(FO.fig, 'CurrentPoint');\n\nclickloc = [];\nif FO.stateAxisToggleModeBool\n    xy = FO.lax.Position;\n    xs = [xy(1) xy(1) xy(1)+xy(3) xy(1)+xy(3)];\n    ys = [xy(2) xy(2)+xy(4) xy(2)+xy(4) xy(2)];\n    inp = inpolygon(c(1),c(2),xs,ys);%if in top axes\n    if inp\n        clickloc = 'activestateaxes';\n    end\nend\n    %get coordinate in that axes\nif isempty(clickloc)\n    xG = (c(1) >= FO.xplotLims(1)) & (c(1) <=  FO.xplotLims(2));\n    yG = sum((c(2) >= FO.yplotLims(:, 1)) & c(2) <= FO.yplotLims(:, 2)) == 1;\n    clickloc = 'outside';\n    if ~(xG && yG)\n\n        yG = sum((c(2) >= FO.yplotLFPLims(:, 1)) & c(2) <= FO.yplotLFPLims(:, 2)) ~= 0;\n        if ~(xG && yG)\n            return;\n        else\n            clickloc = 'timeaxes';\n        end\n    end\nend\n\n% %taking care of weird error I can't figure out -BW\n% if strcmp('browse',lower(FO.currAction))\n% %     if ~isempty(strfind(get(FO.fig,'name'),'Add State'))\n%     if ~isempty(FO.startLine)\n%         FO.startLine = {};\n%     end\n% end\n\n\nswitch(clickloc)\n    case 'outside'\n        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n        xl = get(FO.sax{1}, 'XLim');\n        pointTo = xl(1) + (diff(xl)*d);\n        button = lastButton;\n        \n        \n        switch(FO.currAction);\n            case 'Add'\n                switch(clickType)\n                    case 'Single'\n                        FO = addStateLine(FO,pointTo);\n                    case 'Double'\n                        FO = addStateLine(FO,pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.sax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.sax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n%                             set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        set(gcf, 'Pointer', 'arrow');\n                        if FO.EegUpdateBoolean\n                            FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n                        end\n%                         updateEegToClick = 0;\n                end\n            case 'AddEvent'\n                switch(clickType)\n                    case 'Single'\n                        FO = addEvent(FO,pointTo);\n                    case 'Double'\n                        FO = addEvent(FO,pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.sax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.sax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n%                             set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        set(gcf, 'Pointer', 'crosshair');\n                        if FO.EegUpdateBoolean\n                            FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n                        end\n%                         updateEegToClick = 0;\n                end\n            case 'DeleteEvent'\n                switch(clickType)\n                    case 'Single'\n                        FO = deleteEvent(FO,pointTo);\n                    case 'Double'\n                        FO = deleteEvent(FO,pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.sax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.sax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n%                             set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        set(gcf, 'Pointer', 'crosshair');\n                        if FO.EegUpdateBoolean\n                            FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n                        end\n%                         updateEegToClick = 0;\n                end\n            case 'Zoom'\n                switch(clickType)\n                    case 'Single'\n                        switch(button)\n                            case 'alt'\n                                xl = xl*1.25;\n                                X1 = ((pointTo) - diff(xl)/2);\n                                X2 = ((pointTo) + diff(xl)/2);\n                                if X1 < FO.lims(1)\n                                    X2 = X2 + (FO.lims(1) - X1);\n                                    X1 = FO.lims(1);\n                                end\n                                \n                                if X2 > FO.lims(2)\n                                    X1 = X1 - (X2 - FO.lims(2));\n                                    X2 = FO.lims(2);\n                                end\n                                if X1 < FO.lims(1)\n                                    X1 = FO.lims(1);\n                                end\n                                set(FO.sax{1}, 'XLim', [X1, X2]);\n                            case 'normal'\n                                xl = xl*0.75;\n                                X1 = ((pointTo) - diff(xl)/2);\n                                X2 = ((pointTo) + diff(xl)/2);\n                                if X1 < FO.lims(1)\n                                    X2 = X2 + (FO.lims(1) - X1);\n                                    X1 = FO.lims(1);\n                                end\n                                \n                                if X2 > FO.lims(2)\n                                    X1 = X1 - (X2 - FO.lims(2));\n                                    X2 = FO.lims(2);\n                                end\n                                \n                                if X1 < FO.lims(1)\n                                    X1 = FO.lims(1);\n                                end\n                                set(FO.sax{1}, 'XLim', [X1, X2]);\n                        end\n                    case 'Double'\n                        switch(button)\n                            case 'alt'\n                                set(FO.sax{1}, 'XLim', FO.lims);\n                            case 'normal'\n                                xl = xl*0.25;\n                                X1 = ((pointTo) - diff(xl)/2);\n                                X2 = ((pointTo) + diff(xl)/2);\n                                if X1 < FO.lims(1)\n                                    X2 = X2 + (FO.lims(1) - X1);\n                                    X1 = FO.lims(1);\n                                end\n                                \n                                if X2 > FO.lims(2)\n                                    X1 = X1 - (X2 - FO.lims(2));\n                                    X2 = FO.lims(2);\n                                end\n                                \n                                if X1 < FO.lims(1)\n                                    X1 = FO.lims(1);\n                                end\n                                set(FO.sax{1}, 'XLim', [X1, X2]);\n                        end\n                    case 'Hold'\n                        switch(button)\n                            case 'normal'\n                                if FO.EegUpdateBoolean\n                                    FO = updateEEG(FO);\n                                end\n                                set(gcf, 'Pointer', 'circle');\n                                point1 = get(gcf,'CurrentPoint');    % button down detected\n%                                 finalRect = rbbox;                   % return figure units\n                                point2 = get(gcf,'CurrentPoint');    % button up detected\n                                point1 = point1(1,1);\n                                point2 = point2(1,1);\n                                d1 = (point1 - FO.xplotLims(1))./diff(FO.xplotLims);\n                                d2 = (point2 - FO.xplotLims(1))./diff(FO.xplotLims);\n                                xl = get(FO.sax{1}, 'XLim');\n                                pointTo1 = xl(1) + (diff(xl)*d1);\n                                pointTo2 = xl(1) + (diff(xl)*d2);\n                                if pointTo1 > pointTo2\n                                    p = pointTo2;\n                                    pointTo2 = pointTo1;\n                                    pointTo1 = p;\n                                end\n                                if pointTo1 < FO.lims(1)\n                                    pointTo1 = FO.lims(1);\n                                end\n                                if pointTo2 > FO.lims(2)\n                                    pointTo2 = FO.lims(2);\n                                end\n                                set(gcf, 'Pointer', 'crosshair');\n                                set(FO.sax{1}, 'XLim', [pointTo1, pointTo2]);\n                        end\n                end\n                \n            case 'Browse'\n                if strcmp(clickType, 'Double')\n                    clickType = 'Single';\n                end\n                switch(clickType)\n                    case 'Single'\n                        if (((pointTo) - diff(xl)/2) >= FO.lims(1)) & (((pointTo) + diff(xl)/2) <= FO.lims(2))\n                            set(FO.sax{1}, 'XLim', [((pointTo) - diff(xl)/2), ((pointTo) + diff(xl)/2)]);\n                        end\n                    case 'Hold'\n                        if FO.EegUpdateBoolean\n                            FO = updateEEG(FO);\n                        end\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.sax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            delta = pointTo - newPoint;\n                            set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n%                             set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.sax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n%                             set(FO.sax{end},'xticklabel',num2str(get(FO.sax{end},'xtick')'));\n                            \n                            pause(0.01);\n                        end\n                        set(gcf, 'Pointer', 'hand');\n                        if FO.EegUpdateBoolean\n                            FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n                        end\n%                         updateEegToClick = 0;\n                end\n        end\n    case 'timeaxes'\n        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n        xl = get(FO.eax{1}, 'XLim');\n        pointTo = xl(1) + (diff(xl)*d);\n        button = lastButton;\n        switch(FO.currAction);\n            case 'Add'\n                switch(clickType)\n                    case 'Single'\n                        FO = addStateLine(FO,pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.eax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.eax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            pause(0.025);\n                        end\n                        set(gcf, 'Pointer', 'arrow');\n                end\n            case 'AddEvent'\n                switch(clickType)\n                    case 'Single'\n                        FO = addEvent(FO,pointTo);\n                    case 'Double'\n                        FO = addEvent(FO,pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.eax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            %    updateEEG(newPoint);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.eax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.eax{end},'xticklabel',num2str(get(FO.eax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        \n                        set(gcf, 'Pointer', 'crosshair');\n                end\n            case 'DeleteEvent'\n                switch(clickType)\n                    case 'Single'\n                        FO = deleteEvent(pointTo);\n                    case 'Double'\n                        FO = deleteEvent(pointTo);\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.eax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            %    updateEEG(newPoint);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.eax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.eax{end},'xticklabel',num2str(get(FO.eax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        \n                        skullCursor;\n                end\n            case 'Browse'\n                if strcmp(clickType, 'Double')\n                    clickType = 'Single';\n                end\n                switch(clickType)\n                    case 'Single'\n                        if (((pointTo) - diff(xl)/2) >= FO.lims(1)) & (((pointTo) + diff(xl)/2) <= FO.lims(2))\n                            set(FO.eax{1}, 'XLim', [((pointTo) - diff(xl)/2), ((pointTo) + diff(xl)/2)]);\n                        end\n                    case 'Hold'\n                        c = holdC;\n                        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                        xl = get(FO.eax{1}, 'XLim');\n                        pointTo = xl(1) + (diff(xl)*d);\n                        origin = xl;\n                        while isClicking == 1\n                            set(gcf, 'Pointer', 'fleur');\n                            c = get(gcf, 'CurrentPoint');\n                            d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n                            newPoint = xl(1) + (diff(xl)*d);\n                            %    updateEEG(newPoint);\n                            delta = pointTo - newPoint;\n                            \n                            if ((origin(1) + delta) >= FO.lims(1)) & ((origin(2) + delta) <= FO.lims(2))\n                                set(FO.eax{1}, 'XLim', [origin(1) + delta, origin(2) + delta]);\n                            end\n                            set(FO.eax{end},'xticklabel',num2str(get(FO.eax{end},'xtick')'));\n                            pause(0.025);\n                        end\n                        \n                        set(gcf, 'Pointer', 'hand');\n                end\n        end\n        pointTo = mean(get(FO.eax{1}, 'XLim'));\n        if FO.EegUpdateBoolean\n            FO = updateEEG(FO,pointTo);\n        end\n        xl = (get(FO.sax{1}, 'XLim'));\n        if (((pointTo) - diff(xl)/2) >= FO.lims(1)) & (((pointTo) + diff(xl)/2) <= FO.lims(2))\n            set(FO.sax{1}, 'XLim', [((pointTo) - diff(xl)/2), ((pointTo) + diff(xl)/2)]);\n        end\n    case 'activestateaxes'\n        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n        xl = get(FO.lax, 'XLim');\n        pointTo = xl(1) + (diff(xl)*d);\n        pointTo = round(pointTo);\n        \n        FO = ChangeThisStateAssigmnent_Setup(FO,pointTo);\n%         states = FO.States;\n%         ds = logical(abs(diff(states)));%find state switches with 1's\n%         ds = cat(2,ds,0);%pad\n%         %find start\n%         spanstart = find(ds(1:pointTo)>0,1,'last')+1;\n%         if isempty(spanstart)\n%             spanstart = 1;\n%         end\n%         if spanstart<1\n%             spanstart = 1;\n%         end\n%         %find end\n%         spanend = find(ds(pointTo:end)>0,1,'first') + pointTo-1;\n%         if isempty(spanend)\n%             spanend = length(states);;\n%         end\n%         if spanend>length(states)\n%             spanend = length(states);\n%         end\n% \n%         set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Choose New State (1-5)'});\n%         \n%         set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Browse'});\n\n        \n%         button = lastButton;\n        % execute state switching:\n            %find span occupying this click\n            %ask user what to change it to with 1-5 input\n            %if anything else just run the defkey='c' code\n\nend\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n% disp('after obj')    \n\n\nFO.clickPoint = pointTo;\nif FO.EegUpdateBoolean\n%     disp('before updateEEG')\n    FO = updateEEG(FO,pointTo);\n%     disp('after updateEEG')    \nend\n\n\n%Set GUI\n% disp('before FO = UpdateText(FO);')\nFO = UpdateGUI(FO);\nguidata(obj, FO);\n% dbstack\n% disp('END')\nend\n\nfunction MouseScroll(obj, src)\nst = dbstack;%make sure not overloading thestateeditor\nif length(st)>1\n    for idx = 2:length(st)\n        if strmatch (st(idx).file,'TheStateEditor.m')%if state editor is already running\n            disp('You scrolled while TheStateEditor was still running, click later')\n            return\n        end\n    end\nend\n\n% obj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj);\n\nc = get(FO.fig, 'CurrentPoint');\nxG = (c(1) >= FO.xplotLims(1)) & (c(1) <=  FO.xplotLims(2));\nyG = sum((c(2) >= FO.yplotLims(:, 1)) & c(2) <= FO.yplotLims(:, 2)) == 1;\nscrollLoc = 0;\nif ~(xG && yG)\n    yG = sum((c(2) >= FO.yplotLFPLims(:, 1)) & c(2) <= FO.yplotLFPLims(:, 2)) ~= 0;\n    if ~(xG && yG)\n        return;\n    else\n        scrollLoc = 1;\n    end\nend\nswitch scrollLoc\n    case 0\n        d = (c(1) - FO.xplotLims(1))./diff(FO.xplotLims);\n        xl = get(FO.sax{1}, 'XLim');\n        pointTo = xl(1) + (diff(xl)*d);\n        \n        if src.VerticalScrollCount > 0\n            xl = xl*1.25;\n            X1 = ((pointTo) - diff(xl)/2);\n            X2 = ((pointTo) + diff(xl)/2);\n            if X1 < FO.lims(1)\n                X2 = X2 + (FO.lims(1) - X1);\n                X1 = FO.lims(1);\n            end\n            \n            if X2 > FO.lims(2)\n                X1 = X1 - (X2 - FO.lims(2));\n                X2 = FO.lims(2);\n            end\n            if X1 < FO.lims(1)\n                X1 = FO.lims(1);\n            end\n            set(FO.sax{1}, 'XLim', [X1, X2]);\n        else\n            xl = xl*0.75;\n            X1 = ((pointTo) - diff(xl)/2);\n            X2 = ((pointTo) + diff(xl)/2);\n            if X1 < FO.lims(1)\n                X2 = X2 + (FO.lims(1) - X1);\n                X1 = FO.lims(1);\n            end\n            if X2 > FO.lims(2)\n                X1 = X1 - (X2 - FO.lims(2));\n                X2 = FO.lims(2);\n            end\n            set(FO.sax{1}, 'XLim', [X1, X2]);\n        end\n    case 1\n        if src.VerticalScrollCount > 0\n            f = find(histc(FO.eegDisplaySeconds, [0, 0.24, 1.99, 4.99, 14.99, 29.9,  60]) == 1);\n            switch f\n                case 2\n                    delta = 0.25;\n                case 3\n                    delta = 0.5;\n                case 4\n                    delta = 1;\n                case 5\n                    delta = 2.5;\n                case 6\n                    delta = 5;\n                case 7\n                    delta = 0;\n            end\n            FO.eegDisplaySeconds = FO.eegDisplaySeconds + delta;\n%             guidata(FO.fig, FO);\n            \n            if FO.EegUpdateBoolean\n                FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n            end\n            FO = UpdateGUI(FO);\n            return;\n        else\n            f = find(histc(FO.eegDisplaySeconds, [0, 0.26, 2.1, 5.1, 15.1, 30.1,  60.1]) == 1);\n            switch f\n                case 1\n                    delta = 0;\n                case 2\n                    delta = 0.25;\n                case 3\n                    delta = 0.5;\n                case 4\n                    delta = 1;\n                case 5\n                    delta = 2.5;\n                case 6\n                    delta = 5;\n            end\n            \n            FO.eegDisplaySeconds = FO.eegDisplaySeconds - delta;\n%             guidata(FO.fig, FO); \n            if FO.EegUpdateBoolean\n                FO = updateEEG(FO,mean(get(FO.sax{1}, 'XLim')));\n            end\n            FO = UpdateGUI(FO);\n            return;\n        end\nend\n\n\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nFO.clickPoint = pointTo;\n\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO,pointTo);\nend\nFO = UpdateGUI(FO);\nguidata(FO.fig, FO); \n\nend\n\n\n\nfunction unMouseClick(e, src)\nglobal isClicking\nisClicking = 0;\nend\n\nfunction Nothing(e, src)\na = 0;\nend\n\nfunction FO = addStateLine(FO,location)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj);\nif isempty(FO.startLine) \n    ax = FO.lax;\n    yl = get(ax, 'YLim');\n    axes(ax);\n    hold on;\n    FO.startLine{end + 1} = plot([location, location], [yl(1), yl(2)], '-k');\n    \n    for i = 1:FO.nCh\n        ax = FO.sax{i};\n        yl = get(ax, 'YLim');\n        axes(ax);\n        hold on;\n        FO.startLine{end + 1} = plot([location, location], [yl(1), yl(2)], '-k');\n    end\n    \n    ax = FO.max;\n    yl = get(ax, 'YLim');\n    axes(ax);\n    hold on;\n    FO.startLine{end + 1} = plot([location, location], [yl(1), yl(2)], '-k');\n    \n    for i = 1:FO.nCh\n        ax = FO.eax{i};\n        yl = get(ax, 'YLim');\n        axes(ax);\n        hold on;\n        FO.startLine{end + 1} = plot([location, location], [yl(1), yl(2)], '-k');\n    end\n    \n    FO.startLocation = location;\n%     guidata(FO.fig, FO); \n    \nelse    \n    \n    for i = 1:length(FO.startLine)%delete graphical lines\n        delete(FO.startLine{i});\n    end    \n    FO = addState(location);\n\n    FO.currAction = 'Browse';\n    FO.startLocation = [];\n    FO.startLine = {};\n    set(gcf, 'Name', ['States: ', FO.baseName, ' - Default']);\n    \n%     guidata(FO.fig, FO); \n\n    \n%     FO.currAction = 'Browse';\n%     if ~isempty(FO.startLine)\n%         for i = 1:length(FO.startLine)\n%             delete(FO.startLine{i});\n%         end\n%         FO.startLine = {};\n% \n%     end\n%     set(gcf, 'Name', ['States: ', FO.baseName, ' - Default']);\n\n%     obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \nend\n% FO = UpdateText(FO);\nguidata(FO.fig, FO); \nend\n\nfunction FO = addState(loc2)\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \ns = FO.currentState;\nf1 = dsearchn(FO.to, FO.startLocation);\nf2 = dsearchn(FO.to, loc2);\n\n% f = [min([f1, f2]), max([f1, f2])];\nf = sort([f1 f2]);\nnewState = zeros(1, diff(f) + 1) + s;\noldState = FO.States(f(1):f(2));\nif length(FO.stateHistory) > FO.stateHistoryNum\n    FO.stateHistory = FO.stateHistory(1:FO.stateHistoryNum);\n    FO.newStates = FO.newStates(1:FO.stateHistoryNum);\n    b = msgbox('Losing a bit of history');\n    uiwait(b);\nend\n% if FO.startLocation > loc2\n%     FO.Transitions = [FO.Transitions; s, loc2, FO.startLocation];\n% else\n    FO.Transitions = [FO.Transitions; s, f(1), f(2)];\n% end\nFO.TransHistoryTracker = [FO.TransHistoryTracker, 1];\nFO.stateHistory{end + 1}.location = f(1);\nFO.stateHistory{end}.state = oldState;\nFO.stateHistoryNum = FO.stateHistoryNum + 1;\nFO.States(f(1):f(2)) = newState;\nFO.newStates{end + 1}.state = newState;\nFO.newStates{end}.location = f(1);\nFO.startLocation  = [];\nguidata(FO.fig, FO); \nFO = modifyStates(f(1), newState);\nFO = guidata(FO.fig);\n% updateEEG;\n\n%Reset StateAxis ative click toggle based on checkbox status - since adding\n%state temporarily turns it off.\n% FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\nFO = UpdateGUI(FO);\n\nend\n\n\nfunction FO = modifyStates(startLoc, newState, varargin)\n\nif isempty(varargin)\n    makeGrey = 1;\nelse\n    makeGrey = varargin{1};\nend\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n\ncolors = FO.colors;\nrows = FO.rows;\nnewC = ones(size(FO.SM, 1), length(newState), 3);\nif makeGrey == 1\n    newC = repmat(colors.grey, [size(FO.SM, 1), length(newState), 1]);\nend\n\nfor i = 1:5\n    f = find(newState == i);\n    newC(rows{i}, f, :) = repmat(colors.states{i}, [length(rows{i}), length(f), 1]);\nend\n\nloc = startLoc:(startLoc + length(newState) - 1);\n\nFO.SM(:, loc, :) = newC;\nFO.madeChanges = 1;\nset(FO.ilab, 'CData', FO.SM);\n\nFO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n\nguidata(FO.fig, FO); \nend\n\n\nfunction undoChange(varargin)\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n\nif FO.stateHistoryNum >= 1\n    newState = FO.stateHistory{FO.stateHistoryNum}.state;\n    startLoc = FO.stateHistory{FO.stateHistoryNum}.location;\n    FO.stateHistoryNum = FO.stateHistoryNum - 1;\n    guidata(FO.fig, FO); \n    modifyStates(startLoc, newState);\n    obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n    latestTrans = max(find(FO.TransHistoryTracker == 1));\n    FO.TransHistoryTracker(latestTrans) = 0;\n    set(gcf, 'Name', ['States: ', FO.baseName, '- History rewound to ', int2str(FO.stateHistoryNum), ' of ', int2str(length(FO.stateHistory))]);\n    \nelse\n    b = msgbox('Sorry pal, we are at the beginning of time, there are no changes to undo');\n    uiwait(b);\nend\nguidata(FO.fig, FO); \nend\n\nfunction redoChange(varargin)\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj);\nif length(FO.newStates) > FO.stateHistoryNum\n    FO.stateHistoryNum = FO.stateHistoryNum + 1;\n    newState = FO.newStates{FO.stateHistoryNum}.state;\n    startLoc = FO.newStates{FO.stateHistoryNum}.location;\n    \n    guidata(FO.fig, FO); \n    modifyStates(startLoc, newState);\n    \n    latestTrans = max(find(FO.TransHistoryTracker == 0));\n    FO.TransHistoryTracker(latestTrans) = 1;\n    guidata(FO.fig, FO); \n    set(gcf, 'Name', ['States: ', FO.baseName, '- History moved forward to ', int2str(FO.stateHistoryNum), ' of ', int2str(length(FO.stateHistory))]);\n    \nelse\n    b = msgbox('The management regretfully informs you there are no changes to redo.');\n    uiwait(b);\nend\n\nguidata(FO.fig, FO); \nend\n\n\nfunction changeEEGDisplaySeconds(obj,~)\nFO = guidata(obj);\nsec = get(FO.eegDisplayWidthBox,'String');\nsec = str2double(sec);\nif sec>30\n    disp('Cannot exceed 30 seconds width')\n    sec = 30;\nend\nset(FO.eegDisplayWidthBox,'String',num2str(sec))\nFO.eegDisplaySeconds = sec;\nFO = updateEEG(FO);\n\nguidata(FO.fig, FO); \nend\n\n\n\nfunction saveRawEEG(obj) %save eeg data to a file so you don't have to have the .lfp file\n% obj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj);\n\nRawEegData.data = getappdata(obj,'eeg');\nfor eix = 1:length(RawEegData.data)\n    RawEegData.data{eix} = int16(RawEegData.data{eix});\nend\n\nRawEegData.channels = FO.Chs;\nsave(fullfile(FO.basePath,[FO.baseName, '.RawEEG.eegstates.mat']), 'RawEegData');\ndisp(['EEG/LFP saved to disk as ' FO.baseName, '.RawEEG.eegstates.mat'])\nend\n\nfunction ToggleUpdateEeg(obj,~)\n% obj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj);\n\nfor i = 1:FO.nCh%blank out plots\n    set(FO.Eplot{i}, 'XData', []);\nend\nFO.EegUpdateBoolean = ~FO.EegUpdateBoolean;\nguidata(FO.fig, FO); \nend\n\nfunction ToggleStateAxisActive(obj,~)\n% obj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj);\nFO.stateAxisToggleModeBool = ~FO.stateAxisToggleModeBool;\nguidata(FO.fig, FO); \nend\n\n\nfunction saved = saveStates\n% ?Give user question of whether to impose minimum MA onto\n% SleepState.state.mat?\n\n%get figure and figure data\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj);\nFO = guidata(obj(end));\nbaseName = FO.baseName;\nbasePath = FO.basePath;\n\n%Load baseName.SleepState.states.mat\n[SleepState,sleepstatefilename] = bz_LoadStates(basePath,'SleepState');\n\n%Check if the SleepState file is new, manually detected, or auto-detected\nif isempty(SleepState)\n    STATESFILETYPE = 'new';\n    SleepState.detectorinfo.detectorname = 'TheStateEditor';\n    SleepState.detectorinfo.detectiondate = datestr(now,'yyyy-mm-dd'); \n    SleepState.idx.statenames = {'','','','',''};\n    SleepState.idx.timestamps = FO.to;\nelseif isfield(FO,'AutoScore')\n    STATESFILETYPE = 'auto';\nelseif isfield(SleepState,'detectorinfo')\n        if isfield(SleepState.detectorinfo,'detectorname')\n            switch SleepState.detectorinfo.detectorname\n                case 'SleepScoreMaster'\n                    STATESFILETYPE = 'auto';\n                case 'TheStateEditor'\n                    STATESFILETYPE = 'manual';\n                otherwise\n                    STATESFILETYPE = 'unknown'; \n            end\n        end\nelse\n\tSTATESFILETYPE = 'unknown';   \nend\n\n\n%Put the new states in format for buzcode\n%Make an buzcode-style idx structure\nif isfield(SleepState,'idx')\n    idx.statenames = SleepState.idx.statenames;\nelse\n    idx.statenames = {'WAKE','','NREM','','REM'}; %assume...\nend\n%Interpolate back to the scoring timestamps\nidx.timestamps = SleepState.idx.timestamps;\nidx.states = interp1(FO.to,FO.States,idx.timestamps,'nearest');\n\n\n%Make a buzcode-style ints structure (should wrap this into IDXtoINT.mat)\nints = bz_IDXtoINT(idx,'nameStates',true);\n\n\nswitch STATESFILETYPE\n    case 'auto'\n        %Save old Autoscoring in AutoScoreInts\n        if ~isfield(SleepState,'AutoScoreInts') \n            if isfield(SleepState,'detectorinfo')\n                if isfield(SleepState.detectorinfo,'detectorname')\n                    if strcmp(SleepState.detectorinfo.detectorname,'SleepScoreMaster')\n                        disp('Original State Scoring from SleepScoreMaster detected...')\n                        disp('   saving old states as SleepState.AutoScoreInts')\n                        SleepState.AutoScoreInts = SleepState.ints;\n                    end\n                end\n            end\n        end\n\n        %Save histsandthreshs... different depending on whether AutoScore was\n        %used or not\n        HistAndThreshAlready_Bool = 0;\n        if isfield(FO,'AutoScore')\n            if isfield(FO.AutoScore,'histsandthreshs')\n                HistAndThreshAlready_Bool = 1;\n            end\n        end\n        if HistAndThreshAlready_Bool\n            histsandthreshs = FO.AutoScore.histsandthreshs;\n        else\n            answer = questdlg({'We usually save hisograms and thresholds for sleep autoscoring, but they are not here... Regenerate them?'});\n            switch answer\n                case 'Yes'\n                    histsandthreshs = SSHistogramsAndThresholds_In(baseName,basePath);\n            end\n        end\n        if exist('histsandthreshs','var')\n            SleepState.detectorinfo.detectionparms.SleepScoreMetrics.histsandthreshs = histsandthreshs;\n        end\nend\n\n%Write the new ints/idx\nSleepState.ints = ints;\nSleepState.idx = idx;\nSleepState.detectorinfo.LastManualUpdate = datestr(now,'yyyy-mm-dd');\n\n%Save the results!\nsave(sleepstatefilename,'SleepState')\n\n\n%Make a new figure\ntry\n    ClusterStates_MakeFigure(SleepState,basePath,true);\n    disp('Figures Saved to StateScoreFigures')\ncatch\n    disp('Figure making error')\nend\n\n%If autoscored, calculate and save new StateEpisodes\nswitch STATESFILETYPE\n    case 'auto'\n        StatesToEpisodes(SleepState,basePath);\nend\n\n\n\nb = msgbox(['Saved work to ', baseName, '.SleepState.states.mat']);\nsaved = 1;\nuiwait(b);\n\n% \n% global answer1\n% saved = 0;\n% name = [];\n% name = FO.baseName;\n% name = [name '-states'];\n% \n% answer1 = 0;\n% FO.saveFig = figure('Position', [382   353   438   200]);\n% tx1 = annotation('textbox',  'Position', [0.02, 0.8, 0.5, 0.1], 'string', 'Please Enter File Name:', 'EdgeColor', 'none');\n% name1 = uicontrol('style', 'edit', 'string', name, 'FontSize', 10, 'Units', 'Normalized', 'Position', [0.37, 0.78, 0.5, 0.12]);\n% set(name1, 'HorizontalAlignment', 'left');\n% \n% incEvents = uicontrol('style', 'checkbox', 'string', 'Include Event Times');\n% set(incEvents, 'Units', 'normalized', 'Position', [0.1, 0.6, 0.35, 0.1], 'Value', 1);\n% \n% incTransitions = uicontrol('style', 'checkbox', 'string', 'Include Transition Times (higher resolution than state vector)');\n% set(incTransitions, 'Units', 'normalized', 'Position', [0.1, 0.48, 0.72, 0.1], 'Value', 1);\n% \n% incHist = uicontrol('style', 'checkbox', 'string', 'Include History of Changes');\n% set(incHist, 'Units', 'normalized', 'Position', [0.1, 0.36, 0.35, 0.1], 'Value', 1);\n% \n% saveb = uicontrol('style', 'pushbutton', 'string', 'Save', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 1;');\n% set(saveb, 'Units', 'normalized', 'Position', [0.4, 0.1, 0.25, 0.2], 'FontSize', 12);\n% \n% cancelb = uicontrol('style', 'pushbutton', 'string', 'Cancel', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 0;');\n% set(cancelb, 'Units', 'normalized', 'Position', [0.7, 0.1, 0.25, 0.2], 'FontSize', 12);\n% \n% uiwait(FO.saveFig);\n% fileName = get(name1, 'string');\n% includeH = get(incHist, 'Value');\n% includeEvents = get(incEvents, 'Value');\n% incTransitions = get(incTransitions, 'Value');\n% \n% close(FO.saveFig);\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n% if answer1 == 0\n%     return;\n% else\n%     oldFile = 0;\n%     try\n%         p = fopen([fileName, '.mat']);\n%         fclose(p);\n%         oldFile = 1;\n%     catch\n%         oldFie = 0;\n%         \n%     end\n%     if oldFile == 1\n%         choice = questdlg([fileName, '.mat already exists, do you wish to overwrite?']);\n%         if strcmpi(choice, 'Yes');\n%             delete([fileName, '.mat']);\n%         else\n%             return;\n%         end\n%     end\n%     \n%     states = FO.States;\n%     events = FO.Events;\n%     \n%     toSave = [' ''states'','];\n%     if includeEvents == 1\n%         toSave = [toSave, ' ''events'','];\n%     end\n%     \n%     if includeEvents == 1\n%         if ~isempty(FO.TransHistoryTracker)\n%             transitions = FO.Transitions(FO.TransHistoryTracker == 1, :);\n%         else\n%             transitions = [];\n%         end\n%         toSave = [toSave, ' ''transitions'','];\n%     end\n%     \n%     if includeH\n%         history.stateHistory = FO.stateHistory;\n%         history.newStates = FO.newStates;\n%         history.stateHistoryNum = FO.stateHistoryNum;\n%         toSave = [toSave, ' ''history'','];\n%     end\n%     \n%     try\n%         eval(['save(fileName, ', toSave(1:(end - 1)), ');']);\n%         b = msgbox(['Saved work to ', fileName, '.mat']);\n%         saved = 1;\n%         uiwait(b);\n%         FO.madeChanges = 0;\n%         guidata(FO.fig, FO); \n%     catch\n%         b = msgbox(['Warning, failed to save ', fileName, '.mat']);\n%         saved = 0;\n%         uiwait(b);\n%         \n%     end\n%     \n%     \n% end\n% \n% guidata(FO.fig, FO); \nend\n\n\nfunction LoadStates(filepath)\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \nglobal answer1;\nanswer1 = 0;\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); \n% if answer1 == 0\n%     return;\n% else\n    \n    if exist('filepath','var')\n        [path,name] = fileparts(filepath);\n    else\n        [name, path] = uigetfile('*mat', 'Choose a file to load:');\n    end\n    \n    if name == 0\n        return;\n    end\n    \n    if strcmp(name(end-21:end),'.SleepState.states.mat')%buzcode format\n        thispath = FO.basePath;\n        timevector = FO.to;\n        states = bz_LoadStates_StateEditorWrapper_In(thispath,timevector);\n        FO.States = states;\n        \n    elseif strcmp(name(end-14:end),'_SleepScore.mat')%2016 format\n        load([path,name])\n%         stateslen = max([max(max(StateIntervals.NREMstate)) max(max(StateIntervals.REMstate)) max(max(StateIntervals.WAKEstate)) ]); \n        stateslen = size(FO.to,1);\n        states = zeros(1,stateslen);\n        states(find(inttoboolIn(SleepState.ints.WAKEstate))) = 1;\n        %states(find(inttoboolIn(SleepState.ints.MAstate))) = 2;\n        states(find(inttoboolIn(SleepState.ints.NREMstate))) = 3;\n        states(find(inttoboolIn(SleepState.ints.REMstate))) = 5;\n        states = cat(2,states,zeros(1,numel(FO.States)-length(states)));\n        FO.States = states;\n    else %Andres original TheStateEditor format\n\n        FO.loadFig = figure('Position', [382   353   438   200], 'Name', 'Load');\n        warn1 = {'\\color{red}\\fontsize{12}Warning: \\color{black}Loading files will overwrite current work.'};\n        tx1 = annotation('textbox',  'Position', [0.02, 0.9, 0.9, 0.1], 'string', warn1 , 'EdgeColor', 'none');\n\n        loadStates = uicontrol('style', 'checkbox', 'string', 'Load State Vector (if ''.states'' field exists)');\n        set(loadStates, 'Units', 'normalized', 'Position', [0.1, 0.71, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n\n        loadEvents = uicontrol('style', 'checkbox', 'string', 'Load Event Matrix (if ''.events'' field exists)');\n        set(loadEvents, 'Units', 'normalized', 'Position', [0.1, 0.51, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n\n        loadTransitions =  uicontrol('style', 'checkbox', 'string', 'Load Transition Matrix (if ''.transitions'' field exists)');\n        set(loadTransitions, 'Units', 'normalized', 'Position', [0.1, 0.31, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n\n        loadb = uicontrol('style', 'pushbutton', 'string', 'Load ''.mat'' File', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 1;');\n        set(loadb, 'Units', 'normalized', 'Position', [0.25, 0.06, 0.4, 0.2], 'FontSize', 12);\n\n        cancelb = uicontrol('style', 'pushbutton', 'string', 'Cancel', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 0;');\n        set(cancelb, 'Units', 'normalized', 'Position', [0.7, 0.06, 0.25, 0.2], 'FontSize', 12);\n        uiwait(FO.loadFig);\n\n        loadStates = get(loadStates, 'Value');\n        loadEvents = get(loadEvents, 'Value');\n        loadTransitions = get(loadTransitions, 'Value');\n\n        close(FO.loadFig);\n\n        \n        newS = load([path, name]);\n\n        if ~isstruct(newS)\n            warndlg('Input must be a structure with fields ''.states'', ''.events'' and/or ''.transitions''.')\n            return;\n        end\n\n        loaded = {};\n        if isfield(newS, 'States')\n            st = 'States';\n        else\n            st = 'states';\n        end\n\n        if loadStates == 1    \n            if isfield(newS, st)\n                if length(size(newS.states))==2 && sum(size(newS.states)==1) && numel(newS.states) == numel(FO.States)%make tolerant to vert or horiz vectors\n                    newS.states = newS.states(:)';\n                end\n\n                if sum(size(FO.States) == size(newS.(st))) ~= 2\n                    b = msgbox({'Error: states field must be a 1xN vector file', 'where N == the number of bins.'});\n                    uiwait(b);\n                    obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n                    return;\n                end\n\n                FO.States = newS.(st);\n                loaded{end + 1} = 'states vector';\n            end\n        end\n\n        if loadEvents == 1    \n            if isfield(newS, 'events')\n                events = newS.events;\n                if size(events, 2) ~= 2 & ~isempty(events)\n                    b = msgbox({'Error: events field must be a Nx2 matrix file', 'where N == the number of events.'});\n                    uiwait(b);\n                    obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n                    return;\n                end\n\n                FO.Events = events;\n                loaded{end + 1} = 'event matrix';\n            end\n        end\n\n\n        if loadTransitions == 1\n            if isfield(newS, 'transitions')\n                transitions = newS.transitions;\n                if size(transitions, 2) ~= 3 & ~isempty(transitions)\n                    b = msgbox({'Error: transitions field must be a Nx3 matrix file', 'where N == the number of transitions.'});\n                    uiwait(b);\n                    obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n                    return;\n                end\n\n                FO.Transitions = transitions;\n                loaded{end + 1} = 'transition matrix';\n            end\n        end\n    end\n% end\n\n% successMsg = ['Found and loaded '];\n% \n% for i = 1:length(loaded)\n%     successMsg = [successMsg, loaded{i}, ', '];\n% end\n% successMsg = [successMsg(1:(end - 2)), '.'];\n% \n% guidata(FO.fig, FO); \n% b = msgbox(successMsg);\n% uiwait(b);\n\nEN = FO.eventNum;\nif isempty(FO.Events)\n    FO = updateEventLines(FO,[]);\nelse\n    FO = updateEventLines(FO,FO.Events(FO.Events(:, 1) == EN, 2));\nend\nmodifyStates(1, FO.States, 0);\nguidata(obj, FO); \nend\n\n% \n% function LoadStatesAutoNoMsgs\n% % global answer1;\n% % answer1 = 0;\n% % FO.loadFig = figure('Position', [382   353   438   200], 'Name', 'Load');\n% % warn1 = {'\\color{red}\\fontsize{12}Warning: \\color{black}Loading files will overwrite current work.'};\n% % tx1 = annotation('textbox',  'Position', [0.02, 0.9, 0.9, 0.1], 'string', warn1 , 'EdgeColor', 'none');\n% \n% % loadStates = uicontrol('style', 'checkbox', 'string', 'Load State Vector (if ''.states'' field exists)');\n% % set(loadStates, 'Units', 'normalized', 'Position', [0.1, 0.71, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n% % \n% % loadEvents = uicontrol('style', 'checkbox', 'string', 'Load Event Matrix (if ''.events'' field exists)');\n% % set(loadEvents, 'Units', 'normalized', 'Position', [0.1, 0.51, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n% % \n% % loadTransitions =  uicontrol('style', 'checkbox', 'string', 'Load Transition Matrix (if ''.transitions'' field exists)');\n% % set(loadTransitions, 'Units', 'normalized', 'Position', [0.1, 0.31, 0.72, 0.15], 'Value', 1, 'FontSize', 10);\n% % \n% % loadb = uicontrol('style', 'pushbutton', 'string', 'Load ''.mat'' File', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 1;');\n% % set(loadb, 'Units', 'normalized', 'Position', [0.25, 0.06, 0.4, 0.2], 'FontSize', 12);\n% % \n% % cancelb = uicontrol('style', 'pushbutton', 'string', 'Cancel', 'Callback', 'global answer1; uiresume(gcbf); answer1 = 0;');\n% % set(cancelb, 'Units', 'normalized', 'Position', [0.7, 0.06, 0.25, 0.2], 'FontSize', 12);\n% % uiwait(FO.loadFig);\n% % \n% % loadStates = get(loadStates, 'Value');\n% % loadEvents = get(loadEvents, 'Value');\n% % loadTransitions = get(loadTransitions, 'Value');\n% loadStates = 1;\n% loadEvents = 1;\n% loadTransitions = 1;\n% \n% % close(FO.loadFig);\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n% % if answer1 == 0\n% %     return;\n% % else\n% %     \n% %     [name, path] = uigetfile('*mat', 'Choose a state vector to load:');\n% %     \n% %     if name == 0\n% %         return;\n% %     end\n%     \n%     path = cd;\n%     name = [FO.baseName '-states.mat'];\n%     newS = load(fullfile(path, name));\n%     \n%     if ~isstruct(newS)\n%         warndlg('Input must be a structure with fields ''.states'', ''.events'' and/or ''.transitions''.')\n%         return;\n%     end\n%     \n%     loaded = {};\n%     if isfield(newS, 'States')\n%         st = 'States';\n%     else\n%         st = 'states';\n%     end\n%     \n%     if loadStates == 1    \n%         if isfield(newS, st)\n% \n%             if sum(size(FO.States) == size(newS.(st))) ~= 2\n%                 b = msgbox({'Error: states field must be a 1xN vector file', 'where N == the number of bins.'});\n%                 uiwait(b);\n%                 obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n%                 return;\n%             end\n% \n%             FO.States = newS.(st);\n% %             loaded{end + 1} = 'states vector';\n%         end\n%     end\n%     \n%     if loadEvents == 1    \n%         if isfield(newS, 'events')\n%             events = newS.events;\n%             if size(events, 2) ~= 2 & ~isempty(events)\n%                 b = msgbox({'Error: events field must be a Nx2 matrix file', 'where N == the number of events.'});\n%                 uiwait(b);\n%                 obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n%                 return;\n%             end\n% \n%             FO.Events = events;\n% %             loaded{end + 1} = 'event matrix';\n%         end\n%     end\n%     \n%     \n%     if loadTransitions == 1\n%         if isfield(newS, 'transitions')\n%             transitions = newS.transitions;\n%             if size(transitions, 2) ~= 3 & ~isempty(transitions)\n%                 b = msgbox({'Error: transitions field must be a Nx3 matrix file', 'where N == the number of transitions.'});\n%                 uiwait(b);\n%                 obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n%                 return;\n%             end\n%             \n%             FO.Transitions = transitions;\n% %             loaded{end + 1} = 'transition matrix';\n%         end\n%     end\n% % end\n% \n% % successMsg = ['Found and loaded '];\n% % \n% % for i = 1:length(loaded)\n% %     successMsg = [successMsg, loaded{i}, ', '];\n% % end\n% % successMsg = [successMsg(1:(end - 2)), '.'];\n% \n% guidata(FO.fig, FO); \n% % b = msgbox(successMsg);\n% % uiwait(b);\n% \n% EN = FO.eventNum;\n% if isempty(FO.Events)\n%     FO = updateEventLines(FO,[]);\n% else\n%     FO = updateEventLines(FO,FO.Events(FO.Events(:, 1) == EN, 2));\n% end\n% if isfield(newS,'states')\n%     modifyStates(1, newS.(st), 0);\n% end\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n% FO.madeChanges = 0;\n% guidata(FO.fig, FO); \n% end\n\n\n\nfunction out = convWithIn(sp, win1)\n%function out = convWith(sp, win1) - win1 convtrimmed with collumns of sp\n\nout = [];\nfor I = 1:size(sp, 2)\n    \n    out = [out, convtrimIn(sp(:, I), win1)/sum(win1)];\nend\nend\n\nfunction FO = UpdateGUI(FO);\nif ~exist('FO','var')\n    obj = findobj('tag','StateEditorMaster');  FO = guidata(obj);\nend\naction = FO.currAction;\n\n%reset action of clicking state axes plot\nset(FO.actionDisp, 'color', 'k','backgroundcolor','none');%defaults to offset ResetState\n\nswitch action\n    case 'Browse'\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Browse'});\n        set(FO.fig,'Pointer','hand');\n    case 'Add'\n        set(gcf,'Pointer','arrow');\n        colors = FO.colors;\n        s1 = FO.currentState;\n        if s1 == 0\n            s2 = 1;\n        else\n            s2 = s1;\n        end\n        h = ['\\fontsize{42}\\color[rgb]{', num2str(colors.states{s2}), '}',int2str(s1)];\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', 'Add state:', h});\n    case 'AddEvent'\n        h = ['\\fontsize{42}', int2str(FO.eventNum)];\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', 'Add event:', h});\n    case 'DeleteEvent'\n        h = ['\\fontsize{42}', int2str(FO.eventNum)];\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', 'Delete event:', h});\n    case 'Zoom'\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Zooming', '\\fontsize{20}about'});\n        set(gcf,'Pointer','cross');\n    case 'FreqResize'\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Rescale Frequencies'});\n        set(gcf,'Pointer','hand');\n    case 'ResetState'\n        set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Choose New State (1-5)'});\n        set(FO.actionDisp, 'color', [1 0 0],'backgroundcolor',[0 0 1]);\n        set(gcf,'Pointer','arrow');\nend\n\nset(FO.max,'xticklabel',num2str(get(FO.max,'xtick')'));\n\ndrawnow\nset(FO.lastClickDisp, 'String', {'Last Click at sec:', num2str(FO.clickPoint, 7), ['(of ', num2str(FO.lims(2), 7), ')']});\nset(FO.eegWidthDisp, 'String', ['\\bf\\color{red}\\fontsize{11}', num2str(FO.eegDisplaySeconds), ' sec']);\n% if isempty(FO.startLocation)\n%     set(FO.startLocDisp, 'Visible', 'off');\n% else\n% %     set(FO.startLocDisp, 'String', {'First bound at sec:', num2str(FO.startLocDisp, 7)});\n%     set(FO.startLocDisp, 'Visible', 'on');\n% end\n\nset(FO.xlimbox, 'String', int2str(round(diff(get(FO.sax{1}, 'XLim')))));\n% guidata(FO.fig, FO); \nfigure(FO.fig)\nend\n\nfunction ResizeFreqY(direction)\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj);\nspec = getappdata(gcf,'spec');\n\nif direction == 1\n    m = FO.maxFreq + 10;\n    if m <= max(FO.fo);\n        FO.maxFreq = m;\n        for i = 1:FO.nCh\n            set(FO.iSpec{i}, 'CData', spec{i}(:, FO.fo <= m)', 'YData', FO.fo(FO.fo <= m));\n            set(FO.sax{i}, 'Ylim', [min(FO.fo), m]);\n        end\n    end\nelse\n    m = FO.maxFreq - 10;\n    if m >= 10\n        FO.maxFreq = m;\n        for i = 1:FO.nCh\n            set(FO.iSpec{i}, 'CData', spec{i}(:, FO.fo <= m)', 'YData', FO.fo(FO.fo <= m));\n            set(FO.sax{i}, 'Ylim', [min(FO.fo), m]);\n        end\n    end\nend\n\nguidata(FO.fig, FO); \nend\n\nfunction CloseDialog(e, src)\nFO = guidata(e);\nif isempty(FO)\n    delete(gcf);\n    return;\nend\nif FO.madeChanges == 0\n    warning('on', 'MATLAB:hg:default_child_strategy:IllegalPermutation')\n    delete(e);\nelse\n    choice = questdlg(['Save all your hard work before closing?']);\n    switch choice\n        case 'Yes'\n            saved = saveStates;\n            if saved == 1\n                warning('on', 'MATLAB:hg:default_child_strategy:IllegalPermutation')\n                delete(e);\n            else\n                return;\n            end\n        case 'No'\n            warning('on', 'MATLAB:hg:default_child_strategy:IllegalPermutation')\n            delete(e);\n        case 'Cancel'\n            return;\n    end\nend\n\nend\n\n\nfunction ChangeSmoothingWindow(e, src)\nFO = guidata(e);\nspec = getappdata(gcf,'spec');\nunsmoothedSpec = getappdata(gcf,'unsmoothedSpec');\n\nval = get(FO.hanningWDisp, 'Value');\n\nWoptions = FO.Woptions;\nnewW = Woptions(val);\nif FO.hanningW == newW\n    return;\nelse\n    FO.hanningW = newW;\n    if newW == 0\n        for i = 1:FO.nCh\n            spec{i} = log10(unsmoothedSpec{i});\n        end\n    else\n        for i = 1:FO.nCh\n            spec{i} = log10(convWithIn(unsmoothedSpec{i}, hanning(FO.hanningW)));\n        end\n    end\n    for i = 1:FO.nCh\n        set(FO.iSpec{i}, 'CData', spec{i}(:, FO.fo <= FO.maxFreq)');\n    end\nend\n\nsetappdata(gcf,'spec',spec)\nguidata(FO.fig, FO); \nend\n\nfunction OverlayDisplay(e, src)\nFO = guidata(e);\nunsmoothedSpec = getappdata(gcf,'unsmoothedSpec');\n\nswitch get(FO.overlayDisp, 'Value')\n    case 1  %none\n        if isempty(FO.overlayLines)\n            return;\n        else\n            for i = 1:length(FO.overlayLines)\n                delete(FO.overlayLines{i})\n            end\n            FO.overlayLines = {};\n        end\n    case 2  %Theta ratio\n        if ~isempty(FO.overlayLines)\n            for i = 1:length(FO.overlayLines)\n                delete(FO.overlayLines{i})\n            end\n            FO.overlayLines = {};\n        end\n        \n        maxF = FO.maxFreq;\n        fo = FO.fo;\n        for i = 1:length(FO.sax)\n            m = mean(unsmoothedSpec{i}(:, fo >= 5 & fo <= 10), 2)./mean(unsmoothedSpec{i}(:, fo >= 0.5 & fo <= 4), 2);\n            if FO.hanningW > 0\n                m = convtrimIn(m, hanning(FO.hanningW));\n            end\n            m = m - prctile(m, 1);\n            m = m./prctile(m, 99);\n            range = maxF*(1/2);\n            base = maxF*(1/2);\n            m  = m*range;\n            m = m + base;\n            axes(FO.sax{i});\n            hold on;\n            FO.overlayLines{i} = plot(FO.to, m, '-w', 'LineWidth', 2.5);\n        end\n    case 3  %From SleepScoreMaster\n        basePath = FO.basePath;\n        SleepState = bz_LoadStates(basePath,'SleepState');   \n        \n        maxF = FO.maxFreq;\n        \n        if isempty(SleepState.detectorinfo.detectionparms.SleepScoreMetrics)\n            disp('No SleepScoreMetrics to Overlay')\n        else\n            broadbandSlowWave = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.broadbandSlowWave;\n            thratio = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.thratio;\n            over_timestamps = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.t_clus;\n            chans = FO.Chs;\n\n            overlaychoicefig = figure('closerequestfcn',@OverlaySleepStateSelectCallback);\n            for cidx = 1:length(chans)\n                   bg(cidx) = uibuttongroup(overlaychoicefig,...\n                      'Position',[(cidx-1)*.33 0 .3 1],...\n                      'Title',['Overlay for Ch' num2str(chans(cidx))]);\n\n                    % Create radio buttons in the button group.\n                    r1(cidx) = uicontrol(bg(cidx),'Style','radiobutton',...\n                          'String','Broaband SlowWave Power',...\n                          'Units','Normalized',....\n                          'Position',[.05 .55 1 .1]);\n                    r2(cidx) = uicontrol(bg(cidx),'Style','radiobutton',...\n                          'String','Theta Ratio 5-10Hz/2-20Hz',...\n                          'Units','Normalized',....\n                          'Position',[.05 .1 1 .08]);\n\n                    if chans(cidx) == SleepState.detectorinfo.detectionparms.SleepScoreMetrics.SWchanID\n                        r1(cidx).Value = true;\n                        r2(cidx).Value = false;\n                    end\n                    if chans(cidx) == SleepState.detectorinfo.detectionparms.SleepScoreMetrics.THchanID\n                        r1(cidx).Value = false;\n                        r2(cidx).Value = true;\n                    end\n\n            end            \n            closebutt = uicontrol('style','pushbutton','units','normalized',... %lol butt. - Good Dan  - :D \n                'position',[.91 .05 .08 .1],'String','Finish',...\n                'callback',@OverlaySleepStateSelectCallback);\n            localguidata = v2struct(overlaychoicefig,bg,r1,r2,closebutt);\n            guidata(overlaychoicefig,localguidata)\n            waitfor(overlaychoicefig)\n\n            choices = get(FO.fig,'userdata');\n            for cidx = 1:length(choices)%for each channel/choice (should be same)\n                switch choices(cidx)\n                    case 1\n                        t = broadbandSlowWave;\n                    case 2\n                        t = thratio;\n                end\n\n                t = t';\n                t = t - prctile(t, 1);\n                t = t./prctile(t, 99);\n                range = maxF*(1/2);\n                base = maxF*(1/2);\n                t  = t*range;\n                t = t + base;\n\n                axes(FO.sax{cidx});\n                hold on;\n                FO.overlayLines{cidx} = plot(over_timestamps, t, '-w', 'LineWidth', 2.5);\n            end\n        end                        \n  \n        \n    case 4  %From File\n        helpdlg({['load a .mat with a single variable with n columns of time bins'],...\n            ['(n = ', int2str(length(FO.to)),') and up to ', int2str(FO.nCh), ' rows. Successive rows of the'],...\n            ['input will be displayed overlayed on on successive'],...\n            ['spectrogram channels']});\n        \n        [name, path] = uigetfile('*mat', 'Choose overlay data to load:');\n        \n        maxF = FO.maxFreq;\n        \n\n        if name == 0\n            guidata(FO.fig, FO); \n            set(FO.overlayDisp, 'Value', 1);\n        else\n\n            input1 = load([path, name]);\n\n            if isstruct(input1) && ~isfield(input1,'timestamps')\n                t = fieldnames(input1);\n                input1 = input1.(t{1});\n            end\n            \n            %Buzcode structure with timestamps and data - still needs\n            %work....\n            if isfield(input1,'timestamps')\n                maxF = FO.maxFreq;\n                \n                [ m ] = bz_NormToRange(input1.data,[0.5*maxF maxF]);\n                hold on;\n                FO.overlayLines{1} = plot(input1.timestamps, m, '-w', 'LineWidth', 2.5);\n            else\n\n\n                if size(input1, 2) ~= length(FO.to)\n                    b = msgbox('Error: number of columns in input does not match the number of bins');\n                    uiwait(b);\n\n                    set(FO.overlayDisp, 'Value', 1);\n                    guidata(FO.fig, FO); \n                    return;\n                end\n\n                if ~isempty(FO.overlayLines)\n                    for i = 1:length(FO.overlayLines)\n                        delete(FO.overlayLines{i})\n                    end\n                    FO.overlayLines = {};\n                end\n\n                m1 = min([FO.nCh; size(input1, 1)]);\n                maxF = FO.maxFreq;\n                for i = 1:m1\n                    m = input1(i, :);\n                    m = m - prctile(m, 1);\n                    m = m./prctile(m, 99);\n                    range = maxF*(1/2);\n                    base = maxF*(1/2);\n                    m  = m*range;\n                    m = m + base;\n                    axes(FO.sax{i});\n                    hold on;\n                    FO.overlayLines{i} = plot(FO.to, m, '-w', 'LineWidth', 2.5);\n                end\n            \n            end\n        end\n                \nend\n\nguidata(FO.fig, FO); \nFO = UpdateGUI(FO);\n\nend\n\nfunction OverlaySleepStateSelectCallback(obj,ev)\nf = get(obj,'parent');\nlgd = guidata(f);\n\nfor idx = 1:length(lgd.r1) %only BBSlowWave and ThetaRatio\n    if lgd.r1(idx).Value\n        out(idx) = 1;%if value1 is 1, save out as 1\n    else\n        out(idx) = 2;%else save as 2\n    end\nend\nTSEFig = findobj('tag','StateEditorMaster');  \nset(TSEFig,'userdata',out)\ndelete(f)\n\nend\n\n\nfunction motion = LoadFromWhl(baseName, tos, varargin)\nif length(varargin) >= 1\n    whl = varargin{1};\nelse\n    [whl,to,~] = LoadFromWhlHelper1(baseName);\nend\nif size(whl,2) == 2 %if two LEDs then take the one with fewest NaN's, then fill in NaN's from other light if neccesary\n    d = [abs(diff(whl(:, 1))) + abs(diff(whl(:, 2))), abs(diff(whl(:, 3))) + abs(diff(whl(:, 4)))];\n    [~, mGood] = find(min(mean(isnan(d))));\n    if mGood == 1\n        mBad = 2;\n        \n    else\n        mBad = 1;\n    end\n    motion1 = d(:, mGood);\n    motion1(isnan(d(:, mGood))) = d(isnan(d(:, mGood)), mBad);\nelse\n    motion1 = abs(diff(whl));\nend\nf = find(isnan(motion1));\nmotion = motion1;\n\nfor i = 1:length(f) %%%this looks 3 seconds before and after each NaN value to find a non-NaN estimate (mean of non-NaN neighbors)\n    h = [f(i) - 39*3, f(i) + 39*3];\n    if h(1) < 1\n        h(1) = 1;\n    else\n        if h(2) > length(motion1)\n            h(2) = length(motion1);\n        end\n    end\n    c = motion1(h(1):h(2));\n    motion(f(i)) = mean(c(~isnan(c)));\nend\n\nto2 = to(2:end) - (diff(to)/2);\n\nmotion2 = motion;\nmotion = [];\nfor i = 1:length(tos) %avearge over same bins as spectrogram\n    motion = [motion, mean(motion2(to2 > tos(i) & to2 <= (tos(i) + 1)))];\nend\n\n\nend\n\nfunction [whl,t,GoodRanges] = LoadFromWhlHelper1(fbasename)\n% USAGE\n% [whl,t,GoodRanges,ep] = LoadPosition(fbasename)\n%\n% output:\n%   whl: the position matrix\n%   t: time vector\n%   Good Ranges:\n\nFs = 1250/32;\n\nwhlt = dlmread([fbasename '.whl']);\n[whl GoodRanges] = LoadFromWhlHelper2(whlt);\n\nt = (1:size(whlt,1))'/Fs;\nGoodRanges = GoodRanges/Fs;\nend\n\nfunction  [cWhl, GoodRanges_F] = LoadFromWhlHelper2(Whl, StretchLen, JumpSize, Gap)\n\n% If the gap between the good strech is more than StrethcLen in terms of Whl row number,remove interporated values.\nif nargin<2\n    StretchLen = 30;\nend\n\n% If the Gap between the good strech is more than JumpSize, remove interporated values.\nif nargin<3\n    JumpSize = 30;\nend\n\n% if the distance between the two contimous rows are more than Gap centimeter, It's a big jump and do not use as an input for inpterp1.\nif nargin<4,\n    Gap = 30;\nend\n\nnWhl = size(Whl,1);\n\n% interpolate missing values or large jumps.\n% the value of whl(:,3:4) is also taken into account for the rang of interpolation.\n% A transision to and form (-1,-1) should be taken as a BigJump.\n\n% I hsould use distance, not the one dimentinal projection of trajectory, by the way.\n\nwhltemp = Whl;\nwhltemp(find(whltemp)==-1) = -Gap;\ndist_F = sqrt(diff(whltemp(:,1)).^2+diff(whltemp(:,2)).^2);\ndist_R = sqrt(diff(whltemp(:,3)).^2+diff(whltemp(:,4)).^2);\nBigJump_F = dist_F>Gap;\nBigJump_R = dist_R>Gap;\n\nGood_F = find(Whl(:,1)>-1 & ~([BigJump_F;0] | [0;BigJump_F]));\nBad_F = find(~(Whl(:,1)>-1 & ~([BigJump_F;0] | [0;BigJump_F])));\nGood_R = find(Whl(:,3)>-1 & ~([BigJump_R;0] | [0;BigJump_R]));\nBad_R = find(~(Whl(:,3)>-1 & ~([BigJump_R;0] | [0;BigJump_R])));\n\nwhltemp(Bad_F,1:2) = -Gap;\nwhltemp(Bad_R,3:4) = -Gap;\n\nWhlNaN = Whl;\nWhlNaN(find(Whl==-1)) = NaN;\n\n% Give -1 outside of the interpolation.\n\nif length(Good_F)<2 || length(Good_R)<2;\n    cWhl(:,1:2) = -ones(size(Whl,1),2);\nelse\n    cWhl(:,1:2) = interp1(Good_F, Whl(Good_F,1:2), 1:nWhl, 'linear', -1);\n    cWhl(:,3:4) = interp1(Good_R, Whl(Good_R,3:4), 1:nWhl, 'linear', -1);\nend\n\n% find missing stretches for Front LED\ndGoodF = [-(whltemp(1,1)==-Gap) ; diff(whltemp(:,1)>-Gap)];\nBadStartF = find(dGoodF<0);\nBadEndF = find(dGoodF>0)-1;\n% if last point is bad, need to finish off BadEnd\nif Whl(end,1)==-1\n    BadEndF = [BadEndF; nWhl];\nend\n\nif length(BadStartF)>length(BadEndF)\n    BadEndF = [BadEndF; nWhl];\nend\n\n\n% find ranges to chuck\n% jump size ...\nif any(BadStartF>0)\n    \n    StartIndF = clip(BadStartF-1, 1, nWhl); % StartInd and EndInd give the\n    EndIndF = clip(BadEndF+1, 1, nWhl);     % points you are interpolating between\n    \n    dist_F = sqrt((Whl(StartIndF,1)-Whl(EndIndF,1)).^2+(Whl(StartIndF,2)-Whl(EndIndF,2)).^2);\n    ToChuckF = find(BadEndF-BadStartF>=StretchLen ...\n        | dist_F > JumpSize);\n    % chuck em\n    \n    for i=ToChuckF(:)'\n        cWhl(BadStartF(i):BadEndF(i),1:2) = NaN;\n    end\nend\n\n% find missing stretches for Rear LED\ndGoodR = [-(whltemp(1,3)==-Gap) ; diff(whltemp(:,3)>-Gap)];\nBadStartR = find(dGoodR<0);\nBadEndR = find(dGoodR>0)-1;\n% if last point is bad, need to finish off BadEnd\nif Whl(end,3)==-1\n    BadEndR = [BadEndR; nWhl];\nend\n\nif length(BadStartR)>length(BadEndR)\n    BadEndR = [BadEndR; nWhl];\nend\n\n\n% find ranges to chuck\n% jump size ...\nif any(BadStartR>0)\n    StartIndR = clip(BadStartR-1, 1, nWhl); % StartInd and EndInd give the\n    EndIndR = clip(BadEndR+1, 1, nWhl);     % points you are interpolating between\n    \n    dist_R = sqrt((Whl(StartIndR,3)-Whl(EndIndR,3)).^2+(Whl(StartIndR,4)-Whl(EndIndR,4)).^2);\n    ToChuckR = find(BadEndR-BadStartR>=StretchLen ...\n        | dist_R > JumpSize);\n    \n    % chuck em\n    for i=ToChuckR(:)'\n        cWhl(BadStartR(i):BadEndR(i),3:4) = NaN;\n    end\nend\n\n\nif 0 % OLD VERSION (BUG?)\n    % % now find good ranges\n    % dcGood = [-(Whl(1,1)==1) ; diff(cWhl(:,1)>-1)];\n    % GoodStart = find(dcGood>0);\n    % GoodEnd = find(dcGood<0)-1;\n    % % if last point is good, need to finish GoodEnd\n    % if cWhl(end,1)>-1\n    %     GoodEnd = [GoodEnd; nWhl];\n    % end\n    % GoodRanges = [GoodStart, GoodEnd];\nelse\n    dcGood_F = diff([0; cWhl(:,1)>-1; 0]);\n    GoodStart_F = find(dcGood_F>0);\n    GoodEnd_F = find(dcGood_F<0)-1;\n    GoodRanges_F = [GoodStart_F, GoodEnd_F];\nend\n\n\nreturn\n\nend\n\n\nfunction motion = LoadTimeStampValuePairs(tos,fname,varname);\nif ~exist('varname','var')\n    t = load(fname);\nelse\n    t = load(fname,varname);\nend\nfn = fieldnames(t);\nt = getfield(t,fn{1});\nvals = t(:,2);\ntimes = t(:,1);\nmotion = ResampleTolerant_IN(vals,length(tos),length(times));\n\nend\n\n\nfunction Par = LoadParIn(FileName, varargin)\n% LoadPar(FileName)\n% loads the specified par file and returns a structure with these elements:\n%\n% .FileName      -> name of file loaded from\n% .nChannels     -> number of total channels\n% .nBits         -> number of bits of the file\n% .SampleTime    -> time, in microseconds, of 1 sample (ie 1e6 / sample rate)\n% .HiPassFreq    -> High pass filter frequency\n% .nElecGps      -> number of electrodes (i.e. electrode groups)\n% .ElecGp        -> a cell array giving the channels in the electrodes\n%                    e.g. if .ElectrodeGroup{3} = [2 3 4 5], electrode 3\n%                    is a tetrode for channels 2 3 4 and 5. \n% channel numbers here are from 0. be carefull.\n[SpecInfo] = DefaultArgsIn(varargin,{1});\n\nif ~isempty(strfind(FileName,'.par'))\n    FileBase = FileName(1:strfind(FileName,'.par')-1);\nelseif ~isempty(strfind(FileName,'.xml'))\n    FileBase = FileName(1:strfind(FileName,'.xml')-1);\nelse \n    FileBase = FileName;\nend\n\n\nif FileExistsIn([FileBase '.xml']) %& ~isempty(strfind(FileName,'.xml'))\n    Par = LoadParameters([FileBase '.xml']);\nelseif FileExistsIn([FileBase '.par'])\n\n\n    % open file\n\n    fp = fopen([FileBase '.par'], 'r');\n    Par.FileName = FileBase;\n\n    % read in nChannels and nBits\n    Line = fgets(fp);\n    A = sscanf(Line, '%d %d');\n    Par.nChannels = A(1);\n    Par.nBits = A(2);\n\n    % read in SampleTime and HiPassFreq\n    Line = fgets(fp);\n    A = sscanf(Line, '%d %f', 2);\n    Par.SampleTime = A(1);\n    Par.HiPassFreq = A(2);\n\n    % read in nElectrodes\n    Line = fgets(fp);\n    if Line==-1\n        fclose(fp);\n        return;\n    end\n    A = sscanf(Line, '%d', 1);\n    Par.nElecGps = A(1);\n\n    % read in ElectrodeGroup\n    for i=1:Par.nElecGps\n        Line = fgets(fp);\n        A = sscanf(Line, '%d');\n        Par.ElecGp{i} = A(2:end);\n    end\n    fclose(fp);\nelse\n    error('Par or Xml file do not exist!');\nend\n\nif SpecInfo\n    if FileExistsIn([FileBase '.eeg.par'])\n        if ~isfield(Par,'nElecGps')\n            ParTmp = LoadPar([FileBase '.par']);\n        else\n            ParTmp = Par;\n        end\n\n        EegPar=LoadEegPar(FileBase);\n        for el=1:ParTmp.nElecGps\n            for eegel=1:EegPar.nElec\n                if ~isempty(intersect(ParTmp.ElecGp{el},EegPar.ElecChannels{eegel}))\n                    Par.ElecLoc{el} = EegPar.ElecLoc{eegel};\n                end\n            end\n        end\n   \n    end\nend\nend\n\n\nfunction [c] = convtrimIn(a,b)\n% CONVTRIM trimmed convolution\n% c = convtrim(a,b) convolves vectors A and B. The resulting\n% vector is length LENGTH(a)\n%\n% this function is a wrapper for conv - the only difference is the trimming\n\nif (length(a) <= length(b))\n    error('convtrim: the length of vector a must be larger than vector b');\nend\n\ntempC = conv(a,b);\nFrontTrim = floor(length(b)/2);\n\nif (mod(length(b),2) ~= 0)\n    BackTrim = floor(length(b)/2);\nelse\n    BackTrim = floor(length(b)/2)-1;\nend\n\nc = tempC(FrontTrim+1:end-BackTrim);\n\n\n\nend\n\nfunction changeXlim(obj,~)\nFO = guidata(obj);\nxmax = diff(FO.lims);\nn1 = get(FO.xlimbox, 'String');\nn2 = round(str2double(n1));\noldx = get(FO.sax{1}, 'XLim');\nif (n2 <= xmax) && n2 > 0\n    m1 = mean(oldx);\n    newx = [m1 - n2/2, m1 + n2/2];\n    if min(newx) < 0\n        newx = newx - min(newx);\n    end\n    if max(newx) > FO.lims(2)\n        newx = [FO.lims(2) - diff(newx), FO.lims(2)];\n    end\n    \n    set(FO.sax{1}, 'XLim', newx);\n    axes(FO.sax{1});\n    FO = UpdateGUI(FO);\n    if FO.EegUpdateBoolean\n        FO = updateEEG(FO);\n    end\nelse\n    set(FO.xlimbox, 'String', int2str(round(diff(oldx))));\n    return;\nend\nend\n\n\nfunction goToSecond(obj,~)\n% get xlims to generate range\n% get the string to get what the mean should be\n% make newx based on that\n% if less than 0, or greater than max possible, keep the range and set the\n%    one end at the boundary and the other\n% set FO.sax\nFO = guidata(obj);%get guidata\n% xmax = diff(FO.lims);%max x possible\ngotopoint = str2double(get(FO.gotosecondbox, 'String'));\noldrange = get(FO.sax{1}, 'XLim');\nwindowwidth = diff(oldrange);\n% if (n2 <= xmax) & n2 > 0\n\nnewrange = [gotopoint - windowwidth/2, gotopoint + windowwidth/2];\n\nif min(newrange) < 0\n    newrange = [0 windowwidth-1];\nend\nif max(newrange) > FO.lims(2)\n    newrange = [(FO.lims(2)-windowwidth+1), FO.lims(2)];\nend\n\n% set(FO.sax{1}, 'XLim', newrange);  %action step: set axis1, if there are other axes, updateEEG will set any other axes to match it\n% axes(FO.sax{1});\nfor idx = 1:length(FO.sax)\n    set(FO.sax{idx}, 'XLim', newrange);  %action step: set axis1, if there are other axes, updateEEG will set any other axes to match it\n%     axes(FO.sax{idx});\nend\n\nset(FO.gotosecondbox, 'String', '');\n\nFO = UpdateGUI(FO);\nif FO.EegUpdateBoolean\n    if gotopoint > FO.lims(1) && gotopoint <= FO.lims(2)\n        FO = updateEEG(FO,gotopoint);\n    end\nend\n% else\n%     set(FO.xlimbox, 'String', int2str(round(diff(oldx))));\n%     return;\n% end\nend\n\n\nfunction rightScreenOver(obj,~)\n% move over with only 10% overlap from previous screen\nFO = guidata(obj);%get guidata\noldrange = get(FO.sax{1}, 'XLim');\nwindowwidth = diff(oldrange);\n\nnewrange = oldrange+windowwidth*0.9;\n\nif min(newrange) < 0\n    newrange = [0 windowwidth-1];\nend\nif max(newrange) > FO.lims(2)\n    newrange = [(FO.lims(2)-windowwidth+1), FO.lims(2)];\nend\n\nfor idx = 1:length(FO.sax)\n    set(FO.sax{idx}, 'XLim', newrange);  %action step: set axis1, if there are other axes, updateEEG will set any other axes to match it\nend\n\nset(FO.gotosecondbox, 'String', '');\n\nFO = UpdateGUI(FO);\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO);\nend\nend\n\nfunction leftScreenOver(obj,event)\n% move over with only 10% overlap from previous screen\nFO = guidata(obj);%get guidata\noldrange = get(FO.sax{1}, 'XLim');\nwindowwidth = diff(oldrange);\n\nnewrange = oldrange-windowwidth*0.9;\n\nif min(newrange) < 0\n    newrange = [0 windowwidth-1];\nend\nif max(newrange) > FO.lims(2)\n    newrange = [(FO.lims(2)-windowwidth+1), FO.lims(2)];\nend\n\nfor idx = 1:length(FO.sax)\n    set(FO.sax{idx}, 'XLim', newrange);  %action step: set axis1, if there are other axes, updateEEG will set any other axes to match it\nend\n\nset(FO.gotosecondbox, 'String', '');\n\nFO = UpdateGUI(FO);\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO);\nend\nend\n\nfunction FO = ChangeThisStateAssigmnent_Setup(FO,pointTo)\nstates = FO.States;\nds = logical(abs(diff(states)));%find state switches with 1's\nds = cat(2,ds(:)',0);%pad\n\n%find start\nspanstart = find(ds(1:pointTo)>0,1,'last')+1;\nif isempty(spanstart)\n    spanstart = 1;\nend\nif spanstart<1\n    spanstart = 1;\nend\n%find end\nspanend = find(ds(pointTo:end)>0,1,'first') + pointTo-1;\nif isempty(spanend)\n    spanend = length(states);\nend\nif spanend>length(states)\n    spanend = length(states);\nend\nspan = [spanstart spanend];\nFO.spanToReset = span;\n\nFO.currAction = 'ResetState';\n% set(FO.actionDisp, 'String', {'\\fontsize{12}\\bfCurrent Action:', ' ', '\\fontsize{20}Choose New State (1-5)'});\nset(FO.fig,'KeyReleaseFcn', {@ChangeThisStateAssigmnent_Key});\nend\n\nfunction ChangeThisStateAssigmnent_Key(obj,ev)\nFO = guidata(obj);\nstatetype = ev.Key;\nif sum(strcmp(statetype,{'1','2','3','4','5'}))%if key was 1:5\n    if ~isempty(FO.spanToReset)\n        statetype = str2double(statetype);        \n        span = FO.spanToReset;\n        newState = statetype * ones(1,diff(span)+1);\n        \n% s = FO.currentState;\n% f1 = dsearchn(FO.to, FO.startLocation);\n% f2 = dsearchn(FO.to, pointTo);\n% f = [min([f1, f2]), max([f1, f2])];\n% newState = zeros(1, diff(f) + 1) + s;\n\n        oldState = FO.States(span(1):span(2));\n        if length(FO.stateHistory) > FO.stateHistoryNum\n            FO.stateHistory = FO.stateHistory(1:FO.stateHistoryNum);\n            FO.newStates = FO.newStates(1:FO.stateHistoryNum);\n            b = msgbox('Losing a bit of history');\n            uiwait(b);\n        end\n        FO.States(span(1):span(2)) = newState;\n\n        FO.Transitions = [FO.Transitions; statetype, span(1), span(2)];\n        FO.TransHistoryTracker = [FO.TransHistoryTracker, 1];\n        FO.stateHistory{end + 1}.location = span(1);\n        FO.stateHistory{end}.state = oldState;\n        FO.stateHistoryNum = FO.stateHistoryNum + 1;\n        FO.newStates{end + 1}.state = newState;\n        FO.newStates{end}.location = span(1);\n        FO.startLocation  = [];\n% % guidata(FO.fig, FO); \n% FO = modifyStates(f(1), newState);\n% FO = guidata(FO.fig);\n% % updateEEG;\n% \n% %Reset StateAxis ative click toggle based on checkbox status - since adding\n% %state temporarily turns it off.\n% % FO = ResetStateAxisClicabilityByCheckboxStatus(FO);\n% FO = UpdateGUI(FO);        \n        \n        guidata(FO.fig, FO); \n        modifyStates(span(1), newState);\n        FO = guidata(FO.fig);\n    end    \nend\n\nFO.spanToReset = [];\nFO.currAction = 'Browse';\nset(FO.fig,'KeyReleaseFcn', {@DefKey});\n\nFO = UpdateGUI(FO);\nguidata(FO.fig,FO)\nend\n\nfunction FO = ResetStateAxisClicabilityByCheckboxStatus(FO)\n%Reset StateAxis ative click toggle based on checkbox status - since adding\n%state temporarily turns it off.\n\n% if strmatch(FO.currAction,'Add')\n    SAACBool = get(FO.stateAxisActiveCheckbox,'value');\n    if SAACBool\n        FO.stateAxisToggleModeBool = logical(1);\n    elseif ~SAACBool \n        FO.stateAxisToggleModeBool = logical(0);\n    end\n% end\n\nend\n\nfunction a = clip(b, min, max)\n% clip(b, min, max)\n% takes a matrix and replaces any elements below min\n% with min and any above max with max\n\nshape = size(b);\nb = b(:);\nb(find(b<min)) = min;\nb(find(b>max)) = max;\na = reshape(b, shape);\nend\n\nfunction EventNumber(e, src)\n\nobj = findobj('tag','StateEditorMaster');  \nFO = guidata(obj); ;\nEN = get(FO.eventDisp, 'Value') - 1;\n\noldNum = FO.eventNum;\nif EN > 0\n    FO.eventNum = EN;\nelse\n    FO.eventNum = 'none';\nend\nguidata(FO.fig, FO); \n\n% if ~isempty(FO.Events)\n    FO = updateEventLines(FO,FO.Events(FO.Events(:, 1) == EN, 2));\n% else \n% end\n\nguidata(FO.fig, FO); \nif strcmp(FO.currAction, 'AddEvent')\n    if EN == 0\n        FO.currAction = 'Browse';\n        set(gcf, 'Pointer', 'hand');\n        guidata(FO.fig, FO); \n    end\n    FO = UpdateGUI(FO);\nend\n\nend\n\nfunction FO = addEvent(FO,location)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nEN = FO.eventNum;\nFO.Events = [FO.Events; EN, location];\n% guidata(FO.fig, FO); \nFO = updateEventLines(FO,FO.Events(FO.Events(:, 1) == EN, 2));\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n% FO.CurrEventLines{end + 1} = [];\n% \n% for i = 1:FO.nCh\n%     ax = FO.sax{i};\n%     yl = [0 300];\n%     axes(ax);\n%     hold on;\n%     FO.CurrEventLines{end}{panelN} = plot([location, location], [yl(1), yl(2)], ':m', 'LineWidth', 2);\n%     panelN = panelN + 1;\n%     ax = FO.eax{i};\n%     yl = [-10000 10000];\n%     axes(ax);\n%     hold on;\n%     FO.CurrEventLines{end}{panelN} = plot([location, location], [yl(1), yl(2)], ':m', 'LineWidth', 2);\n%     panelN = panelN + 1;\n% end\n% \n% ax = FO.max;\n% yl = get(FO.max, 'YLim');\n% axes(ax);\n% hold on;\n% FO.CurrEventLines{end}{panelN} = plot([location, location], [yl(1), yl(2)], ':m', 'LineWidth', 2);\n% FO.madeChanges = 1;\n\nFO.currAction = 'Browse';\nset(FO.fig, 'Pointer', 'hand');\n% guidata(FO.fig, FO); \nif FO.EegUpdateBoolean\n    FO = updateEEG(FO,location);\nend\nend\n\nfunction FO = deleteEvent(FO,location)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nx1 = get(gca, 'XLim');\nEN = FO.eventNum;\nevents = FO.Events;\nind1 = find(events(:, 1) == EN);\nid = dsearchn(events(events(:, 1) == EN, 2), location);\nif (abs(location - events(ind1(id), 2))/diff(x1)) < 0.01;\n   \n    events = events((1:size(events, 1)) ~= ind1(id), :);\n    FO.Events = events;\n%     guidata(FO.fig, FO); \n    FO = updateEventLines(FO,events(events(:, 1) == EN, 2));\n%     obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\n    \n    FO.currAction = 'Browse';\n    set(FO.fig, 'Pointer', 'hand');\nend\n\n% guidata(FO.fig, FO); \n\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO,location);\nend\n% FO = UpdateText(FO);;\nend\n\nfunction FO = updateEventLines(FO,newTimes)\n% obj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nif isempty(newTimes)\n    for i = 1:length(FO.CurrEventLines)\n        set(FO.CurrEventLines{i}, 'XData', [], 'YData', []);\n    end\n    FO.CurrEventLines = {};\nelse\n    panelN = 1;\n    \n    \n    \n    z = zeros(length(newTimes)*2, 1);\n    z(mod(1:(length(newTimes)*2), 2) == 0) = newTimes;\n    z(mod(1:(length(newTimes)*2), 2) == 1) = newTimes;\n    if mod(length(newTimes), 2) == 1\n        y = repmat([0; 1; 1; 0], (length(newTimes) - 1)/2, 1);\n        y = [y; 0; 1];\n    else\n        y = repmat([0; 1; 1; 0], (length(newTimes))/2, 1);\n    end\n    \n    linesExist = length(FO.CurrEventLines) > 0;\n    for i = 1:FO.nCh\n        \n        axes(FO.sax{i});\n        hold on;\n        yl = y;\n        yl(yl == 0) = FO.saxYLim(1) - 10;\n        yl(yl == 1) = FO.saxYLim(2) + 10;\n        if linesExist == 0\n            FO.CurrEventLines{panelN} = plot(z, yl , ':m', 'LineWidth', 2);\n        else\n            set(FO.CurrEventLines{panelN}, 'XData', z, 'YData', yl);\n        end\n        panelN = panelN + 1;\n        axes(FO.eax{i});\n        hold on;\n        yl = y;\n        yl(yl == 0) = FO.eegYLim(1) - 10;\n        yl(yl == 1) = FO.eegYLim(2) + 10;\n        if linesExist == 0\n            FO.CurrEventLines{panelN} = plot(z, yl , ':m', 'LineWidth', 2);\n        else\n            set(FO.CurrEventLines{panelN}, 'XData', z, 'YData', yl);\n        end\n        panelN = panelN + 1;\n    end\n    axes(FO.max);\n    hold on;\n    yl = y;\n    yl(yl == 0) = FO.mpYLim(1) - 10;\n    yl(yl == 1) = FO.mpYLim(2) + 10;\n    if linesExist == 0\n        FO.CurrEventLines{panelN} = plot(z, yl , ':m', 'LineWidth', 2);\n    else\n        set(FO.CurrEventLines{panelN}, 'XData', z, 'YData', yl);\n    end\n    panelN = panelN + 1;\nend\nnewString = 'none';\n\nevents = FO.Events;\nif isempty(events)\nfor i = 1:10\n        newString = [newString, '|', int2str(i), ' (0 events)'];\n    end\nelse\n    for i = 1:10\n        newString = [newString, '|', int2str(i), ' (', int2str(sum(events(:, 1) == i)), ' events)'];\n    end\nend\nset(FO.eventDisp, 'String', newString);\n\n\n% guidata(FO.fig, FO); \n\nend\n\nfunction nextEvent\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nevents = FO.Events;\nEN = FO.eventNum;\nif isempty(events)\n    warndlg('No events currently selected.');\n    return;\nend\n\nev = events(events(:, 1) == EN, 2);\nif length(ev) == 0\n    warndlg('No events currently selected.');\n    return;\nend\n\n\nev = sort(ev);\ncurrPoint = mean(get(FO.eax{1}, 'XLim'));\nnextE = ev(find(ev > currPoint, 1, 'first'));\nif isempty(nextE)\n    warndlg('No further events to jump to.');\n    return;\nend\n\nsaxLim = diff(get(FO.sax{1}, 'XLim'));\n\nnewLims = [nextE - saxLim/2, nextE + saxLim/2];\nif newLims(1) < FO.lims(1)\n    newLims(2) = newLims(2) + (FO.lims(1) - newLims(1)); \n    newLims(1) = FO.lims(1);\nend\n\nif newLims(2) > FO.lims(2)\n    newLims(1) = newLims(1) + (FO.lims(2) - newLims(2));\n    newLims(2) = FO.lims(2);\nend\n\nif newLims(1) < FO.lims(1)\n    newLims(2) = newLims(2) + (FO.lims(1) - newLims(1)); \n    newLims(1) = FO.lims(1);\nend\n\nset(FO.sax{1}, 'XLim', newLims);\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO,nextE);\nend\nend\n\n\n\nfunction previousEvent\nobj = findobj('tag','StateEditorMaster');  FO = guidata(obj); ;\nevents = FO.Events;\nEN = FO.eventNum;\nif isempty(events)\n    warndlg('No events currently selected.');\n    return;\nend\n\nev = events(events(:, 1) == EN, 2);\nif length(ev) == 0\n    warndlg('No events currently selected.');\n    return;\nend\n\n\nev = sort(ev);\ncurrPoint = mean(get(FO.eax{1}, 'XLim'));\nnextE = ev(find(ev < currPoint, 1, 'last'));\nif isempty(nextE)\n    warndlg('No previous events to jump to.');\n    return;\nend\n\nsaxLim = diff(get(FO.sax{1}, 'XLim'));\n\nnewLims = [nextE - saxLim/2, nextE + saxLim/2];\nif newLims(1) < FO.lims(1)\n    newLims(2) = newLims(2) + (FO.lims(1) - newLims(1)); \n    newLims(1) = FO.lims(1);\nend\n\nif newLims(2) > FO.lims(2)\n    newLims(1) = newLims(1) + (FO.lims(2) - newLims(2));\n    newLims(2) = FO.lims(2);\nend\n\nif newLims(1) < FO.lims(1)\n    newLims(2) = newLims(2) + (FO.lims(1) - newLims(1)); \n    newLims(1) = FO.lims(1);\nend\n\nset(FO.sax{1}, 'XLim', newLims);\nif FO.EegUpdateBoolean\n    FO = updateEEG(FO,nextE);\nend\nend\n\nfunction E = FileExistsIn(name)\nif length(dir(name)) > 0\n    E = 1;\nelse\n    E = 0;\nend\nend\n\nfunction skullCursor\n\nskull = [NaN   NaN   NaN     2     1     1     1     1     1     1     1     2   NaN   NaN   NaN   NaN\n    NaN     2     1     1     1     1   NaN     1     1     1     1     1     1     2   NaN   NaN\n    2     1     1     1     1   NaN   NaN   NaN     1     1     1     1     1     1     2   NaN\n    2     1     1     1     1     1   NaN     1     1     1     1     1     1     1     2   NaN\n    2     1     1     1     1     1     1     1     1     1     1     1     1     1     2   NaN\n    2     1     1     2     2     2     1     1     1     2     2     2     1     1     2   NaN\n    2     1     1     2     2     2     1     1     1     2     2     2     1     1     2   NaN\n    2     1     1     1     2     1     1     1     1     1     2     1     1     1     2   NaN\n    NaN     2     1     1     1     1     1     2     1     1     1     1     1     2   NaN   NaN\n    NaN     2     1     1     1     1     2     2     2     1     1     1     1     2   NaN   NaN\n    NaN   NaN     2     1     1     1     1     1     1     1     1     1     2   NaN   NaN   NaN\n    NaN   NaN     2     1     2     1     1     1     1     1     2     1     2   NaN   NaN   NaN\n    NaN   NaN     2     1     1     2     1     1     1     2     1     1     2   NaN   NaN   NaN\n    NaN   NaN   NaN     2     1     1     2     2     2     1     1     2   NaN   NaN   NaN   NaN\n    NaN   NaN   NaN   NaN     2     1     1     1     1     1     2   NaN   NaN   NaN   NaN   NaN\n    NaN   NaN   NaN   NaN   NaN     2     1     1     1     2   NaN   NaN   NaN   NaN   NaN   NaN];\n\nset(gcf, 'PointerShapeCData', skull );\nset(gcf, 'Pointer', 'custom');\nend\n\nfunction [y, f, t, phi, FStats]=mtchglongIn(varargin);\n%function [yo, fo, to, phi, FStats]=mtchglong(x,nFFT,Fs,WinLength,nOverlap,NW,Detrend,nTapers,FreqRange);\n% Multitaper Time-Frequency Cross-Spectrum (cross spectrogram)\n% for long files - splits data into blockes to save memory\n% function A=mtcsg(x,nFFT,Fs,WinLength,nOverlap,NW,nTapers)\n% x : input time series\n% nFFT = number of points of FFT to calculate (default 1024)\n% Fs = sampling frequency (default 2)\n% WinLength = length of moving window (default is nFFT)\n% nOverlap = overlap between successive windows (default is WinLength/2)\n% NW = time bandwidth parameter (e.g. 3 or 4), default 3\n% nTapers = number of data tapers kept, default 2*NW -1\n%\n% output yo is yo(f, t)\n%\n% If x is a multicolumn matrix, each column will be treated as a time\n% series and you'll get a matrix of cross-spectra out yo(f, t, Ch1, Ch2)\n% NB they are cross-spectra not coherences. If you want coherences use\n% mtcohere\n\n% Original code by Partha Mitra - modified by Ken Harris \n% and adopted for long files and phase by Anton Sirota\n% Also containing elements from specgram.m\n\n% default arguments and that\n[x,nFFT,Fs,WinLength,nOverlap,NW,Detrend,nTapers,nChannels,nSamples,nFFTChunks,winstep,select,nFreqBins,f,t] = mtparamIn(varargin);\n\n% allocate memory now to avoid nasty surprises later\ny=complex(zeros(nFFTChunks,nFreqBins, nChannels, nChannels)); % output array\nif nargout>3\n    phi=complex(zeros(nFFTChunks,nFreqBins, nChannels, nChannels));\nend\nnFFTChunksall= nFFTChunks;\nfreemem = FreeMemoryIn;\nBlockSize = 2^8;\nnBlocks = ceil(nFFTChunksall/BlockSize);\n%h = waitbar(0,'Wait..');\nfor Block=1:nBlocks\n    %   waitbar(Block/nBlocks,h);\n    minChunk = 1+(Block-1)*BlockSize;\n    maxChunk = min(Block*BlockSize,nFFTChunksall);\n    nFFTChunks = maxChunk - minChunk+1;\n    iChunks = [minChunk:maxChunk];\n    Periodogram = complex(zeros(nFreqBins, nTapers, nChannels, nFFTChunks)); % intermediate FFTs\n    Temp1 = complex(zeros(nFreqBins, nTapers, nFFTChunks));\n    Temp2 = complex(zeros(nFreqBins, nTapers, nFFTChunks));\n    Temp3 = complex(zeros(nFreqBins, nTapers, nFFTChunks));\n    eJ = complex(zeros(nFreqBins, nFFTChunks));\n    tmpy =complex(zeros(nFreqBins,nFFTChunks, nChannels, nChannels));\n    % calculate Slepian sequences.  Tapers is a matrix of size [WinLength, nTapers]\n    [Tapers V]=dpss(WinLength,NW,nTapers, 'calc');\n    % New super duper vectorized alogirthm\n    % compute tapered periodogram with FFT \n    % This involves lots of wrangling with multidimensional arrays.\n    \n    TaperingArray = repmat(Tapers, [1 1 nChannels]);\n    for j=1:nFFTChunks\n        jcur = iChunks(j);\n        Segment = x((jcur-1)*winstep+[1:WinLength], :);\n        if (~isempty(Detrend))\n            Segment = detrend(Segment, Detrend);\n        end;\n        SegmentsArray = permute(repmat(Segment, [1 1 nTapers]), [1 3 2]);\n        TaperedSegments = TaperingArray .* SegmentsArray;\n        \n        fftOut = fft(TaperedSegments,nFFT);\n        normfac = sqrt(2/nFFT); %to get back rms of original units\n        Periodogram(:,:,:,j) = fftOut(select,:,:)*normfac; %fft(TaperedSegments,nFFT);\n        % Periodogram: size  = nFreqBins, nTapers, nChannels, nFFTChunks\n    end\t\n    if nargout>4\n        U0 = repmat(sum(Tapers(:,1:2:end)),[nFreqBins,1,nChannels,   nFFTChunks]);\n        Mu = sq(sum(Periodogram(:,1:2:end,:,:) .* conj(U0), 2) ./  sum(abs(U0).^2, 2));\n        Num = abs(Mu).^2;\n        Sp = sq(sum(abs(Periodogram).^2,2));\n        chunkFS = (nTapers-1) * Num ./ (Sp ./ sq(sum(abs(U0).^2, 2))- Num );\n        %\tsum(abs(Periodogram - U0.*repmat(Mu,[1,nTapers,1,1])), 2);\n        FStats(iChunks, :, :)  = permute(reshape(chunkFS, [nFreqBins, nChannels, nFFTChunks]),[ 3 1, 2]);\n    end\n    % Now make cross-products of them to fill cross-spectrum matrix\n    for Ch1 = 1:nChannels\n        for Ch2 = Ch1:nChannels % don't compute cross-spectra twice\n            Temp1 = reshape(Periodogram(:,:,Ch1,:), [nFreqBins,nTapers,nFFTChunks]);\n            Temp2 = reshape(Periodogram(:,:,Ch2,:), [nFreqBins,nTapers,nFFTChunks]);\n            Temp2 = conj(Temp2);\n            Temp3 = Temp1 .* Temp2;\n            eJ=sum(Temp3, 2);\n            tmpy(:,:, Ch1, Ch2)= eJ/nTapers;\n            \n            % for off-diagonal elements copy into bottom half of matrix\n            if (Ch1 ~= Ch2)\n                tmpy(:,:, Ch2, Ch1) = conj(eJ) / nTapers;\n            end            \n            \n        end\n    end\n    \n    for Ch1 = 1:nChannels\n        for Ch2 = 1:nChannels % don't compute cross-spectra twice\n            \n            if (Ch1 == Ch2)\n                % for diagonal elements (i.e. power spectra) leave unchanged\n                y(iChunks,:,Ch1, Ch2) = permute(tmpy(:,:,Ch1, Ch2),[2 1 3 4]);\n            else\n                % for off-diagonal elements, scale\n                \n                y(iChunks,:,Ch1, Ch2) = permute((abs(tmpy(:,:,Ch1, Ch2).^2) ...\n                    ./ (tmpy(:,:,Ch1,Ch1) .* tmpy(:,:,Ch2,Ch2))), [2 1 3 4]);\n                if nargout>3\n                    phi(iChunks,:,Ch1,Ch2) = permute(angle(tmpy(:,:,Ch1, Ch2) ...\n                        ./ sqrt(tmpy(:,:,Ch1,Ch1) .* tmpy(:,:,Ch2,Ch2))), [2 1 3 4]); \n                end\n            end\n        end\n    end\n    \n    \nend\n%close(h);\n% we've now done the computation.  the rest of this code is stolen from\n% specgram and just deals with the output stage\n\nif nargout == 0\n    % take abs, and use image to display results\n    newplot;\n    for Ch1=1:nChannels, for Ch2 = 1:nChannels\n            subplot(nChannels, nChannels, Ch1 + (Ch2-1)*nChannels);\n\t    if Ch1==Ch2\n\t\tif length(t)==1\n\t\t\timagesc([0 1/f(2)],f,20*log10(abs(y(:,:,Ch1,Ch2))+eps)');axis xy; colormap(jet);\n\t\telse\n\t\t\timagesc(t,f,20*log10(abs(y(:,:,Ch1,Ch2))+eps)');axis xy; colormap(jet);\n\t\tend\n\t    else\n\t    \timagesc(t,f,(abs(y(:,:,Ch1,Ch2)))');axis xy; colormap(jet);\n\t    end\n        end; end;\n    xlabel('Time')\n    ylabel('Frequency')\nend\nend\n\n\n%LoadBinary - Load data from a binary file.\n%\n%  USAGE\n%\n%    data = LoadBinary(filename,<options>)\n%\n%    filename       file to read\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'duration'    duration to read (in s) (default = Inf)\n%     'frequency'   sampling rate (in Hz) (default = 20kHz)\n%     'start'       position to start reading (in s) (default = 0)\n%     'nChannels'   number of data channels in the file (default = 1)\n%     'channels'    channels to read (default = all)\n%     'precision'   sample precision (default = 'int16')\n%     'skip'        number of bytes to skip after each value is read\n%                   (default = 0)\n%    =========================================================================\n\n% Copyright (C) 2004-2006 by Micha?l 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 2 of the License, or\n% (at your option) any later version.\n\nfunction data = LoadBinaryIn(filename,varargin)\n\n% Default values\nstart = 0;\nnChannels = 1;\nprecision = 'int16';\nskip = 0;\nduration = Inf;\nfrequency = 20000;\nchannels = 1;\n\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n  error('Incorrect number of parameters (type ''help LoadBinary'' for details).');\nend\n\n% Parse options\nfor i = 1:2:length(varargin),\n  if ~isa(varargin{i},'char'),\n    error(['Parameter ' num2str(i+3) ' is not a property (type ''help LoadBinary'' for details).']);\n  end\n  switch(lower(varargin{i})),\n    case 'duration',\n      duration = varargin{i+1};\n      if ~isa(duration,'numeric') | length(duration) ~= 1 | duration < 0,\n        error('Incorrect value for property ''duration'' (type ''help LoadBinary'' for details).');\n      end\n    case 'frequency',\n      frequency = varargin{i+1};\n      if ~isa(frequency,'numeric') | length(frequency) ~= 1 | frequency <= 0,\n        error('Incorrect value for property ''frequency'' (type ''help LoadBinary'' for details).');\n      end\n    case 'start',\n      start = varargin{i+1};\n      if ~isa(start,'numeric') | length(start) ~= 1,\n        error('Incorrect value for property ''start'' (type ''help LoadBinary'' for details).');\n      end\n\t\tif start < 0, start = 0; end\n    case 'nchannels',\n      nChannels = varargin{i+1};\n      if ~((round(channels) == channels & channels > 0)) | length(nChannels) ~= 1,\n        error('Incorrect value for property ''nChannels'' (type ''help LoadBinary'' for details).');\n      end\n    case 'channels',\n      channels = varargin{i+1};\n      if ~(round(channels) == channels & channels > 0)\n        error('Incorrect value for property ''channels'' (type ''help LoadBinary'' for details).');\n      end\n    case 'precision',\n      precision = varargin{i+1};\n      if ~isa(precision,'char'),\n        error('Incorrect value for property ''precision'' (type ''help LoadBinary'' for details).');\n      end\n    case 'skip',\n      skip = varargin{i+1};\n      if ~IsPositiveInteger(skip) | length(skip) ~= 1,\n        error('Incorrect value for property ''skip'' (type ''help LoadBinary'' for details).');\n      end\n    otherwise,\n      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help LoadBinary'' for details).']);\n  end\nend\n\nsizeInBytes = 0;\nswitch precision,\n\tcase {'uchar','unsigned char','schar','signed char','int8','integer*1','uint8','integer*1'},\n\t\tsizeInBytes = 1;\n\tcase {'int16','integer*2','uint16','integer*2'},\n\t\tsizeInBytes = 2;\n\tcase {'int32','integer*4','uint32','integer*4','single','real*4','float32','real*4'},\n\t\tsizeInBytes = 4;\n\tcase {'int64','integer*8','uint64','integer*8','double','real*8','float64','real*8'},\n\t\tsizeInBytes = 8;\nend\n\nf = fopen(filename,'r');\n\n% Position file index for reading\nstart = floor(start*frequency)*nChannels*sizeInBytes;\nstatus = fseek(f,start,'bof');\nif status ~= 0,\n    fclose(f);\n    error('Could not start reading (possible reasons include trying to read past the end of the file).');\nend\n\n% Determine number of samples when duration is 'inf'\nif isinf(duration),\n\tfileStart = ftell(f);\n\tstatus = fseek(f,0,'eof');\n\tif status ~= 0,\n\t\tfclose(f);\n\t\terror('Error reading the data file (possible reasons include trying to read past the end of the file).');\n\tend\n\tfileStop = ftell(f);\n\tnSamplesPerChannel = (fileStop-fileStart)/nChannels/sizeInBytes;\n\tduration = nSamplesPerChannel/frequency;\n\tfrewind(f);\n\tstatus = fseek(f,start,'bof');\n\tif status ~= 0,\n\t\tfclose(f);\n\t\terror('Could not start reading (possible reasons include trying to read past the end of the file).');\n\tend\nelse\n    nSamplesPerChannel = floor(frequency*duration);\n    if nSamplesPerChannel ~= frequency*duration,\n        %disp(['Warning: rounding duration (' num2str(duration) ' -> ' num2str(nSamplesPerChannel/frequency) ')']);\n        duration = nSamplesPerChannel/frequency;\n    end\nend\n\n% For large amounts of data, read chunk by chunkChangeThisStateAssigmnent_Key\n\nmaxSamplesPerChunk = 100000;\nnSamples = nChannels*nSamplesPerChannel;\nif nSamples > maxSamplesPerChunk,\n\t% Determine chunk duration and number of chunks\n\tnSamplesPerChunk = floor(maxSamplesPerChunk/nChannels)*nChannels;\n\tdurationPerChunk = nSamplesPerChunk/frequency/nChannels;\n\tnChunks = floor(duration/durationPerChunk);\n\t% Preallocate memory\n\tdata = zeros(nSamplesPerChannel,length(channels),precision);\n\t% Read all chunks\n\ti = 1;\n\tfor j = 1:nChunks,\n\t\td = LoadBinaryChunkIn(f,'frequency',frequency,'nChannels',nChannels,'channels',channels,'duration',durationPerChunk,'skip',skip);\n\t\t[m,n] = size(d);\n\t\tif m == 0, break; end\n\t\tdata(i:i+m-1,:) = d;\n\t\ti = i+m;\n%  \t\th=waitbar(j/nChunks);\n\tend\n%  \tclose(h)\n\t% If the data size is not a multiple of the chunk size, read the remainder\n\tremainder = duration - nChunks*durationPerChunk;\n\tif remainder ~= 0,\n\t\td = LoadBinaryChunkIn(f,'frequency',frequency,'nChannels',nChannels,'channels',channels,'duration',remainder,'skip',skip);\n\t\t[m,n] = size(d);\n\t\tif m ~= 0,\n\t\t\tdata(i:i+m-1,:) = d;\n\t\tend\n\tend\nelse\n    if skip ~= 0,\n        data = fread(f,[nChannels frequency*duration],precision,skip);\n    else\n        data = fread(f,[nChannels frequency*duration],precision);\n    end\n    data=data';\n    \n    if ~isempty(channels),\n        data = data(:,channels);\n    end\nend\nfclose(f);\nend\n\n% helper function to do argument defaults etc for mt functions\nfunction [x,nFFT,Fs,WinLength,nOverlap,NW,Detrend,nTapers,nChannels,nSamples,nFFTChunks,winstep,select,nFreqBins,f,t,FreqRange] ...\n    = mtparamIn(P)\n\nnargs = length(P);\n\nx = P{1};\nif (nargs<2 | isempty(P{2})) nFFT = 1024; else nFFT = P{2}; end;\nif (nargs<3 | isempty(P{3})) Fs = 1250; else Fs = P{3}; end;\nif (nargs<4 | isempty(P{4})) WinLength = nFFT; else WinLength = P{4}; end;\nif (nargs<5 | isempty(P{5})) nOverlap = WinLength/2; else nOverlap = P{5}; end;\nif (nargs<6 | isempty(P{6})) NW = 3; else NW = P{6}; end;\nif (nargs<7 | isempty(P{7})) Detrend = ''; else Detrend = P{7}; end;\nif (nargs<8 | isempty(P{8})) nTapers = 2*NW -1; else nTapers = P{8}; end;\nif (nargs<9 | isempty(P{9})) FreqRange = [0 Fs/2]; else FreqRange = P{9}; end\n% Now do some compuatations that are common to all spectrogram functions\nif size(x,1)<size(x,2)\n    x = x';\nend\nnChannels = size(x, 2);\nnSamples = size(x,1);\n\nif length(nOverlap)==1\n    winstep = WinLength - nOverlap;\n    % calculate number of FFTChunks per channel\n    %remChunk = rem(nSamples-Window)\n    nFFTChunks = max(1,round(((nSamples-WinLength)/winstep))); %+1  - is it ? but then get some error in the chunking in mtcsd... let's figure it later\n    t = winstep*(0:(nFFTChunks-1))'/Fs;\nelse\n    winstep = 0;\n    nOverlap = nOverlap(nOverlap>WinLength/2 & nOverlap<nSamples-WinLength/2);\n    nFFTChunks = length(nOverlap);\n    t = nOverlap(:)/Fs; \nend \n%here is how welch.m of matlab does it:\n% LminusOverlap = L-noverlap;\n% xStart = 1:LminusOverlap:k*LminusOverlap;\n% xEnd   = xStart+L-1;\n% welch is doing k = fix((M-noverlap)./(L-noverlap)); why?\n% turn this into time, using the sample frequency\n\n\n% set up f and t arrays\nif isreal(x)%~any(any(imag(x)))    % x purely real\n\tif rem(nFFT,2),    % nfft odd\n\t\tselect = [1:(nFFT+1)/2];\n\telse\n\t\tselect = [1:nFFT/2+1];\n\tend\n\tnFreqBins = length(select);\nelse\n\tselect = 1:nFFT;\nend\nf = (select - 1)'*Fs/nFFT;\nnFreqRanges = size(FreqRange,1);\n%if (FreqRange(end)<Fs/2)\nif nFreqRanges==1\n    select = find(f>FreqRange(1) & f<FreqRange(end));\n    f = f(select);\n    nFreqBins = length(select);\nelse\n    select=[];\n    for i=1:nFreqRanges\n        select=cat(1,select,find(f>FreqRange(i,1) & f<FreqRange(i,2)));\n    end\n    f = f(select);\n    nFreqBins = length(select);\nend\n%end\nend\n\n%LoadBinaryChunk - Load data chunck from an open binary file.\n%\n%  USAGE\n%\n%    data = LoadBinaryChunk(fid,<options>)\n%\n%    fid            file id (obtained via fopen)\n%    <options>      optional list of property-value pairs (see table below)\n%\n%    =========================================================================\n%     Properties    Values\n%    -------------------------------------------------------------------------\n%     'duration'    duration to read (in s) (default = 1s)\n%     'frequency'   sampling rate (in Hz) (default = 20kHz)\n%     'start'       position to start reading (in s) (default = from current\n%                   index, allowing to read a file chunck by chunck)\n%     'nChannels'   number of data channels in the file (default = 1)\n%     'precision'   sample precision (default = 'int16')\n%    =========================================================================\n\n% Copyright (C) 2004-2006 by Micha?l 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 2 of the License, or\n% (at your option) any later version.\n\nfunction data = LoadBinaryChunkIn(fid,varargin)\n\n% Default values\nstart = 0;\nfromCurrentIndex = true;\nnChannels = 1;\nprecision = 'int16';\nduration = 1;\nfrequency = 20000;\nchannels = [];\n\nif nargin < 1 | mod(length(varargin),2) ~= 0,\n  error('Incorrect number of parameters (type ''help LoadBinaryChunk'' for details).');\nend\n\n% Parse options\nfor i = 1:2:length(varargin),\n  if ~isa(varargin{i},'char'),\n    error(['Parameter ' num2str(i+3) ' is not a property (type ''help LoadBinaryChunk'' for details).']);\n  end\n  switch(lower(varargin{i})),\n    case 'duration',\n      duration = varargin{i+1};\n      if ~isa(duration,'numeric') | length(duration) ~= 1 | duration < 0,\n        error('Incorrect value for property ''duration'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    case 'frequency',\n      frequency = varargin{i+1};\n      if ~isa(frequency,'numeric') | length(frequency) ~= 1 | frequency <= 0,\n        error('Incorrect value for property ''frequency'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    case 'start',\n      start = varargin{i+1};\n      fromCurrentIndex = false;\n      if ~isa(start,'numeric') | length(start) ~= 1,\n        error('Incorrect value for property ''start'' (type ''help LoadBinaryChunk'' for details).');\n      end\n\t\tif start < 0, start = 0; end\n    case 'nchannels',\n      nChannels = varargin{i+1};\n      if ~isa(nChannels,'numeric') | length(nChannels) ~= 1,\n        error('Incorrect value for property ''nChannels'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    case 'channels',\n      channels = varargin{i+1};\n      if ~isa(channels,'numeric'),\n        error('Incorrect value for property ''channels'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    case 'precision',\n      precision = varargin{i+1};\n      if ~isa(precision,'char'),\n        error('Incorrect value for property ''precision'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    case 'skip',\n      skip = varargin{i+1};\n      if ~isa(skip,'numeric') | length(skip) ~= 1,\n        error('Incorrect value for property ''skip'' (type ''help LoadBinaryChunk'' for details).');\n      end\n    otherwise,\n      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help LoadBinaryChunk'' for details).']);\n  end\nend\n\nsizeInBytes = 0;\nswitch precision,\n\tcase {'uchar','unsigned char','schar','signed char','int8','integer*1','uint8','integer*1'},\n\t\tsizeInBytes = 1;\n\tcase {'int16','integer*2','uint16','integer*2'},\n\t\tsizeInBytes = 2;\n\tcase {'int32','integer*4','uint32','integer*4','single','real*4','float32','real*4'},\n\t\tsizeInBytes = 4;\n\tcase {'int64','integer*8','uint64','integer*8','double','real*8','float64','real*8'},\n\t\tsizeInBytes = 8;\nend\n\n% Position file index for reading\nif ~fromCurrentIndex,\n\tstart = floor(start*frequency)*nChannels*sizeInBytes;\n\tstatus = fseek(fid,start,'bof');\n\tif status ~= 0,\n\t\terror('Could not start reading (possible reasons include trying to read a closed file or past the end of the file).');\n\tend\nend\n\n% Read data chunck\nif skip ~= 0,\n\tdata = fread(fid,[nChannels frequency*duration],precision,skip);\nelse\n\tdata = fread(fid,[nChannels frequency*duration],precision);\nend;\ndata=data';\n\n% Keep only required channels\nif ~isempty(channels) & ~isempty(data),\n\tdata = data(:,channels);\nend\n\nend\n\nfunction [y, A] = WhitenSignalIn(x,varargin)\n\n%artype =2; %Signal processing toolbox\nartype =1; %arfit toolbox, (crushes sometimes with old version and single data type)\n\n[window,CommonAR, ARmodel,ArOrder] = DefaultArgsIn(varargin,{[],1,[],1});\nArOrder = ArOrder+1;\nTrans = 0;\nif size(x,1)<size(x,2)\n    x = x';\n    Transf =1;\nend\n[nT nCh]  = size(x);\ny = zeros(nT,nCh);\nif isempty(window)\n    seg = [1 nT];\n    nwin=1;\nelse\n    nwin = floor(nT/window)+1;\n    seg = repmat([1 window],nwin,1)+repmat([0:nwin-1]'*window,1,2);\n    if nwin*window>nT\n        seg(end,2) =nT;\n    end   \nend\n\nfor j=1:nwin\n    if ~isempty(ARmodel) \n        A = ARmodel;\n        for i=1:nCh\n            y(seg(j,1):seg(j,2),i) = Filter0In(A, x(seg(j,1):seg(j,2),i));\n        end\n    else\n        if CommonAR % meaning common model for all channels and segments!!! \n            for i=1:nCh\n                if  j==1 & i==1\n                    switch artype\n                        case 1\n                            [w Atmp] = arfitIn(x(seg(j,1):seg(j,2),i),ArOrder,ArOrder);\n                            A = [1 -Atmp];\n                        case 2\n                            A = arburg(x(seg(j,1):seg(j,2),i),ArOrder);\n                    end\n                    ARmodel = A;\n                end\n                y(seg(j,1):seg(j,2),i) = Filter0In(A, x(seg(j,1):seg(j,2),i));\n            end\n        else\n            for i=1:nCh\n                switch artype\n                    case 1\n                        [w Atmp] = arfitIn(x(seg(j,1):seg(j,2),i),ArOrder,ArOrder);\n                        A =[1 -Atmp];\n                    case 2\n                        A = arburg(x(seg(j,1):seg(j,2),i),ArOrder);\n                end\n                y(seg(j,1):seg(j,2),i) = Filter0In(A, x(seg(j,1):seg(j,2),i));\n            end\n        end\n    end\nend\n\nif Trans\n    y =y';\nend\n\nend\n\n\nfunction varargout = DefaultArgsIn(Args, DefArgs)\n% auxillary function to replace argument check in the beginning and def. args assigment\n% sets the absent or empty values of the Args (cell array, usually varargin)\n% to their default values from the cell array DefArgs. \n% Output should contain the actuall names of arguments that you use in the function\n\n% e.g. : in function MyFunction(somearguments , varargin)\n% calling [SampleRate, BinSize] = DefaultArgs(varargin, {20000, 20});\n% will assign the defualt values to SampleRate and BinSize arguments if they\n% are empty or absent in the varargin cell list \n% (not passed to a function or passed empty)\nif isempty(Args)\n    Args ={[]};\nend\n\nif iscell(Args{1}) & length(Args)==1\n    Args = Args{1};\nend\n\nnDefArgs = length(DefArgs);\nnInArgs = length(Args);\n%out = cell(nDefArgs,1);\nif (nargout~=nDefArgs)\n    error('number of defaults is different from assigned');\n    keyboard\nend\nfor i=1:nDefArgs\n    if (i>nInArgs | isempty(Args{i}))\n        varargout(i) = {DefArgs{i}};\n    else \n        varargout(i) = {Args{i}};\n    end\nend\n\nend\n\n\nfunction [w, A, C, sbc, fpe, th]=arfitIn(v, pmin, pmax, selector, no_const)\n%ARFIT\tStepwise least squares estimation of multivariate AR model.\n%\n%  [w,A,C,SBC,FPE,th]=ARFIT(v,pmin,pmax) produces estimates of the\n%  parameters of a multivariate AR model of order p,\n%\n%      v(k,:)' = w' + A1*v(k-1,:)' +...+ Ap*v(k-p,:)' + noise(C),\n%\n%  where p lies between pmin and pmax and is chosen as the optimizer\n%  of Schwarz's Bayesian Criterion. The input matrix v must contain\n%  the time series data, with columns of v representing variables\n%  and rows of v representing observations.  ARFIT returns least\n%  squares estimates of the intercept vector w, of the coefficient\n%  matrices A1,...,Ap (as A=[A1 ... Ap]), and of the noise covariance\n%  matrix C.\n%\n%  As order selection criteria, ARFIT computes approximations to\n%  Schwarz's Bayesian Criterion and to the logarithm of Akaike's Final\n%  Prediction Error. The order selection criteria for models of order\n%  pmin:pmax are returned as the vectors SBC and FPE.\n%\n%  The matrix th contains information needed for the computation of\n%  confidence intervals. ARMODE and ARCONF require th as input\n%  arguments.\n%       \n%  If the optional argument SELECTOR is included in the function call,\n%  as in ARFIT(v,pmin,pmax,SELECTOR), SELECTOR is used as the order\n%  selection criterion in determining the optimum model order. The\n%  three letter string SELECTOR must have one of the two values 'sbc'\n%  or 'fpe'. (By default, Schwarz's criterion SBC is used.) If the\n%  bounds pmin and pmax coincide, the order of the estimated model\n%  is p=pmin=pmax. \n%\n%  If the function call contains the optional argument 'zero' as the\n%  fourth or fifth argument, a model of the form\n%\n%         v(k,:)' = A1*v(k-1,:)' +...+ Ap*v(k-p,:)' + noise(C) \n%\n%  is fitted to the time series data. That is, the intercept vector w\n%  is taken to be zero, which amounts to assuming that the AR(p)\n%  process has zero mean.\n\n%  Modified 14-Oct-00\n%  Authors: Tapio Schneider\n%           tapio@gps.caltech.edu\n%\n%           Arnold Neumaier\n%           neum@cma.univie.ac.at\n\n  % n: number of observations; m: dimension of state vectors\n  [n,m]   = size(v);     \n\n  if (pmin ~= round(pmin) | pmax ~= round(pmax))\n    error('Order must be integer.');\n  end\n  if (pmax < pmin)\n    error('PMAX must be greater than or equal to PMIN.')\n  end\n\n  % set defaults and check for optional arguments\n  if (nargin == 3)              % no optional arguments => set default values\n    mcor       = 1;               % fit intercept vector\n    selector   = 'sbc';\t          % use SBC as order selection criterion\n  elseif (nargin == 4)          % one optional argument\n    if strcmp(selector, 'zero')\n      mcor     = 0;               % no intercept vector to be fitted\n      selector = 'sbc';\t          % default order selection \n    else\n      mcor     = 1; \t\t  % fit intercept vector\n    end\n  elseif (nargin == 5)          % two optional arguments\n    if strcmp(no_const, 'zero')\n      mcor     = 0;               % no intercept vector to be fitted\n    else\n      error(['Bad argument. Usage: ', ...\n\t     '[w,A,C,SBC,FPE,th]=AR(v,pmin,pmax,SELECTOR,''zero'')'])\n    end\n  end\n\n  ne  \t= n-pmax;               % number of block equations of size m\n  npmax\t= m*pmax+mcor;          % maximum number of parameter vectors of length m\n\n  if (ne <= npmax)\n    error('Time series too short.')\n  end\n\n  % compute QR factorization for model of order pmax\n  [R, scale]   = arqrIn(v, pmax, mcor);\n\n  % compute approximate order selection criteria for models \n  % of order pmin:pmax\n  [sbc, fpe]   = arordIn(R, m, mcor, ne, pmin, pmax);\n\n  % get index iopt of order that minimizes the order selection \n  % criterion specified by the variable selector\n  [val, iopt]  = min(eval(selector)); \n\n  % select order of model\n  popt         = pmin + iopt-1; % estimated optimum order \n  np           = m*popt + mcor; % number of parameter vectors of length m\n\n  % decompose R for the optimal model order popt according to \n  %\n  %   | R11  R12 |\n  % R=|          |\n  %   | 0    R22 |\n  %\n  R11   = R(1:np, 1:np);\n  R12   = R(1:np, npmax+1:npmax+m);    \n  R22   = R(np+1:npmax+m, npmax+1:npmax+m);\n\n  % get augmented parameter matrix Aaug=[w A] if mcor=1 and Aaug=A if mcor=0\n  if (np > 0)   \n    if (mcor == 1)\n      % improve condition of R11 by re-scaling first column\n      con \t= max(scale(2:npmax+m)) / scale(1); \n      R11(:,1)\t= R11(:,1)*con; \n    end;\n    Aaug = (R11\\R12)';\n    \n    %  return coefficient matrix A and intercept vector w separately\n    if (mcor == 1)\n      % intercept vector w is first column of Aaug, rest of Aaug is \n      % coefficient matrix A\n      w = Aaug(:,1)*con;        % undo condition-improving scaling\n      A = Aaug(:,2:np);\n    else\n      % return an intercept vector of zeros \n      w = zeros(m,1);\n      A = Aaug;\n    end\n  else\n    % no parameters have been estimated \n    % => return only covariance matrix estimate and order selection \n    % criteria for ``zeroth order model''  \n    w   = zeros(m,1);\n    A   = [];\n  end\n  \n  % return covariance matrix\n  dof   = ne-np;                % number of block degrees of freedom\n  C     = R22'*R22./dof;        % bias-corrected estimate of covariance matrix\n  \n  % for later computation of confidence intervals return in th: \n  % (i)  the inverse of U=R11'*R11, which appears in the asymptotic \n  %      covariance matrix of the least squares estimator\n  % (ii) the number of degrees of freedom of the residual covariance matrix \n  invR11 = inv(R11);\n  if (mcor == 1)\n    % undo condition improving scaling\n    invR11(1, :) = invR11(1, :) * con;\n  end\n  Uinv   = invR11*invR11';\n  th     = [dof zeros(1,size(Uinv,2)-1); Uinv];\nend\n\nfunction [R, scale]=arqrIn(v, p, mcor)\n%ARQR\tQR factorization for least squares estimation of AR model.\n%\n%  [R, SCALE]=ARQR(v,p,mcor) computes the QR factorization needed in\n%  the least squares estimation of parameters of an AR(p) model. If\n%  the input flag mcor equals one, a vector of intercept terms is\n%  being fitted. If mcor equals zero, the process v is assumed to have\n%  mean zero. The output argument R is the upper triangular matrix\n%  appearing in the QR factorization of the AR model, and SCALE is a\n%  vector of scaling factors used to regularize the QR factorization.\n%\n%  ARQR is called by ARFIT. \n%\n%  See also ARFIT.\n\n%  Modified 29-Dec-99\n%  Author: Tapio Schneider\n%          tapio@gps.caltech.edu\n\n  % n: number of time steps; m: dimension of state vectors\n  [n,m] = size(v);     \n\n  ne    = n-p;                  % number of block equations of size m\n  np    = m*p+mcor;             % number of parameter vectors of size m\n\n  % If the intercept vector w is to be fitted, least squares (LS)\n  % estimation proceeds by solving the normal equations for the linear\n  % regression model\n  %\n  %                  v(k,:)' = Aaug*u(k,:)' + noise(C)\n  %\n  % with Aaug=[w A] and `predictors' \n  %\n  %              u(k,:) = [1 v(k-1,:) ...  v(k-p,:)]. \n  %\n  % If the process mean is taken to be zero, the augmented coefficient\n  % matrix is Aaug=A, and the regression model\n  %\n  %                u(k,:) = [v(k-1,:) ...  v(k-p,:)]\n  %\n  % is fitted. \n  % The number np is the dimension of the `predictors' u(k). \n\n  % Assemble the data matrix K (of which a QR factorization will be computed)\n  K = zeros(ne,np+m);                 % initialize K\n  if (mcor == 1)\n    % first column of K consists of ones for estimation of intercept vector w\n    K(:,1) = ones(ne,1);\n  end\n  \n  % Assemble `predictors' u in K \n  for j=1:p\n    K(:, mcor+m*(j-1)+1:mcor+m*j) = [v(p-j+1:n-j, :)];\n  end\n  % Add `observations' v (left hand side of regression model) to K\n  K(:,np+1:np+m) = [v(p+1:n, :)];\n  \n  % Compute regularized QR factorization of K: The regularization\n  % parameter delta is chosen according to Higham's (1996) Theorem\n  % 10.7 on the stability of a Cholesky factorization. Replace the\n  % regularization parameter delta below by a parameter that depends\n  % on the observational error if the observational error dominates\n  % the rounding error (cf. Neumaier, A. and T. Schneider, 2001:\n  % \"Estimation of parameters and eigenmodes of multivariate\n  % autoregressive models\", ACM Trans. Math. Softw., 27, 27--57.).\n  q     = np + m;             % number of columns of K\n  delta = (q^2 + q + 1)*eps;  % Higham's choice for a Cholesky factorization\n  scale = sqrt(delta)*sqrt(sum(K.^2));   \n  R     = triu(qr([K; diag(scale)]));\n\n% Add `observations' v (left hand side of regression model) to K\nK(:,np+1:np+m) = [v(p+1:n, :)];\n\n% Compute regularized QR factorization of K: The regularization\n% parameter delta is chosen according to Higham's (1996) Theorem\n% 10.7 on the stability of a Cholesky factorization. Replace the\n% regularization parameter delta below by a parameter that depends\n% on the observational error if the observational error dominates\n% the rounding error (cf. Neumaier, A. and T. Schneider, 2001:\n% \"Estimation of parameters and eigenmodes of multivariate\n% autoregressive models\", ACM Trans. Math. Softw., 27, 27--57.).\nq     = np + m;             % number of columns of K\ndelta = (q^2 + q + 1)*eps;  % Higham's choice for a Cholesky factorization\nscale = sqrt(delta)*sqrt(sum(K.^2));\nR     = triu(qr([K; diag(scale)]));\nend\n\nfunction [sbc, fpe, logdp, np] = arordIn(R, m, mcor, ne, pmin, pmax)\n%ARORD\tEvaluates criteria for selecting the order of an AR model.\n%\n%  [SBC,FPE]=ARORD(R,m,mcor,ne,pmin,pmax) returns approximate values\n%  of the order selection criteria SBC and FPE for models of order\n%  pmin:pmax. The input matrix R is the upper triangular factor in the\n%  QR factorization of the AR model; m is the dimension of the state\n%  vectors; the flag mcor indicates whether or not an intercept vector\n%  is being fitted; and ne is the number of block equations of size m\n%  used in the estimation. The returned values of the order selection\n%  criteria are approximate in that in evaluating a selection\n%  criterion for an AR model of order p < pmax, pmax-p initial values\n%  of the given time series are ignored.\n%\n%  ARORD is called by ARFIT. \n%\t\n%  See also ARFIT, ARQR.\n\n%  For testing purposes, ARORD also returns the vectors logdp and np,\n%  containing the logarithms of the determinants of the (scaled)\n%  covariance matrix estimates and the number of parameter vectors at\n%  each order pmin:pmax.\n\n%  Modified 17-Dec-99\n%  Author: Tapio Schneider\n%          tapio@gps.caltech.edu\n\nimax \t  = pmax-pmin+1;        % maximum index of output vectors\n\n% initialize output vectors\nsbc     = zeros(1, imax);     % Schwarz's Bayesian Criterion\nfpe     = zeros(1, imax);     % log of Akaike's Final Prediction Error\nlogdp   = zeros(1, imax);     % determinant of (scaled) covariance matrix\nnp      = zeros(1, imax);     % number of parameter vectors of length m\nnp(imax)= m*pmax+mcor;\n\n% Get lower right triangle R22 of R:\n%\n%   | R11  R12 |\n% R=|          |\n%   | 0    R22 |\n%\nR22     = R(np(imax)+1 : np(imax)+m, np(imax)+1 : np(imax)+m);\n\n% From R22, get inverse of residual cross-product matrix for model\n% of order pmax\ninvR22  = inv(R22);\nMp      = invR22*invR22';\n\n% For order selection, get determinant of residual cross-product matrix\n%       logdp = log det(residual cross-product matrix)\nlogdp(imax) = 2.*log(abs(prod(diag(R22))));\n\n% Compute approximate order selection criteria for models of\n% order pmin:pmax\ni = imax;\nfor p = pmax:-1:pmin\n    np(i)      = m*p + mcor;\t% number of parameter vectors of length m\n    if p < pmax\n        % Downdate determinant of residual cross-product matrix\n        % Rp: Part of R to be added to Cholesky factor of covariance matrix\n        Rp       = R(np(i)+1:np(i)+m, np(imax)+1:np(imax)+m);\n        \n        % Get Mp, the downdated inverse of the residual cross-product\n        % matrix, using the Woodbury formula\n        L        = chol(eye(m) + Rp*Mp*Rp')';\n        N        = L \\ Rp*Mp;\n        Mp       = Mp - N'*N;\n        \n        % Get downdated logarithm of determinant\n        logdp(i) = logdp(i+1) + 2.* log(abs(prod(diag(L))));\n    end\n    \n    % Schwarz's Bayesian Criterion\n    sbc(i) = logdp(i)/m - log(ne) * (ne-np(i))/ne;\n    \n    % logarithm of Akaike's Final Prediction Error\n    fpe(i) = logdp(i)/m - log(ne*(ne-np(i))/(ne+np(i)));\n    \n    % Modified Schwarz criterion (MSC):\n    % msc(i) = logdp(i)/m - (log(ne) - 2.5) * (1 - 2.5*np(i)/(ne-np(i)));\n    \n    i      = i-1;                % go to next lower order\nend\n\nend\n\n\n\n% y = Filter0(b, x)\n%\n% filters x with a fir filter so it has zero phase, i.e. shifts the\n% filtered signal to the right half of the length of b.\n%\n% for now it zero pads the original signal\n% later it might also do reflecton boundary conditions.\n%\n% be careful about the order of b!\n% for even filters it is not exact  (change of Anton)\n% - tired that even filterss dont' work\n\n\nfunction y = Filter0In(b, x)\n\nif size(x,1) == 1\n\tx = x(:);\nend\n\n% if mod(length(b),2)~=1\n% \terror('filter order should be odd');\n% end\nif mod(length(b),2)~=1\n    shift = length(b)/2;\nelse\n    shift = (length(b)-1)/2;\nend\n\n[y0 z] = filter(b,1,single(x));\n\ny = [y0(shift+1:end,:) ; z(1:shift,:)];\n\nend\n\n\n% computes the available memory in bytes\nfunction HowMuch = FreeMemoryIn\nif isunix\n\t[junk mem] = unix('vmstat |tail -1|awk ''{print $4} {print $6}''');\n\tHowMuch = sum(mem);\nelse\n\tHowMuch = 200;\n\t%200Mb for windows machin\n\t\nend\nend\n\nfunction bool = inttoboolIn(ints,totalpoints)\n% Takes a series of start-stop intervals (one row for each int, each row is\n% [startpoint stoppoint]) and converts to a boolean with length\n% (totalpoints) with zeros by default but 1s wherever points are inside\n% \"ints\".  If totalpoints is not input then length is set by the last point\n% in the last int.\n\nwarning off\n\nif ~exist('totalpoints','var')\n    totalpoints = 1;\nend\n\nbool = zeros(1,totalpoints);\nfor a = 1:size(ints,1);\n    bool(round(ints(a,1)):round(ints(a,2))) = 1;\nend\nend\n\n\nfunction FO = ViewAutoScoreThresholds(obj,event)\n%Pull up window for user to look at where auto-scoring thresholds were and \n%also allow them to change them\nFO = guidata(obj);\nbaseName = FO.baseName;\nbasePath = FO.basePath;\n\nif ~isfield(FO,'AutoScore')\n    FO.AutoScore = [];\nend\n\n% auto-load DetectionParameters, if they exist.  Save for later\nSleepState = bz_LoadStates(basePath,'SleepState');\n\nparamsAvailBool = 0;\ndetectnameAvailBool = 0;\nif isempty(SleepState)\n    answer = questdlg({'No SleepState.states.mat. Would you like to run SleepScoreMaster?', 'WARNING: will lose current states!!!'},...\n        'AutoScore?');\n    switch answer\n        case 'Yes'\n            %answer = questdlg('Use Loaded Channels?','Yes','No, Auto select channgels for scoring');\n            SleepScoreMaster(basePath)\n        case {'No','Cancel'}\n            return\n    end\nelseif isfield(SleepState,'detectorinfo')\n    if isfield(SleepState.detectorinfo,'detectorname')\n        detectorname = SleepState.detectorinfo.detectorname;\n        detectnameAvailBool = 1;\n    end\n    if isfield(SleepState.detectorinfo,'detectionparms')\n        detectionparms = SleepState.detectorinfo.detectionparms;\n        paramsAvailBool = 1;\n    end\nelseif isfield(SleepState,'detectorname') %old version of data\n    detectorname = SleepState.detectorname;\n    detectnameAvailBool = 1;\n    if isfield(SleepState,'detectorparms')\n        detectionparms = SleepState.detectorparms;\n        paramsAvailBool = 1;\n    end\nend\n\nif detectnameAvailBool\n    switch detectorname\n        case {'TheStateEditor'}\n            answer = questdlg({'States manually detected. Would you like to run SleepScoreMaster?',...\n                'WARNING: will lose current states!!!'},...\n                'AutoScore?');\n            switch answer\n                case 'Yes'\n                    SleepScoreMaster(basePath)\n                case {'No','Cancel'}\n                    return\n            end\n    end\nelse\n    disp('No Detector name recorded or found')\nend\n        \n\nif paramsAvailBool \n    %DL: this seems weird to me... \n    %why do we assume the detectionparms in SleepState are auto?\n    FO.AutoScore.detectionparms =  detectionparms;\nelse\n    FO.AutoScore.detectionparms = [];\nend\n\n\n% get histograms and thresholds that were used to determine states\nHistAndThreshAlready_Bool = 0;\nif isfield(FO,'AutoScore')\n    if isfield(FO.AutoScore,'histsandthreshs')\n        HistAndThreshAlready_Bool = 1;\n    end\nend\nif HistAndThreshAlready_Bool\n    histsandthreshs = FO.AutoScore.histsandthreshs;\nelse\n    histsandthreshs = SSHistogramsAndThresholds_In(baseName,basePath);\n    if isempty(histsandthreshs)\n        disp('Exiting, no HistsAndThreshs')\n        return\n    end\nend\nif ~isfield(histsandthreshs,'stickySW'); histsandthreshs.stickySW = false; end\nif ~isfield(histsandthreshs,'stickyTH'); histsandthreshs.stickyTH = false; end\nif ~isfield(histsandthreshs,'stickyEMG');histsandthreshs.stickyEMG = false; end\nFO.AutoScore.histsandthreshs = histsandthreshs;\n\n% get histograms and thresholds of original detection\nHistAndThreshOrigAlready_Bool = 0;\nif isfield(SleepState,'detectorinfo')\n    if isfield(SleepState.detectorinfo,'detectionparms')\n        if isfield(SleepState.detectorinfo.detectionparms,'SleepScoreMetrics')\n            if isfield(SleepState.detectorinfo.detectionparms.SleepScoreMetrics,'histsandthreshs_orig')\n                HistAndThreshOrigAlready_Bool = 1;\n            end\n        end\n    end\nend\nif HistAndThreshOrigAlready_Bool\n    histsandthreshs_orig = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.histsandthreshs_orig;\nelse\n    histsandthreshs_orig = histsandthreshs;\nend\nFO.AutoScore.histsandthreshs_orig = histsandthreshs_orig;\n\n\n\n% start figure\nh = figure('position',[940 5 960 720]);\nset(h, 'MenuBar', 'none');\nset(h, 'ToolBar', 'none');\n\n%top plot: Slow wave power\nax1 = subplot(3,2,2,'ButtonDownFcn',@ClickSetsLineXIn);hold on;\nbar(histsandthreshs.swhistbins,histsandthreshs.swhist)\nswline = plot(ax1,[histsandthreshs.swthresh histsandthreshs.swthresh],ylim(ax1),'r','tag','bw');\nxlabel('SWS Band Power (NREM vs other)')\nylabel('Counts (sec)')\nResetToInitButton_sw = uicontrol('style', 'pushbutton', 'String', 'Init', 'Units', 'normalized', 'Position',  [0.92, 0.87, 0.08, 0.05]);\nset(ResetToInitButton_sw,'Callback',@ResetToInitSw);\nResetToOrigButton_sw = uicontrol('style', 'pushbutton', 'String', 'Orig', 'Units', 'normalized', 'Position',  [0.92, 0.82, 0.08, 0.05]);\nset(ResetToOrigButton_sw,'Callback',@ResetToOrigSw);\nStickyThreshCheck_sw = uicontrol('style', 'checkbox', 'String', 'Sticky', 'Units', 'normalized', 'Position',  [0.92, 0.77, 0.08, 0.05],...\n    'Value',histsandthreshs.stickySW);\n%set(StickyThreshCheck_sw,'Callback',@SetStickySw);\n\ntitle({'Click in plots to reset X value of thresholds',...\n    'Setting thresholds to ''Sticky'' will reduce noise'})\n\n%middle plot: EMG amplitude\nax2 = subplot(3,2,4,'ButtonDownFcn',@ClickSetsLineXIn);hold on;\nbar(histsandthreshs.EMGhistbins,histsandthreshs.EMGhist)\nEMGline = plot(ax2,[histsandthreshs.EMGthresh histsandthreshs.EMGthresh],ylim(ax2),'r','tag','bw');\nxlabel('EMG (300-600Hz Correlation, active WAKE vs REM/inactive)')\nylabel('Counts (sec)')\nResetToInitButton_EMG = uicontrol('style', 'pushbutton', 'String', 'Init', 'Units', 'normalized', 'Position',  [0.92, 0.58, 0.08, 0.05]);\nset(ResetToInitButton_EMG,'Callback',@ResetToInitEMG);\nResetToOrigButton_EMG = uicontrol('style', 'pushbutton', 'String', 'Orig', 'Units', 'normalized', 'Position',  [0.92, 0.53, 0.08, 0.05]);\nset(ResetToOrigButton_EMG,'Callback',@ResetToOrigEMG);\nStickyThreshCheck_EMG = uicontrol('style', 'checkbox', 'String', 'Sticky', 'Units', 'normalized', 'Position',  [0.92, 0.48, 0.08, 0.05],...\n    'Value',histsandthreshs.stickyEMG);\n%set(StickyThreshCheck_EMG,'Callback',@SetStickyEMG);\n\n%bottom plot: Theta power\nax3 = subplot(3,2,6,'ButtonDownFcn',@ClickSetsLineXIn);hold on;\nbar(histsandthreshs.THhistbins,histsandthreshs.THhist)\nTHline = plot(ax3,[histsandthreshs.THthresh histsandthreshs.THthresh],ylim(ax3),'r','tag','bw');\nxlabel('Theta ratio (5-10Hz/2-15Hz, REM vs inactive WAKE)')\nylabel('Counts (sec)')\nResetToInitButton_TH = uicontrol('style', 'pushbutton', 'String', 'Init', 'Units', 'normalized', 'Position',  [0.92, 0.28, 0.08, 0.05]);\nset(ResetToInitButton_TH,'Callback',@ResetToInitTH);\nResetToOrigButton_TH = uicontrol('style', 'pushbutton', 'String', 'Orig', 'Units', 'normalized', 'Position',  [0.92, 0.23, 0.08, 0.05]);\nset(ResetToOrigButton_TH,'Callback',@ResetToOrigTH);\nStickyThreshCheck_TH = uicontrol('style', 'checkbox', 'String', 'Sticky', 'Units', 'normalized', 'Position',  [0.92, 0.18, 0.08, 0.05],...\n    'Value',histsandthreshs.stickyTH);\n%set(StickyThreshCheck_TH,'Callback',@SetStickyTH);\n\n%For 2d cluster plots\nbroadbandSlowWave = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.broadbandSlowWave;\nthratio = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.thratio;\nEMG = SleepState.detectorinfo.detectionparms.SleepScoreMetrics.EMG;\nplotstates = interp1(FO.to,FO.States,SleepState.detectorinfo.detectionparms.SleepScoreMetrics.t_clus,'nearest');\n%right plot\nax4 = subplot(2,2,1);hold on;\n    for ss = 1:5\n        plot(ax4,broadbandSlowWave(plotstates==ss),EMG(plotstates==ss),'.','color',FO.colors.states{ss},'markersize',1)\n    end\n    swline2 = plot(histsandthreshs.swthresh*[1 1],ylim(ax4),'r','LineWidth',1);\n    EMGline2 = plot(histsandthreshs.swthresh*[0 1],histsandthreshs.EMGthresh*[1 1],'r','LineWidth',1);\n    xlabel('Broadband SW');ylabel('EMG')\n    title('Isolate NREM')\n    \n    \nax5 = subplot(2,2,3);hold on;\n    for ss = [1 2 4 5]\n    plot(ax5,thratio(plotstates==ss),EMG(plotstates==ss),'.','color',FO.colors.states{ss},'markersize',1)\n    end\n    xlabel('Narrowband Theta');ylabel('EMG')\n    thline2 = plot(histsandthreshs.THthresh*[1 1],histsandthreshs.EMGthresh*[0 1],'r','LineWidth',1);\n    EMGline3 = plot([0 1],histsandthreshs.EMGthresh*[1 1],'r','LineWidth',1);\n    title('Isolate REM from WAKE')\n\n%RESCORE!\nReScoreButton = uicontrol('style', 'pushbutton', 'String', 'Re-Score', 'Units', 'normalized', 'Position',  [0.4, 0.01, 0.2, 0.05]);\nset(ReScoreButton,'Callback',@ReClusterStates_In);\n\n\nAutoClusterFig.fig = h;\nAutoClusterFig.ax1 = ax1;\nAutoClusterFig.ax2 = ax2;\nAutoClusterFig.ax3 = ax3;\nAutoClusterFig.ax4 = ax4;\nAutoClusterFig.ax5 = ax5;\nAutoClusterFig.swline = swline;\nAutoClusterFig.EMGline = EMGline;\nAutoClusterFig.THline = THline;\nAutoClusterFig.swline2 = swline2;\nAutoClusterFig.EMGline2 = EMGline2;\nAutoClusterFig.thline2 = thline2;\nAutoClusterFig.EMGline3 = EMGline3;\nAutoClusterFig.stickySWbox = StickyThreshCheck_sw;\nAutoClusterFig.stickyEMGbox = StickyThreshCheck_EMG;\nAutoClusterFig.stickyTHbox = StickyThreshCheck_TH;\nAutoClusterFig.histsandthreshs_init = histsandthreshs;%store first value\n\nFO.AutoClusterFig = AutoClusterFig;\nFO.AutoScore.histsandthreshs = histsandthreshs;\n\nbool = 0;\nif isfield(FO,'AutoScore')\n    if isfield(FO.AutoScore,'histsandthreshs_orig')\n        bool = 1;\n    end\nend\nif ~bool\n    FO.AutoScore.histsandthreshs_orig = histsandthreshs;\nend\n\n% guidata update is done after output\nguidata(FO.fig,FO)\n\nend\n\n\nfunction ClickSetsLineXIn(obj,ev)\n%For Autoscore fig (a push), lets a click set the location of a thresh line\ncp = get(obj,'CurrentPoint');\nnewx = cp(1);\nlo = findobj('parent',obj,'type','line','tag','bw');\nset(lo,'XData',[newx newx])\n\nend\n\n\nfunction histsandthreshs = SSHistogramsAndThresholds_In(baseName,basePath)\n% Get initial histograms and thresholds as calculated by SleepScoreMaster.m\nSleepState = bz_LoadStates(basePath,'SleepState');\n\nif isempty(SleepState) %If there is no saved SleepState already. \n    %Will also need something here if the name of the Detector isn't\n    %'SleepScoreMaster'... sorry I didn't fix this -DL\n    error('No SleepState.states.mat detected');\nend\n\nif isfield(SleepState,'detectorinfo')%handing different historical versions - for back compatibility\n    dp = SleepState.detectorinfo.detectionparms;%current version\nelseif isfield(SleepState,'detectorparams')\n    dp = SleepState.detectorparams;%old version\nend\n    \n%if already exists, just take from saved data\nhistsandthreshsOK = 0;\nif isfield(dp,'histsandthreshs')\n    histsandthreshs = dp.histsandthreshs;\n    histsandthreshsOK = 1;\nelseif isfield(dp,'SleepScoreMetrics')\n    if isfield(dp.SleepScoreMetrics,'histsandthreshs')\n        %this is the proper formatting, everything else in here is to deal\n        %with legacy issues (DL 3/18/18)\n        histsandthreshs = dp.SleepScoreMetrics.histsandthreshs;\n    \thistsandthreshsOK = 1;  \n    end\nend\n%if not, try to re-make it\nif ~histsandthreshsOK\n    warning('We were unable to find histsandthreshs in your SleepState. Trying to recalculate...')\n\n    loadgood = 1;\n    if exist(fullfile(basePath,[baseName '.SleepScoreLFP.LFP.mat']),'file')\n        s = load(fullfile(basePath,[baseName '.SleepScoreLFP.LFP.mat']));\n    else\n        loadgood = 0;%signify couldn't find preprocessed data\n    end\n    \n    if exist(fullfile(basePath,[baseName '.EMGFromLFP.LFP.mat']),'file')\n        e = load(fullfile(basePath,[baseName '.EMGFromLFP.LFP.mat']));\n    else\n        loadgood = 0;%signify couldn't find preprocessed data\n    end\n    \n    \n    if ~loadgood\n        answer = questdlg({'No HistsAndThreshs.  Also no SleepscoreLFP.LFP.mat or .EMGFromLFP.LFP.mat found. Would you like to run SleepScoreMaster?', 'WARNING: Will lose current states!!!'},...\n        'AutoScore?');\n        switch answer\n            case 'Yes'\n                %answer = questdlg('Use Loaded Channels?','Yes','No, Auto select channgels for scoring');\n                SleepScoreMaster(basePath)\n                s = load(fullfile(basePath,[baseName '.SleepScoreLFP.LFP.mat']));\n                e = load(fullfile(basePath,[baseName '.EMGFromLFP.LFP.mat']));\n            case {'No','Cancel'}\n                histsandthreshs = [];\n                return\n        end\n    end\n\n    \n    [SleepScoreMetrics,StatePlotMaterials] = ClusterStates_GetMetrics(...\n                                           basePath,s.SleepScoreLFP,e.EMGFromLFP,false);\n\n    histsandthreshs = SleepScoreMetrics.histsandthreshs;\n\n    SleepState.detectorinfo.detectionparms.SleepScoreMetrics = SleepScoreMetrics;\n    SleepState.detectorinfo.StatePlotMaterials = StatePlotMaterials;\n    save(fullfile(basePath,[baseName '.SleepState.states.mat']),'SleepState');\nend\nend\n\nfunction [states] = ReClusterStates_In(obj,ev)\n% Wrapper around functions ClusterStates_DetermineStates and\n% StatesToEpisodes.  Note only the more raw (but not totally raw) \n% SleepState output from StatesToEpisodes is used... not the Episodes.\n% One could consider excluding the refining step of StatesToEpidodes,\n% but I think Dan Levenstein would not stand by that approach as\n% appropriate and vetted\n%\n\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\nbasePath = FO.basePath;\n\n% load detectionparameters if not loaded when user pressed \"a\" in ViewAutoScoreThresholds\nif isfield(FO,'AutoScore')\n    if isfield(FO.AutoScore,'detectionparms')\n        dp = FO.AutoScore.detectionparms;\n    end\nend\nif ~exist('dp','var')\n    SleepState = bz_LoadStates(basePath,'SleepState');\n    dp = SleepState.detectorinfo.detectionparms;\nend\n\n% grab user-entered thresholds from GUI, for final input to DetermineStates\nswthresh = get(FO.AutoClusterFig.swline,'XData');\nswthresh = swthresh(1,1);\nEMGthresh = get(FO.AutoClusterFig.EMGline,'XData');\nEMGthresh = EMGthresh(1,1);\nTHthresh = get(FO.AutoClusterFig.THline,'XData');\nTHthresh = THthresh(1,1);\nFO.AutoScore.histsandthreshs.swthresh = swthresh;\nFO.AutoScore.histsandthreshs.EMGthresh = EMGthresh;\nFO.AutoScore.histsandthreshs.THthresh = THthresh;\n\nFO.AutoScore.histsandthreshs.stickySW = FO.AutoClusterFig.stickySWbox.Value;\nFO.AutoScore.histsandthreshs.stickyTH = FO.AutoClusterFig.stickyTHbox.Value;\nFO.AutoScore.histsandthreshs.stickyEMG = FO.AutoClusterFig.stickyEMGbox.Value;\n\n\nif ~isfield(dp,'MinTimeWindowParms')\n    display('No MinTimeWindowParms found... using defaults')\n    dp.MinTimeWindowParms = [];\nend\n\n% Execute scoring - USE SleepScore toolbox functions\n[stateintervals,stateidx,~] = ClusterStates_DetermineStates(...\n                                           dp.SleepScoreMetrics,dp.MinTimeWindowParms,FO.AutoScore.histsandthreshs);\n\nplotstates = interp1(stateidx.timestamps,stateidx.states,dp.SleepScoreMetrics.t_clus,'nearest');\n%Redraw 2d cluster plots\ncla(FO.AutoClusterFig.ax4)\n    for ss = 1:5\n        plot(FO.AutoClusterFig.ax4,dp.SleepScoreMetrics.broadbandSlowWave(plotstates==ss),...\n            dp.SleepScoreMetrics.EMG(plotstates==ss),'.','color',FO.colors.states{ss},'markersize',1)\n    end\n    plot(FO.AutoClusterFig.ax4,swthresh.*[1 1],ylim(FO.AutoClusterFig.ax4),'r','LineWidth',1);\n    plot(FO.AutoClusterFig.ax4,[0 swthresh],EMGthresh.*[1 1],'r','LineWidth',1);\n    \ncla(FO.AutoClusterFig.ax5)\n    for ss = [1 2 4 5]\n        plot(FO.AutoClusterFig.ax5,dp.SleepScoreMetrics.thratio(plotstates==ss),...\n            dp.SleepScoreMetrics.EMG(plotstates==ss),'.','color',FO.colors.states{ss},'markersize',1)\n    end\n    plot(FO.AutoClusterFig.ax5,THthresh.*[1 1],[0 EMGthresh],'r','LineWidth',1);\n    plot(FO.AutoClusterFig.ax5,[0 1],EMGthresh.*[1 1],'r','LineWidth',1); \n\n%Interpolate to match fspec{1}.to\nstates = interp1(stateidx.timestamps,stateidx.states,FO.to,'nearest');\nstates(isnan(states)) = 0; %Bug fix DL - FO.to starts at time 0....    \n    \nFO.States = states;\nguidata(FO.fig,FO);\nmodifyStates(1, states, 0);\n\nend\n\n\nfunction ResetToOrigSw(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoScore.histsandthreshs_orig.swhist)];\nx = [FO.AutoScore.histsandthreshs_orig.swthresh FO.AutoScore.histsandthreshs_orig.swthresh];\nset(FO.AutoClusterFig.swline,'XData',x);\nend\n\nfunction ResetToOrigEMG(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoScore.histsandthreshs_orig.EMGhist)];\nx = [FO.AutoScore.histsandthreshs_orig.EMGthresh FO.AutoScore.histsandthreshs_orig.EMGthresh];\nset(FO.AutoClusterFig.EMGline,'XData',x);\nend\n\nfunction ResetToOrigTH(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoScore.histsandthreshs_orig.THhist)];\nx = [FO.AutoScore.histsandthreshs_orig.THthresh FO.AutoScore.histsandthreshs_orig.THthresh];\nset(FO.AutoClusterFig.THline,'XData',x);\nend\n\nfunction ResetToInitSw(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoClusterFig.histsandthreshs_init.swhist)];\nx = [FO.AutoClusterFig.histsandthreshs_init.swthresh FO.AutoClusterFig.histsandthreshs_init.swthresh];\nset(FO.AutoClusterFig.swline,'XData',x);\nend\n\nfunction ResetToInitEMG(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoClusterFig.histsandthreshs_init.EMGhist)];\nx = [FO.AutoClusterFig.histsandthreshs_init.EMGthresh FO.AutoClusterFig.histsandthreshs_init.EMGthresh];\nset(FO.AutoClusterFig.EMGline,'XData',x);\nend\n\nfunction ResetToInitTH(obj,ev)\nobj = findobj('tag','StateEditorMaster');\nFO = guidata(obj(end));\nbaseName = FO.baseName;\ny = [0 max(FO.AutoClusterFig.histsandthreshs_init.THhist)];\nx = [FO.AutoClusterFig.histsandthreshs_init.THthresh FO.AutoClusterFig.histsandthreshs_init.THthresh];\nset(FO.AutoClusterFig.THline,'XData',x);\nend\n\n% function SetStickySw(obj,ev)\n% obj = findobj('tag','StateEditorMaster');\n% FO = guidata(obj(end));\n% \n% set(FO.AutoClusterFig.swline,'XData',x);\n% end\n\nfunction [ INT ] = IDXtoINT_In( IDX ,numstates)\n%IDXtoINT_In(IDX) Converts state indices to state on/offsets\n%\n%INPUT\n%   IDX:    [t x 1] vector of state indices, where states are identified by\n%           integers starting from 1. Times with IDX 0 will not be counted\n%           in any interval INT\n%   numstates (optional)  number of interval types (for use\n%\n%OUTPUT\n%   INT:    {nstates} cell array of intervals - start and end times\n%\n%DLevenstein 2015-16\n%%\nif ~exist('numstates','var')\n    numstates = max(IDX);\nend\nstates = 1:numstates;\nif isrow(IDX)\n    IDX = IDX';\nend\nIDX = [0; IDX; 0];\nfor ss = 1:numstates\n    statetimes = IDX==states(ss);\n    INT{ss} = [find(diff(statetimes)==1) find(diff(statetimes)==-1)-1];\nend\n\nend\n\n\nfunction newvals = ResampleTolerant_IN(vals,length1,length2)\n% Wrapper around the resample function that allows it to work even if\n% the product of the lengths are long enough to overwhelm the resample.m \n% limit of 2^31\n% Works by finding a rational number approximation of the requested length\n% ratio... to within a particular tolerance.\n% INPUTS\n% vals = vector of values to be resampled\n% length1 = desired length\n% length2 = initial length (often equals length(vals))\n%\n% Dan Levenstein code made into a function by Brendon Watson\n% August 2016\n\n\nif length1*length2 < 2^31 % if no need to change factors don't\n    newvals = resample(vals,length1,length2);\nelse\n    newvals = [1 1];\n    \n    resamplefact = length1/length2;\n    tol = 0.0001;\n    while length(newvals(:,1)) ~= length1\n        [P,Q] = rat(resamplefact,tol);\n        if P==0\n            tol = tol/10;\n            continue\n        end\n        if P*Q >=2^20 || tol<1e-300  %Avoid crashing resample...\n            vals([1,end],:) = [];\n            length2 = length2-2;\n            resamplefact = length1/length2;\n            tol = 0.0001;\n            continue\n        end\n        newvals = resample(vals,P,Q);\n        tol = tol/10;\n    end\nend\n\nend\n\n\nfunction [Ypk,Xpk,Wpk,Ppk] = findpeaks_In(Yin,varargin)\n%FINDPEAKS Find local peaks in data\n%   PKS = FINDPEAKS(Y) finds local peaks in the data vector Y. A local peak\n%   is defined as a data sample which is either larger than the two\n%   neighboring samples or is equal to Inf.\n%\n%   [PKS,LOCS]= FINDPEAKS(Y) also returns the indices LOCS at which the\n%   peaks occur.\n%\n%   [PKS,LOCS] = FINDPEAKS(Y,X) specifies X as the location vector of data\n%   vector Y. X must be a strictly increasing vector of the same length as\n%   Y. LOCS returns the corresponding value of X for each peak detected.\n%   If X is omitted, then X will correspond to the indices of Y.\n%\n%   [PKS,LOCS] = FINDPEAKS(Y,Fs) specifies the sample rate, Fs, as a\n%   positive scalar, where the first sample instant of Y corresponds to a\n%   time of zero.\n%\n%   [...] = FINDPEAKS(...,'MinPeakHeight',MPH) finds only those peaks that\n%   are greater than the minimum peak height, MPH. MPH is a real valued\n%   scalar. The default value of MPH is -Inf.\n%\n%   [...] = FINDPEAKS(...,'MinPeakProminence',MPP) finds peaks guaranteed\n%   to have a vertical drop of more than MPP from the peak on both sides\n%   without encountering either the end of the signal or a larger\n%   intervening peak. The default value of MPP is zero.\n%\n%   [...] = FINDPEAKS(...,'Threshold',TH) finds peaks that are at least\n%   greater than both adjacent samples by the threshold, TH. TH is real\n%   valued scalar greater than or equal to zero. The default value of TH is\n%   zero.\n%\n%   FINDPEAKS(...,'WidthReference',WR) estimates the width of the peak as\n%   the distance between the points where the signal intercepts a\n%   horizontal reference line. The points are found by linear\n%   interpolation. The height of the line is selected using the criterion\n%   specified in WR:\n% \n%    'halfprom' - the reference line is positioned beneath the peak at a\n%       vertical distance equal to half the peak prominence.\n% \n%    'halfheight' - the reference line is positioned at one-half the peak \n%       height. The line is truncated if any of its intercept points lie\n%       beyond the borders of the peaks selected by the 'MinPeakHeight',\n%       'MinPeakProminence' and 'Threshold' parameters. The border between\n%       peaks is defined by the horizontal position of the lowest valley\n%       between them. Peaks with heights less than zero are discarded.\n% \n%    The default value of WR is 'halfprom'.\n%\n%   [...] = FINDPEAKS(...,'MinPeakWidth',MINW) finds peaks whose width is\n%   at least MINW. The default value of MINW is zero.\n%\n%   [...] = FINDPEAKS(...,'MaxPeakWidth',MAXW) finds peaks whose width is\n%   at most MAXW. The default value of MAXW is Inf.\n%\n%   [...] = FINDPEAKS(...,'MinPeakDistance',MPD) finds peaks separated by\n%   more than the minimum peak distance, MPD. This parameter may be\n%   specified to ignore smaller peaks that may occur in close proximity to\n%   a large local peak. For example, if a large local peak occurs at LOC,\n%   then all smaller peaks in the range [N-MPD, N+MPD] are ignored. If not\n%   specified, MPD is assigned a value of zero.\n%\n%   [...] = FINDPEAKS(...,'SortStr',DIR) specifies the direction of sorting\n%   of peaks. DIR can take values of 'ascend', 'descend' or 'none'. If not\n%   specified, DIR takes the value of 'none' and the peaks are returned in\n%   the order of their occurrence.\n%\n%   [...] = FINDPEAKS(...,'NPeaks',NP) specifies the maximum number of peaks\n%   to be found. NP is an integer greater than zero. If not specified, all\n%   peaks are returned. Use this parameter in conjunction with setting the\n%   sort direction to 'descend' to return the NP largest peaks. (see\n%   'SortStr')\n%\n%   [PKS,LOCS,W] = FINDPEAKS(...) returns the width, W, of each peak by\n%   linear interpolation of the left- and right- intercept points to the\n%   reference defined by 'WidthReference'.\n%\n%   [PKS,LOCS,W,P] = FINDPEAKS(...) returns the prominence, P, of each\n%   peak.\n%\n%   FINDPEAKS(...) without output arguments plots the signal and the peak\n%   values it finds\n%\n%   FINDPEAKS(...,'Annotate',PLOTSTYLE) will annotate a plot of the\n%   signal with PLOTSTYLE. If PLOTSTYLE is 'peaks' the peaks will be\n%   plotted. If PLOTSTYLE is 'extents' the signal, peak values, widths,\n%   prominences of each peak will be annotated. 'Annotate' will be ignored\n%   if called with output arguments. The default value of PLOTSTYLE is\n%   'peaks'.\n%\n%   % Example 1:\n%   %   Plot the Zurich numbers of sunspot activity from years 1700-1987\n%   %   and identify all local maxima at least six years apart\n%   load sunspot.dat\n%   findpeaks(sunspot(:,2),sunspot(:,1),'MinPeakDistance',6)\n%   xlabel('Year');\n%   ylabel('Zurich number');\n%\n%   % Example 2: \n%   %   Plot peak values of an audio signal that drop at least 1V on either\n%   %   side without encountering values larger than the peak.\n%   load mtlb\n%   findpeaks(mtlb,Fs,'MinPeakProminence',1)\n%\n%   % Example 3:\n%   %   Plot all peaks of a chirp signal whose widths are between .5 and 1 \n%   %   milliseconds.\n%   Fs = 44.1e3; N = 1000;\n%   x = sin(2*pi*(1:N)/N + (10*(1:N)/N).^2);\n%   findpeaks(x,Fs,'MinPeakWidth',.5e-3,'MaxPeakWidth',1e-3, ...\n%             'Annotate','extents')\n\n%   Copyright 2007-2014 The MathWorks, Inc.\n\n%#ok<*EMCLS>\n%#ok<*EMCA>\n%#codegen\n\ncond = nargin >= 1;\nif ~cond\n    coder.internal.assert(cond,'MATLAB:narginchk:notEnoughInputs');\nend\n\ncond = nargin <= 22;\nif ~cond\n    coder.internal.assert(cond,'MATLAB:narginchk:tooManyInputs');\nend\n\n% extract the parameters from the input argument list\n[y,yIsRow,x,xIsRow,minH,minP,minW,maxW,minD,minT,maxN,sortDir,annotate,refW] ...\n  = parse_inputs(Yin,varargin{:});\n\n% find indices of all finite and infinite peaks and the inflection points\n[iFinite,iInfite,iInflect] = getAllPeaks(y);\n\n% keep only the indices of finite peaks that meet the required \n% minimum height and threshold\niPk = removePeaksBelowMinPeakHeight(y,iFinite,minH,refW);\niPk = removePeaksBelowThreshold(y,iPk,minT);\n\n% indicate if we need to compute the extent of a peak\nneedWidth = minW>0 || maxW<inf || minP>0 || nargout>2 || strcmp(annotate,'extents');\n\nif needWidth\n  % obtain the indices of each peak (iPk), the prominence base (bPk), and\n  % the x- and y- coordinates of the peak base (bxPk, byPk) and the width\n  % (wxPk)\n  [iPk,bPk,bxPk,byPk,wxPk] = findExtents(y,x,iPk,iFinite,iInfite,iInflect,minP,minW,maxW,refW);\nelse\n  % combine finite and infinite peaks into one list\n  [iPk,bPk,bxPk,byPk,wxPk] = combinePeaks(iPk,iInfite);\nend\n\n% find the indices of the largest peaks within the specified distance\nidx = findPeaksSeparatedByMoreThanMinPeakDistance(y,x,iPk,minD);\n\n% re-order and bound the number of peaks based upon the index vector\nidx = orderPeaks(y,iPk,idx,sortDir);\nidx = keepAtMostNpPeaks(idx,maxN);\n\n% use the index vector to fetch the correct peaks.\niPk = iPk(idx);\nif needWidth\n  [bPk, bxPk, byPk, wxPk] = fetchPeakExtents(idx,bPk,bxPk,byPk,wxPk);\nend\n\nif nargout > 0\n  % assign output variables\n  if needWidth\n    [Ypk,Xpk,Wpk,Ppk] = assignFullOutputs(y,x,iPk,wxPk,bPk,yIsRow,xIsRow);\n  else\n    [Ypk,Xpk] = assignOutputs(y,x,iPk,yIsRow,xIsRow);\n  end    \nelse\n  % no output arguments specified. plot and optionally annotate\n  hAxes = plotSignalWithPeaks(x,y,iPk);\n  if strcmp(annotate,'extents')\n    plotExtents(hAxes,x,y,iPk,bPk,bxPk,byPk,wxPk,refW);\n  end\n  \n  scalePlot(hAxes);\nend\n\nend\n%--------------------------------------------------------------------------\nfunction [y,yIsRow,x,xIsRow,Ph,Pp,Wmin,Wmax,Pd,Th,NpOut,Str,Ann,Ref] = parse_inputs(Yin,varargin)\n\n% Validate input signal\nvalidateattributes(Yin,{'numeric'},{'nonempty','real','vector'},...\n    'findpeaks','Y');\nyIsRow = isrow(Yin);\ny = Yin(:);\n\n% copy over orientation of y to x.\nxIsRow = yIsRow;\n\n% indicate if the user specified an Fs or X\nhasX = ~isempty(varargin) && isnumeric(varargin{1});\n\nif hasX\n  startArg = 2;\n  if isscalar(varargin{1})\n    % Fs\n    Fs = varargin{1};\n    validateattributes(Fs,{'double'},{'real','finite','positive'},'findpeaks','Fs');\n    x = (0:numel(y)-1).'/Fs;\n  else\n    % X\n    Xin = varargin{1};\n    validateattributes(Xin,{'double'},{'real','finite','vector','increasing'},'findpeaks','X');\n    if numel(Xin) ~= numel(Yin)\n      if coder.target('MATLAB')\n        throwAsCaller(MException(message('signal:findpeaks:mismatchYX')));\n      else\n        coder.internal.errorIf(true,'signal:findpeaks:mismatchYX');\n      end\n    end\n    xIsRow = isrow(Xin);\n    x = Xin(:);\n  end\nelse\n  startArg = 1;\n  % unspecified, use index vector\n  x = (1:numel(y)).';\nend\n\nif coder.target('MATLAB')\n    try %#ok<EMTC>\n        % Check the input data type. Single precision is not supported.\n        chkinputdatatype_In(y);\n        chkinputdatatype_In(x);\n    catch ME\n        throwAsCaller(ME);\n    end\nelse\n    chkinputdatatype_In(y);\n    chkinputdatatype_In(x);\nend\n\nM = numel(y);\ncond = (M < 3);\nif cond\n    coder.internal.errorIf(cond,'signal:findpeaks:emptyDataSet');\nend\n\n%#function dspopts.findpeaks\ndefaultMinPeakHeight = -inf;\ndefaultMinPeakProminence = 0;\ndefaultMinPeakWidth = 0;\ndefaultMaxPeakWidth = Inf;\ndefaultMinPeakDistance = 0;\ndefaultThreshold = 0;\ndefaultNPeaks = [];\ndefaultSortStr = 'none';\ndefaultAnnotate = 'peaks';\ndefaultWidthReference = 'halfprom';\n\nif coder.target('MATLAB')\n    p = inputParser;\n    addParameter(p,'MinPeakHeight',defaultMinPeakHeight);\n    addParameter(p,'MinPeakProminence',defaultMinPeakProminence);\n    addParameter(p,'MinPeakWidth',defaultMinPeakWidth);\n    addParameter(p,'MaxPeakWidth',defaultMaxPeakWidth);\n    addParameter(p,'MinPeakDistance',defaultMinPeakDistance);\n    addParameter(p,'Threshold',defaultThreshold);\n    addParameter(p,'NPeaks',defaultNPeaks);\n    addParameter(p,'SortStr',defaultSortStr);\n    addParameter(p,'Annotate',defaultAnnotate);\n    addParameter(p,'WidthReference',defaultWidthReference);\n    parse(p,varargin{startArg:end});\n    Ph = p.Results.MinPeakHeight;\n    Pp = p.Results.MinPeakProminence;\n    Wmin = p.Results.MinPeakWidth;\n    Wmax = p.Results.MaxPeakWidth;\n    Pd = p.Results.MinPeakDistance;\n    Th = p.Results.Threshold;\n    Np = p.Results.NPeaks;\n    Str = p.Results.SortStr;\n    Ann = p.Results.Annotate;\n    Ref = p.Results.WidthReference;\nelse\n    parms = struct('MinPeakHeight',uint32(0), ...\n                'MinPeakProminence',uint32(0), ...\n                'MinPeakWidth',uint32(0), ...\n                'MaxPeakWidth',uint32(0), ...\n                'MinPeakDistance',uint32(0), ...\n                'Threshold',uint32(0), ...\n                'NPeaks',uint32(0), ...\n                'SortStr',uint32(0), ...\n                'Annotate',uint32(0), ...\n                'WidthReference',uint32(0));\n    pstruct = eml_parse_parameter_inputs(parms,[],varargin{startArg:end});\n    Ph = eml_get_parameter_value(pstruct.MinPeakHeight,defaultMinPeakHeight,varargin{startArg:end});\n    Pp = eml_get_parameter_value(pstruct.MinPeakProminence,defaultMinPeakProminence,varargin{startArg:end});\n    Wmin = eml_get_parameter_value(pstruct.MinPeakWidth,defaultMinPeakWidth,varargin{startArg:end});\n    Wmax = eml_get_parameter_value(pstruct.MaxPeakWidth,defaultMaxPeakWidth,varargin{startArg:end});\n    Pd = eml_get_parameter_value(pstruct.MinPeakDistance,defaultMinPeakDistance,varargin{startArg:end});\n    Th = eml_get_parameter_value(pstruct.Threshold,defaultThreshold,varargin{startArg:end});\n    Np = eml_get_parameter_value(pstruct.NPeaks,defaultNPeaks,varargin{startArg:end});\n    Str = eml_get_parameter_value(pstruct.SortStr,defaultSortStr,varargin{startArg:end});\n    Ann = eml_get_parameter_value(pstruct.Annotate,defaultAnnotate,varargin{startArg:end});\n    Ref = eml_get_parameter_value(pstruct.WidthReference,defaultWidthReference,varargin{startArg:end});\nend\n\n% limit the number of peaks to the number of input samples\nif isempty(Np)\n    NpOut = M;\nelse\n    NpOut = Np;\nend\n\n% ignore peaks below zero when using halfheight width reference\nif strcmp(Ref,'halfheight')\n  Ph = max(Ph,0);\nend\n\nvalidateattributes(Ph,{'numeric'},{'real','scalar','nonempty'},'findpeaks','MinPeakHeight');\nvalidateattributes(Pd,{'numeric'},{'real','scalar','nonempty','nonnegative','<',x(M)-x(1)},'findpeaks','MinPeakDistance');\nvalidateattributes(Pp,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakProminence');\nvalidateattributes(Wmin,{'numeric'},{'real','scalar','finite','nonempty','nonnegative'},'findpeaks','MinPeakWidth');\nvalidateattributes(Wmax,{'numeric'},{'real','scalar','nonnan','nonempty','nonnegative'},'findpeaks','MaxPeakWidth');\nvalidateattributes(Pd,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakDistance');\nvalidateattributes(Th,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','Threshold');\nvalidateattributes(NpOut,{'numeric'},{'real','scalar','nonempty','integer','positive'},'findpeaks','NPeaks');\nStr = validatestring(Str,{'ascend','none','descend'},'findpeaks','SortStr');\nAnn = validatestring(Ann,{'peaks','extents'},'findpeaks','SortStr');\nRef = validatestring(Ref,{'halfprom','halfheight'},'findpeaks','WidthReference');\n\nend\n%--------------------------------------------------------------------------\nfunction [iPk,iInf,iInflect] = getAllPeaks(y)\n% fetch indices all infinite peaks\niInf = find(isinf(y) & y>0);\n\n% temporarily remove all +Inf values\nyTemp = y;\nyTemp(iInf) = NaN;\n\n% determine the peaks and inflection points of the signal\n[iPk,iInflect] = findLocalMaxima(yTemp);\n\n\nend\n%--------------------------------------------------------------------------\nfunction [iPk, iInflect] = findLocalMaxima(yTemp)\n% bookend Y by NaN and make index vector\nyTemp = [NaN; yTemp; NaN];\niTemp = (1:numel(yTemp)).';\n\n% keep only the first of any adjacent pairs of equal values (including NaN).\nyFinite = ~isnan(yTemp);\niNeq = [1; 1 + find((yTemp(1:end-1) ~= yTemp(2:end)) & ...\n                    (yFinite(1:end-1) | yFinite(2:end)))];\niTemp = iTemp(iNeq);\n\n% take the sign of the first sample derivative\ns = sign(diff(yTemp(iTemp)));\n\n% find local maxima\niMax = 1 + find(diff(s)<0);\n\n% find all transitions from rising to falling or to NaN\niAny = 1 + find(s(1:end-1)~=s(2:end));\n\n% index into the original index vector without the NaN bookend.\niInflect = iTemp(iAny)-1;\niPk = iTemp(iMax)-1;\n\nend\n%--------------------------------------------------------------------------\nfunction iPk = removePeaksBelowMinPeakHeight(Y,iPk,Ph,widthRef)\nif ~isempty(iPk) \n  iPk = iPk(Y(iPk) > Ph);\n  if isempty(iPk) && ~strcmp(widthRef,'halfheight')\n    if coder.target('MATLAB')\n        warning(message('signal:findpeaks:largeMinPeakHeight', 'MinPeakHeight', 'MinPeakHeight'));\n    end\n  end\nend\n\nend\n%--------------------------------------------------------------------------\nfunction iPk = removePeaksBelowThreshold(Y,iPk,Th)\n\nbase = max(Y(iPk-1),Y(iPk+1));\niPk = iPk(Y(iPk)-base >= Th);\n\nend\n%--------------------------------------------------------------------------\nfunction [iPk,bPk,bxPk,byPk,wxPk] = findExtents(y,x,iPk,iFin,iInf,iInflect,minP,minW,maxW,refW)\n% temporarily filter out +Inf from the input\nyFinite = y;\nyFinite(iInf) = NaN;\n\n% get the base and left and right indices of each prominence base\n[bPk,iLB,iRB] = getPeakBase(yFinite,iPk,iFin,iInflect);\n\n% keep only those indices with at least the specified prominence\n[iPk,bPk,iLB,iRB] = removePeaksBelowMinPeakProminence(yFinite,iPk,bPk,iLB,iRB,minP);\n\n% get the x-coordinates of the half-height width borders of each peak\n[wxPk,iLBh,iRBh] = getPeakWidth(yFinite,x,iPk,bPk,iLB,iRB,refW);\n\n% merge finite and infinite peaks together into one list\n[iPk,bPk,bxPk,byPk,wxPk] = combineFullPeaks(y,x,iPk,bPk,iLBh,iRBh,wxPk,iInf);\n\n% keep only those in the range minW < w < maxW\n[iPk,bPk,bxPk,byPk,wxPk] = removePeaksOutsideWidth(iPk,bPk,bxPk,byPk,wxPk,minW,maxW);\n\nend\n\n%--------------------------------------------------------------------------\nfunction [peakBase,iLeftSaddle,iRightSaddle] = getPeakBase(yTemp,iPk,iFin,iInflect)\n% determine the indices that border each finite peak\n[iLeftBase, iLeftSaddle] = getLeftBase(yTemp,iPk,iFin,iInflect);\n[iRightBase, iRightSaddle] = getLeftBase(yTemp,flipud(iPk),flipud(iFin),flipud(iInflect));\niRightBase = flipud(iRightBase);\niRightSaddle = flipud(iRightSaddle);\npeakBase = max(yTemp(iLeftBase),yTemp(iRightBase));\n\nend\n%--------------------------------------------------------------------------\nfunction [iBase, iSaddle] = getLeftBase(yTemp,iPeak,iFinite,iInflect)\n% pre-initialize output base and saddle indices\niBase = zeros(size(iPeak));\niSaddle = zeros(size(iPeak));\n\n% table stores the most recently encountered peaks in order of height\npeak = zeros(size(iFinite));\nvalley = zeros(size(iFinite));\niValley = zeros(size(iFinite));\n\nn = 0;\ni = 1;\nj = 1;\nk = 1;\n\n% pre-initialize v for code generation\nv = NaN; \niv = 1;\n\nwhile k<=numel(iPeak)\n  % walk through the inflections until you reach a peak\n  while iInflect(i) ~= iFinite(j) \n    v = yTemp(iInflect(i));\n    iv = iInflect(i);\n    if isnan(v)\n      % border seen, start over.\n      n = 0;\n    else\n      % ignore previously stored peaks with a valley larger than this one\n      while n>0 && valley(n)>v\n        n = n - 1;\n      end\n    end\n    i = i + 1;\n  end\n  % get the peak\n  p = yTemp(iInflect(i));\n  \n  % keep the smallest valley of all smaller peaks\n  while n>0 && peak(n) < p\n    if valley(n) < v\n      v = valley(n);\n      iv = iValley(n);\n    end\n    n = n - 1;\n  end\n\n  % record \"saddle\" valleys in between equal-height peaks\n  isv = iv;\n  \n  % keep seeking smaller valleys until you reach a larger peak\n  while n>0 && peak(n) <= p\n    if valley(n) < v\n      v = valley(n);\n      iv = iValley(n);\n    end\n    n = n - 1;      \n  end\n  \n  % record the new peak and save the index of the valley into the base\n  % and saddle\n  n = n + 1;\n  peak(n) = p;\n  valley(n) = v;\n  iValley(n) = iv;\n\n  if iInflect(i) == iPeak(k)\n    iBase(k) = iv;\n    iSaddle(k) = isv;\n    k = k + 1;\n  end\n  \n  i = i + 1;\n  j = j + 1;\nend\n\nend\n%--------------------------------------------------------------------------\nfunction [iPk,pbPk,iLB,iRB] = removePeaksBelowMinPeakProminence(y,iPk,pbPk,iLB,iRB,minP)\n% compute the prominence of each peak\nPpk = y(iPk)-pbPk;\n\n% keep those that are above the specified prominence\nidx = find(Ppk >= minP);\niPk = iPk(idx);\npbPk = pbPk(idx);\niLB = iLB(idx);\niRB = iRB(idx);\n\nend\n%--------------------------------------------------------------------------\nfunction [wxPk,iLBh,iRBh] = getPeakWidth(y,x,iPk,pbPk,iLB,iRB,wRef)\nif isempty(iPk)\n  % no peaks.  define empty containers\n  base = zeros(size(iPk));\n  iLBh = zeros(size(iPk));\n  iRBh = zeros(size(iPk));  \nelseif strcmp(wRef,'halfheight')\n  % set the baseline to zero\n  base = zeros(size(iPk));\n\n  % border the width by no more than the lowest valley between this peak\n  % and the next peak\n  iLBh = [iLB(1); max(iLB(2:end),iRB(1:end-1))];\n  iRBh = [min(iRB(1:end-1),iLB(2:end)); iRB(end)];\n  iGuard = iLBh > iPk;\n  iLBh(iGuard) = iLB(iGuard);\n  iGuard = iRBh < iPk;\n  iRBh(iGuard) = iRB(iGuard);\nelse\n  % use the prominence base\n  base = pbPk;\n  \n  % border the width by the saddle of the peak\n  iLBh = iLB;\n  iRBh = iRB;\nend\n\n% get the width boundaries of each peak\nwxPk = getHalfMaxBounds(y, x, iPk, base, iLBh, iRBh);\n\nend\n%--------------------------------------------------------------------------\nfunction bounds = getHalfMaxBounds(y, x, iPk, base, iLB, iRB)\nbounds = zeros(numel(iPk),2);\n\n% interpolate both the left and right bounds clamping at borders\nfor i=1:numel(iPk)\n  \n  % compute the desired reference level at half-height or half-prominence\n  refHeight = (y(iPk(i))+base(i))/2;\n  \n  % compute the index of the left-intercept at half max\n  iLeft = findLeftIntercept(y, iPk(i), iLB(i), refHeight);\n  if iLeft < iLB(i)\n    xLeft = x(iLB(i));\n  else\n    xLeft = linterp(x(iLeft),x(iLeft+1),y(iLeft),y(iLeft+1),y(iPk(i)),base(i));\n  end\n  \n  % compute the index of the right-intercept\n  iRight = findRightIntercept(y, iPk(i), iRB(i), refHeight);\n  if iRight > iRB(i)\n    xRight = x(iRB(i));\n  else\n    xRight = linterp(x(iRight), x(iRight-1), y(iRight), y(iRight-1), y(iPk(i)),base(i));\n  end\n\n  % store result\n  bounds(i,:) = [xLeft xRight];\nend\n\nend\n%--------------------------------------------------------------------------\nfunction idx = findLeftIntercept(y, idx, borderIdx, refHeight)\n% decrement index until you pass under the reference height or pass the\n% index of the left border, whichever comes first\nwhile idx>=borderIdx && y(idx) > refHeight\n  idx = idx - 1;\nend\n\nend\n%--------------------------------------------------------------------------\nfunction idx = findRightIntercept(y, idx, borderIdx, refHeight)\n% increment index until you pass under the reference height or pass the\n% index of the right border, whichever comes first\nwhile idx<=borderIdx && y(idx) > refHeight\n  idx = idx + 1;\nend\n\nend\n%--------------------------------------------------------------------------\nfunction xc = linterp(xa,xb,ya,yb,yc,bc)\n% interpolate between points (xa,ya) and (xb,yb) to find (xc, 0.5*(yc-yc)).\nxc = xa + (xb-xa) .* (0.5*(yc+bc)-ya) ./ (yb-ya);\n\n% invoke L'Hospital's rule when -Inf is encountered. \nif isnan(xc)\n  % yc and yb are guaranteed to be finite. \n  if isinf(bc)\n    % both ya and bc are -Inf.\n    xc = 0.5*(xa+xb);\n  else\n    % only ya is -Inf.\n    xc = xb;\n  end\nend\n\nend\n%--------------------------------------------------------------------------\nfunction [iPk,bPk,bxPk,byPk,wxPk] = removePeaksOutsideWidth(iPk,bPk,bxPk,byPk,wxPk,minW,maxW)\n\nif isempty(iPk) || minW==0 && maxW == inf\n  return\nend\n\n% compute the width of each peak and extract the matching indices\nw = diff(wxPk,1,2);\nidx = find(minW <= w & w <= maxW);\n\n% fetch the surviving peaks\niPk = iPk(idx);\nbPk = bPk(idx);\nbxPk = bxPk(idx,:);\nbyPk = byPk(idx,:);\nwxPk = wxPk(idx,:);\n\nend\n%--------------------------------------------------------------------------\nfunction [iPkOut,bPk,bxPk,byPk,wxPk] = combinePeaks(iPk,iInf)\niPkOut = union(iPk,iInf);\nbPk = zeros(0,1);\nbxPk = zeros(0,2);\nbyPk = zeros(0,2);\nwxPk = zeros(0,2);\n\nend\n%--------------------------------------------------------------------------\nfunction [iPkOut,bPkOut,bxPkOut,byPkOut,wxPkOut] = combineFullPeaks(y,x,iPk,bPk,iLBw,iRBw,wPk,iInf)\niPkOut = union(iPk, iInf);\n\n% create map of new indices to old indices\n[~, iFinite] = intersect(iPkOut,iPk);\n[~, iInfinite] = intersect(iPkOut,iInf);\n\n% prevent row concatenation when iPk and iInf both have less than one\n% element\niPkOut = iPkOut(:);\n\n% compute prominence base\nbPkOut = zeros(size(iPkOut));\nbPkOut(iFinite) = bPk;\nbPkOut(iInfinite) = 0;\n\n% compute indices of left and right infinite borders\niInfL = max(1,iInf-1);\niInfR = min(iInf+1,numel(x));\n\n% copy out x- values of the left and right prominence base\n% set each base border of an infinite peaks halfway between itself and\n% the next adjacent sample\nbxPkOut = zeros(size(iPkOut,1),2);\nbxPkOut(iFinite,1) = x(iLBw);\nbxPkOut(iFinite,2) = x(iRBw);\nbxPkOut(iInfinite,1) = 0.5*(x(iInf)+x(iInfL));\nbxPkOut(iInfinite,2) = 0.5*(x(iInf)+x(iInfR));\n\n% copy out y- values of the left and right prominence base\nbyPkOut = zeros(size(iPkOut,1),2);\nbyPkOut(iFinite,1) = y(iLBw);\nbyPkOut(iFinite,2) = y(iRBw);\nbyPkOut(iInfinite,1) = y(iInfL);\nbyPkOut(iInfinite,2) = y(iInfR);\n\n% copy out x- values of the width borders\n% set each width borders of an infinite peaks halfway between itself and\n% the next adjacent sample\nwxPkOut = zeros(size(iPkOut,1),2);\nwxPkOut(iFinite,:) = wPk;\nwxPkOut(iInfinite,1) = 0.5*(x(iInf)+x(iInfL));\nwxPkOut(iInfinite,2) = 0.5*(x(iInf)+x(iInfR));\n\nend\n%--------------------------------------------------------------------------\nfunction idx = findPeaksSeparatedByMoreThanMinPeakDistance(y,x,iPk,Pd)\n% Start with the larger peaks to make sure we don't accidentally keep a\n% small peak and remove a large peak in its neighborhood. \n\nif isempty(iPk) || Pd==0\n  idx = (1:numel(iPk)).';\n  return\nend\n\n% copy peak values and locations to a temporary place\npks = y(iPk);\nlocs = x(iPk);\n\n% Order peaks from large to small\n[~, sortIdx] = sort(pks,'descend');\nlocs_temp = locs(sortIdx);\n\nidelete = ones(size(locs_temp))<0;\nfor i = 1:length(locs_temp)\n  if ~idelete(i)\n    % If the peak is not in the neighborhood of a larger peak, find\n    % secondary peaks to eliminate.\n    idelete = idelete | (locs_temp>=locs_temp(i)-Pd)&(locs_temp<=locs_temp(i)+Pd); \n    idelete(i) = 0; % Keep current peak\n  end\nend\n\n% report back indices in consecutive order\nidx = sort(sortIdx(~idelete));\n\n\nend\n\n%--------------------------------------------------------------------------\nfunction idx = orderPeaks(Y,iPk,idx,Str)\n\nif isempty(idx) || strcmp(Str,'none')\n  return\nend\n\nif strcmp(Str,'ascend')\n  [~,s]  = sort(Y(iPk(idx)),'ascend');\nelse\n  [~,s]  = sort(Y(iPk(idx)),'descend');\nend\n\nidx = idx(s);\n\n\nend\n%--------------------------------------------------------------------------\nfunction idx = keepAtMostNpPeaks(idx,Np)\n\nif length(idx)>Np\n  idx = idx(1:Np);\nend\n\nend\n%--------------------------------------------------------------------------\nfunction [bPk,bxPk,byPk,wxPk] = fetchPeakExtents(idx,bPk,bxPk,byPk,wxPk)\nbPk = bPk(idx);\nbxPk = bxPk(idx,:);\nbyPk = byPk(idx,:);\nwxPk = wxPk(idx,:);\n\nend\n%--------------------------------------------------------------------------\nfunction [YpkOut,XpkOut] = assignOutputs(y,x,iPk,yIsRow,xIsRow)\n\n% fetch the coordinates of the peak\nYpk = y(iPk);\nXpk = x(iPk);\n\n% preserve orientation of Y\nif yIsRow\n  YpkOut = Ypk.';\nelse\n  YpkOut = Ypk;\nend\n\n% preserve orientation of X\nif xIsRow\n  XpkOut = Xpk.';\nelse\n  XpkOut = Xpk;\nend\n\nend\n%--------------------------------------------------------------------------\nfunction [YpkOut,XpkOut,WpkOut,PpkOut] = assignFullOutputs(y,x,iPk,wxPk,bPk,yIsRow,xIsRow)\n\n% fetch the coordinates of the peak\nYpk = y(iPk);\nXpk = x(iPk);\n\n% compute the width and prominence\nWpk = diff(wxPk,1,2);\nPpk = Ypk-bPk;\n\n% preserve orientation of Y (and P)\nif yIsRow\n  YpkOut = Ypk.';\n  PpkOut = Ppk.';\nelse\n  YpkOut = Ypk;\n  PpkOut = Ppk;  \nend\n\n% preserve orientation of X (and W)\nif xIsRow\n  XpkOut = Xpk.';\n  WpkOut = Wpk.';\nelse\n  XpkOut = Xpk;\n  WpkOut = Wpk;  \nend\n\nend\n%--------------------------------------------------------------------------\nfunction hAxes = plotSignalWithPeaks(x,y,iPk)\n\n% plot signal\nhLine = plot(x,y,'Tag','Signal');\nhAxes = ancestor(hLine,'Axes');\n% turn on grid\ngrid on;\n\n% use the color of the line\ncolor = get(hLine,'Color');\nhLine = line(x(iPk),y(iPk),'Parent',hAxes, ...\n     'Marker','o','LineStyle','none','Color',color,'tag','Peak');\n\n% if using MATLAB use offset inverted triangular marker\nif coder.target('MATLAB')\n  plotpkmarkers(hLine,y(iPk));\nend\n\nend\n\n%--------------------------------------------------------------------------\nfunction plotExtents(hAxes,x,y,iPk,bPk,bxPk,byPk,wxPk,refW)\n\n% compute level of half-maximum (height or prominence)\nif strcmp(refW,'halfheight')\n  hm = 0.5*y(iPk);\nelse\n  hm = 0.5*(y(iPk)+bPk);\nend\n\n% get the default color order\ncolors = get(0,'DefaultAxesColorOrder');\n\n% plot boundaries between adjacent peaks when using half-height\nif strcmp(refW,'halfheight')\n  % plot height\n  plotLines(hAxes,'Height',x(iPk),y(iPk),x(iPk),zeros(numel(iPk),1),colors(2,:));  \n\n  % plot width\n  plotLines(hAxes,'HalfHeightWidth',wxPk(:,1),hm,wxPk(:,2),hm,colors(3,:));\n      \n  % plot peak borders\n  idx = find(byPk(:,1)>0);\n  plotLines(hAxes,'Border',bxPk(idx,1),zeros(numel(idx),1),bxPk(idx,1),byPk(idx,1),colors(4,:));\n  idx = find(byPk(:,2)>0);\n  plotLines(hAxes,'Border',bxPk(idx,2),zeros(numel(idx),1),bxPk(idx,2),byPk(idx,2),colors(4,:));\n  \nelse\n  % plot prominence\n  plotLines(hAxes,'Prominence',x(iPk), y(iPk), x(iPk), bPk, colors(2,:));  \n  \n  % plot width\n  plotLines(hAxes,'HalfProminenceWidth',wxPk(:,1), hm, wxPk(:,2), hm, colors(3,:));\n  \n  % plot peak borders\n  idx = find(bPk(:)<byPk(:,1));\n  plotLines(hAxes,'Border',bxPk(idx,1),bPk(idx),bxPk(idx,1),byPk(idx,1),colors(4,:));\n  idx = find(bPk(:)<byPk(:,2));\n  plotLines(hAxes,'Border',bxPk(idx,2),bPk(idx),bxPk(idx,2),byPk(idx,2),colors(4,:));\nend\n\nif coder.target('MATLAB')\n  hLine = get(hAxes,'Children');\n  tags = get(hLine,'tag');\n  \n  legendStrs = {};\n  searchTags = {'Signal','Peak','Prominence','Height','HalfProminenceWidth','HalfHeightWidth','Border'};\n  for i=1:numel(searchTags)\n    if any(strcmp(searchTags{i},tags))\n      legendStrs = [legendStrs, ...\n        {getString(message(['signal:findpeaks:Legend' searchTags{i}]))}]; %#ok<AGROW>\n    end\n  end\n  \n  if numel(hLine)==1\n    legend(getString(message('signal:findpeaks:LegendSignalNoPeaks')), ...\n      'Location','best');\n  else\n    legend(legendStrs,'Location','best');\n  end  \nend\n\nend\n%--------------------------------------------------------------------------\nfunction plotLines(hAxes,tag,x1,y1,x2,y2,c)\n% concatenate multiple lines into a single line and fencepost with NaN\nn = numel(x1);\nline(reshape([x1(:).'; x2(:).'; NaN(1,n)], 3*n, 1), ...\n     reshape([y1(:).'; y2(:).'; NaN(1,n)], 3*n, 1), ...\n     'Color',c,'Parent',hAxes,'tag',tag);\n\nend\n%--------------------------------------------------------------------------\nfunction scalePlot(hAxes)\n\n% In the event that the plot has integer valued y limits, 'axis auto' may\n% clip the YLimits directly to the data with no margin.  We search every\n% line for its max and minimum value and create a temporary annotation that\n% is 10% larger than the min and max values.  We then feed this to \"axis\n% auto\", save the y limits, set axis to \"tight\" then restore the y limits.\n% This obviates the need to check each line for its max and minimum x\n% values as well.\n\nminVal = Inf;\nmaxVal = -Inf;\n\nif coder.target('MATLAB')\n  hLines = findall(hAxes,'Type','line');\n  for i=1:numel(hLines)\n    data = get(hLines(i),'YData');\n    data = data(isfinite(data));\n    if ~isempty(data)\n      minVal = min(minVal, min(data(:)));\n      maxVal = max(maxVal, max(data(:)));\n    end\n  end\n  \n  axis auto\n  xlimits = xlim;\n  \n  % grow upper and lower y extent by 5% (a total of 10%)\n  p = .05;    \n  y1 = (1+p)*maxVal - p*minVal;\n  y2 = (1+p)*minVal - p*maxVal;\n  \n  % artificially expand the data range by the specified amount\n  hTempLine = line(xlimits([1 1]),[y1 y2],'Parent',hAxes);  \n  \n  % save the limits\n  ylimits = ylim;\n  delete(hTempLine);  \nelse\n  axis auto\n  ylimits = ylim;\nend\n\n% preserve expanded y limits but tighten x axis.\naxis tight\nylim(ylimits);  \n\n% [EOF]\n\nend\n\n\nfunction chkinputdatatype_In(varargin)\n%CHKINPUTDATATYPE Check that all inputs are double\n\n%   Copyright 2009-2013 The MathWorks, Inc.\nfor n = 1:nargin\n    if ~isa(varargin{n},'double')\n        error(message('signal:chkinputdatatype:NotSupported'));\n    end\nend\nend\n\nfunction states = bz_LoadStates_StateEditorWrapper_In(basePath,timevector)\n% TheStateEditor-appropriate loading function for loading buzcode SleepState.states.mat files.\n% Abstracted here so it can be used both during initial load and during LoadStates calls\n% Brendon Watson 4/2018\nbaseName=bz_BasenameFromBasepath(basePath);\n\nSleepState = bz_LoadStates(basePath,'SleepState');\nif isfield(SleepState,'idx')\n    %Interpolate to the StateEditor timestamps\n    states = interp1(SleepState.idx.timestamps,SleepState.idx.states,timevector,'nearest');\nelseif isfield(SleepState,'ints')\n    %If no idx saved... get from  .ints and save with idx\n    SleepState.idx = bz_INTtoIDX(SleepState.ints,'statenames',{'WAKE','','NREM','','REM'});\n    save(fullfile(basePath,[baseName '.SleepState.states.mat']),'SleepState') %Save with new idx\n    %Interpolate to the StateEditor timestamps\n    states = interp1(SleepState.idx.timestamps,SleepState.idx.states,timevector,'nearest');\nelseif isempty(SleepState)\n    states = zeros(1,length(timevector));\nelse\n   error('Your SleepState is broken.')\nend\n\nstates(isnan(states)) = 0; %Bug fix DL\n\n%% END for TheStateEditor\nend\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/GUITools/TheStateEditor/TheStateEditor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.14615149542966688}}
{"text": "function [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,multipleCellScoring,hpaLevelScores)\n% scoreRxns\n%   Scores the reactions and genes in a model based on expression data\n%   from HPA and/or gene arrays\n%\n%   Input:\n%   model               a model structure\n%   hpaData             HPA data structure from parseHPA (opt if arrayData is\n%                       supplied, default [])\n%   arrayData           gene expression data structure (opt if hpaData is\n%                       supplied, default [])\n%       genes           cell array with the unique gene names\n%       tissues         cell array with the tissue names. The list may not be\n%                       unique, as there can be multiple cell types per tissue\n%       celltypes       cell array with the cell type names for each tissue\n%       levels          GENESxTISSUES array with the expression level for\n%                       each gene in each tissue/celltype. NaN should be\n%                       used when no measurement was performed\n%       threshold       a single value or a vector of gene expression \n%                       thresholds, above which genes are considered to be\n%                       \"expressed\". (opt, by default, the mean expression\n%                       levels of each gene across all tissues in arrayData\n%                       will be used as the threshold values)\n%   tissue              tissue to score for. Should exist in either\n%                       hpaData.tissues or arrayData.tissues\n%   celltype            cell type to score for. Should exist in either\n%                       hpaData.celltypes or arrayData.celltypes for this\n%                       tissue (opt, default is to use the best values\n%                       among all the cell types for the tissue. Use [] if\n%                       you want to supply more arguments)\n%   noGeneScore         score for reactions without genes (opt, default -2)\n%   multipleGeneScoring determines how scores are calculated for reactions\n%                       with several genes ('best' or 'average')\n%                       (opt, default 'best')\n%   multipleCellScoring determines how scores are calculated when several\n%                       cell types are used ('best' or 'average')\n%                       (opt, default 'best')\n%   hpaLevelScores      structure with numerical scores for the expression\n%                       level categories from HPA. The structure should have a\n%                       \"names\" and a \"scores\" field (opt, see code for\n%                       default scores)\n%\n%\n%   Output:\n%   rxnScores       scores for each of the reactions in model\n%   geneScores      scores for each of the genes in model. Genes which are\n%                   not in the dataset(s) have -Inf as scores\n%   hpaScores       scores for each of the genes in model if only taking hpaData\n%                   into account. Genes which are not in the dataset(s)\n%                   have -Inf as scores\n%   arrayScores     scores for each of the genes in model if only taking arrayData\n%                   into account. Genes which are not in the dataset(s)\n%                   have -Inf as scores\n%\n%   Usage: [rxnScores, geneScores, hpaScores, arrayScores]=scoreModel(model,...\n%               hpaData,arrayData,tissue,celltype,noGeneScore,multipleGeneScoring,...\n%               multipleCellScoring,hpaLevelScores)\n\nif nargin<3\n    arrayData=[];\nend\nif nargin<5\n    celltype=[];\nelse\n    celltype=char(celltype);\nend\nif nargin<6\n    noGeneScore=-2;\nend\nif nargin<7\n    multipleGeneScoring='best';\nelse\n    multipleGeneScoring=char(multipleGeneScoring);\nend\nif nargin<8\n    multipleCellScoring='best';\nelse\n    multipleCellScoring=char(multipleCellScoring);    \nend\nif nargin<9\n    %The first four are for APE, the other ones for staining\n    hpaLevelScores.names={'High' 'Medium' 'Low' 'None' 'Strong' 'Moderate' 'Weak' 'Negative' 'Not detected'};\n    hpaLevelScores.scores=[20 15 10 -8 20 15 10 -8 -8];\nend\n\nif isempty(hpaData) && isempty(arrayData)\n    EM='Must supply hpaData, arrayData or both';\n    dispEM(EM);\nend\nif ~strcmpi(multipleGeneScoring,'best') && ~strcmpi(multipleGeneScoring,'average')\n    EM='Valid options for multipleGeneScoring are \"best\" or \"average\"';\n    dispEM(EM);\nend\nif ~strcmpi(multipleCellScoring,'best') && ~strcmpi(multipleCellScoring,'average')\n    EM='Valid options for multipleCellScoring are \"best\" or \"average\"';\n    dispEM(EM);\nend\n\n\n%Throw an error if array data for only one tissue is supplied without\n%specifying threshold values\nif ~isempty(arrayData)\n    if numel(unique(arrayData.tissues))<2\n        if ~isfield(arrayData,'threshold') || isempty(arrayData.threshold)\n            EM='arrayData must contain measurements for at least two celltypes/tissues since the score is calculated based on the expression level compared to the overall average';\n            dispEM(EM);\n        end\n    end\nend\n\n%Process arrayData.threshold if necessary\nif isfield(arrayData,'threshold') && (numel(arrayData.threshold) == 1)\n    % if only a single gene threshold value is provided, then just\n    % duplicate this value for all genes.\n    arrayData.threshold = arrayData.threshold*ones(size(arrayData.genes));\nend\n\n%This is so that the code can ignore which combination of input data that is\n%used\nif isempty(arrayData)\n    arrayData.genes={};\n    arrayData.tissues={};\n    arrayData.celltypes={};\n    arrayData.levels=[];\n    arrayData.threshold=[];\nend\nif isempty(hpaData)\n    hpaData.genes={};\n    hpaData.tissues={};\n    hpaData.celltypes={};\n    hpaData.levels={};\n    hpaData.types={};\n    hpaData.reliabilities={};\n    hpaData.gene2Level=[];\n    hpaData.gene2Type=[];\n    hpaData.gene2Reliability=[];\nend\n\n%Check that the tissue exists\nif ~ismember(upper(tissue),upper(hpaData.tissues)) && ~ismember(upper(tissue),upper(arrayData.tissues))\n    EM='The tissue name does not match';\n    dispEM(EM);\nend\nif any(celltype)\n    %Check that both data types has cell type defined if that is to be used\n    if ~isfield(hpaData,'celltypes') || ~isfield(arrayData,'celltypes')\n        EM='Both hpaData and arrayData must contain cell type information if cell type is to be used';\n        dispEM(EM);\n    end\n    if ~ismember(upper(celltype),upper(hpaData.celltypes)) && ~ismember(upper(celltype),upper(arrayData.celltypes))\n        EM='The cell type name does not match';\n        dispEM(EM);\n    end\nend\n\n%Some preprocessing of the structures to speed up a little Remove all\n%tissues that are not the correct one\nJ=~strcmpi(hpaData.tissues,tissue);\n\n%If cell type is supplied, then only keep that cell type\nif any(celltype)\n    J=J | ~strcmpi(hpaData.celltypes,celltype);\nend\n\nhpaData.tissues(J)=[];\nif isfield(hpaData,'celltypes')\n    hpaData.celltypes(J)=[];\nend\nif isfield(hpaData,'gene2Level')\n    hpaData.gene2Level(:,J)=[];\nend\nif isfield(hpaData,'gene2Type')\n    hpaData.gene2Type(:,J)=[];\nend\nif isfield(hpaData,'gene2Reliability')\n    hpaData.gene2Reliability(:,J)=[];\nend\n\n%Remove all genes from the structures that are not in model or that aren't\n%measured in the tissue\nif ~isempty(hpaData.genes) %This should not be necessary, but the summation is a 0x1 matrix and the other is []\n    I=~ismember(hpaData.genes,model.genes) | sum(hpaData.gene2Level,2)==0;\nelse\n    I=[];\nend\nhpaData.genes(I)=[];\nif isfield(hpaData,'gene2Level')\n    hpaData.gene2Level(I,:)=[];\nend\nif isfield(hpaData,'gene2Type')\n    hpaData.gene2Type(I,:)=[];\nend\nif isfield(hpaData,'gene2Reliability')\n    hpaData.gene2Reliability(I,:)=[];\nend\n\nI=strcmpi(arrayData.tissues,tissue);\n%If cell type is supplied, then only keep that cell type\nif any(celltype)\n    I=I & strcmpi(arrayData.celltypes,celltype);\nend\n\n%Remove all genes from the structures that are not in model or that aren't\n%measured in the tissue\nJ=~ismember(arrayData.genes,model.genes) | myAll(isnan(arrayData.levels(:,I)),2);\narrayData.genes(J)=[];\narrayData.levels(J,:)=[];\nif isfield(arrayData,'threshold')\n    arrayData.threshold(J) = [];\nend\n\n%Calculate the scores for the arrayData. These scores are calculated for\n%each genes from its fold change between the tissue/celltype(s) in question\n%and all other celltypes. This is a lower quality data than protein\n%abundance, since a gene that is equally highly expressed in all cell types\n%will have a score of 0.0. These scores are therefore only used for genes\n%for which there is no HPA data available. The fold changes are transformed\n%as min(log(x),10) for x>1 and max(log(x),-5) for x<1 in order to have\n%negative scores for lower expressed genes and to scale the scrores to have\n%somewhat lower weights than the HPA scores\ntempArrayLevels=arrayData.levels;\ntempArrayLevels(isnan(tempArrayLevels))=0;\nif isfield(arrayData,'threshold') && ~isempty(arrayData.threshold)\n    % if provided, the user-supplied expression threshold value(s) will be\n    % used as the \"average\" expression level to which each gene is\n    % compared.\n    average=arrayData.threshold;\nelse\n    average=sum(tempArrayLevels,2)./sum(~isnan(arrayData.levels),2);\nend\nif strcmpi(multipleCellScoring,'best')\n    current=max(tempArrayLevels(:,I),[],2);\nelse\n    current=sum(tempArrayLevels(:,I),2)./sum(~isnan(arrayData.levels(:,I)),2);\nend\nif ~isempty(current)\n    aScores=5*log(current./average);\nelse\n    aScores=[];\nend\naScores(aScores>0)=min(aScores(aScores>0),10);\naScores(aScores<0)=max(aScores(aScores<0),-5);\naScores(isnan(aScores)) = -5;  % NaNs occur when gene expression is zero across all tissues\n\n%Map the HPA levels to scores\n[I, J]=ismember(upper(hpaData.levels),upper(hpaLevelScores.names));\nif ~all(I)\n    EM='There are expression level categories that do not match to hpaLevelScores';\n    dispEM(EM);\nend\n[K, L, M]=find(hpaData.gene2Level);\nscores=hpaLevelScores.scores(J);\nif strcmpi(multipleCellScoring,'best')\n    hScores=max(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),[],2);\nelse\n    hScores=mean(sparse(K,L,scores(M),numel(hpaData.genes),numel(hpaData.tissues)),2);\nend\n\n%Get the scores for the genes, only use HPA if available\ngeneScores=inf(numel(model.genes),1)*-1;\nhpaScores=geneScores;\narrayScores=geneScores;\n\n[I, J]=ismember(model.genes,hpaData.genes);\nhpaScores(I)=hScores(J(I));\ngeneScores(I)=hScores(J(I));\n[I, J]=ismember(model.genes,arrayData.genes);\narrayScores(I)=aScores(J(I));\ngeneScores(I & myIsInf(geneScores))=aScores(J(I & myIsInf(geneScores)));\n\n%Remove the genes that have no data from the model\nI=ismember(model.genes,hpaData.genes) | ismember(model.genes,arrayData.genes);\nmodel.genes(~I)=[];\nmodel.rxnGeneMat(:,~I)=[];\n\n%Map the genes to the HPA/array genes\n[hpaExist, hpaMap]=ismember(model.genes,hpaData.genes);\n[arrayExist, arrayMap]=ismember(model.genes,arrayData.genes);\n\n%Set the default scores for reactions without genes\nrxnScores=ones(numel(model.rxns),1)*noGeneScore;\n\n%Loop through the reactions and calculate the scores\nfor i=1:numel(model.rxns)\n    %Check if it has genes\n    I=find(model.rxnGeneMat(i,:));\n    if any(I)\n        %If any of the genes exist in hpaData, then don't use arrayData\n        if any(hpaExist(I))\n            %At least one gene was found in HPA\n            if strcmpi(multipleGeneScoring,'best')\n                rxnScores(i)=max(hScores(hpaMap(I(hpaExist(I)))));\n            else\n                rxnScores(i)=mean(hScores(hpaMap(I(hpaExist(I)))));\n            end\n        else\n            %Use array data\n            if any(arrayExist(I))\n                %At least one gene was found in the array data\n                if strcmpi(multipleGeneScoring,'best')\n                    rxnScores(i)=max(aScores(arrayMap(I(arrayExist(I)))));\n                else\n                    rxnScores(i)=mean(aScores(arrayMap(I(arrayExist(I)))));\n                end\n            end\n        end\n    end\nend\nend\n\n%This is because isinf and all returns 0x1 for empty set, which gives a\n%concatenation error. Do like this instead of having many if statements\nfunction y=myIsInf(x)\ny=isinf(x);\nif isempty(y)\n    y=[];\nend\nend\nfunction y=myAll(x,dim)\ny=all(x,dim);\nif isempty(y)\n    y=[];\nend\nend\n", "meta": {"author": "SysBioChalmers", "repo": "RAVEN", "sha": "cf4d3e0be954fde96a1a09ae3353dd2ee46552ed", "save_path": "github-repos/MATLAB/SysBioChalmers-RAVEN", "path": "github-repos/MATLAB/SysBioChalmers-RAVEN/RAVEN-cf4d3e0be954fde96a1a09ae3353dd2ee46552ed/hpa/scoreModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.146131911001175}}
{"text": "function Grasping_and_twist\n\n%% Grasping and twisting Function with EEG recording\nclear; close; clc;\n%% Initializing EEG recording device\nbbci_acquire_bv('close');\nstartup_bbci;\n\n%% RoboticArm communication channel opened\njc = JacoComm;\nconnect(jc);\ncalibrateFingers(jc);\n\n%% Query individual object properties\njc.JointPos\n%%\njc.JointVel\n%%\njc.JointTorque\n%%\njc.JointTemp\n%%\njc.FingerPos\n%%\njc.FingerVel\n%%\njc.FingerTorque\n%%\njc.FingerTemp\n%%\njc.EndEffectorPose\n%%\njc.EndEffectorWrench\n%%\njc.ProtectionZone\n%%\njc.EndEffectorOffset\n%%\njc.DOF\n%%\njc.TrajectoryInfo\n\n%% Methods to query joint and finger values all at once\npos = getJointAndFingerPos(jc);\nvel = getJointAndFingerVel(jc);\n\ntorque = getJointAndFingerTorque(jc);\ntemp = getJointAndFingerTemp(jc);\n\nsetPositionControlMode(jc);\ngoToHomePosition(jc);\n\ncurrent_pos=jc.EndEffectorPose;\nhome_pos=jc.EndEffectorPose;\nprevious_pos=current_pos;\n\nsetPositionControlMode(jc);\nfCmd = 0*ones(3,1);\nsendFingerPositionCommand(jc,fCmd);\n\n%% Offline model training\nglobal EEG_MAT_DIR\nEEG_MAT_DIR = '';\n\ndd = 'MotorImagery Converted Data\\';\nfilelist= {'20191113_demo_bhkwon'};\n\n%% Preprocessing Offline Data\nBandpass_Filter = [4 40];\n\n% Offline Classifier Training\n[cnt, mrk, mnt] = eegfile_loadMatlab([dd filelist{1}]);\n\nival = [0 3000]; % 3s interval\n\ncnt_filt = proc_filtButter(cnt, 5, Bandpass_Filter);\nepo = cntToEpo(cnt_filt,mrk,ival);\n\n[fv, Out.csp_w]=  proc_multicsp(epo, 3);\nfv = proc_variance(fv); fv= proc_logarithm(fv);\n\nfv.classifier_param = {'RLDAshrink','prior', nan, 'store_prior', 1, 'store_means', 1, ...\n    'store_cov', 1, 'store_invcov', 1, 'scaling', 1};\n\nproc = {'wr_multiClass','policy','one-vs-all','coding','hamming'}; % one-vs-all all-pairs\n\nOut.C = trainClassifier(fv, proc);\nOut.out_eeg = applyClassifier(fv, 'wr_multiClass', Out.C);\n\n%% Onling Initialization\nparams = struct;\nstate = bbci_acquire_bv('init', params);\nEEG_data = [];\nmnt = getElectrodePositions(state.clab);\n\nepo.clab = state.clab;\nepo.fs = state.fs;\nepo.title = filelist{1};\nAns = zeros(1,3);\n%% Get EEG data\npy.SharedDemo_6_Vision_LBH.getPerspectiveMine(); % vision model upload\n\ncoord=py.SharedDemo_6_Vision_LBH.mainRunning(1);\ncoord=double(py.array.array('d',py.numpy.nditer(coord)));\ncoord=uint8(coord/5);\npause(1);\n\nhome_pos=jc.EndEffectorPose;\ncurrent_pos=jc.EndEffectorPose;\nprev_pos=current_pos;\n\ntargetX = coord(1);\ntargetY = coord(2);\ntargetX = double(targetX);\ntargetY = double(targetY);\nx_origin = (102 - targetX)/100\ny_origin = (5+targetY)/100\n\ndesired_pos=[x_origin; -y_origin; 0.1; home_pos(4); home_pos(5); home_pos(6)];\nmoveToCP(jc,desired_pos);\n% YOLO to RoboticArm coordinate axis\nwhile 1\n    %% Sound cue\n    [A,AFs] = audioread('grasp.mp3');\n    sound(A,AFs);\n    pause(2);\n    \n    eog_ch = [1 ,31];\n    eog_th = 18;\n    time_window = 20;\n    \n    eog_test(eog_ch, eog_th, time_window);\n    disp('Receiving brain signal')\n    \n    pause(2);\n    \n    %% Initializing EEG recording\n    % Initialization communication channel\n    bbci_acquire_bv('close');\n    EEG_MAT_DIR = '';\n    params=struct;\n    state=bbci_acquire_bv('init',params);\n    EEGData=[];\n    mnt=getElectrodePositions(state.clab);\n    epo.clab = state.clab;\n    epo.fs = state.fs;\n    epo.title = filelist{1};\n    pause('on')\n    \n    [B,BFs] = audioread('censor-beep-4.wav');\n    sound(B,BFs);\n    pause(4);\n    \n    data = bbci_acquire_bv(state);\n    EEG_data = [EEG_data; data];\n    \n    % Sampling Rate: 250Hz, get data every 3 sec\n    if size(EEG_data,1) >= 750\n        epo.x = EEG_data;\n        \n        % EEG filtering\n        Wps= [42 49]/epo.fs*2;\n        [n, Ws]= cheb2ord(Wps(1), Wps(2),3, 40);\n        [filt.b, filt.a]= cheby2(n, 50, Ws);\n        epo = proc_filt(epo, filt.b, filt.a);\n        \n        % Feature Extraction and Classification\n        Classification_Result = MotorImagery_Online_Fn(epo, Bandpass_Filter, Out);\n        \n        disp('Signal processing');\n        pause(2);\n        disp('Decoding signal');\n        pause(2);\n        \n        \n        disp('Grasp');\n        \n        disp('robotic arm activation');\n        pause(2)\n        \n        setPositionControlMode(jc);\n        fCmd = 4000*ones(3,1);\n        sendFingerPositionCommand(jc,fCmd);\n        \n        pause(1);\n        \n        desired_pos=[0.6; -0.2; 0.15; home_pos(4); home_pos(5); home_pos(6)];\n        moveToCP(jc,desired_pos);\n        \n        pause(1);\n        \n    end\n    \n    [B,BFs] = audioread('drinkwater.mp3');\n    sound(B,BFs);\n    pause(2);\n    \n    eog_ch = [1 ,31];\n    eog_th = 18;\n    time_window = 20;\n    \n    \n    \n    eog_test(eog_ch, eog_th, time_window);\n    disp('Receiving brain signal')\n    \n    bbci_acquire_bv('close');\n    EEG_MAT_DIR = '';\n    params=struct;\n    state=bbci_acquire_bv('init',params);\n    EEGData=[];\n    data=[];\n    mnt=getElectrodePositions(state.clab);\n    epo.clab = state.clab;\n    epo.fs = state.fs;\n    epo.title = filelist{1};\n    \n    [B,BFs] = audioread('censor-beep-4.wav');\n    sound(B,BFs);\n    pause(4);\n    \n    data = bbci_acquire_bv(state);\n    EEG_data = [EEG_data; data];\n    \n    if size(EEG_data,1) >= 750\n        epo.x = EEG_data;\n        \n        % EEG filtering\n        Wps= [42 49]/epo.fs*2;\n        [n, Ws]= cheb2ord(Wps(1), Wps(2),3, 40);\n        [filt.b, filt.a]= cheby2(n, 50, Ws);\n        epo = proc_filt(epo, filt.b, filt.a);\n        \n        % Feature Extraction and Classification\n        Classification_Result = MotorImagery_Online_Fn(epo, Bandpass_Filter, Out);\n        \n        disp('Signal processing');\n        pause(2);\n        disp('Decoding signal');\n        pause(2);\n        \n        desired_pos=[0.6; 0.15; 0.15; home_pos(4); home_pos(5); home_pos(6)];\n        moveToCP(jc,desired_pos);\n        \n        jntVelCmd = [0;0;0;0;0;0;0.2]; %7DOF\n        for i=1:300\n            sendJointVelocityCommand(jc,jntVelCmd);\n        end\n        \n        pause(5);\n        \n        jntVelCmd = [0;0;0;0;0;0;-0.2]; %7DOF\n        for i=1:260\n            sendJointVelocityCommand(jc,jntVelCmd);\n        end\n        \n        pause(1);\n        \n        desired_pos=[x_origin; -y_origin; 0.08; home_pos(4); home_pos(5); home_pos(6)];\n        moveToCP(jc,desired_pos);\n        \n        pause(1);\n        \n        setPositionControlMode(jc);\n        fCmd = 0*ones(3,1);\n        sendFingerPositionCommand(jc,fCmd);\n        \n        desired_pos=[x_origin; -y_origin; 0.2; home_pos(4); home_pos(5); home_pos(6)];\n        moveToCP(jc,desired_pos);\n        \n        pause(1);\n        \n        goToHomePosition(jc);\n        \n        break;\n    end\n    \n    disp('Decoding Error!');\n    disp('Receiving brain signal again....');\n    \n    pause(2);\n    \n    desired_pos=[x_origin; -y_origin; 0.07; home_pos(4); home_pos(5); home_pos(6)];\n    moveToCP(jc,desired_pos);\n    \n    pause(1);\n    \n    setPositionControlMode(jc);\n    fCmd = 0*ones(3,1);\n    sendFingerPositionCommand(jc,fCmd);\n    \n    pause(1);\n    \n    desired_pos=[x_origin; -y_origin; 0.2; home_pos(4); home_pos(5); home_pos(6)];\n    moveToCP(jc,desired_pos);\n    \n    goToHomePosition(jc);\n    \n    pause(1);\n    \n    break\n    \n    bbci_acquire_bv('close');\nend\nend\n\n\n\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_RobotArm/BHLee/Grasping_and_twist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.14573803257660442}}
{"text": "% pop_chanplot() - graphic user interface (GUI)-based function with plotting \n%                options for visualizing. Only channel measures (e.g., spectra, \n%                ERPs, ERSPs, ITCs) that have been computed and saved in the study EEG \n%                datasets can be visualized. These can be computed using the GUI-based \n%                pop_precomp().\n% Usage:    \n%                >> STUDY = pop_chanplot(STUDY, ALLEEG);   \n% Inputs:\n%   ALLEEG     - Top-level EEGLAB vector of loaded EEG structures for the dataset(s) \n%                in the STUDY. ALLEEG for a STUDY set is typically loaded using \n%                pop_loadstudy(), or in creating a new STUDY, using pop_createstudy().  \n%   STUDY      - EEGLAB STUDY set comprising some or all of the EEG\n%   datasets in ALLEEG.\n%\n% Outputs:\n%   STUDY      - The input STUDY set structure modified according to specified user edits,\n%                if any. Plotted channel measure means (maps, ERSPs, etc.) are added to \n%                the STUDY structure after they are first plotted to allow quick replotting.  \n%\n% Graphic interface buttons:\n%  \"Select channel to plot\" - [list box] Displays available channels to plot (format is\n%                'channel name (number of channels)'). The presented channels depend s\n%                on the optional input variable 'channels'. Selecting (clicking on) a \n%                channel from the list will display the selected channel channels in the \n%                \"Select channel(s) to plot\" list box. Use the plotting buttons below \n%                to plot selected measures of the selected channel. Additional editing \n%                options (renaming the channel, rejecting outliers, moving channels to \n%                another channel) are also available. The option 'All N channel centroids' \n%                at the top of the list displays all the channels in the list except the \n%                'Notchannel', 'Outlier' and 'Parentchannel' channels. Selecting this option \n%                will plot the channel centroids (i.e. ERP, ERSP, ...) in a single figure.\n%  \"Select channel(s) to plot\" - [list box] Displays the ICA channels of the currently \n%                selected channel (in the \"Select channel to plot\" list box). Each channel \n%                has the format: 'subject name, channel index'. Multiple channels can be \n%                selected from the list. Use the plotting buttons below to plot different \n%                measures of the selected channels on different figures. Selecting the \n%                \"all subjects\" option is  equivalent to using the channel plotting buttons. \n%                Additional editing options are reassigning the selected channels to \n%                another channel or moving them to the outlier channel.\n%  \"Plot channel properties\" - [button] Displays in one figure all the mean channel measures\n%                (e.g., dipole locations, scalp maps, spectra, etc.) that were calculated\n%                and saved in the EEG datsets. If there is more than one condition, the ERP \n%                and the spectrum will have different colors for each condition. The ERSP \n%                and ITC plots will show only the first condition; clicking on the subplot \n%                will open a new figure with the different conditions displayed together. \n%                Uses the command line function std_propplot().\n%  \"Plot scalp maps\"  - [button] Displays the scalp maps of channel channels.\n%                If applied to a channel, scalp maps of the channel channels\n%                are plotted along with the channel mean scalp map in one figure. \n%                If \"All # channel centroids\" option is selected, all channel scalp map\n%                means are plotted in the same figure. If applied to channels, displays\n%                the scalp maps of the specified channel channels in separate figures.\n%                Uses the command line functions std_plotmap() and std_plotchanmap().\n%  \"Plot ERSPs\" - [button] Displays the channel channel ERSPs. \n%                If applied to a channel, channel ERSPs are plotted in one figure  \n%                (per condition) with the channel mean ERSP. If \"All # channel centroids\" \n%                option is selected, plots all average ERSPs of the channels in one figure \n%                per condition. If applied to channels, display the ERSP images of specified \n%                channel channels in separate figures, using one figure for all conditions.\n%                Uses the command line functions std_plotersp() and std_plotchannelsp().\n%  \"Plot ITCs\" - [button] Same as  \"Plot ERSPs\" but with ITC.\n%                Uses the command line functions std_plotitc() and std_plotchanitc().\n%  \"Plot dipoles\" - [button] Displays the dipoles of the channel channels.\n%                If applied to a channel, plots the channel channel dipoles (in blue) \n%                plus the average channel dipole (in red). If \"All # channel centroids\" option \n%                is selected, all channel plots are displayed in one figure each channel in \n%                a separate subplot. If applied to channels, displays the ERSP images of the\n%                specified channel. For specific channels displays channels dipole (in blue) \n%                plus the average channel dipole (in Red) in separate figures. \n%                Uses the command line functions std_dipplot() and std_plotchandip().\n%  \"Plot spectra\" - [button] Displays the channel channel spectra.   \n%                If applied to a channel, displays channel spectra plus the average channel \n%                spectrum in bold. For a specific channel, displays the channel channel \n%                spectra plus the average channel spectrum (in bold) in one figure per condition.\n%                If the \"All # channel centroids\" option is selected, displays the average \n%                spectrum of all channels in the same figure, with spectrum for different \n%                conditions (if any) plotted in different colors.  \n%                If applied to channels, displays the spectrum of specified channel \n%                channels in separate figures using one figure for all conditions.  \n%                Uses the command line functions std_plotspec() and std_plotonechanpec().\n%  \"Plot ERPs\" - [button] Same as \"Plot spectra\" but for ERPs.\n%                Uses the command line functions std_ploterp() and std_plotchannelp().\n%  \"Create new channel\" - [button] Creates a new empty channel.\n%                Opens a popup window in which a name for the new channel can be entered.\n%                If no name is given the default name is 'Cls #', where '#' is the next\n%                available channel number. For changes to take place, press the popup \n%                window 'OK' button, else press the 'Cancel' button. After the empty \n%                channel is created, channels can be moved into it using, \n%                'Reassign selected channel(s)' (see below). Uses the command line \n%                function std_createchant().\n%  \"Rename selected channel\" - [button] Renames a channel using the selected (mnemonic) name. \n%                Opens a popup window in which a new name for the selected channel can be \n%                entered. For changes to take place, press the popup window 'OK' button, \n%                else press the 'Cancel' button. Uses the command line function std_renamechant().\n%  \"Reject outlier channels\" - [button] rejects outlier channels to an outlier channel.\n%                Opens a popup window to specify the outlier threshold. Move outlier \n%                channels that are more than x standard deviations devs from the \n%                channel centroid to an outlier channel. For changes to take place, \n%                press the popup window 'OK' button, else press the 'Cancel' button. \n%                Uses the command line function std_rejectoutliers().\n%  \"Merge channels\" - [button] Merges several channels into one channel.\n%                Opens a popup window in which the channels to merge may be specified \n%                An optional name can be given to the merged channel. If no name is given, \n%                the default name is 'Cls #', where '#' is the next available channel number.   \n%                For changes to take place, press the popup window 'OK' button, else press\n%                the 'Cancel' button. Uses the command line function std_mergechant().\n%  \"Remove selected outlier channel(s)\" - [button] Moves selected channel(s) to the \n%                outlier channel. The channels that will be moved are the ones selected \n%                in the \"Select channel(s) to plot\" list box. Opens a popup window in which \n%                a list of the selected channel(s) is presented. For changes to take place,\n%                press the popup window 'OK' button, else press the 'Cancel' button. \n%                Uses the command line function std_moveoutlier().\n%  \"Reassign selected channel(s)\" - [button] Moves selected channel(s) from one channel \n%                to another. The channels that will reassign are the ones selected in the\n%                \"Select channel(s) to plot\" list box. Opens a popup window in which \n%                a list of possible channels to which to move the selected channel(s) is \n%                presented. For changes to take place, press the popup window 'OK' button, \n%                else press the 'Cancel' button. Uses the command line function std_movecomp().\n%  \"Save STUDY set to disk\" - [check box] Saves the STUDY set structure modified according \n%                to specified user edits to the disk. If no file name is entered will\n%                overwrite the current STUDY set file. \n%\n% See also:  pop_prechant(), pop_chant().         \n%\n% Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN/INC/UCSD, October 11, 2004\n\n% Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, arno@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% Coding notes: Useful information on functions and global variables used.\n\nfunction [STUDY, com] = pop_chanplot(varargin)\n\nicadefs;\ncom = [];\nif ~isstr(varargin{1})\n    if nargin < 2\n        error('pop_chanplot(): You must provide ALLEEG and STUDY structures');\n    end\n    STUDY  = varargin{1};\n    STUDY.etc.erpparams.topotime  = []; % [] for channels and NaN for components\n    STUDY.etc.specparams.topofreq = []; % NaN -> GUI disabled\n    STUDY.etc.erspparams.topotime = [];\n    STUDY.etc.erspparams.topofreq = [];\n    \n    % test path\n    % ---------\n    pathwarn = 'off';\n    if ~strcmpi(pwd, STUDY.filepath)\n        if length(STUDY.datasetinfo(1).filepath) < 1\n            pathwarn = 'on';\n        elseif STUDY.datasetinfo(1).filepath(1) == '.'\n            pathwarn = 'on';\n        end;\n    end;\n    if strcmpi(pathwarn, 'on')\n        warndlg2(strvcat('You have changed your working path and data files are', ...\n                         'no longer available; Cancel, and go back to your STUDY folder'), 'warning');\n    end;\n        \n    oldhistory = STUDY.history;\n    STUDY.history = '';\n    ALLEEG = varargin{2};\n    if ~isfield(STUDY, 'changrp')\n        STUDY = std_changroup(STUDY, ALLEEG);\n        disp('Warning: history not saved for group creation');\n    elseif isempty(STUDY.changrp)\n        STUDY = std_changroup(STUDY, ALLEEG);\n        disp('Warning: history not saved for group creation');\n    end;\n    \n    show_chan          = ['pop_chanplot(''showchan'',gcf);'];\n    show_onechan       = ['pop_chanplot(''showchanlist'',gcf);'];\n\tplot_chan_maps     = ['pop_chanplot(''topoplot'',gcf); ']; \n    plot_onechan_maps  = ['pop_chanplot(''plotchantopo'',gcf); ']; \n    plot_chan_ersps    = ['pop_chanplot(''erspplot'',gcf); '];\n    plot_onechan_ersps = ['pop_chanplot(''plotchanersp'',gcf); '];\n    plot_chan_itcs     = ['pop_chanplot(''itcplot'',gcf); '];\n    plot_onechan_itcs  = ['pop_chanplot(''plotchanitc'',gcf); '];\n    plot_chan_spectra  = ['pop_chanplot(''specplot'',gcf); '];\n    plot_onechan_spectra = ['pop_chanplot(''plotchanspec'',gcf); '];\n    plot_chan_erp      = ['pop_chanplot(''erpplot'',gcf); '];\n    plot_onechan_erp   = ['pop_chanplot(''plotchanerp'',gcf); '];\n    plot_chan_dip      = ['pop_chanplot(''dipplot'',gcf); '];\n    plot_onechan_dip   = ['pop_chanplot(''plotchandip'',gcf); '];\n    plot_chan_sum      = ['pop_chanplot(''plotsum'',gcf); '];\n    plot_onechan_sum   = ['pop_chanplot(''plotonechanum'',gcf); '];\n    rename_chan        = ['pop_chanplot(''renamechan'',gcf);']; \n    move_onechan       = ['pop_chanplot(''movecomp'',gcf);'];\n    move_outlier       = ['pop_chanplot(''moveoutlier'',gcf);'];\n    create_chan        = ['pop_chanplot(''createchan'',gcf);'];\n    reject_outliers    = ['pop_chanplot(''rejectoutliers'',gcf);'];\n    merge_channels     = ['pop_chanplot(''mergechannels'',gcf);'];\n    erp_opt            = ['pop_chanplot(''erp_opt'',gcf);'];\n    spec_opt           = ['pop_chanplot(''spec_opt'',gcf);'];\n    ersp_opt           = ['pop_chanplot(''ersp_opt'',gcf);'];\n    create_group       = ['pop_chanplot(''create_group'',gcf);'];\n    edit_group         = ['pop_chanplot(''edit_group'',gcf);'];\n    delete_group       = ['pop_chanplot(''delete_group'',gcf);'];\n    saveSTUDY          = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ];\n    browsesave         = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_chan()''); ' ... \n                           'set(faindobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ];\n    sel_all_chans      = ['pop_chanplot(''sel_all_chans'',gcf);'];\n                       \n    % list of channel groups\n    % ----------------------\n    show_options = {};\n    for index = 1:length(STUDY.changrp)\n        show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];\n    end;\n    \n    % enable buttons\n    % --------------\n    filename = STUDY.design(STUDY.currentdesign).cell(1).filebase;\n    if exist([filename '.datspec']) , spec_enable = 'on'; else spec_enable  = 'off'; end;\n    if exist([filename '.daterp'] )  , erp_enable = 'on'; else  erp_enable  = 'off'; end;\n    if exist([filename '.datersp']) , ersp_enable = 'on'; else ersp_enable  = 'off'; end;\n    if exist([filename '.datitc'])  ,  itc_enable = 'on'; else  itc_enable  = 'off'; end;\n    \n    if isfield(ALLEEG(1).dipfit, 'model'), dip_enable   = 'on'; else dip_enable   = 'off'; end;\n    \n    % userdata below\n    % --------------\n    fig_arg{1}{1} = ALLEEG;\n    fig_arg{1}{2} = STUDY;\n    fig_arg{1}{3} = STUDY.changrp;\n    fig_arg{1}{4} = { STUDY.changrp.name };\n    fig_arg{2}    = length(STUDY.changrp);\n        \n    geometry = { [4] [1] [0.7 0.3 0.3 0.1 0.9] [1 0.3 1] [1 0.3 1] [1 0.3 1] [1 0.3 1] ...\n                 [1 0.3 1] [1 0.3 1] };\n    str_name       = sprintf('STUDY name ''%s'' - ''%s''', STUDY.name, STUDY.design(STUDY.currentdesign).name);\n    if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end;\n             \n    uilist   = { ...\n        {'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} {} ...\n        {'style' 'text'       'string' 'Select channel to plot' 'FontWeight' 'Bold' } ...\n        {'style' 'pushbutton' 'string' 'Sel. all' 'callback' sel_all_chans } {} {} ...\n        {'style' 'text'       'string' 'Select subject(s) to plot' 'FontWeight' 'Bold'} ...\n        {'style' 'listbox'    'string' show_options 'value' 1 'max' 2 'tag' 'chan_list' 'Callback' show_chan } {} ...\n        {'style' 'listbox'    'string' '' 'tag' 'chan_onechan' 'max' 2 'min' 1 'callback'    show_onechan } ... \n        {'style' 'pushbutton' 'enable'   erp_enable 'string' 'Plot ERPs' 'Callback' plot_chan_erp} ...\n        {'style' 'pushbutton' 'enable'   erp_enable 'string' 'Params' 'Callback' erp_opt }  ...\n        {'style' 'pushbutton' 'enable'   erp_enable 'string' 'Plot ERP(s)' 'Callback' plot_onechan_erp} ...\n        {'style' 'pushbutton' 'enable'  spec_enable 'string' 'Plot spectra' 'Callback' plot_chan_spectra} ...\n        {'style' 'pushbutton' 'enable'  spec_enable 'string' 'Params' 'Callback' spec_opt }  ...\n        {'style' 'pushbutton' 'enable'  spec_enable 'string' 'Plot spectra' 'Callback' plot_onechan_spectra} ...\n        {'style' 'pushbutton' 'enable'  ersp_enable 'string' 'Plot ERSPs' 'Callback' plot_chan_ersps} ...\n        {'vertshift' 'style' 'pushbutton' 'enable'  ersp_enable 'string' 'Params' 'Callback' ersp_opt }  ...\n        {'style' 'pushbutton' 'enable'  ersp_enable 'string' 'Plot ERSP(s)' 'Callback' plot_onechan_ersps}...\n        {'style' 'pushbutton' 'enable'   itc_enable 'string' 'Plot ITCs' 'Callback' plot_chan_itcs} { }  ...\n        {'style' 'pushbutton' 'enable'   itc_enable 'string' 'Plot ITC(s)' 'Callback' plot_onechan_itcs}...\n        {'style' 'pushbutton' 'string' 'Plot channel properties' 'Callback' plot_chan_sum} {} ... \n        {'style' 'pushbutton' 'string' 'Plot channel properties (soon)' 'Callback' plot_onechan_sum 'enable' 'off'} };\n    \n   [out_param userdat] = inputgui( 'geometry' , geometry, 'uilist', uilist, ...\n                                   'helpcom', 'pophelp(''pop_chanplot'')', ...\n                                   'title', 'View and edit current channels -- pop_chanplot()' , 'userdata', fig_arg, ...\n                                   'geomvert', [ 1 0.5 1 5 1 1 1 1 1], 'eval', show_chan );\n\t\n   if ~isempty(userdat)\n       ALLEEG = userdat{1}{1};\n       STUDY  = userdat{1}{2};\n   end\n\n   % history\n   % -------\n   com = STUDY.history;\n   STUDY.history =  sprintf('%s%s', oldhistory, com);              \n   \nelse\n    hdl = varargin{2};  %figure handle\n    userdat  = get(varargin{2}, 'userdat');    \n    ALLEEG   = userdat{1}{1};\n    STUDY    = userdat{1}{2};\n    cls      = userdat{1}{3};\n    allchans = userdat{1}{4};\n    \n    changrp = get(findobj('parent', hdl, 'tag', 'chan_list')   , 'value');\n    onechan = get(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value');\n   \n    switch  varargin{1}\n        \n        case {'topoplot', 'erspplot','itcplot','specplot', 'erpplot'}\n            changrpstr = allchans(changrp);\n            plotting_option = varargin{1};\n            plotting_option = [ plotting_option(1:end-4) 'plot' ];\n            a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'','  vararg2str({changrpstr}) ');' ];\n             % update Study history\n            eval(a); STUDY.history =  sprintf('%s\\n%s',  STUDY.history, a);  \n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); \n\n        case {'plotchantopo', 'plotchanersp','plotchanitc','plotchanspec', 'plotchanerp','plotchandip'}\n            changrpstr    = allchans(changrp);\n            %if length(changrp) > 1\n            %    subject = STUDY.subject{onechan-1};\n            %else\n            %    changrpstruct = STUDY.changrp(changrp);\n            %    allsubjects   = unique({ STUDY.datasetinfo([ changrpstruct.setinds{:} ]).subject });\n            %    subject = allsubjects{onechan-1};\n            %end;\n            plotting_option = varargin{1};\n            plotting_option = [ plotting_option(9:end) 'plot' ];\n            if onechan(1) ~= 1  % check that not all onechan in channel are requested\n                 subject = STUDY.design(STUDY.currentdesign).cases.value{onechan-1};\n                 a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'','  vararg2str({changrpstr}) ', ''subject'', ''' subject ''' );' ];\n                 eval(a); STUDY.history =  sprintf('%s\\n%s',  STUDY.history, a);  \n             else\n                a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'','  vararg2str({changrpstr}) ', ''plotsubjects'', ''on'' );' ];\n                eval(a); STUDY.history =  sprintf('%s\\n%s',  STUDY.history, a);\n             end;\n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); \n            \n        case 'erp_opt' % save the list of selected channels\n            [STUDY com] = pop_erpparams(STUDY);\n            if ~isempty(com)\n                STUDY.history =  sprintf('%s\\n%s',  STUDY.history, com);\n            end;\n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); %update information (STUDY)     \n\n        case 'spec_opt' % save the list of selected channels\n            [STUDY com] = pop_specparams(STUDY);\n            if ~isempty(com)\n                STUDY.history =  sprintf('%s\\n%s',  STUDY.history, com);\n            end;\n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); %update information (STUDY)     \n         \n        case 'ersp_opt' % save the list of selected channels\n            [STUDY com] = pop_erspparams(STUDY);\n            if ~isempty(com)\n                STUDY.history =  sprintf('%s\\n%s',  STUDY.history, com);\n            end;\n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); %update information (STUDY)     \n            \n        case 'showchanlist' % save the list of selected channels\n            if length(changrp) == 1\n                STUDY.changrp(changrp).selected = onechan;\n            end;\n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat); %update information (STUDY)     \n               \n       case 'showchan'\n            cind     = get(findobj('parent', hdl, 'tag', 'chan_list')   , 'value');\n            changrp  = STUDY.changrp(cind);\n            \n            % Find datasets availaible\n            % ------------------------\n            %setind = STUDY.setind .* (changrp.chaninds > 0); % set to 0 the cell not\n            %%                                       % containing any electrode\n            %allchansets = unique( setind(find(setind(:))) );\n            \n            % Generate channel list\n            % ---------------------\n            chanid{1} = 'All subjects';\n            if length(changrp) == 1\n                allsubjects = unique({ STUDY.design(STUDY.currentdesign).cell([ changrp.setinds{:} ]).case });\n                for l = 1:length(allsubjects)\n                    chanid{end+1} = [ allsubjects{l} ' ' changrp.name ];\n                end;\n            else\n                for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value)\n                    chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ];\n                end;\n            end;\n                \n            selected = 1;\n            if isfield(changrp, 'selected') & length(cind) == 1\n                if ~isempty(STUDY.changrp(cind).selected)\n                    selected = min(STUDY.changrp(cind).selected, 1+length(chanid));\n                    STUDY.changrp(cind).selected = selected;\n                end;\n            end;\n\n            set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid);\n        \n        case 'sel_all_chans'\n            set(findobj('parent', hdl, 'tag', 'chan_list'), 'value', [1:length(STUDY.changrp)]);\n            \n            % Generate channel list\n            % ---------------------\n            chanid{1} = 'All subjects';\n            for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value)\n                chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ' All' ];\n            end;\n            selected = 1;\n            set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid);\n\n        case 'plotsum'\n            changrpstr = allchans(changrp);\n            [STUDY] = std_propplot(STUDY, ALLEEG, allchans(changrp));\n            a = ['STUDY = std_propplot(STUDY, ALLEEG, ' vararg2str({ allchans(changrp) }) ' );'  ];\n            STUDY.history =  sprintf('%s\\n%s',  STUDY.history, a);  \n            userdat{1}{2} = STUDY;\n            set(hdl, 'userdat',userdat);    \n                       \n        case 'create_group'\n            channames = { STUDY.changrp(changrp).name };\n            for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end;\n            channamestr = strcat(channames{:});\n            res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', 1, { '' channamestr(2:end) });\n            if isempty(res), return; end;\n            STUDY.changrp(end+1).name = res{1};\n            allchans(end+1)         = { res{1} };\n            chanlabels = parsetxt(res{2});\n            if length(chanlabels) == 1\n                warndlg2('Cannot create a channel group with a single channel');\n                return;\n            end;\n            STUDY.changrp(end).channels = chanlabels;\n            tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end));\n            STUDY.changrp(end).chaninds = tmp.chaninds;\n            userdat{1}{2} = STUDY;\n            userdat{1}{4} = allchans;\n            set(hdl, 'userdat',userdat);    \n            \n            % list of channel groups\n            % ----------------------\n            tmpobj  = findobj('parent', hdl, 'tag', 'chan_list');\n            tmptext = get(tmpobj, 'string');\n            tmptext{end+1} = [ 'All ' STUDY.changrp(end).name ];\n            set(tmpobj, 'string', tmptext, 'value', length(tmptext));\n\n        case 'edit_group'\n            if length(changrp) > 1, return; end;\n            if length(STUDY.changrp(changrp).channels) < 2, return; end;\n            channames = STUDY.changrp(changrp).channels;\n            for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end;\n            channamestr = strcat(channames{:});\n            res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', ...\n                            1, { STUDY.changrp(changrp).name channamestr(2:end) });\n            if isempty(res), return; end;\n            STUDY.changrp(end+1).name = '';\n            STUDY.changrp(changrp)    = STUDY.changrp(end);\n            STUDY.changrp(end)        = [];\n            STUDY.changrp(changrp).name = res{1};\n            allchans(changrp)         = { res{1} };\n            chanlabels = parsetxt(res{2});\n            STUDY.changrp(changrp).channels = chanlabels;\n            tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end));\n            STUDY.changrp(changrp).chaninds = tmp.chaninds;\n            userdat{1}{2} = STUDY;\n            userdat{1}{4} = allchans;\n            set(hdl, 'userdat',userdat);    \n            \n            % list of channel groups\n            % ----------------------\n            show_options = {};\n            for index = 1:length(STUDY.changrp)\n                show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];\n            end;\n            tmpobj  = findobj('parent', hdl, 'tag', 'chan_list');\n            set(tmpobj, 'string', show_options, 'value', changrp);\n            \n        case 'delete_group'\n            if length(changrp) > 1, return; end;\n            if length(STUDY.changrp(changrp).channels) < 2, return; end;\n            STUDY.changrp(changrp)    = [];\n            \n            % list of channel groups\n            % ----------------------\n            show_options = {};\n            for index = 1:length(STUDY.changrp)\n                show_options{end+1} = [ 'All ' STUDY.changrp(index).name ];\n            end;\n            tmpobj  = findobj('parent', hdl, 'tag', 'chan_list');\n            set(tmpobj, 'string', show_options, 'value', changrp-1);\n            \n        case 'renamechan'\n            STUDY.saved = 'no';\n            chan_name_list = get(findobj('parent', hdl, 'tag', 'chan_list'), 'String');\n            chan_num = get(findobj('parent', hdl, 'tag', 'chan_list'), 'Value') -1;\n            if chan_num == 0  % 'all subjects' option \n                return;\n            end\n            % Don't rename 'Notchan' and 'Outliers'  channels.\n            if strncmpi('Notchan',STUDY.channel(cls(chan_num)).name,8) | strncmpi('Outliers',STUDY.channel(cls(chan_num)).name,8) | ...\n                    strncmpi('Parentchannel',STUDY.channel(cls(chan_num)).name,13)\n                warndlg2('The Parentchannel, Outliers, and Notchan channels cannot be renamed');\n                return;\n\t\t\tend\n            old_name = STUDY.channel(cls(chan_num)).name;\n            rename_param  = inputgui( { [1] [1] [1]}, ...\n                { {'style' 'text' 'string' ['Rename ' old_name] 'FontWeight' 'Bold'} {'style' 'edit' 'string' '' 'tag' 'chan_rename' } {} }, ...\n            '', 'Rename channel - from pop_chanplot()' );\n            if ~isempty(rename_param) %if not canceled\n                new_name = rename_param{1};\n                STUDY = std_renamechan(STUDY, ALLEEG, cls(chan_num), new_name);\n                % update Study history\n                a = ['STUDY = std_renamechan(STUDY, ALLEEG, ' num2str(cls(chan_num)) ', ' STUDY.channel(cls(chan_num)).name  ');'];\n                STUDY.history =  sprintf('%s\\n%s',  STUDY.history, a);  \n                \n                new_name = [ STUDY.channel(cls(chan_num)).name ' (' num2str(length(STUDY.channel(cls(chan_num)).onechan))  ' ICs)'];\n                chan_name_list{chan_num+1} = renamechan( chan_name_list{chan_num+1}, new_name);\n                set(findobj('parent', hdl, 'tag', 'chan_list'), 'String', chan_name_list);\n                set(findobj('parent', hdl, 'tag', 'chan_rename'), 'String', '');\n                userdat{1}{2} = STUDY;\n                set(hdl, 'userdat',userdat); %update STUDY\n            end            \n    end\nend\n\nfunction newname = renamechan(oldname, newname);\n    \n    tmpname = deblank(oldname(end:-1:1));\n    strpos  = strfind(oldname, tmpname(end:-1:1));\n    \n    newname = [ oldname(1:strpos-1) newname ];\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/pop_chanplot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.14500797496370582}}
{"text": "%% To-do\n% - Delete rhs_shapefunction -> use funs\n% - Clean RHSunfitted\n% OK! - switch class(mesh.type) @ RHSfactory\n% - filter_pde_density using rhs_unfitted (now rhs_shapefunctionfun*\n% - filter_pde_levelset name change for unfitted\n\n%% Questions\n% - Filter_P1_LevelSet.getP0fromP1() ??\n% - Careful: unfittedmesh needed to properly integrate!!!\n\n%% Results\n% \n\n\n%% Long-term\n% - Use FeFunctions in TopOpt_Problem\n% - PDE belongs to Optimizer, not ShapeFunctional\n% - Micro as three elasticity problems\n\n%% Backlog\n% - Move Input folder to a separate repository\n% - Geometry only in Mesh\n\n% EXTRAS\n%  - Investigate: converting data to binary format to save read'n'write\n%                 resources for paraview\n%  - Tutorial for printing\n%  - Study file ouptut size vs time (GiD/Paraview) to see which is better\n%    for printing (test + graph)\n%  - Check XY component of fgaussfunctions\n% - Recuperar gid unfitted mesh photo GiDimagecapturer\n%      density --(project)--> unfittedmesh -> innermesh/photo\n\n% - GiDImageCapturer -> some variables should be \"user variables\", defined\n%   once in a centralized file", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/todo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.2689414096510108, "lm_q1q2_score": 0.1449549071499876}}
{"text": "function simulate_2spk_mix(data_type, wsj0root, output_dir, fs8k, min_max)\n% Simulate 2-speaker mixture data for speaker extraction.\n% Call:\n%     simulate_2spk_mix(data_type, wsj0root, output_dir, fs8k, min_max)\n%     e.g., simulate_2spk_mix('tt', '/media/clx214/data/wsj/', '/media/clx214/data/wsj0_2mix_extr_tmp/wav8k', 8000, 'max')\n% Paras:\n%     data_type: data set to generate, (tr|cv|tt), e.g., 'tt'\n%     wsj0root: YOUR_PATH/, the folder containing converted wsj0/, e.g., '/media/clx214/data/wsj/'\n%     output_dir: the folder to save simulated data for extraction, e.g., '/media/clx214/data/wsj0_2mix_extr_tmp/wav8k'\n%     fs8k: sampling rate of the simulated data, e.g., 8000\n%     min_max: get the mininium or maximum wav length, when simulating mixture data, e.g, 'max'\n%\n% The code is based on \"create_wav_2speakers_extr.m\" from \"http://www.merl.com/demos/deep-clustering\"\n%\n% 1. Assume that WSJ0's wv1 sphere files is converted to wav files. The folder\n%    structure and file name are kept same under wsj0/, e.g.,\n%    ORG_PATH/wsj0/si_tr_s/01t/01to030v.wv1 is converted to wav and\n%    stored in YOUR_PATH/wsj0/si_tr_s/01t/01to030v.wv1.\n%    Relevant data ('si_tr_s', 'si_dt_05' and 'si_et_05') are under YOUR_PATH/wsj0/\n% 2. Put 'voicebox' toolbox in current folder. (http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html)\n% 3. Set your 'YOUR_PATH' and 'OUTPUT_PATH' properly, then run this script in Matlab.\n%    (The max lenght of the wav will be kept when generate the mixture. The sampling rate will be 8kHz.)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%   Copyright (C) 2016 Mitsubishi Electric Research Labs\n%                          (Jonathan Le Roux, John R. Hershey, Zhuo Chen)\n%   Apache 2.0  (http://www.apache.org/licenses/LICENSE-2.0)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Copyright 2018 Chenglin Xu, Nanyang Technological University, Singapore\n%\n%Licensed under the Apache License, Version 2.0 (the \"License\");\n%you may not use this file except in compliance with the License.\n%You may obtain a copy of the License at\n%\n%    http://www.apache.org/licenses/LICENSE-2.0\n%\n%Unless required by applicable law or agreed to in writing, software\n%distributed under the License is distributed on an \"AS IS\" BASIS,\n%WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n%See the License for the specific language governing permissions and\n%limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ~exist([output_dir '/' min_max '/' data_type],'dir')\n    mkdir([output_dir '/' min_max '/' data_type]);\nend\nmkdir([output_dir  '/' min_max '/' data_type '/s1/']);\nmkdir([output_dir  '/' min_max '/' data_type '/aux/']);\nmkdir([output_dir  '/' min_max '/' data_type '/mix/']);\n\nTaskFile = ['mix_2_spk_' data_type '_extr.txt'];\nfid = fopen(TaskFile,'r');\nC = textscan(fid,'%s %f %s %f %s');\nnum_files = length(C{1});\n\nfprintf(1,'Start to generate data for %s\\n', [min_max '_' data_type]);\nfor i = 1:num_files\n    [inwav1_dir,invwav1_name,inwav1_ext] = fileparts(C{1}{i});\n    [inwav2_dir,invwav2_name,inwav2_ext] = fileparts(C{3}{i});\n    [inwav_aux_dir,invwav_aux_name,inwav_aux_ext] = fileparts(C{5}{i});\n    \n    inwav1_snr = C{2}(i);\n    inwav2_snr = C{4}(i);\n    mix_name = [invwav1_name,'_',num2str(inwav1_snr),'_',invwav2_name,'_',num2str(inwav2_snr),'_',invwav_aux_name];\n    \n    % get input wavs\n    [s1, fs] = audioread([wsj0root C{1}{i}]);\n    s2       = audioread([wsj0root C{3}{i}]);\n    s_aux    = audioread([wsj0root C{5}{i}]);\n    \n    % resample, normalize to 8 kHz file\n    s1_8k = resample(s1,fs8k,fs);\n    [s1_8k,lev1] = activlev(s1_8k,fs8k,'n'); % y_norm = y /sqrt(lev);\n    s2_8k = resample(s2,fs8k,fs);\n    [s2_8k,lev2] = activlev(s2_8k,fs8k,'n');\n    s_aux_8k = resample(s_aux,fs8k,fs);\n    [s_aux_8k,lev_aux] = activlev(s_aux_8k,fs8k,'n');\n    \n    weight_1 = 10^(inwav1_snr/20);\n    weight_2 = 10^(inwav2_snr/20);\n    \n    s1_8k = weight_1 * s1_8k;\n    s2_8k = weight_2 * s2_8k;\n    \n    switch min_max\n        case 'max'\n            mix_8k_length = max(length(s1_8k),length(s2_8k));\n            s1_8k = cat(1,s1_8k,zeros(mix_8k_length - length(s1_8k),1));\n            s2_8k = cat(1,s2_8k,zeros(mix_8k_length - length(s2_8k),1));\n        case 'min'\n            mix_8k_length = min(length(s1_8k),length(s2_8k));\n            s1_8k = s1_8k(1:mix_8k_length);\n            s2_8k = s2_8k(1:mix_8k_length);\n    end\n    mix_8k = s1_8k + s2_8k;\n    \n    max_amp_8k = max(cat(1,abs(mix_8k(:)),abs(s1_8k(:)),abs(s2_8k(:)),abs(s_aux_8k(:))));\n    mix_scaling_8k = 1/max_amp_8k*0.9;\n    s1_8k = mix_scaling_8k * s1_8k;\n    mix_8k = mix_scaling_8k * mix_8k;\n    s_aux_8k = mix_scaling_8k * s_aux_8k;\n    \n    audiowrite([output_dir '/' min_max '/' data_type '/s1/' mix_name '.wav'],s1_8k,fs8k);\n    audiowrite([output_dir '/' min_max '/' data_type '/aux/' mix_name '.wav'],s_aux_8k,fs8k);\n    audiowrite([output_dir '/' min_max '/' data_type '/mix/' mix_name '.wav'],mix_8k,fs8k);\nend\nfclose(fid);\nfprintf(1,'End of generating data for %s\\n', [min_max '_' data_type]);\nend\n", "meta": {"author": "gemengtju", "repo": "Tutorial_Separation", "sha": "c47dca746fa2e123868f5fbf2aed70ab3809925b", "save_path": "github-repos/MATLAB/gemengtju-Tutorial_Separation", "path": "github-repos/MATLAB/gemengtju-Tutorial_Separation/Tutorial_Separation-c47dca746fa2e123868f5fbf2aed70ab3809925b/generation/wsj0-2mix-extr/simulate_2spk_mix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.24220563966531902, "lm_q1q2_score": 0.1444594717086224}}
{"text": "function [align] = mamarama(in,config)\n\nCst = in.Cst;\nRot = in.Rot;\n\nOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;\nif ~Octave,\n  drawscene(in.Xe,Cst',Rot,41,'cloud','Graphical Output Validation: View from top or bottom (no sRt)',config.cal.cams2use);\nend\n\n% definition of the absolute world frame (in cm)\n\n%% for hummingbird cage\n%\n%cam(3).C = [168, 173, 185]';\n%cam(4).C = [142, 76, 89]';\n%cam(1).C = [81, 72, 165]';\n%cam(2).C = [22,  15, 176]';\n%cam(5).C = [53.5, 175, 78]';\n\n% definition of the absolute world frame (in mm) (Doug's cube)\n\n% cam(1).C = [10, 390, 600]';\n% cam(2).C = [460,  380, 600]';\n% cam(3).C = [430, 115, 580]';\n% cam(4).C = [0, 0, 610]';\n% cam(5).C = [240, 150, 610]';\n\n% definition of the absolute world frame (in mm) (windtunnel June 2005)\n\n%cam(1).C = [1510, 180, 500+322]';\n%cam(2).C = [1140,  260, 450+322]';\n%cam(3).C = [1040, 25, 480+322]';\n%cam(4).C = [490, 160, 390+322]';\n%cam(5).C = [900, 25, 400+322]';\n\n% the above numbers (from June 2005) transformed to acheive better\n% agreement (July 3, 2005)\n\n%cam(1).C = [1585.0266, 157.1808, 725.3687]';\n%cam(2).C = [1221.0045, 230.7819, 717.1524]';\n%cam(3).C = [1123.2774, -2.1424, 731.8758]';\n%cam(4).C = [580.8019, 124.5745, 705.3737]';\n%cam(5).C = [978.8653, 3.3878, 663.1311]';\n\n% cal July 5, 2005\n\n%cam(1).C = [1710, 375, 820]';\n%cam(2).C = [1110, 316, 800]';\n%cam(3).C = [1110, 100, 466]';\n%cam(4).C = [-380, 290, 875]';\n%cam(5).C = [440, 15, 680]';\n\n% touch-up July 6, 2005 (5c)\n\n%cam(1).C = [1853.5325, 228.1160, 971.5365]';\n%cam(2).C = [1202.0386, 199.5437, 953.7752]';\n%cam(3).C = [1183.3920, 41.6797, 537.2034]';\n%cam(4).C = [-406.8365, 229.6378, 1073.0449]';\n%cam(5).C = [460.2840, -60.0974, 778.1218]';\n\n% touch-up Aug 22, 2005 (touch-up from A applied to B)\n\n%cam(1).C = cam(1).C - [130.0*0.83, 0., 110.0*0.83]';\n%cam(2).C = cam(2).C - [130.0*0.83, 0., 110.0*0.83]';\n%cam(3).C = cam(3).C - [130.0*0.83, 0., 110.0*0.83]';\n%cam(4).C = cam(4).C - [130.0*0.83, 0., 110.0*0.83]';\n%cam(5).C = cam(5).C - [130.0*0.83, 0., 110.0*0.83]';\n\n% touch-up Jan 27, 2006 ( hacked-in estimate )\n\n%cam(1).C = cam(1).C - [130.0*0.83+20.0, 0., 110.0*0.83]';\n%cam(2).C = cam(2).C - [130.0*0.83+10.0, 0., 110.0*0.83]';\n%cam(3).C = cam(3).C - [130.0*0.83+10.0, 0., 110.0*0.83]';\n%cam(4).C = cam(4).C - [130.0*0.83, 0., 110.0*0.83]';\n%cam(5).C = cam(5).C - [130.0*0.83, 0., 110.0*0.83]';\n\n% new Feb 14, 2006\n\n%cam(1).C = [1760, 190, 850]';\n%cam(2).C = [1060, 260, 785]';\n%cam(3).C = [1070, 70, 470 ]';\n%cam(4).C = [-380, 230, 873]';\n%cam(5).C = [380, -10, 670]';\n\n% moved cam 2006 03 07 19:45\n\n%cam(1).C = [1760, 190, 850]';\n%cam(2).C = [1060, 260, 785]';\n%cam(3).C = [1070, 190, 510 ]';\n%cam(4).C = [-380, 230, 873]';\n%cam(5).C = [380, 120, 670]';\n\nif 1,\n\n% 2006 03 31\n\n%cam(1).C = [640, -105, 170]';\n%cam(2).C = [1220, 172, 912]';\n%cam(3).C = [475, 172, 580 ]';\n%cam(4).C = [-350, 172, 932]';\n%cam(5).C = [320, -105, 170]';\n\n% 2006 04 03e\n\n%cam(3).C = [380, 240, 530 ]';\n\n% 2006 04 04a\n\n%cam(4).C = [-115, 220, 800]';\nend\n\n% 2006 09 14\n\n%cam(1).C = [685, 220, 775]';\n%cam(2).C = [1220, 172, 912]';\n%cam(3).C = [380, 240, 530 ]';\n%cam(4).C = [-115, 220, 800]';\n%cam(5).C = [180, 240, 740]';\n\n%% 2006 10 23 (from DLT)\n%cam(1).C = [ 651.7963301   169.95615265  749.51356735]';\n%cam(2).C = [ 1090.40810501   190.82014771   866.8980674 ]';\n%cam(3).C = [ 327.41874025  237.43022637  539.80942371]';\n%cam(4).C = [-241.364468    194.27934314  767.35249515]';\n%cam(5).C = [ 147.20028399  171.45774441  725.08522715]';\n\n% 2006 12 19 riverside hummingbirds\n% estimates from DLT\n%cam(1).C = [976.22314128 -2289.85157108   489.78104927]';\n%cam(2).C = [-17278.94752856   1794.85211148  15855.51116479]';\n%cam(3).C = [ 2266.45466953  2590.2964507    -74.53159994]';\n%cam(4).C = [-329.01069449  796.46308431  624.04191004]';\n\n% hand measurements\n%ft2mm = 12*25.4;\n%cam(1).C = [ 1350 -1580 540]';\n%cam(2).C = [ -450 770 (750+5*ft2mm) ]';\n%cam(3).C = [ 1500 -1600 2250]';\n%cam(4).C = [-280 820 570]';\n\n% 2006 12 01 DLT in flydra WT\n%cam(1).C = [867.37446261  198.97798549  832.51824736]';\n%cam(2).C = [1194.97461953 206.718389208 898.66723201]';\n%cam(3).C = [459.669418616 168.068949056 713.890827]';\n%cam(4).C = [-186.0833207 207.892635698 775.298571621]';\n%cam(5).C = [115.230367611 202.584140956 904.723766629]';\n\n% 2007 10 03 DLT in flydra WT\n%cam(1).C = [ 985.827871     182.49267738  1134.97921258]';\n%cam(2).C = [362.27817754   189.63204145  1134.23310277]';\n%cam(3).C = [721.10852967  167.31210242  932.32564817]';\n%cam(4).C = [-330.47764957   168.38518854  1014.81801646]';\n%cam(5).C = [1774.53765317   144.79725152   928.10954671]';\n\n% 2007 11 16 mamarama\n%cam(1).C = ([20     25  30]*25.4)';\n%cam(2).C = ([26   36  33]*25.4)';\n%cam(3).C = ([26  -36  31]*25.4)';\n%cam(4).C = ([74   2  30]*25.4)';\n%cam(5).C = ([17   -25   30]*25.4)';\n\n% 2007 12 18 mamarama\n% cam(1).C = [130   450    705]';\n% cam(2).C = [0     660    665]';\n% cam(3).C = [1460  640    665]';\n% cam(4).C = [685   1865   710]';\n% cam(5).C = [1315  480    715]';\n\n% % 2008 03 12 mamarama\n% cam(1).C = [710   1350    785]';\n% cam(2).C = [795   1255    785]';\n% cam(3).C = [-610   1255    790]';\n% cam(4).C = [-505   1355    790]';\n% cam(5).C = [110   -355     785]';\n% cam(6).C = [-850   305     785]'; %mama07.2\n% cam(7).C = [-810   190     785]';\n% cam(8).C = [1020   305     785]'; %mama08.2\n% cam(9).C = [980   190     785]';\n\n% 2008 04 17 mamarama\ncam(1).C = [645   -265    760]';    %mama01\ncam(2).C = [640   1250    760]';    %mama02\ncam(3).C = [-455  1260    780]';   %mama03\ncam(4).C = [-450  -295    780]';   %mama04\ncam(5).C = [100   495     805]';   %mama05\ncam(6).C = [85    1460    780]';   %mama06_0\ncam(7).C = [85    -470    780]';   %mama06_1\ncam(8).C = [-745  920     775]';   %mama07_0\ncam(9).C = [-685  -65     775]';    %mama07_1\ncam(10).C = [890   1030    775]';  %mama08_0\ncam(11).C = [935   80     775]';   %mama08_1\n\n% of the similarity computation\n\n[align.simT.s, align.simT.R, align.simT.t]  = estsimt([Cst'],[cam(:).C]);\n[align.P, align.X] = align3d(in.Pe,in.Xe,align.simT);\n% save aligned data\nif 1 % SAVE_STEPHI | SAVE_PGUHA\n\t[align.Cst,align.Rot] = savecalpar(align.P,config);\nend\n\nif ~Octave,\n  drawscene(align.X,align.Cst',align.Rot,61,'cloud','Graphical Output Validation: Aligned data',config.cal.cams2use);\n\n  set(gca,'CameraTarget',[0,0,0]);\n  set(gca,'CameraPosition',[0,0,1]);\n\n  figure(61),\n  % print -depsc graphevalaligned.eps\n  eval(['print -depsc ', config.paths.data, 'topview.eps'])\n\n  drawscene(align.X,align.Cst',align.Rot,62,'cloud','Graphical Output Validation: Aligned data',config.cal.cams2use);\n\n  set(gca,'CameraTarget',[0,0,0.9]);\n  set(gca,'CameraPosition',[2,0,0.9]);\n\n  %figure(62),\n  % print -depsc graphevalaligned.eps\n  %eval(['print -depsc ', config.paths.data, 'sideview.eps'])\nend\n\nreturn\n", "meta": {"author": "strawlab", "repo": "MultiCamSelfCal", "sha": "0a26c88c63d8513eab76553033a9a6fb15ba6575", "save_path": "github-repos/MATLAB/strawlab-MultiCamSelfCal", "path": "github-repos/MATLAB/strawlab-MultiCamSelfCal/MultiCamSelfCal-0a26c88c63d8513eab76553033a9a6fb15ba6575/MultiCamSelfCal/BlueCLocal/mamarama.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.14433674655842557}}
{"text": "% ------------------------------------------------------------------------ \n%  Copyright (C)\n%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain\n%  University of California Berkeley (UCB) - USA\n% \n%  Jordi Pont-Tuset <jordi.pont@upc.edu>\n%  Pablo Arbelaez <arbelaez@berkeley.edu>\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% ------------------------------------------------------------------------\n%\n% Create random divisions of the training set for cross-validation\n%\n% ------------------------------------------------------------------------\n\n% Create random divisions of the training set\nid = '3';\npercentage_train = 0.5;\nfull_set = 'train2012';\n\n% Get full ids \nim_ids = database_ids('pascal2012',full_set);\n\nids_a = sort(randperm(length(im_ids),floor(percentage_train*length(im_ids))));\nids_b = setdiff(1:length(im_ids),ids_a);\nim_ids_a = im_ids(ids_a);\nim_ids_b = im_ids(ids_b);\n\n% Write to file\nfile_a = fullfile(mcg_root,'datasets', 'pascal2012','gt_sets',[full_set '_' id 'a.txt']);\nfile_b = fullfile(mcg_root,'datasets', 'pascal2012','gt_sets',[full_set '_' id 'b.txt']);\n\ndlmwrite(file_a,im_ids_a,'')\ndlmwrite(file_b,im_ids_b,'')", "meta": {"author": "jponttuset", "repo": "mcg", "sha": "e72031d793abf8921e39a8ef3c20de2198c8b26f", "save_path": "github-repos/MATLAB/jponttuset-mcg", "path": "github-repos/MATLAB/jponttuset-mcg/mcg-e72031d793abf8921e39a8ef3c20de2198c8b26f/pre-trained/src/aux/create_train_samples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2814055953761018, "lm_q1q2_score": 0.143999915810613}}
{"text": "function [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, varargin)\n\n% FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume\n% conductor model and the sensor array are ready for subsequent forward\n% leadfield computations. It takes care of some pre-computations that can\n% be done efficiently prior to the leadfield calculations.\n%\n% Use as\n%   [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, ...)\n% with input arguments\n%   headmodel = structure with volume conductor definition\n%   sens      = structure with gradiometer or electrode definition\n%\n% The headmodel structure represents a volume conductor model of the head,\n% its contents depend on the type of model. It is described in more detail\n% in FT_DATATYPE_HEADMODEL. The sens structure represents a electrode or\n% gradiometer array. It is described in more detail in FT_DATATYPE_SENS.\n%\n% Additional options should be specified in key-value pairs and can be\n%   'channel'  = cell-array with strings (default = 'all')\n%\n% The detailed behavior of this function depends on whether the input\n% consists of EEG or MEG and furthermoree depends on the type of volume\n% conductor model:\n% - in case of EEG single and concentric sphere models, the electrodes are\n%   projected onto the skin surface.\n% - in case of EEG boundary element models, the electrodes are projected on\n%   the surface and a blilinear interpoaltion matrix from vertices to\n%   electrodes is computed.\n% - in case of MEG and a localspheres model, a local sphere is determined\n%   for each coil in the gradiometer definition.\n%  - in case of MEG with a singleshell Nolte model, the volume conduction\n%    model is initialized\n% In any case channel selection and reordering will be done. The channel\n% order returned by this function corresponds to the order in the 'channel'\n% option, or if not specified, to the order in the input sensor array.\n%\n% See also FT_COMPUTE_LEADFIELD, FT_READ_HEADMODEL, FT_READ_SENS\n\n% Copyright (C) 2004-2015, 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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif iscell(headmodel) && iscell(sens)\n  % this represents combined EEG, ECoG and/or MEG\n  for i=1:numel(headmodel)\n    [headmodel{i}, sens{i}] = ft_prepare_vol_sens(headmodel{i}, sens{i}, varargin{:});\n  end\n  return\nend\n\n% get the optional input arguments\n% fileformat = ft_getopt(varargin, 'fileformat');\nchannel = ft_getopt(varargin, 'channel', sens.label);   % cell-array with channel labels, default is all\n\n% ensure that the sensor description is up-to-date (Aug 2011)\nsens = ft_datatype_sens(sens);\n\n% this is to support volumes saved in mat-files, particularly interpolated\nif ischar(headmodel)\n  vpath     = fileparts(headmodel);   % remember the path to the file\n  headmodel = ft_read_headmodel(headmodel); % replace the filename with the content of the file\nend\n\n% ensure that the volume conduction description is up-to-date (Jul 2012)\nheadmodel = ft_datatype_headmodel(headmodel);\n\n% determine whether the input contains EEG or MEG sensors\niseeg = ft_senstype(sens, 'eeg');\nismeg = ft_senstype(sens, 'meg');\n\n% determine the skin compartment\nif ~isfield(headmodel, 'skin_surface')\n  if isfield(headmodel, 'bnd')\n    headmodel.skin_surface   = find_outermost_boundary(headmodel.bnd);\n  elseif isfield(headmodel, 'r') && length(headmodel.r)<=4\n    [dum, headmodel.skin_surface] = max(headmodel.r);\n  end\nend\n\n% determine the inner_skull_surface compartment\nif ~isfield(headmodel, 'inner_skull_surface')\n  if isfield(headmodel, 'bnd')\n    headmodel.inner_skull_surface  = find_innermost_boundary(headmodel.bnd);\n  elseif isfield(headmodel, 'r') && length(headmodel.r)<=4\n    [dum, headmodel.inner_skull_surface] = min(headmodel.r);\n  end\nend\n\n% FT_HEADMODELTYPE to an empty struct won't work further down\nif isempty(headmodel)\n  headmodel = [];\nend\n\n% this makes them easier to recognise\nsens.type       = ft_senstype(sens);\nheadmodel.type  = ft_headmodeltype(headmodel);\n\nif isfield(headmodel, 'unit') && isfield(sens, 'unit') && ~strcmp(headmodel.unit, sens.unit)\n  ft_error('inconsistency in the units of the volume conductor and the sensor array');\nend\n\nif ismeg && iseeg\n  % this is something that could be implemented relatively easily\n  ft_error('simultaneous EEG and MEG not yet supported');\n\nelseif ~ismeg && ~iseeg\n  ft_error('the input does not look like EEG, nor like MEG');\n\nelseif ismeg\n\n  % always ensure that there is a linear transfer matrix for combining the coils into gradiometers\n  if ~isfield(sens, 'tra');\n    Nchans = length(sens.label);\n    Ncoils = size(sens.coilpos,1);\n    if Nchans~=Ncoils\n      ft_error('inconsistent number of channels and coils');\n    end\n    sens.tra = eye(Nchans, Ncoils);\n  end\n\n  if ~ft_headmodeltype(headmodel, 'localspheres')\n    % select the desired channels from the gradiometer array\n    [selchan, selsens] = match_str(channel, sens.label);\n    % only keep the desired channels, order them according to the users specification\n    try, sens.chantype = sens.chantype(selsens,:); end\n    try, sens.chanunit = sens.chanunit(selsens,:); end\n    try, sens.chanpos  = sens.chanpos (selsens,:); end\n    try, sens.chanori  = sens.chanori (selsens,:); end\n    sens.label    = sens.label(selsens);\n    sens.tra      = sens.tra(selsens,:);\n  else\n    % for the localspheres model it is done further down\n  end\n\n  % remove the coils that do not contribute to any channel output\n  selcoil      = any(sens.tra~=0,1);\n  sens.coilpos = sens.coilpos(selcoil,:);\n  sens.coilori = sens.coilori(selcoil,:);\n  sens.tra     = sens.tra(:,selcoil);\n\n  switch ft_headmodeltype(headmodel)\n    case {'infinite' 'infinite_monopole' 'infinite_currentdipole' 'infinite_magneticdipole'}\n      % nothing to do\n\n    case 'singlesphere'\n      % nothing to do\n\n    case 'concentricspheres'\n      % nothing to do\n\n    case 'neuromag'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % if the forward model is computed using the external Neuromag toolbox,\n      % we have to add a selection of the channels so that the channels\n      % in the forward model correspond with those in the data.\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      [selchan, selsens] = match_str(channel, sens.label);\n      headmodel.chansel = selsens;\n\n    case 'localspheres'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % If the volume conduction model consists of multiple spheres then we\n      % have to match the channels in the gradiometer array and the volume\n      % conduction model.\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      % the initial localspheres volume conductor has a local sphere per\n      % channel, whereas it should have a local sphere for each coil\n      if size(headmodel.r,1)==size(sens.coilpos,1) && ~isfield(headmodel, 'label')\n        % it appears that each coil already has a sphere, which suggests\n        % that the volume conductor already has been prepared to match the\n        % sensor array\n        return\n      elseif size(headmodel.r,1)==size(sens.coilpos,1) && isfield(headmodel, 'label')\n        if ~isequal(headmodel.label(:), sens.label(:))\n          % if only the order is different, it would be possible to reorder them\n          ft_error('the coils in the volume conduction model do not correspond to the sensor array');\n        else\n          % the coil-specific spheres in the volume conductor should not have a label\n          % because the label is already specified for the coils in the\n          % sensor array\n          headmodel = rmfield(headmodel, 'label');\n        end\n        return\n      end\n\n      % the CTF way of representing the headmodel is one-sphere-per-channel\n      % whereas the FieldTrip way of doing the forward computation is one-sphere-per-coil\n      Nchans   = size(sens.tra,1);\n      Ncoils   = size(sens.tra,2);\n      Nspheres = size(headmodel.label);\n\n      if isfield(headmodel, 'orig')\n        % these are present in a CTF *.hdm file\n        singlesphere.o(1,1) = headmodel.orig.MEG_Sphere.ORIGIN_X;\n        singlesphere.o(1,2) = headmodel.orig.MEG_Sphere.ORIGIN_Y;\n        singlesphere.o(1,3) = headmodel.orig.MEG_Sphere.ORIGIN_Z;\n        singlesphere.r      = headmodel.orig.MEG_Sphere.RADIUS;\n        % ensure consistent units\n        singlesphere = ft_convert_units(singlesphere, headmodel.unit);\n        % determine the channels that do not have a corresponding sphere\n        % and use the globally fitted single sphere for those\n        missing = setdiff(sens.label, headmodel.label);\n        if ~isempty(missing)\n          ft_warning('using the global fitted single sphere for %d channels that do not have a local sphere', length(missing));\n        end\n        for i=1:length(missing)\n          headmodel.label(end+1) = missing(i);\n          headmodel.r(end+1,:)   = singlesphere.r;\n          headmodel.o(end+1,:)   = singlesphere.o;\n        end\n      end\n\n      % make a new structure that only holds the local spheres, one per coil\n      localspheres = [];\n      localspheres.type = headmodel.type;\n      localspheres.unit = headmodel.unit;\n\n      % for each coil in the MEG helmet, determine the corresponding channel and from that the corresponding local sphere\n      for i=1:Ncoils\n        coilindex = find(sens.tra(:,i)~=0); % to which channel does this coil belong\n        if length(coilindex)>1\n          % this indicates that there are multiple channels to which this coil contributes,\n          % which happens if the sensor array represents a synthetic higher-order gradient.\n          [dum, coilindex] = max(abs(sens.tra(:,i)));\n        end\n\n        coillabel = sens.label{coilindex};               % what is the label of this channel\n        chanindex = find(strcmp(coillabel, headmodel.label));  % what is the index of this channel in the list of local spheres\n        localspheres.r(i,:) = headmodel.r(chanindex);\n        localspheres.o(i,:) = headmodel.o(chanindex,:);\n      end\n      headmodel = localspheres;\n\n      % finally do the selection of channels and coils\n      % order them according to the users specification\n      [selchan, selsens] = match_str(channel, sens.label);\n\n      % first only modify the linear combination of coils into channels\n      try, sens.chantype = sens.chantype(selsens,:); end\n      try, sens.chanunit = sens.chanunit(selsens,:); end\n      try, sens.chanpos  = sens.chanpos (selsens,:); end\n      try, sens.chanori  = sens.chanori (selsens,:); end\n      sens.label   = sens.label(selsens);\n      sens.tra     = sens.tra(selsens,:);\n      % subsequently remove the coils that do not contribute to any sensor output\n      selcoil      = find(sum(sens.tra,1)~=0);\n      sens.coilpos = sens.coilpos(selcoil,:);\n      sens.coilori = sens.coilori(selcoil,:);\n      sens.tra     = sens.tra(:,selcoil);\n      % make the same selection of coils in the localspheres model\n      headmodel.r = headmodel.r(selcoil);\n      headmodel.o = headmodel.o(selcoil,:);\n\n    case 'singleshell'\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % if the forward model is computed using the code from Guido Nolte, we\n      % have to initialize the volume model using the gradiometer coil\n      % locations\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      % compute the surface normals for each vertex point\n      if ~isfield(headmodel.bnd, 'nrm')\n        fprintf('computing surface normals\\n');\n        headmodel.bnd.nrm = normals(headmodel.bnd.pos, headmodel.bnd.tri);\n      end\n\n      % estimate center and radius\n      [center, radius] = fitsphere(headmodel.bnd.pos);\n\n      % order of spherical spherical harmonics, for 'real' realistic volume conductors order=10 is o.k\n      if isfield(headmodel, 'order')\n        order = headmodel.order;\n      else\n        order = 10;\n      end\n\n      % initialize the forward calculation (only if  coils are available)\n      if size(sens.coilpos,1)>0 && ~isfield(headmodel, 'forwpar')\n        s = ft_scalingfactor(headmodel.unit, 'cm');\n        headmodel.forwpar = meg_ini([s*headmodel.bnd.pos headmodel.bnd.nrm], s*center', order, [s*sens.coilpos sens.coilori]);\n        headmodel.forwpar.scale = s;\n      end\n\n    case  'openmeeg'\n        % don't do anything, h2em or h2mm generated later in ft_prepare_leadfield\n\n    case 'simbio'\n      ft_error('MEG not yet supported with simbio');\n\n    otherwise\n      ft_error('unsupported volume conductor model for MEG');\n  end\n\nelseif iseeg\n\n  % the electrodes are used, the channel positions are not relevant any more\n  % channel positinos need to be recomputed after projecting the electrodes on the skin\n  if isfield(sens, 'chanpos'); sens = rmfield(sens, 'chanpos'); end\n\n  % select the desired channels from the electrode array\n  % order them according to the users specification\n  [selchan, selsens] = match_str(channel, sens.label);\n  Nchans = length(sens.label);\n\n  sens.label     = sens.label(selsens);\n  try, sens.chantype  = sens.chantype(selsens); end\n  try, sens.chanunit  = sens.chanunit(selsens); end\n\n  if isfield(sens, 'tra')\n    % first only modify the linear combination of electrodes into channels\n    sens.tra     = sens.tra(selsens,:);\n    % subsequently remove the electrodes that do not contribute to any channel output\n    selelec      = any(sens.tra~=0,1);\n    sens.elecpos = sens.elecpos(selelec,:);\n    sens.tra     = sens.tra(:,selelec);\n  else\n    % the electrodes and channels are identical\n    sens.elecpos = sens.elecpos(selsens,:);\n  end\n\n  switch ft_headmodeltype(headmodel)\n    case {'infinite' 'infinite_monopole' 'infinite_currentdipole'}\n      % nothing to do\n\n    case {'halfspace', 'halfspace_monopole'}\n      % electrodes' all-to-all distances\n      numelec = size(sens.elecpos,1);\n      ref_el = sens.elecpos(1,:);\n      md = dist( (sens.elecpos-repmat(ref_el,[numelec 1]))' );\n      % take the min distance as reference\n      md = min(md(1,2:end));\n      pos = sens.elecpos;\n      % scan the electrodes and reposition the ones which are in the\n      % wrong halfspace (projected on the plane)... if not too far away!\n      for i=1:size(pos,1)\n        P = pos(i,:);\n        is_in_empty = acos(dot(headmodel.ori,(P-headmodel.pos)./norm(P-headmodel.pos))) < pi/2;\n        if is_in_empty\n          dPplane = abs(dot(headmodel.ori, headmodel.pos-P, 2));\n          if dPplane>md\n            ft_error('Some electrodes are too distant from the plane: consider repositioning them')\n          else\n            % project point on plane\n            Ppr = pointproj(P,[headmodel.pos headmodel.ori]);\n            pos(i,:) = Ppr;\n          end\n        end\n      end\n      sens.elecpos = pos;\n\n    case {'slab_monopole'}\n      % electrodes' all-to-all distances\n      numelc  = size(sens.elecpos,1);\n      ref_elc = sens.elecpos(1,:);\n      md  = dist( (sens.elecpos-repmat(ref_elc,[numelc 1]))' );\n      % choose min distance between electrodes\n      md  = min(md(1,2:end));\n      pos = sens.elecpos;\n      % looks for contacts outside the strip which are not too far away\n      % and projects them on the nearest plane\n      for i=1:size(pos,1)\n        P = pos(i,:);\n        instrip1 = acos(dot(headmodel.ori1,(P-headmodel.pos1)./norm(P-headmodel.pos1))) > pi/2;\n        instrip2 = acos(dot(headmodel.ori2,(P-headmodel.pos2)./norm(P-headmodel.pos2))) > pi/2;\n        is_in_empty = ~(instrip1&instrip2);\n        if is_in_empty\n          dPplane1 = abs(dot(headmodel.ori1, headmodel.pos1-P, 2));\n          dPplane2 = abs(dot(headmodel.ori2, headmodel.pos2-P, 2));\n          if dPplane1>md && dPplane2>md\n            ft_error('Some electrodes are too distant from the planes: consider repositioning them')\n          elseif dPplane2>dPplane1\n            % project point on nearest plane\n            Ppr = pointproj(P,[headmodel.pos1 headmodel.ori1]);\n            pos(i,:) = Ppr;\n          else\n            % project point on nearest plane\n            Ppr = pointproj(P,[headmodel.pos2 headmodel.ori2]);\n            pos(i,:) = Ppr;\n          end\n        end\n      end\n      sens.elecpos = pos;\n\n    case {'singlesphere', 'concentricspheres'}\n      % ensure that the electrodes ly on the skin surface\n      radius = max(headmodel.r);\n      pos    = sens.elecpos;\n      if isfield(headmodel, 'o')\n        % shift the the centre of the sphere to the origin\n        pos(:,1) = pos(:,1) - headmodel.o(1);\n        pos(:,2) = pos(:,2) - headmodel.o(2);\n        pos(:,3) = pos(:,3) - headmodel.o(3);\n      end\n      distance = sqrt(sum(pos.^2,2)); % to the center of the sphere\n      if any((abs(distance-radius)/radius)>0.005)\n        ft_warning('electrodes do not lie on skin surface -> using radial projection')\n      end\n      pos = pos * radius ./ [distance distance distance];\n      if isfield(headmodel, 'o')\n        % shift the center back to the original location\n        pos(:,1) = pos(:,1) + headmodel.o(1);\n        pos(:,2) = pos(:,2) + headmodel.o(2);\n        pos(:,3) = pos(:,3) + headmodel.o(3);\n      end\n      sens.elecpos = pos;\n\n    case {'bem', 'dipoli', 'asa', 'bemcp'}\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n      % do postprocessing of volume and electrodes in case of BEM model\n      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n      % project the electrodes on the skin and determine the bilinear interpolation matrix\n      if ~isfield(headmodel, 'tra') && (isfield(headmodel, 'mat') && ~isempty(headmodel.mat))\n        % determine boundary corresponding with skin and inner_skull_surface\n        if ~isfield(headmodel, 'skin_surface')\n          headmodel.skin_surface = find_outermost_boundary(headmodel.bnd);\n          fprintf('determining skin compartment (%d)\\n', headmodel.skin_surface);\n        end\n        if ~isfield(headmodel, 'source')\n          headmodel.source = find_innermost_boundary(headmodel.bnd);\n          fprintf('determining source compartment (%d)\\n', headmodel.source);\n        end\n        if size(headmodel.mat,1)~=size(headmodel.mat,2) && size(headmodel.mat,1)==length(sens.elecpos)\n          fprintf('electrode transfer and system matrix were already combined\\n');\n        else\n          fprintf('projecting electrodes on skin surface\\n');\n          % compute linear interpolation from triangle vertices towards electrodes\n          [el, prj] = project_elec(sens.elecpos, headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri);\n          tra       = transfer_elec(headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri, el);\n\n          % replace the original electrode positions by the projected positions\n          sens.elecpos = prj;\n\n          if size(headmodel.mat,1)==size(headmodel.bnd(headmodel.skin_surface).pos,1)\n            % construct the transfer from only the skin vertices towards electrodes\n            interp = tra;\n          else\n            % construct the transfer from all vertices (also inner_skull_surface/outer_skull_surface) towards electrodes\n            interp = [];\n            for i=1:length(headmodel.bnd)\n              if i==headmodel.skin_surface\n                interp = [interp, tra];\n              else\n                interp = [interp, zeros(size(el,1), size(headmodel.bnd(i).pos,1))];\n              end\n            end\n          end\n\n          % incorporate the linear interpolation matrix and the system matrix into one matrix\n          % this speeds up the subsequent repeated leadfield computations\n          fprintf('combining electrode transfer and system matrix\\n');\n\n          % convert to sparse matrix to speed up the subsequent multiplication\n          interp  = sparse(interp);\n          headmodel.mat = interp * headmodel.mat;\n          % ensure that the model potential will be average referenced\n          avg = mean(headmodel.mat, 1);\n          headmodel.mat = headmodel.mat - repmat(avg, size(headmodel.mat,1), 1);\n        end\n      end\n    case  'openmeeg'\n        % don't do anything, h2em or h2mm generated later in ft_prepare_leadfield\n\n    case 'fns'\n      if isfield(headmodel,'bnd')\n        [el, prj] = project_elec(sens.elecpos, headmodel.bnd.pos, headmodel.bnd.tri);\n        sens.tra = transfer_elec(headmodel.bnd.pos, headmodel.bnd.tri, el);\n        % replace the original electrode positions by the projected positions\n        sens.elecpos = prj;\n      end\n\n    case 'simbio'\n      % check that the external toolbox is present\n      ft_hastoolbox('simbio', 1);\n\n      % extract the outer surface\n      bnd = mesh2edge(headmodel);\n      for j=1:length(sens.label)\n        d = bsxfun(@minus, bnd.pos, sens.elecpos(j,:));\n        [d, i] = min(sum(d.^2, 2));\n        % replace the position of each electrode by the closest vertex\n        sens.elecpos(j,:) = bnd.pos(i,:);\n      end\n\n      if (isfield(headmodel,'transfer') && isfield(headmodel,'elec'))\n          if all(ismember(sens.label,headmodel.elec.label))\n              [sensmember, senslocation] = ismember(sens.label,headmodel.elec.label);\n              if (norm(sens.elecpos - headmodel.elec.elecpos(senslocation,:))<1e-8)\n                  headmodel.transfer = headmodel.transfer(senslocation,:);\n                  headmodel.elec = sens;\n              else\n                  ft_error('Electrode positions do not fit to the given transfer matrix!');\n              end\n          else\n              ft_error('Transfer matrix does not fit the given set of electrodes!');\n          end\n      else\n          headmodel.transfer = sb_transfer(headmodel,sens);\n          headmodel.elec = sens;\n      end\n\n    case 'interpolate'\n      % this is to allow moving leadfield files\n      if ~exist(headmodel.filename{1}, 'file')\n        for i = 1:length(headmodel.filename)\n          [p, f, x] = fileparts(headmodel.filename{i});\n          headmodel.filename{i} = fullfile(vpath, [f x]);\n        end\n      end\n\n      matchlab = isequal(sens.label, headmodel.sens.label);\n      matchpos = isequal(sens.elecpos, headmodel.sens.elecpos);\n      matchtra = (~isfield(sens, 'tra') && ~isfield(headmodel.sens, 'tra')) || isequal(sens.tra, headmodel.sens.tra);\n\n      if matchlab && matchpos && matchtra\n        % the input sensor array matches precisely with the forward model\n        % no further interpolation is needed\n      else\n        % interpolate the channels in the forward model to the desired channels\n        filename = tempname;\n        headmodel  = ft_headmodel_interpolate(filename, sens, headmodel);\n        % update the sensor array with the one from the volume conductor\n        sens = headmodel.sens;\n      end % if recomputing interpolation\n\n      % for the leadfield computations the @nifti object is used to map the image data into memory\n      ft_hastoolbox('spm8up', 1);\n      for i=1:length(headmodel.sens.label)\n        % map each of the leadfield files into memory\n        headmodel.chan{i} = nifti(headmodel.filename{i});\n      end\n\n    otherwise\n      ft_error('unsupported volume conductor model for EEG');\n  end\n\n  % FIXME this needs careful thought to ensure that the average referencing which is now done here and there, and that the linear interpolation in case of BEM are all dealt with consistently\n  % % always ensure that there is a linear transfer matrix for\n  % % rereferencing the EEG potential\n  % if ~isfield(sens, 'tra');\n  %   sens.tra = eye(length(sens.label));\n  % end\n\n  % update the channel positions as the electrodes were projected to the skin surface\n  [pos, ori, lab] = channelposition(sens);\n  [selsens, selpos] = match_str(sens.label, lab);\n  sens.chanpos = nan(length(sens.label),3);\n  sens.chanpos(selsens,:) = pos(selpos,:);\n\nend % if iseeg or ismeg\n\nif isfield(sens, 'tra')\n  if issparse(sens.tra) && size(sens.tra, 1)==1\n    % this multiplication would result in a sparse leadfield, which is not what we want\n    % the effect can be demonstrated as sparse(1)*rand(1,10), see also http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1169#c7\n    sens.tra = full(sens.tra);\n  elseif ~issparse(sens.tra) && size(sens.tra, 1)>1\n    % the multiplication of the \"sensor\" leadfield (electrode or coil) with the tra matrix to get the \"channel\" leadfield\n    % is faster for most cases if the pre-multiplying weighting matrix is made sparse\n    sens.tra = sparse(sens.tra);\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Ppr = pointproj(P,plane)\n% projects a point on a plane\n% plane(1:3) is a point on the plane\n% plane(4:6) is the ori of the plane\nPpr  = [];\nori  = plane(4:6);\nline = [P ori];\n% get indices of line and plane which are parallel\npar = abs(dot(plane(4:6), line(:,4:6), 2))<1e-14;\n% difference between origins of plane and line\ndp = plane(1:3) - line(:, 1:3);\n% Divide only for non parallel vectors (DL)\nt = dot(ori(~par,:), dp(~par,:), 2)./dot(ori(~par,:), line(~par,4:6), 2);\n% compute coord of intersection point\nPpr(~par, :) = line(~par,1:3) + repmat(t,1,3).*line(~par,4:6);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This function serves as a replacement for the dist function in the Neural\n% Networks toolbox.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [d] = dist(x)\nn = size(x,2);\nd = zeros(n,n);\nfor i=1:n\n  for j=(i+1):n\n    d(i,j) = sqrt(sum((x(:,i)-x(:,j)).^2));\n    d(j,i) = d(i,j);\n  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/external/fieldtrip/forward/ft_prepare_vol_sens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.14339960450921746}}
{"text": "function outFiles = out_demultiplex(DataFile, ChannelFile, OutputDir, UseSsp, ram, parallel)\n% OUT_DEMULTIPLEX: Load a raw data file and creates separate electrode files.\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: Konstantinos Nasiotis, 2018-2022\n%          Martin Cousineau, 2018\n%          Francois Tadel, 2022\n\n% If the output directory doesn't exist: create it\nif ~exist(OutputDir, 'dir')\n    mkdir(OutputDir);\nend\n\n% Load channel file\nChannelMat = in_bst_channel(ChannelFile);\nnumChannels = length(ChannelMat.Channel);\n% Channel names: Remove any special characters\ncleanNames = str_remove_spec_chars({ChannelMat.Channel.Name});\n\n% Assemble output filenames\noutFiles = cellfun(@(c)bst_fullfile(OutputDir, ['raw_elec_', c]), cleanNames, 'UniformOutput', 0);\n% If all files already exist: nothing else to do in this function\nisFileOk = cellfun(@(c)exist([c, '.mat'], 'file'), outFiles);\nif all(isFileOk)\n    % Add the .mat extension to the file names\n    disp(['BST> Channels already demultiplexed in: ' OutputDir]);\n    outFiles = cellfun(@(x) [x '.mat'], outFiles, 'UniformOutput', 0);\n    return;\n% If some files already exist: delete all intermediate existing file, before generating them again\nelseif any(isFileOk)\n    delete(outFiles{isFileOk});\nend\n\n% Load input data file\nDataMat = in_bst_data(DataFile, 'F');\nsFile = DataMat.F;\nsr = sFile.prop.sfreq;\n\n% Apply SSP/ICA when reading from data files\nImportOptions = db_template('ImportOptions');\nImportOptions.UseCtfComp = 0;\nImportOptions.UseSsp     = UseSsp;\n% Special case for supported acquisition systems: Save temporary files\n% using single precision instead of double to save disk space\nif ismember(sFile.format, {'EEG-AXION', 'EEG-BLACKROCK', 'EEG-INTAN', 'EEG-PLEXON'})\n    precision = 'single';\n    nBytes = 4;\nelse\n    precision = 'double';\n    nBytes = 8;\nend\nImportOptions.Precision = precision;\n\n% Separate the file to max length based on RAM\nmax_samples = ram / nBytes / numChannels;\ntotal_samples = round((sFile.prop.times(2) - sFile.prop.times(1)) .* sFile.prop.sfreq); % (Blackrock/Ripple complained). Removed +1\nnum_segments = ceil(total_samples / max_samples);\nnum_samples_per_segment = ceil(total_samples / num_segments);\n\n% Loop on segments\nfor iSegment = 1:num_segments\n    sampleBounds(1) = (iSegment - 1) * num_samples_per_segment + round(sFile.prop.times(1)* sFile.prop.sfreq);\n    if iSegment < num_segments\n        sampleBounds(2) = sampleBounds(1) + num_samples_per_segment - 1;\n    else\n        sampleBounds(2) = total_samples + round(sFile.prop.times(1)* sFile.prop.sfreq);\n    end\n    % Read recordings\n    F = in_fread(sFile, ChannelMat, [], sampleBounds, [], ImportOptions);\n    % Append segment to individual channel file\n    if parallel\n        bst_progress('start', 'Spike-sorting', 'Demultiplexing raw file...');\n        parfor iChannel = 1:numChannels\n            electrode_data = F(iChannel,:);\n            fid = fopen([outFiles{iChannel} '.bin'], 'a');\n            fwrite(fid, electrode_data, precision);\n            fclose(fid);\n        end\n    else\n        bst_progress('start', 'Spike-sorting', 'Demultiplexing raw file...', 0, num_segments * numChannels);\n        for iChannel = 1:numChannels\n            electrode_data = F(iChannel,:);\n            fid = fopen([outFiles{iChannel} '.bin'], 'a');\n            fwrite(fid, electrode_data, precision);\n            fclose(fid);\n            bst_progress('inc', 1);\n        end\n    end\nend\n\n% Convert binary files per channel to Matlab files\nif parallel\n    bst_progress('start', 'Spike-sorting', 'Converting demultiplexed files...');\n    parfor iChannel = 1:numChannels\n        convert2mat(outFiles{iChannel}, sr, precision);\n    end\nelse\n    bst_progress('start', 'Spike-sorting', 'Converting demultiplexed files...', 0, numChannels);\n    for iChannel = 1:numChannels\n        convert2mat(outFiles{iChannel}, sr, precision);\n        bst_progress('inc', 1);\n    end\nend\n\n% Add the .mat extension to the file names\noutFiles = cellfun(@(x) [x '.mat'], outFiles, 'UniformOutput', 0);\n\nend\n\n\n%% ===== CONVERT BIN TO MAT =====\nfunction convert2mat(chanFile, sr, precision)\n    % Read .bin file\n    fid = fopen([chanFile '.bin'], 'rb');\n    data = fread(fid, precision);\n    fclose(fid);\n    % Save .mat file\n    save([chanFile '.mat'], 'data', 'sr');\n    % Delete .bin file\n    delete([chanFile '.bin']);\nend\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/out_demultiplex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.14321158967498882}}
{"text": "% Demo for aggregate channel features object detector on Inria dataset.\n%\n% (1) Download data and helper routines from Caltech Peds Website\n%  www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/\n%  (1a) Download INRIA files: set00.tar, set01.tar, and annotations.zip\n%  (1b) Copy above three files to dataDir/ and untar/unzip contents\n%  (1c) Download evaluation code (routines necessary for extracting images)\n% (2) Set dataDir/ variable below to point to location of INRIA data.\n% (3) Launch \"matlabpool open\" for faster training if available.\n% (4) Run demo script and enjoy your newly minted fast ped detector!\n%\n% Note: pre-trained model files are provided (delete to re-train).\n% Re-training may give slightly variable results on different machines.\n%\n% Piotr's Image&Video Toolbox      Version 3.22\n% Copyright 2013 Piotr Dollar & Ron Appel.  [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\n%% extract training and testing images and ground truth\ndataDir = 'D:\\code\\research\\detectorAcf\\data\\Inria\\';\nfor s=1:2\n  if(s==1), set='00'; type='train'; else set='01'; type='test'; end\n  if(exist([dataDir type '/posGt'],'dir')), continue; end\n  seqIo([dataDir 'set' set '/V000'],'toImgs',[dataDir type '/pos']);\n  seqIo([dataDir 'set' set '/V001'],'toImgs',[dataDir type '/neg']);\n  V=vbb('vbbLoad',[dataDir 'annotations/set' set '/V000']);\n  vbb('vbbToFiles',V,[dataDir type '/posGt']);\nend\n\n%% set up opts for training detector (see acfTrain)\nopts=acfTrain(); opts.modelDs=[100 41]; opts.modelDsPad=[128 64];\nopts.posGtDir=[dataDir 'train/posGt']; opts.nWeak=[32 128 512 2048];\nopts.posImgDir=[dataDir 'train/pos']; opts.pJitter=struct('flip',1);\nopts.negImgDir=[dataDir 'train/neg']; opts.pBoost.pTree.fracFtrs=1/16;\nopts.pLoad={'squarify',{3,.41}}; opts.name='models/AcfInria';\n\n%% train detector (see acfTrain)\ndetector = acfTrain( opts );\n\n%% modify detector (see acfModify)\ndetector = acfModify(detector,'cascThr',-1,'cascCal',0);\n\n%% run detector on a sample image (see acfDetect)\nimgNms=bbGt('getFiles',{[dataDir 'test/pos']});\nI=imread(imgNms{1}); tic, bbs=acfDetect(I,detector); toc\nfigure(1); im(I); bbApply('draw',bbs); pause(.1);\n\n%% test detector and plot roc (see acfTest)\n[miss,~,gt,dt]=acfTest('name',opts.name,'imgDir',[dataDir 'test/pos'],...\n  'gtDir',[dataDir 'test/posGt'],'pLoad',opts.pLoad,'show',2);\n\n%% optional timing test for detector (should be ~30 fps)\nif( 0 )\n  detector1=acfModify(detector,'pad',[0 0]); n=60; Is=cell(1,n);\n  for i=1:n, Is{i}=imResample(imread(imgNms{i}),[480 640]); end\n  tic, for i=1:n, acfDetect(Is{i},detector1); end;\n  fprintf('Detector runs at %.2f fps on 640x480 images.\\n',n/toc);\nend\n\n%% optionally show top false positives ('type' can be 'fp','fn','tp','dt')\nif( 0 ), bbGt('cropRes',gt,dt,imgNms,'type','fn','n',50,...\n    'show',3,'dims',opts.modelDs([2 1])); end\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/detector/acfDemoInria.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2689414330889797, "lm_q1q2_score": 0.1428642101454369}}
{"text": "target_folder = 'aligned_images';\n\npdollar_toolbox_path='D:/face project/pdollar-toolbox';\naddpath(genpath(pdollar_toolbox_path));\n\nMTCNN_path = 'D:\\face project\\MTCNN_face_detection_alignment\\code\\codes\\MTCNNv2';\ncaffe_model_path=[MTCNN_path , '/model'];\naddpath(genpath(MTCNN_path));\n\ncoord5points = [30.2946, 65.5318, 48.0252, 33.5493, 62.7299; ...\n                51.6963, 51.5014, 71.7366, 92.3655, 92.2041];\nimgSize = [112, 96];\n            \n%caffe.set_mode_cpu();\ngpu_id=0;\ncaffe.set_mode_gpu();\t\ncaffe.set_device(gpu_id);\ncaffe.reset_all();\n\n%three steps's threshold\nthreshold=[0.6 0.7 0.7]\n\nminsize = 100;\n\n%scale factor\nfactor=0.709;\n\n%load caffe models\nprototxt_dir =strcat(caffe_model_path,'/det1.prototxt');\nmodel_dir = strcat(caffe_model_path,'/det1.caffemodel');\nPNet=caffe.Net(prototxt_dir,model_dir,'test');\nprototxt_dir = strcat(caffe_model_path,'/det2.prototxt');\nmodel_dir = strcat(caffe_model_path,'/det2.caffemodel');\nRNet=caffe.Net(prototxt_dir,model_dir,'test');\t\nprototxt_dir = strcat(caffe_model_path,'/det3.prototxt');\nmodel_dir = strcat(caffe_model_path,'/det3.caffemodel');\nONet=caffe.Net(prototxt_dir,model_dir,'test');\nprototxt_dir =  strcat(caffe_model_path,'/det4.prototxt');\nmodel_dir =  strcat(caffe_model_path,'/det4.caffemodel');\nLNet=caffe.Net(prototxt_dir,model_dir,'test');\nfaces=cell(0);\t\n\nidentity_list = dir('./Images');\nidentity_list = identity_list(3:end);\n\nfor i=1:length(identity_list)\n    subset_list = dir(fullfile('./Images',identity_list(i).name));\n    subset_list = subset_list(3:end);\n    for j=1:length(subset_list)\n        image_list = dir(fullfile('./Images',identity_list(i).name, subset_list(j).name));\n        image_list = image_list(3:end);\n        disp([fullfile('./Images',identity_list(i).name, subset_list(j).name) ' ' num2str(length(image_list)) ' files']);\n        for k=1:length(image_list)\n            filename = fullfile('./Images',identity_list(i).name, subset_list(j).name, image_list(k).name);\n            [~, ~, c] = fileparts(filename);\n            if strcmp(c,'.png')==0\n                continue;\n            end;\n            img = imread(filename);\n            if size(img,1) == 112 && size(img,2) == 96\n                continue;\n            end;\n            [boundingboxes points]=detect_face(img,minsize,PNet,RNet,ONet,LNet,threshold,false,factor);\n            if isempty(boundingboxes)\n                continue;\n            end;\n            default_face = 1;\n            if size(boundingboxes,1) > 1\n                for bb=2:size(boundingboxes,1)\n                    if abs((boundingboxes(bb,1) + boundingboxes(bb,3))/2 - size(img,2) / 2) + abs((boundingboxes(bb,2) + boundingboxes(bb,4))/2 - size(img,1) / 2) < ...\n                            abs((boundingboxes(default_face,1) + boundingboxes(default_face,3))/2 - size(img,2) / 2) + abs((boundingboxes(default_face,2) + boundingboxes(default_face,4))/2 - size(img,1) / 2)\n                        default_face = bb;\n                    end;\n                end;\n            end;\n            facial5points = double(reshape(points(:,default_face),[5 2])');\n            Tfm =  cp2tform(facial5points', coord5points', 'similarity');\n            cropImg = imtransform(img, Tfm, 'XData', [1 imgSize(2)],...\n                                          'YData', [1 imgSize(1)], 'Size', imgSize);\n            imwrite(cropImg, filename);\n            %show detection result\n        % \tnumbox=size(boundingboxes,1);\n        %     figure(1);\n        % \timshow(img)\n        % \thold on; \n        % \tfor j=1:numbox\n        % \t\tplot(points(1:5,j),points(6:10,j),'g.','MarkerSize',10);\n        % \t\tr=rectangle('Position',[boundingboxes(j,1:2) boundingboxes(j,3:4)-boundingboxes(j,1:2)],'Edgecolor','g','LineWidth',3);\n        %     end\n        %     hold off;\n        %     figure(2);\n        %     imshow(cropImg);\n        % \tpause\n\n        end;\n    end;\nend;\n\n", "meta": {"author": "happynear", "repo": "FaceVerification", "sha": "c8c2b4d805abf7240d9d39d7b57151e04958f6bf", "save_path": "github-repos/MATLAB/happynear-FaceVerification", "path": "github-repos/MATLAB/happynear-FaceVerification/FaceVerification-c8c2b4d805abf7240d9d39d7b57151e04958f6bf/dataset/Pain/create_database.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.14238862477198627}}
{"text": "clear; clc;\nload mariodata;\n\nglobal H;\nglobal A;\nglobal mario;\nglobal dxnkey;\nglobal dxnpressed;\nglobal shiftpressed;\nglobal spacepressed;\nglobal spacetime;\ndxnpressed=0;\nshiftpressed=0;\nspacepressed=0;\ndxnkey='';\n\n\ntimeout\t= 30;\t% duration of sim (sec)\n% rfrsh\t= 1/60;\t% NTSC refresh rate (sec)\nrfrsh\t= 1/10;\t% refresh rate that works for now (want better rate)\nscale\t= 1;\t% \n\n\n%SETUP FIGURE:\nfigure(1); clf; \nhold on;\ngnd=patch([0 0 10000 10000 0],[-20 0 0 -20 -20],7);\nset(gca,'YTick',[],'XTick',[],'Color',[0.3 0.6 0.94]);\nplot3([0 1000],[0 0],[-1 -1],'k','LineWidth',2);\naxis([0 400 -20 200]);\nset(gcf,'keypressfcn',@keypress,'keyreleasefcn',@keyrelease,'WindowButtonUpFcn','');\naxis equal;\n\n%INITIALIZE SPRITE PATCHES:\nmaxdims = [32 17]; %sprite dimensions\ncolormap(clrs);\nfor i=1:maxdims(1)\t%rows\n\tfor j=1:maxdims(2)\t%cols\n\t\tH(i,j)=patch([-1 -1 0 0 -1]+j,[-1 0 0 -1 -1]+i,0,'FaceAlpha',0);\n\tend;\nend;\nshading flat;\nttl = title(sprintf('TIME\\n%03.0f',max(timeout,0)),'FontWeight','bold','Color',[1 1 1],'FontSize',14,'FontName','Monotxt','HorizontalAlignment','right','Position', [390,150,1]);\n\n\n%INITIAL STATE:\n%states:\t1:small, 2:big, 3:firepower\n%actions:\t1:stand, 2:run, 3:jump, 4:duck, 5:skid, 6:climb, 7:switm, 8:shoot, 9: die\n%dxns:\t\t1:right, 2:left\nstate\t= 3;\t\t%current character state\ndxn\t\t= 1;\t\t%current character direction\naction\t= 1;\t\t%current character action\niter\t= 1;\t\t%frame within current action\nloc\t\t= [0 0];\t%initial position\nspd\t\t= [0 0];\t%current x and y speed\nspdlim\t= [8 18];\t%magnitude of max speed in x and y\nacc\t\t= [0 0];\t%current x and y acceleration\nupdatesprite(state,dxn,action,iter,[0 0])\n\n%REMINDER:\n%states:\t1:small\t2:big  3:firepower\n%dxns:\t\t1:right 2:left\n%actions:\t1:stand 2:walk 3:jump 4:duck 5:skid 6:climb 7:swim 8:shoot 9:die\n\n\n%MAIN LOOP:\ntic;\ntnext=0;\nt=toc;\nwhile toc<timeout,\n\t%DIRECTION COMMANDED:\n\tif dxnpressed,\t\t\t\t%accelerate\n\t\tif dxnkey(1)=='d'\t%user pressed down (duck)\n\t\t\taction=4;\n\t\t\tif spd(1)==0\t%stay at rest\n\t\t\t\tacc(1)=0;\n\t\t\telse\n\t\t\t\tacc(1) = -sign(spd(1))*ceil(abs(spd(1)/2)); %decellerate\n\t\t\tend;\n\t\t\t\n\t\telseif dxnkey(1)=='r'\t\t%accelerate right\n\t\t\tacc(1) = 2*(spd(1)<spdlim(1));\n\t\t\tif spd(1)<0\t\t\t%skidding turn left to right\n\t\t\t\taction\t= 5;\n\t\t\t\tdxn\t\t= 2;\n\t\t\telse\t\t\t\t%running right\n\t\t\t\taction\t= 2;\n\t\t\t\tdxn\t\t= 1;\n\t\t\tend;\n\t\t\t\n\t\telseif dxnkey(1)=='l'\t%accelerate left\n\t\t\tacc(1) = -2*(spd(1)>-spdlim(1));\n\t\t\tif spd(1)>0\t\t\t%skidding turn right to left\n\t\t\t\taction\t= 5;\n\t\t\t\tdxn\t\t= 1;\n\t\t\telse\t\t\t\t%running left\n\t\t\t\taction\t= 2;\n\t\t\t\tdxn\t\t= 2;\n\t\t\tend;\n\t\tend;\t\n\t%NO ARROWS PRESSED: slow to rest\n\telse\n\t\tif spd(1)==0\t%stay at rest\n\t\t\tacc(1)=0;\n\t\t\taction=1;\n\t\telse\n\t\t\tacc(1) = -sign(spd(1))*ceil(abs(spd(1)/2)); %decellerate\n\t\tend;\n\tend;\n\t\n\t%SHOOTING:\n\tif state==3 && shiftpressed,\n\t\taction=8;\n\tend;\n\t\n\t%Jumping:\n\tif spacepressed && loc(2)==0,\n\t\tspacepressed = 0;\n\t\tacc(2)=-3;\n\t\tspd(2)=18;\n\tend;\n\t\n\t%UPDATE POSITION:\n\tspd = round(spd+acc);\n\tloc = loc+spd;\n\t\n\t%end jump?\n\tif loc(2)<=0 && spd(2)<0\t%end jump\n\t\tloc(2)=0;\n\t\tspd(2)=0;\n\t\tacc(2)=0;\n\t\tif dxnkey(1)=='l' || dxnkey(1)=='r' %end running\n\t\t\taction=2;\n\t\telseif dxnkey(1)=='d'\t\t\t\t%end ducking\n\t\t\taction=4;\n\t\tend;\n\telseif loc(2)>0\n\t\tif action==4 || action==8 %jumping stance unless ducking or shooting\n\t\telse\n\t\t\taction=3;\t%airborne stance\n\t\tend;\n\tend;\n\t\t\n\t\n\t%INCREMENT FRAME OF CURRENT ACTION:\n\tif action==2,\n\t\tif iter==1, iter=3;\n\t\telse iter=iter-1;\n\t\tend;\n\telseif sum(action==[1 3 4 5 7 9])\n\t\titer=1;\n\tend;\n\t\n\t%UPDATE FIGURE:\n\tupdatesprite(state,dxn,action,iter,loc)\n\taxis([0 400 -20 200])\n\tset(ttl,'String',sprintf('TIME\\n%03.0f',max(timeout-toc,0)));\n\tdrawnow;\n\n\n\t%CONTROL REFRESH RATE:\n% \ttnext\t= tnext+rfrsh;\n% \tt=toc;\n% \ttxtra\t= tnext-t;\n% \tif txtra>0,\n% \t\tpause(txtra);\n% \t\tdisp('paused');\n% \telse\n% \t\tdisp([t,tnext,txtra])\n% \tend;\nend;\n\n\n%DEATH\nylims = get(gca,'YLim');\nspd=[0 12];\nacc=[0 -3];\nupdatesprite(1,1,9,1,loc);\npause(1);\nwhile loc(2)>ylims(1)-30\n\tspd(2)=max(spd(2)+acc(2),-spdlim(2)); %terminal velocity\n\tloc=loc+spd;\n\tupdatesprite(1,1,9,1,loc);\n\tdrawnow;\nend;\n\nclf;\nplot(0,0); \nset(gca,'Color','k','XTick',[],'YTick',[],'ButtonDownFcn','test1');\ntext(140,100,'click to continue','Color','w','FontSize',18);\naxis([0 400 -20 200],'equal');\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/25568-mario-sim-v0-1/mario_v0/test1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14238861864653493}}
{"text": "%                                      [zhi,zlo] = quadadd(xhi,xlo,y)\n% QUADADD   Compute (zhi+zlo) = (xhi+xlo) + y.\n%   x an z are in double-double format (quad precision)\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi\n\nfunction [zhi,zlo] = quadadd(xhi,xlo,y) %#ok\n%\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n%\n\ndisp('The SeDuMi binaries are not installed.')\ndisp('In Matlab, launch \"install_sedumi\" in the folder you put the SeDuMi files.')\ndisp('For more information see the file Install.txt.')\nerror(' ')", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sedumi/quadadd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.14238318236382586}}
{"text": "function producetSNEPlots(propertiesFolder,infoFilePath,reconVersion,customFeatures)\n% This function plots reaction presence and uptake and secretion potential\n% by taxon with t-SNE.\n%\n% USAGE\n%   producetSNEPlots(propertiesFolder,infoFilePath,reconVersion)\n%\n% INPUTS\n% propertiesFolder      Folder where the reaction presences and uptake and\n%                       secretion potential to be analyzed are stored\n%                       (default: current folder)\n% infoFilePath          Path to spreadsheet with taxonomical information of\n%                       the refined strains\n% reconVersion          Name assigned to the reconstruction resource\n% OPTIONAL INPUT\n% customFeatures        Features other than taxonomy to cluster microbes\n%                       by. Need to be a table header in the file with\n%                       information on reconstructions.\n%\n%   - AUTHOR\n%   Almut Heinken, 06/2020\n\n% euclidean should work for most\ndistance='euclidean';\nalg='barneshut';\n\ncurrentDir=pwd;\ncd(propertiesFolder)\nmkdir('tSNE_Plots')\n\nSummary=struct;\n\ntol=0.0000001;\n\n% read the file with organism information\nif contains(infoFilePath,'.xlsx')\n    [~,infoFile,~]=xlsread(infoFilePath);\nelse\n    gettab=tdfread(infoFilePath);\n    getcols=fieldnames(gettab);\n    infoFile={};\n    for j=1:length(getcols)\n        infoFile{1,j}=getcols{j};\n        if isnumeric(gettab.(getcols{j}))\n            infoFile(2:size(gettab.(getcols{j}),1)+1,j)=cellstr(num2str(gettab.(getcols{j})));\n        else\n            infoFile(2:size(gettab.(getcols{j}),1)+1,j)=cellstr(gettab.(getcols{j}));\n        end\n    end\nend\n\n% define files to analyze\nanalyzedFiles={\n    'Reaction presence' ['ReactionMetabolitePresence' filesep 'ReactionPresence_' reconVersion]\n    'Metabolite presence' ['ReactionMetabolitePresence' filesep 'MetabolitePresence_' reconVersion]\n    'Uptake and secretion potential' ['ComputedFluxes' filesep 'UptakeSecretion_' reconVersion]\n    'Internal metabolite production' ['ComputedFluxes' filesep 'InternalProduction_' reconVersion]\n    };\n\nfor k=1:size(analyzedFiles,1)\n    if isfile([propertiesFolder filesep analyzedFiles{k,2} '.txt'])\n        DataToAnalyze = readInputTableForPipeline([propertiesFolder filesep analyzedFiles{k,2} '.txt']);\n        DataToAnalyze=DataToAnalyze';\n        \n        [C,I]=setdiff(DataToAnalyze(1,:),infoFile(:,1),'stable');\n        DataToAnalyze(:,I(2:end))=[];\n        \n        % can only be performed if there are enough strains with taxonomical information\n        if size(DataToAnalyze,2) >= 10\n            \n            if contains(version,'(R202') % for Matlab R2020a and newer\n                rp=cell2mat(DataToAnalyze(2:end,2:end));\n            else\n                rp=str2double(DataToAnalyze(2:end,2:end));\n            end\n            orgs=DataToAnalyze(1,2:end)';\n            \n            taxonlevels={\n                'Phylum'\n                'Class'\n                'Order'\n                'Family'\n                'Genus'\n                'Species'\n                };\n            \n            for i=1:length(taxonlevels)\n                % plot on different taxon levels\n                taxa={};\n                taxcol=find(strcmp(infoFile(1,:),taxonlevels{i}));\n                for j=2:size(DataToAnalyze,2)\n                    if ~any(strcmp(infoFile(:,1),DataToAnalyze{1,j}))\n                        taxa{j-1,1}='N/A';\n                    else\n                        taxa{j-1,1}=infoFile{find(strcmp(infoFile(:,1),DataToAnalyze{1,j})),taxcol};\n                    end\n                end\n                \n                data=rp';\n                red_orgs=orgs;\n                \n                % remove entries that are all zeros\n                toDel=sum(data,1)<tol;\n                data(:,toDel)=[];\n                \n                % remove entries that are NaNs or empty\n                findnans=any(isnan(data));\n                data(:,findnans==1)=[];\n                \n                % remove unclassified organisms\n                data(find(strcmp(taxa,'N/A')),:)=[];\n                red_orgs(strcmp(taxa,'N/A'),:)=[];\n                taxa(find(strcmp(taxa,'N/A')),:)=[];\n                data(find(strcmp(taxa,'NA')),:)=[];\n                red_orgs(strcmp(taxa,'NA'),:)=[];\n                taxa(find(strcmp(taxa,'NA')),:)=[];\n\n                % remove empty cells\n                data(find(strcmp(taxa,'')),:)=[];\n                red_orgs(strcmp(taxa,''),:)=[];\n                taxa(find(strcmp(taxa,'')),:)=[];\n\n                % remove unclassified organisms\n                data(find(strncmp(taxa,'unclassified',length('unclassified'))),:)=[];\n                red_orgs(find(strncmp(taxa,'unclassified',length('unclassified'))),:)=[];\n                taxa(find(strncmp(taxa,'unclassified',length('unclassified'))),:)=[];\n                \n                \n                if i==6\n                    % remove unclassified species\n                    toDel=[];\n                    cnt=1;\n                    for j=1:size(data,1)\n                        if strcmp(taxa{j,1}(length(taxa{j,1})-2:length(taxa{j,1})),' sp')\n                            toDel(cnt)=j;\n                            cnt=cnt+1;\n                        end\n                    end\n                    data(toDel,:)=[];\n                    red_orgs(toDel,:)=[];\n                    taxa(toDel,:)=[];\n                end\n                \n                % remove taxa with too few members\n                [uniqueXX, ~, J]=unique(taxa) ;\n                occ = histc(J, 1:numel(uniqueXX));\n                \n                if length(uniqueXX) >15\n                    % sort by number of entries and remove the ones with the least\n                    % entries\n                    [B,I]=sort(occ,'descend');\n                    uniqueXX=uniqueXX(I);\n                    \n                    if sum(B==1) > length(B)-15\n                        % remove all that are just one entry\n                        uniqueXX(B==1)=[];\n                    else\n                        % remove all but 20 highest\n                        uniqueXX=uniqueXX(1:20);\n                    end\n                    \n                    [C,IA]=setdiff(taxa,uniqueXX);\n                    data(find(ismember(taxa,C)),:)=[];\n                    red_orgs(ismember(taxa,C),:)=[];\n                    taxa(find(ismember(taxa,C)),:)=[];\n                end\n\n                % sort alphabetically\n                [B,I]=sortrows(taxa,'ascend');\n                data = data(I,:);\n                red_orgs = red_orgs(I,:);\n                taxa = taxa(I,:);\n                \n                if size(data,1)>10\n                    \n                    % adjust perplicity to number of variables\n                    if size(data,1) > 150\n                        perpl=50;\n                    elseif size(data,1) >= 50\n                        perpl=30;\n                    elseif size(data,1) >= 20\n                        perpl=10;\n                    else\n                        perpl=5;\n                    end\n                    \n                    Y = tsne(data,'Distance',distance,'Algorithm',alg,'Perplexity',perpl,'NumDimensions',2);\n                    %                 Y = tsne(data,'Distance',distance,'Algorithm',alg,'Perplexity',perpl,'NumDimensions',3);\n                    Summary.([strrep(analyzedFiles{k,1},' ','_') '_' taxonlevels{i}])(:,1)=red_orgs;\n                    Summary.([strrep(analyzedFiles{k,1},' ','_') '_' taxonlevels{i}])(:,2)=taxa;\n                    Summary.([strrep(analyzedFiles{k,1},' ','_') '_' taxonlevels{i}])(:,3:size(Y,2)+2)=cellstr(string(Y));\n                    \n                    if size(data,1) == size(Y,1) && size(Y,2) > 1\n                        f=figure;\n                        cols=hsv(length(unique(taxa)));\n                        % define markers to better distinguish groups\n                        cmarkers='';\n                        for j=1:7:length(unique(taxa))\n                            cmarkers=[cmarkers '+o*xsdp'];\n                        end\n                        cmarkers=cmarkers(1:length(unique(taxa)));\n                        %                     gscatter3(Y(:,1),Y(:,2),Y(:,3),taxa,cols,{},30);\n                        h=gscatter(Y(:,1),Y(:,2),taxa,cols,cmarkers);\n                        set(h,'MarkerSize',4)\n                        hold on\n                        title(analyzedFiles{k,1})\n                        \n                        h=legend('Location','northeastoutside');\n                        if length(uniqueXX) < 12\n                            set(h,'FontSize',12)\n                        elseif length(uniqueXX) < 20\n                            set(h,'FontSize',11)\n                        else\n                            set(h,'FontSize',8)\n                        end\n                        set(h, 'Interpreter', 'none')\n                        grid off\n                        f.Renderer='painters';\n                        print(['tSNE_Plots' filesep taxonlevels{i} '_' strrep(analyzedFiles{k,1},' ','_') '_' reconVersion],'-dpng','-r300')\n                    else\n                        warning('Not enough strains with available organism information. Cannot cluster based on taxonomy.')\n                    end\n                end\n            end\n            \n            % if the data should be clustered by any custom features from the info file\n            if nargin > 3\n                for i=1:length(customFeatures)\n                    % plot on different taxon levels\n                    feats={};\n                    cuscol=find(strcmp(infoFile(1,:),customFeatures{i}));\n                    if ~isempty(cuscol)\n                        for j=2:size(DataToAnalyze,2)\n                            if ~any(strcmp(infoFile(:,1),DataToAnalyze{1,j}))\n                                feats{j-1,1}='N/A';\n                            else\n                                feats{j-1,1}=infoFile{find(strcmp(infoFile(:,1),DataToAnalyze{1,j})),cuscol};\n                            end\n                        end\n                        \n                        data=rp';\n                        red_orgs=orgs;\n                        \n                        % remove organisms with no data\n                        data(find(strcmp(taxa,'N/A')),:)=[];\n                        red_orgs(strcmp(taxa,'N/A'),:)=[];\n                        taxa(find(strcmp(taxa,'N/A')),:)=[];\n                        \n                        if size(data,1) >= 10\n                            \n                            % remove features with too few members\n                            [uniqueXX, ~, J]=unique(feats) ;\n                            occ = histc(J, 1:numel(uniqueXX));\n                            toofew=uniqueXX(occ<sum(occ)/2000);\n                            data(find(ismember(feats,toofew)),:)=[];\n                            red_orgs(ismember(feats,toofew),:)=[];\n                            feats(find(ismember(feats,toofew)),:)=[];\n                            \n                            Y = tsne(data,'Distance',distance,'Algorithm',alg,'Perplexity',perpl,'NumDimensions',3);\n                            Summary.([strrep(analyzedFiles{k,1},' ','_') '_' strrep(customFeatures{i},' ','_')])(:,1)=red_orgs;\n                            Summary.([strrep(analyzedFiles{k,1},' ','_') '_' strrep(customFeatures{i},' ','_')])(:,2)=feats;\n                            Summary.([strrep(analyzedFiles{k,1},' ','_') '_' strrep(customFeatures{i},' ','_')])(:,3:4)=cellstr(string(Y));\n                            \n                            f=figure;\n                            hold on\n                            gscatter3(Y(:,1),Y(:,2),Y(:,3),feats);\n                            title(analyzedFiles{k,1})\n                            h=legend('Location','northeastoutside');\n                            if length(uniqueXX) < 12\n                                set(h,'FontSize',11)\n                            elseif length(uniqueXX) < 20\n                                set(h,'FontSize',9)\n                            else\n                                set(h,'FontSize',6)\n                            end\n                            grid off\n                            set(h, 'Interpreter', 'none')\n                            f.Renderer='painters';\n                            print(['tSNE_Plots' filesep customFeatures{i} '_' strrep(analyzedFiles{k,1},' ','_') '_' reconVersion],'-dpng','-r300')\n                        else\n                            warning('Not enough strains with available organism information. Cannot cluster based on features.')\n                        end\n                    end\n                end\n            end\n        end\n    end\nend\n\n% export computed distance underlying the plots\ndatasets=fieldnames(Summary);\nif length(datasets)>0\n    mkdir(['tSNE_Plots' filesep 'ComputedDistances'])\n    for i=1:length(datasets)\n        data = vertcat({'Data point','Stratifying feature','x-axis value','y-axis value'},Summary.(datasets{i}));\n        cell2csv(['tSNE_Plots' filesep 'ComputedDistances' filesep datasets{i} '.csv'],data)\n    end\nend\n\ncd(currentDir)\n\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/demeter/src/properties/producetSNEPlots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.27202454519235225, "lm_q1q2_score": 0.14238318236382586}}
{"text": "function [trl, conditionlabels, S] = spm_eeg_definetrial(S)\n% Definition of trials based on events\n% FORMAT [trl, conditionlabels, S] = spm_eeg_definetrial(S)\n% S                 - input structure (optional)\n% (optional) fields of S:\n%   S.D             - MEEG object or filename of M/EEG mat-file\n%   S.timewin       - time window {in PST ms}\n%   S.trialdef      - structure array for trial definition with fields (optional)\n%       S.trialdef.conditionlabel - string label for the condition\n%       S.trialdef.eventtype      - string\n%       S.trialdef.eventvalue     - string, numeric or empty\n%       S.trialdef.trlshift       - shift the triggers by a fixed amount {ms} \n%                                   (e.g. projector delay).\n%   S.reviewtrials  - review individual trials after selection [yes/no: 1/0]\n%   S.save          - save trial definition [yes/no: 1/0]\n%\n% OUTPUT:\n%   trl             - Nx3 matrix [start end offset]\n%   conditionlabels - Nx1 cell array of strings, label for each trial\n%   S               - modified configuration structure (for history)\n%__________________________________________________________________________\n% Copyright (C) 2008-2017 Wellcome Trust Centre for Neuroimaging\n\n% Vladimir Litvak, Robert Oostenveld\n% $Id: spm_eeg_definetrial.m 7132 2017-07-10 16:22:58Z guillaume $\n\n\nSVNrev = '$Rev: 7132 $';\n\n%-Startup\n%--------------------------------------------------------------------------\nspm('sFnBanner', mfilename, SVNrev);\nspm_figure('FindWin','Interactive'); spm_clf('Interactive');\n\n%-Get MEEG object\n%--------------------------------------------------------------------------\ntry\n    D = S.D;\ncatch\n    [D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');\n    if ~sts, trl = []; conditionlabels = {}; S = []; return; end\n    S.D = D;\nend\n\nD = spm_eeg_load(D);\n\n%-Get input parameters\n%--------------------------------------------------------------------------\nif ~isequal(D.type, 'continuous')\n    error('Trial definition requires continuous dataset as input.');\nend\n\nevent    = events(D, 1, 'samples');\nfsample  = D.fsample;\n\nif isempty(event)\n    error('No event information was found in the input.');\nend\n\nif ~isfield(S, 'timewin')\n    S.timewin = spm_input('Time window (ms)', '+1', 'r', [], 2);\nend\n\npretrig  = S.timewin(1);\nposttrig = S.timewin(2);\n\nif ~isfield(S, 'trialdef')\n    S.trialdef = [];\n    ncond = spm_input('How many conditions?', '+1', 'n', '1');\n    for i = 1:ncond\n        OK = false;\n        pos = '+1';\n        while ~OK\n            conditionlabel = spm_input(['Label of condition ' num2str(i)], pos, 's');\n            selected = spm_eeg_select_event_ui(event);\n            if isempty(conditionlabel) || isempty(selected)\n                pos = '-1';\n            else\n                shift = spm_input('Shift triggers (ms)', pos, 'r', '0');\n                for j = 1:size(selected, 1)\n                    S.trialdef = [S.trialdef ...\n                        struct('conditionlabel', conditionlabel, ...\n                        'eventtype', selected{j, 1}, ...\n                        'eventvalue', selected{j, 2}, ...\n                        'trlshift', shift)];\n                    OK = true;\n                end\n            end\n        end\n    end\nend\n\nfor i = 1:length(S.trialdef)\n    if ~isfield(S.trialdef(i),'trlshift')\n        trlshift(i) = 0;\n    else\n        trlshift(i) = round(S.trialdef(i).trlshift * fsample/1000); % assume passed as ms\n    end\nend\n\n%-Build trl based on selected events\n%--------------------------------------------------------------------------\ntrl = [];\nconditionlabels = {};\nfor i=1:numel(S.trialdef)\n\n    if ischar(S.trialdef(i).eventvalue)\n        % convert single string into cell-array, otherwise the intersection does not work as intended\n        S.trialdef(i).eventvalue = {S.trialdef(i).eventvalue};\n    end\n\n    sel = [];\n    % select all events of the specified type and with the specified value\n    for j=find(strcmp(S.trialdef(i).eventtype, {event.type}))\n        if isempty(S.trialdef(i).eventvalue)\n            sel = [sel j];\n        elseif ~isempty(intersect(event(j).value, S.trialdef(i).eventvalue))\n            sel = [sel j];\n        end\n    end\n\n    for j=1:length(sel)\n        % override the offset of the event\n        trloff = round(0.001*pretrig*fsample);        \n        % also shift the begin sample with the specified amount\n        if ismember(event(sel(j)).type, {'trial', 'average'})\n            % In case of trial events treat the 0 time point as time of the\n            % event rather than the beginning of the trial \n            trlbeg = event(sel(j)).sample - event(sel(j)).offset + trloff;\n        else\n            trlbeg = event(sel(j)).sample + trloff;\n        end\n        trldur = round(0.001*(-pretrig+posttrig)*fsample);\n        trlend = trlbeg + trldur;\n        \n        % Added by Rik in case wish to shift triggers (e.g, due to a delay\n        % between trigger and visual/auditory stimulus reaching subject).\n        trlbeg = trlbeg + trlshift(i);\n        trlend = trlend + trlshift(i);\n        \n        % add the beginsample, endsample and offset of this trial to the list\n        trl = [trl; trlbeg trlend trloff];\n        conditionlabels{end+1} = S.trialdef(i).conditionlabel;\n    end\nend\n\n%-Sort the trl in right temporal order\n%--------------------------------------------------------------------------\nif isempty(trl)\n    warning('No trials found.');\nelse\n    [junk, sortind] = sort(trl(:,1));\n    trl             = trl(sortind, :);\n    conditionlabels = conditionlabels(sortind);\nend\n\n%-Review selected trials\n%--------------------------------------------------------------------------\nif ~isfield(S, 'reviewtrials')\n    S.reviewtrials = spm_input('Review individual trials?','+1','yes|no',[1 0], 0);\nend\n\nif S.reviewtrials && ~isempty(trl)\n    eventstrings = cell(size(trl,1),1);\n    for i=1:size(trl,1)\n        eventstrings{i} = [num2str(i) ' Label: ' conditionlabels{i} ' Time (sec): ' num2str((trl(i, 1)- trl(i, 3))./fsample)];\n    end\n\n    selected = find(trl(:,1)>0);\n\n    [indx,ok] = listdlg('ListString', eventstrings, 'SelectionMode', 'multiple', 'InitialValue', ...\n        selected, 'Name', 'Select events', 'ListSize', [300 300]);\n\n    if ok\n        trl = trl(indx, :);\n        conditionlabels = conditionlabels(indx);\n    end\nend\n\n%-Create trial definition file\n%--------------------------------------------------------------------------\nif ~isfield(S, 'save')\n    S.save = spm_input('Save trial definition?','+1','yes|no',[1 0], 0);\nend\n\nif S.save\n    [trlfilename, trlpathname] = uiputfile( ...\n        {'*.mat', 'MATLAB File (*.mat)'}, 'Save trial definition as');\n\n    if ~isequal(trlfilename,0) && ~isequal(trlpathname,0)\n        trialdef = S.trialdef;\n        timewin  = S.timewin;\n        source   = D.fname;\n    \n        save(fullfile(trlpathname, trlfilename),...\n            'trl', 'conditionlabels', 'trialdef', 'source', 'timewin', ...\n            spm_get_defaults('mat.format'));\n    end\nend\n\n%-Cleanup\n%--------------------------------------------------------------------------\nspm_clf('Interactive');\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_definetrial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.14180202200502967}}
{"text": "function [ctmediumphantom,ctdensityphantom] = dicomrt_ctcreate(inpct_matrix,ct_xmesh,ct_ymesh,ct_zmesh,rtdose_xmesh,rtdose_ymesh,rtdose_zmesh,plotramp,int)\n% dicomrt_ctcreate(inpct_matrix,ct_xmesh,ct_ymesh,ct_zmesh,rtdose_xmesh,rtdose_ymesh,rtdose_zmesh,plotramp,int)\n%\n% Create a ct phantom for BEAM/DOSXYZ simulation. Light Version.\n%\n% inpct_matrix is the CT dataset\n% ct_xmesh, ct_ymesh, ct_zmesh are the coordinates of the voxels for the CT dataset\n% rtdose_xmesh, rtdose_ymesh, rtdose_zmesh are the coordinates of the voxels\n% of the 3D dose distribution\n% plotramp is an option for plotting the CT ramp (~=0 plot, =0[default] no plot)\n% Int is a parameter for interactive session. \n%     If int ~=1 or if int is not given session is not interactive\n%     and default parameters (e.g. directories names) will be used. If int = 1 the user will \n%     be asked to set some parameters.\n%\n% Parameters for this specific m file are:\n%\n% nmat\t\t\t\t    number of material\n% materials\t\t\t    materials name\n% medium\t\t\t\tmaterials number\n% mat_ct_up_bound\t\tmaterials upper bound (see dosxyz user's manual)\n% density_lo_bound\t\tdensity lower bound (see dosxyz user's manual)\n% density_up_bound\t\tdensity upper bound (see dosxyz user's manual)\n% estepe\t\t\t\testepe (see dosxyz user's manual)\n% filename\t\t\t    ct phantom filename for export\n%\n% See also dicomrt_loaddose, dicomrt_rotate180x\n%\n% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org) \n\n% Check number of argument\nerror(nargchk(8,9,nargin))\n\nif nargin<=8\n    int=0;\nend\n\n% Check case and set-up some parameters and variables\n[ct_matrix_temp,type_dose,label,PatientPosition]=dicomrt_checkinput(inpct_matrix);\nct_matrix=dicomrt_varfilter(ct_matrix_temp);\n\n[ct_xmesh_2d,ct_ymesh_2d]=dicomrt_build2dgrid(ct_xmesh,ct_ymesh);\n[dose_xmesh_2d,dose_ymesh_2d]=dicomrt_build2dgrid(rtdose_xmesh,rtdose_ymesh);\n\n% 1a) resize ct_matrix using dose_xmesh, dose_ymesh, dose_zmesh\n% loop over dose_zmesh size since the rt plan could have been performed on a subset of the original ct images\nfor i=1:length(rtdose_zmesh)\n    if i==1 % locate z position of the first slice to start with\n      first_zlocation=rtdose_zmesh(i);\n      for k=1:length(ct_zmesh)\n         temp=num2str(ct_zmesh(k));\n         array=char(temp,num2str(first_zlocation));\n         if array(1,:)==array(2,:);\n            break\n         end\n      end\n      zstart=k; % match with dose matrix\n   end\n   ctphantom(:,:,i)=interp2(ct_xmesh_2d,ct_ymesh_2d,ct_matrix(:,:,k+i-1), ...\n       dose_xmesh_2d,dose_ymesh_2d,'nearest');\nend\n\n% 1b) Cut off negative values form outside CT FOV\nctphantom(find((ctphantom)<=0))=10; % a CT value for air\n\n% 2a) Retrieve ctphantom parameters: if int==1 start interactive session\nif isnumeric(int)==1 &  int==1\n    nmat = input('Input the number of materials [Enter for default]: '); % Number of material\n    if isempty(nmat)==1\n        nmat=4;\n        %disp('The following materials will be used: ');\n        materials          = char('AIR521ICRU','LUNG521ICRU','ICRUTISSUE521ICRU','ICRPBONE521ICRU');\n        medium             = [1;     2;     3;     4];\n        mat_ct_up_bound    = [50;    300;   1125;  5000];\n        density_lo_bound   = [0.001; 0.044; 0.302; 1.101];\n        density_up_bound   = [0.044; 0.302; 1.101; 3.48];\n        estepe             = [0.25;  0.25;  0.25;  0.25];\n    else\n        medium = [1:nmat]';\n        for i=1:nmat\n            mat = input('Input the name of material: ','s'); % Name of material\n            if i==1\n                materials = mat;\n            else\n                materials = char(materials,mat);\n            end\n            mat_ct_up_bound(i) = input('Input the material ct upper bound: ');\n            density_lo_bound(i) = input('Input the density ct lower bound: ');\n            density_up_bound(i) = input('Input the density ct upper bound: ');\n            estepe(i) = input('Input estepe for this material: ');\n        end\n        estepe=estepe';\n    end % ctphantom parameters retrieved  \nelse\n    nmat=4;\n    %disp('The following materials will be used: ');\n    materials          = char('AIR521ICRU','LUNG521ICRU','ICRUTISSUE521ICRU','ICRPBONE521ICRU');\n    medium             = [1;     2;     3;     4];\n    mat_ct_up_bound    = [50;    300;   1125;  5000];\n    density_lo_bound   = [0.001; 0.044; 0.302; 1.101];\n    density_up_bound   = [0.044; 0.302; 1.101; 3.84];\n    estepe             = [0.25;  0.25;  0.25;  0.25];\nend\n\n% 2b) Plot CT ramp\nif plotramp~=0\n    disp('Plotting CT conversion ramp being used: ');\n    dicomrt_plotctramp(inputname(1),materials,mat_ct_up_bound,density_lo_bound,density_up_bound);\nend\n\n% 3) Build ctphantom\n\n% 3a) CT to medium\nctmediumphantom=ctphantom;\nfor i=1:nmat\n    if i==1\n        ctmediumphantom(find((ctmediumphantom<=mat_ct_up_bound(i) & ...\n            ctmediumphantom>0)))=medium(i);\n    else\n        ctmediumphantom(find((ctmediumphantom<=mat_ct_up_bound(i) & ...\n            ctmediumphantom>mat_ct_up_bound(i-1))))=medium(i);\n    end\nend\n\n% 3b) Convert CT data to density\nctdensityphantom=ones(size(ctmediumphantom,1),size(ctmediumphantom,2),size(ctmediumphantom,3));\nfor i=1:nmat\n    if i==1\n        a=density_lo_bound(i);\n        b=density_up_bound(i)-density_lo_bound(i);\n        c=mat_ct_up_bound(i);\n        d=ctphantom(find((ctmediumphantom==medium(i))));\n        ctdensityphantom(find((ctmediumphantom==medium(i)))) = a+(b/c)*d;\n    else\n        a=density_lo_bound(i);\n        b=density_up_bound(i)-density_lo_bound(i);\n        c=mat_ct_up_bound(i)-mat_ct_up_bound(i-1);\n        d=ctphantom(find((ctmediumphantom==medium(i))))-mat_ct_up_bound(i-1);\n        ctdensityphantom(find((ctmediumphantom==medium(i)))) = a+(b/c)*d;\n    end\nend\n\n% 5) Export to file. \n%\n% ImagePositionPatient is the (x,y,z) coordinate of the first pixel (mm).\n% Therefore the mesh produced so far represent the coordinates of the center of the voxels.\n% CTphantom need the coordinates of the boundaries of the voxels.\n%\nif isnumeric(int)==1 &  int==1\n    export = input('Do you want to export the ctphantom ? Y/N [N]: ','s');\n    if export == 'Y' | export == 'y';\n        % Prepare to export\n        % pixel spacing\n        xthick=abs(rtdose_xmesh(1)-rtdose_xmesh(2));\n        ythick=abs(rtdose_ymesh(1)-rtdose_ymesh(2));\n        zthick=abs(rtdose_zmesh(1)-rtdose_zmesh(2));\n        \n        x_bound=dicomrt_createboundgrid(rtdose_xmesh);\n        y_bound=dicomrt_createboundgrid(rtdose_ymesh);\n        z_bound=dicomrt_createboundgrid(rtdose_zmesh);\n                \n        filename = input('Input the egs4phant filename (no ext): ','s'); % Name of the file where to store ctphantom\n        \n        if filename == 'N' | filename == 'n';\n            warning('dicomrt_ctcreate: No filename was input. Filename \"filename\" will be used');\n            filename=['filename.egs4phant'];\n            dicomrt_writeegs4phant(PatientPosition,nmat,materials,estepe,length(rtdose_xmesh),length(rtdose_ymesh), ...\n                length(rtdose_zmesh),x_bound,y_bound,z_bound,ctmediumphantom,ctdensityphantom,filename);\n        else\n            filename=[filename,'.egs4phant'];\n            dicomrt_writeegs4phant(PatientPosition,nmat,materials,estepe,length(rtdose_xmesh),length(rtdose_ymesh), ...\n                length(rtdose_zmesh),x_bound,y_bound,z_bound,ctmediumphantom,ctdensityphantom,filename);\n        end\n    else\n        disp('No export will be performed. Data will be stored on disk');\n        save \n    end\nelse\n    % Prepare to export\n    % pixel spacing\n    xthick=abs(rtdose_xmesh(1)-rtdose_xmesh(2));\n    ythick=abs(rtdose_ymesh(1)-rtdose_ymesh(2));\n    zthick=abs(rtdose_zmesh(1)-rtdose_zmesh(2));\n    \n    x_bound=dicomrt_createboundgrid(rtdose_xmesh);\n    y_bound=dicomrt_createboundgrid(rtdose_ymesh);\n    z_bound=dicomrt_createboundgrid(rtdose_zmesh);\n    \n    filename=inputname(1);\n    filename=[filename,'.egs4phant'];\n    \n    dicomrt_writeegs4phant(PatientPosition,nmat,materials,estepe,length(rtdose_xmesh),length(rtdose_ymesh), ...\n        length(rtdose_zmesh),x_bound,y_bound,z_bound,ctmediumphantom,ctdensityphantom,filename);\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/mctp/plan/dicomrt_ctcreate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2628418373713166, "lm_q1q2_score": 0.14166734003786072}}
{"text": "clc;\n\nclose all;\nclear all;\n\n%discremeinateanalysis\nlinearRegression\n%logisticregression\nnaivbayes\nregresstree\nccaregression\nsvm", "meta": {"author": "faridani", "repo": "MatlabNLP", "sha": "e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f", "save_path": "github-repos/MATLAB/faridani-MatlabNLP", "path": "github-repos/MATLAB/faridani-MatlabNLP/MatlabNLP-e18e8bc44ecbc8bb6aa57312c1ee22930f805a6f/nlp lib/ml/univariate/experiments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2658804789168741, "lm_q1q2_score": 0.1412382025977469}}
{"text": "% IN ORDER TO SIMULATE THE PROGRAM:\n%   A) FIRST, LOAD A ROBOT\n%       robot = load_robot('abb','irb140');\n%   B) NEXT, LOAD SOME EQUIPMENT.\n%       robot.equipment = load_robot('equipment','tables/table_small');\n%       OR\n%       robot.equipment = load_robot('equipment','bumper_cutting');\n%   C) NOW, LOAD AN END TOOL\n%       robot.tool= load_robot('equipment','end_tools/parallel_gripper_0');\n%   D) FINALLY, LOAD A PIECE TO GRAB BY THE ROBOT\n%       robot.piece{1}=load_robot('equipment','cylinders/cylinder_tiny');\n%\n%   E) IF NECESSARY, CHANGE THE POSITION AND ORIENTATION OF THE ROBOT'S\n%   BASE\n%       robot.piece{1}.T0= [1 0 0 -0.35;\n%                        0 1 0 -0.55;\n%                        0 0 1 0.2;\n%                        0 0 0 1]; \n\nfunction kuka_KR60_painting_jaguar_ftype\n\nglobal TD_tool0 RT_tp1 RT_tp2 RT_tp3 RT_tp4 RT_tp5 RT_tp6 RT_tp7 RT_tp8 RT_tp9 RT_tp10 RT_tp11 RT_tp12 RT_tp13 RT_tp14 RT_tp15 RT_tp16\n\n\nTD_tool0=[1,[[0,0,0],[1,0,0,0]],[0,[0,0,0],[1,0,0,0],0,0,0]];\n\nRT_tp1=[[1.3400, -0.0000, 1.8100],[0.7006, -0.0954, 0.7006, -0.0954], [0, 0, 1, 0], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp2=[[1.1648, 0.6617, 1.8206],[0.7233, -0.2626, 0.6324, 0.0894], [-1, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp3=[[1.4924, 0.9803, 1.1556],[0.5816, -0.3339, 0.7362, 0.0911], [-1, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp4=[[1.5020, 0.8533, 1.3436],[0.6364, -0.2942, 0.7086, 0.0787], [-1, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp5=[[1.5207, 0.6786, 1.4836],[0.6784, -0.2480, 0.6898, 0.0507], [-1, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp6=[[1.6593, 0.3815, 1.4044],[0.6580, -0.1850, 0.7298, -0.0146], [-1, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp7=[[1.6990, 0.1099, 1.4044],[0.6547, -0.1255, 0.7423, -0.0677], [-1, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp8=[[1.6707, -0.3278, 1.4044],[0.6406, -0.0289, 0.7523, -0.1514], [0, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp9=[[1.6064, -0.8202, 1.1348],[0.5463, 0.0815, 0.8060, -0.2127], [0, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp10=[[1.4123, -1.1863, 0.9392],[0.5177, 0.1723, 0.7925, -0.2725], [0, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp11=[[1.2529, -1.3639, 0.9736],[0.5680, 0.2052, 0.7172, -0.3476], [0, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp12=[[1.2075, -0.7363, 1.1201],[0.5774, 0.1073, 0.7697, -0.2503], [0, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp13=[[1.2048, -0.5831, 1.2640],[0.5698, 0.0714, 0.7900, -0.2149], [0, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp14=[[1.2754, -0.1696, 1.3640],[0.6362, -0.0526, 0.7587, -0.1299], [0, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp15=[[1.2481, 0.3127, 1.3640],[0.6493, -0.1940, 0.7354, -0.0081], [-1, 0, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nRT_tp16=[[1.1268, 0.6211, 1.3640],[0.6449, -0.2871, 0.7042, 0.0756], [-1, -1, 1, 1], [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]];\nmain\nend\n\nfunction main()\n\nglobal TD_tool0 RT_tp1 RT_tp2 RT_tp3 RT_tp4 RT_tp5 RT_tp6 RT_tp7 RT_tp8 RT_tp9 RT_tp10 RT_tp11 RT_tp12 RT_tp13 RT_tp14 RT_tp15 RT_tp16\n\n MoveL(RT_tp1, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp2, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp3, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp4, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp5, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp6, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp7, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp8, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp9, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp10, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp11, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp12, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp13, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp14, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp15, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n MoveL(RT_tp16, 'vmax' , 'fine' , TD_tool0, 'wobj0');\n\nend\n", "meta": {"author": "4rtur1t0", "repo": "ARTE", "sha": "6e836f3156bb36af63b70bd93375c8ff4ee643c4", "save_path": "github-repos/MATLAB/4rtur1t0-ARTE", "path": "github-repos/MATLAB/4rtur1t0-ARTE/ARTE-6e836f3156bb36af63b70bd93375c8ff4ee643c4/RAPID/programs/advanced_simulations/kuka_KR60_painting_jaguar_ftype.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2689414096510108, "lm_q1q2_score": 0.14076940648295896}}
{"text": "function writeGLTF(filename,V,F,varargin)\n  % writeGLTF(filename,V,F)\n  %\n  % Inputs:\n  %   filename  path to .gltf file\n  %   V  #V by 3 list of mesh vertex positions\n  %   F  #F by 3 list of mesh triangle indices into rows of V\n  %   Optional:\n  %   'SkinningTransforms' followed by\n  %     T  3 by 4 by #T by #A list of animated global skinning transformations\n  %   'SkinningWeights' followed by\n  %     W  #V by #T list of skinning weights\n  %   'MorphTargets' followed by\n  %     MV  #V by 3 by #M list of morph targets\n  %   'MorphWeights' followed by\n  %     MW  #frames by #M list of morph weights\n  %   'TextureCoordinates' followed by\n  %     UV  #V by 2 list of texture coordinates\n  %\n  % Examples:\n  %   !python -m json.tool octopus.gltf > octopus-pretty.gltf\n  NEAREST = 9728;\n  LINEAR = 9729;\n  NEAREST_MIPMAP_NEAREST = 9984;\n  LINEAR_MIPMAP_NEAREST = 9985;\n  NEAREST_MIPMAP_LINEAR = 9986;\n  LINEAR_MIPMAP_LINEAR = 9987;\n  CLAMP_TO_EDGE = 33071;\n  MIRRORED_REPEAT = 33648;\n  REPEAT = 10497;\n\n  T = [];\n  W = [];\n  MV = [];\n  MN = [];\n  MW = [];\n  N = [];\n  fps = 30;\n  nf = 0;\n  UV = [];\n  tex_im = [];\n  mag_filter = LINEAR;\n  min_filter = LINEAR_MIPMAP_LINEAR;\n  wrap_s = MIRRORED_REPEAT;\n  wrap_t = MIRRORED_REPEAT;\n\n\n  % Map of parameter names to variable names\n  params_to_variables = containers.Map( ...\n    {'FPS','MagFilter','MinFilter','MorphTargets','MorphNormals','MorphWeights','Normals','SkinningTransforms','SkinningWeights','TextureCoordinates','TextureImage'}, ...\n    {'fps','mag_filter','min_filter','MV','MN','MW','N','T','W','UV','tex_im'});\n  v = 1;\n  while v <= numel(varargin)\n    param_name = varargin{v};\n    if isKey(params_to_variables,param_name)\n      assert(v+1<=numel(varargin));\n      v = v+1;\n      % Trick: use feval on anonymous function to use assignin to this workspace\n      feval(@()assignin('caller',params_to_variables(param_name),varargin{v}));\n    else\n      error('Unsupported parameter: %s',varargin{v});\n    end\n    v=v+1;\n  end\n\n  mag_filter = string_to_magic_value(mag_filter);\n  min_filter = string_to_magic_value(min_filter);\n  function value = string_to_magic_value(string)\n    if ischar(string)\n      switch(string)\n      case 'LINEAR'\n        value = LINEAR;\n      case 'NEAREST'\n        value = NEAREST;\n      case 'LINEAR_MIPMAP_NEAREST'\n        value = LINEAR_MIPMAP_NEAREST;\n      case 'LINEAR_MIPMAP_LINEAR'\n        value = LINEAR_MIPMAP_LINEAR;\n      otherwise\n        error([string ' not found/implemented.']);\n      end\n    else\n      value = string;\n    end\n  end\n\n\n  % set flags \n  has_normals = ~isempty(N);\n  has_skinning_weights = ~isempty(W);\n  has_skinning_transforms = ~isempty(T);\n  has_morph_target_positions = ~isempty(MV);\n  has_morph_target_weights = ~isempty(MW);\n  has_morph_target_normals = ~isempty(MN);\n  has_texture_coordinates = ~isempty(UV);\n  has_texture_image = ~isempty(tex_im);\n\n\n\n  % Determine what type to use for faces\n  BYTE = 5120;\n  UNSIGNED_BYTE = 5121;\n  SHORT = 5122;\n  UNSIGNED_SHORT = 5123;\n  UNSIGNED_INT = 5125;\n  FLOAT = 5126;\n  ARRAY_BUFFER = 34962;\n  ELEMENT_ARRAY_BUFFER = 34963;\n  if max(F(:)) < 2^16\n    F_size = 2;\n    F_type = UNSIGNED_SHORT;\n    F_matlab_type = 'uint16';\n  else\n    F_size = 4;\n    F_type = UNSIGNED_INT;\n    F_matlab_type = 'uint32';\n  end\n\n  % prepare things to write\n  buffered_data = {};\n  buffered_data{end+1} = struct('Name','F','Data',F,'Type','SCALAR','ComponentType',F_type,'Size',F_size,'MatlabType',F_matlab_type,'Target',ELEMENT_ARRAY_BUFFER);\n  buffered_data{end+1} = struct('Name','V','Data',V,'Target',ARRAY_BUFFER);\n  if has_normals\n    buffered_data{end+1} = struct('Name','N','Data',normalizerow(N),'Target',ARRAY_BUFFER);\n  end\n  if has_morph_target_weights\n    assert(size(MW,2) == size(MV,3));\n    buffered_data{end+1} = struct('Name','MW','Data',MW,'Type','SCALAR');\n    MWt = (0:size(MW,1)-1)*1/fps;\n    buffered_data{end+1} = struct('Name','MWt','Data',MWt,'Type','SCALAR');\n  end\n  if has_morph_target_positions\n    buffered_data{end+1} = struct('Name','MV','Data',MV,'Target',ARRAY_BUFFER);\n  end\n  if has_morph_target_normals\n    buffered_data{end+1} = struct('Name','MN','Data',MN,'Target',ARRAY_BUFFER);\n  end\n  if has_skinning_weights\n    [WIk,Wk] = prepare_skinning_weights(W);\n    if max(WIk(:)) < 2^8\n      WIk_size = 1;\n      WIk_type = UNSIGNED_BYTE;\n      WIk_matlab_type = 'uint8';\n    else\n      WIk_size = 2;\n      WIk_type = UNSIGNED_SHORT;\n      WIk_matlab_type = 'uint16';\n    end\n    buffered_data{end+1} = struct('Name','WIk','Data',WIk,'Size',WIk_size,'MatlabType',WIk_matlab_type,'ComponentType',WIk_type,'Target',ARRAY_BUFFER);\n    buffered_data{end+1} = struct('Name','Wk','Data',Wk,'Target',ARRAY_BUFFER);\n  end\n  if has_skinning_transforms\n    assert(size(W,2) == size(T,3));\n    [tT,qU,sS,qVT] = prepare_skinning_transforms(T);\n    buffered_data{end+1} = struct('Name','tT','Data',tT);\n    buffered_data{end+1} = struct('Name','qU','Data',qU);\n    buffered_data{end+1} = struct('Name','sS','Data',sS);\n    buffered_data{end+1} = struct('Name','qVT','Data',qVT);\n    Tt = (0:size(T,4)-1)*1/fps;\n    buffered_data{end+1} = struct('Name','Tt','Data',Tt,'Type','SCALAR');\n  end\n  if has_texture_coordinates\n    buffered_data{end+1} = struct('Name','UV','Data',UV,'Target',ARRAY_BUFFER);\n  end\n\n  [buffer,bufferViews,accessors,accessor_hash] = prepare_buffer(buffered_data);\n\n  % First node is the mesh\n  attributes = struct(\"POSITION\",accessor_hash.V);\n\n  if has_normals\n    attributes.NORMAL = accessor_hash.N;\n  end\n  if has_texture_coordinates\n    attributes.TEXCOORD_0 = accessor_hash.UV;\n  end\n  if has_skinning_weights\n    attributes.JOINTS_0 = accessor_hash.WIk;\n    attributes.WEIGHTS_0 = accessor_hash.Wk;\n  end\n  mesh = struct( ...\n    \"primitives\",{{struct(\"attributes\",attributes,\"indices\",accessor_hash.F)}});\n  if has_morph_target_positions\n    if ~isfield(mesh.primitives{1},'targets')\n      mesh.primitives{1}.targets = num2cell(repmat(struct(),size(MV,3),1));\n    end\n    for i = 1:size(MV,3)\n      mesh.primitives{1}.targets{i} = setfield(mesh.primitives{1}.targets{i},'POSITION',accessor_hash.MV(i));\n    end\n    mesh.weights = zeros(1,size(MV,3));\n  end\n  if has_morph_target_normals\n    if ~isfield(mesh.primitives{1},'targets')\n      mesh.primitives{1}.targets = num2cell(repmat(struct(),size(MN,3),1));\n    end\n    for i = 1:size(MN,3)\n      mesh.primitives{1}.targets{i} = setfield(mesh.primitives{1}.targets{i},'NORMAL',accessor_hash.MN(i));\n    end\n  end\n\n  nodes_list = {0};\n  nodes = {struct(\"mesh\",0)};\n  if has_skinning_weights\n    m = size(W,2);\n    nodes{end}.skin = 0;\n    % First put leaf nodes that will animate V-rotation\n    for i = 1:m\n      nodes{end+1} = struct( ...\n        \"name\",sprintf('V-%d',i), ...\n        \"rotation\",[0 0 0 1]);\n    end\n    % Then put parent auxiliary nodes that will animate translation, U-rotation, scale\n    for i = 1:m\n      nodes{end+1} = struct( ...\n        \"name\",sprintf('TUS-%d',i), ...\n        \"children\",{{i}}, ...\n        \"translation\",[0 0 0], ...\n        \"rotation\",[0 0 0 1], ...\n        \"scale\",[1 1 1]);\n    end\n    %Put fake root at scene level and attach parents\n    nodes_list{end+1} = 2*m+1;\n    common_root = struct(\"name\",\"root\",\"children\",{num2cell(m+(1:m))});\n    nodes = {nodes{:} common_root};\n  end\n\n  % These {{double-brackets}} are needed when using the `struct` function.\n  gltf = struct( ...\n    \"scene\",0, ...\n    \"scenes\",{{struct(\"nodes\",{nodes_list})}}, ...\n    \"nodes\",{nodes}, ...\n    \"meshes\",{{mesh}}, ...\n    \"buffers\",{{buffer}}, ...\n    \"bufferViews\",{bufferViews}, ...\n    \"accessors\",{accessors}, ...\n    \"asset\",struct(\"version\",\"2.0\") ...\n    );\n\n  % Are these just for animation or do they overlap with texture samplers?\n  samplers = {};\n  channels = {};\n  if has_skinning_weights\n    gltf.skins = {struct('joints',{num2cell(0+1:m)})};\n    if has_skinning_transforms\n      for i = 1:m\n        channels{end+1} = struct('sampler',numel(samplers),'target',struct('node',m+i,'path','translation'));\n        samplers{end+1} = struct('input',accessor_hash.Tt,'output',accessor_hash.tT(i),'interpolation', 'STEP');\n        channels{end+1} = struct('sampler',numel(samplers),'target',struct('node',m+i,'path','rotation'));\n        samplers{end+1} = struct('input',accessor_hash.Tt,'output',accessor_hash.qU(i),'interpolation', 'STEP');\n        channels{end+1} = struct('sampler',numel(samplers),'target',struct('node',m+i,'path','scale'));\n        samplers{end+1} = struct('input',accessor_hash.Tt,'output',accessor_hash.sS(i),'interpolation', 'STEP');\n        channels{end+1} = struct('sampler',numel(samplers),'target',struct('node',i,'path','rotation'));\n        samplers{end+1} = struct('input',accessor_hash.Tt,'output',accessor_hash.qVT(i),'interpolation','STEP');\n      end\n    end\n  end\n  if has_morph_target_weights\n    channels{end+1} = struct('sampler',numel(samplers),'target',struct('node',0,'path','weights'));\n    samplers{end+1} = struct('input',accessor_hash.MWt,'output',accessor_hash.MW,'interpolation','LINEAR');\n  end\n  if ~isempty(samplers)\n    gltf.animations = {struct('samplers',{samplers},'channels',{channels})};\n  end\n  if has_texture_image \n\n    if mag_filter == LINEAR\n      tmpfile = 'writeGLTF.jpg';\n      imwrite(flipud(tex_im),tmpfile,'Quality',100);\n    else\n      tmpfile = 'writeGLTF.png';\n      imwrite(flipud(tex_im),tmpfile);\n    end\n    tex_image_uri = imdata(tmpfile);\n    delete(tmpfile);\n\n\n    gltf.images = {struct('uri',tex_image_uri)};\n    tex_image_index = numel(gltf.images)-1;\n    if ~isfield(gltf,'samplers')\n      gltf.samplers = {};\n    end\n    gltf.samplers{end+1} = struct('magFilter',mag_filter,'minFilter',min_filter,'wrapS',wrap_s,'wrapT',wrap_t);\n    gltf.textures = {struct('sampler',numel(gltf.samplers)-1,'source',tex_image_index)};\n\n    if has_texture_coordinates\n      gltf.materials = {struct( ...\n        'name','default', ...\n        'pbrMetallicRoughness', ...\n          struct( ...\n            'baseColorTexture',struct('index',0), ...\n            'metallicFactor',0, ...\n            'roughnessFactor',1))};\n      gltf.meshes{1}.primitives{1}.material = numel(gltf.materials)-1;\n    end\n  end\n\n  fid = fopen(filename,'w');\n  fprintf(fid,'%s',jsonencode(gltf));\n  fclose(fid);\n\n  function [buffer,bufferViews,accessors,accessor_hash] = prepare_buffer(buffered_data)\n    buffer_index = 0;\n    bufferViews = {};\n    accessors = {};\n    accessor_hash = struct();\n    byte_count = 0;\n    % write all data, tracking offsets\n    tmpfile = 'writeGLTF.tmp';\n    fp = fopen(tmpfile,'wb');\n    for bi = 1:numel(buffered_data)\n      item = buffered_data{bi};\n      if isfield(item,'Size')\n        adjusted_data = item.Data - 1;\n        pad_amount = 4;\n      else\n        % default to single\n        item.ComponentType = FLOAT;\n        item.Size = 4;\n        item.MatlabType = 'single';\n        pad_amount = 8;\n        adjusted_data = item.Data;\n      end\n      if ~isfield(item,'Type')\n        switch(size(adjusted_data,2))\n        case 2\n          item.Type = 'VEC2';\n        case 3\n          item.Type = 'VEC3';\n        case 4\n          item.Type = 'VEC4';\n        otherwise\n          item.Type = 'SCALAR';\n        end\n      end\n\n      accessor_ids = numel(accessors)-1 + (1:size(item.Data,3));\n      for i = 1:size(item.Data,3)\n        adjusted_data_i = adjusted_data(:,:,i);\n        switch(item.Type)\n        case 'SCALAR'\n          accessor_count = numel(adjusted_data_i);\n          accessor_min = {{min(  adjusted_data_i,[],[1 2])}};\n          accessor_max = {{max(  adjusted_data_i,[],[1 2])}};\n        case {'VEC2','VEC3','VEC4'}\n          accessor_count = size( adjusted_data_i,1);\n          accessor_min = min(    adjusted_data_i,[],1);\n          accessor_max = max(    adjusted_data_i,[],1);\n        end\n\n        fwrite(fp,adjusted_data_i',item.MatlabType);\n        % pad so that next block starts aligned at 4-byte\n        bi_pad = mod(pad_amount-mod(numel(adjusted_data_i),pad_amount),pad_amount);\n        fwrite(fp,zeros(bi_pad,1),item.MatlabType);\n        % prepare bufferView and accessor\n        % Always use 'buffer',0  \u2192 caller MUST adjust all if needed\n        bufferViews{end+1} = struct( ...\n          'name',item.Name, ...\n          'buffer',buffer_index, ...\n          'byteOffset',byte_count, ...\n          'byteLength',numel(adjusted_data_i)*item.Size);\n        if isfield(item,'Target')\n          bufferViews{end} = setfield(bufferViews{end},'target',item.Target);\n        end\n        accessors{end+1} = struct( ...\n          'name',item.Name, ...\n          'bufferView',numel(bufferViews)-1, ...\n          'byteOffset',0, ...\n          'componentType',item.ComponentType, ...\n          'type',item.Type, ...\n          'count',accessor_count, ...\n          'min',accessor_min, ...\n          'max',accessor_max);\n        % Increment byte_count\n        byte_count = byte_count + (numel(adjusted_data_i)+bi_pad)*item.Size;\n      end\n      accessor_hash = setfield(accessor_hash,item.Name,accessor_ids);\n    end\n    fclose(fp);\n    fp = fopen(tmpfile,'r');\n    B = fread(fp,byte_count);\n    fclose(fp);\n    delete(tmpfile);\n    Bstr = base64encode(B);\n    %assert(isequal(Bstr,matlab.net.base64encode(uint8(B))))\n    buffer = struct( ...\n      'uri',['data:application/octet-stream;base64,' Bstr], ...\n      'byteLength', numel(B));\n  end\n\n  function [WIk,Wk] = prepare_skinning_weights(W)\n    % Number of skinning weights/handles/bones\n    m = size(W,2) * ~isempty(W);\n    % Convert weight matrix into multiple of 4 index-value pairs\n    assert(size(W,2) == m);\n    k = max(sum(W~=0,2));\n    k4 = ceil(k/4)*4;\n    % I'm not sure how >4 is handled.\n    assert(k4 == 4);\n    [Wk,WIk] = maxk(W,k,2);\n    % Pad with null bones\n    Wk(:,k+1:k4)  = 0;\n    WIk(:,k+1:k4) = 0+1;%repmat(m+(1:k4-k),size(WIk,1),1);\n    WIk(Wk==0) = 0+1;\n  end\n\n  function [tT,qU,sS,qVT] = prepare_skinning_transforms(T)\n    m = size(T,3);\n    nf = size(T,4) * ~isempty(T);\n    T = permute(T,[1 2 4 3]);\n    assert(size(T,2) == 4);\n    tT = T(:,4,:,:);\n    [sU,sS,sV] = pagesvd(T(1:3,1:3,:,:));\n    % Push all of the reflection into sS\n    % matlabFunction(det(sym('m',[3 3])))\n    pagedet = @(m1_1,m1_2,m1_3,m2_1,m2_2,m2_3,m3_1,m3_2,m3_3) m1_1.*m2_2.*m3_3-m1_1.*m2_3.*m3_2-m1_2.*m2_1.*m3_3+m1_2.*m2_3.*m3_1+m1_3.*m2_1.*m3_2-m1_3.*m2_2.*m3_1;\n    pagedet = @(m) pagedet(m(1,1,:,:),m(1,2,:,:),m(1,3,:,:),m(2,1,:,:),m(2,2,:,:),m(2,3,:,:),m(3,1,:,:),m(3,2,:,:),m(3,3,:,:));\n    sUdet = sign(pagedet(sU));\n    sVdet = sign(pagedet(sV));\n    sU = sU.*sUdet;\n    sV = sV.*sVdet;\n    sS = sS.*sVdet.*sUdet;\n    sS = cat(2,sS(1,1,:,:),sS(2,2,:,:),sS(3,3,:,:));\n\n    qU = reshape(mat2quat(reshape(sU,[3 3 m*nf]))',[4 nf m]);\n    qVT = reshape(mat2quat(reshape(permute(sV,[2 1 3 4]),[3 3 m*nf]))',[4 nf m]);\n    for i = 1:m\n      for f = 1:nf\n        assert(norm(T(:,:,f,i) - [quat2mat(qU(:,f,i)')*diag(sS(:,:,f,i))*quat2mat(qVT(:,f,i)') tT(:,:,f,i)],inf)<1e-12);\n      end\n    end\n    % gltf uses ijkw\n    qU = qU([2 3 4 1],:,:);\n    qVT = qVT([2 3 4 1],:,:);\n\n    tT = permute(tT,[3 1 4 2]);\n    sS = permute(sS,[3 2 4 1]);\n    qU = permute(qU,[2 1 3]);\n    qVT = permute(qVT,[2 1 3]);\n  end\n\nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/writeGLTF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2628418489200747, "lm_q1q2_score": 0.14064626033444522}}
{"text": "function [pred_boxes, scores] = rfcn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)\n% [pred_boxes, scores] = rfcn_im_detect(conf, caffe_net, im, boxes, max_rois_num_in_gpu)\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    [im_blob, rois_blob, ~] = get_blobs(conf, im, boxes);\n    \n    % When mapping from image ROIs to feature map ROIs, there's some aliasing\n    % (some distinct image ROIs get mapped to the same feature ROI).\n    % Here, we identify duplicate feature ROIs, so we only compute features\n    % on the unique subset.\n    [~, index, inv_index] = unique(rois_blob, 'rows');\n    rois_blob = rois_blob(index, :);\n    boxes = boxes(index, :);\n    \n    % permute data into caffe c++ memory, thus [num, channels, height, width]\n    im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg\n    im_blob = permute(im_blob, [2, 1, 3, 4]);\n    im_blob = single(im_blob);\n    rois_blob = rois_blob - 1; % to c's index (start from 0)\n    rois_blob = permute(rois_blob, [3, 4, 2, 1]);\n    rois_blob = single(rois_blob);\n    \n    total_rois = size(rois_blob, 4);\n    total_scores = cell(ceil(total_rois / max_rois_num_in_gpu), 1);\n    total_box_deltas = cell(ceil(total_rois / max_rois_num_in_gpu), 1);\n    for i = 1:ceil(total_rois / max_rois_num_in_gpu)\n        \n        sub_ind_start = 1 + (i-1) * max_rois_num_in_gpu;\n        sub_ind_end = min(total_rois, i * max_rois_num_in_gpu);\n        sub_rois_blob = rois_blob(:, :, :, sub_ind_start:sub_ind_end);\n        \n        net_inputs = {im_blob, sub_rois_blob};\n\n        % Reshape net's input blobs\n        caffe_net.reshape_as_input(net_inputs);\n        caffe_net.forward(net_inputs);\n\n        if conf.test_binary\n            % simulate binary logistic regression\n            scores = caffe_net.blobs('cls_score').get_data();\n            scores = squeeze(scores)';\n            % Return scores as fg - bg\n            scores = bsxfun(@minus, scores, scores(:, 1));\n        else\n            % use softmax estimated probabilities\n            scores = caffe_net.blobs('cls_prob').get_data();\n            scores = squeeze(scores)';\n        end\n\n        % Apply bounding-box regression deltas\n        box_deltas = caffe_net.blobs('bbox_pred').get_data();\n        box_deltas = squeeze(box_deltas)';\n        \n        total_scores{i} = scores;\n        total_box_deltas{i} = box_deltas;\n    end \n    \n    scores = cell2mat(total_scores);\n    box_deltas = cell2mat(total_box_deltas);\n    \n    pred_boxes = rfcn_bbox_transform_inv(boxes, box_deltas);\n    pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));\n\n    % Map scores and predictions back to the original set of boxes\n    scores = scores(inv_index, :);\n    pred_boxes = pred_boxes(inv_index, :);\n    \n    % remove scores and boxes for back-ground\n    pred_boxes = pred_boxes(:, 5:end);\n    scores = scores(:, 2:end);\n    if conf.bbox_class_agnostic\n        pred_boxes = repmat(pred_boxes, [1, size(scores,2)]);\n    end\nend\n\nfunction [data_blob, rois_blob, im_scale_factors] = get_blobs(conf, im, rois)\n    [data_blob, im_scale_factors] = get_image_blob(conf, im);\n    rois_blob = get_rois_blob(conf, rois, im_scale_factors);\nend\n\nfunction [blob, im_scales] = get_image_blob(conf, im)\n    [ims, im_scales] = arrayfun(@(x) prep_im_for_blob(im, conf.image_means, x, conf.test_max_size), conf.test_scales, 'UniformOutput', false);\n    im_scales = cell2mat(im_scales);\n    blob = im_list_to_blob(ims);    \nend\n\nfunction [rois_blob] = get_rois_blob(conf, im_rois, im_scale_factors)\n    [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, im_scale_factors);\n    rois_blob = single([levels, feat_rois]);\nend\n\nfunction [feat_rois, levels] = map_im_rois_to_feat_rois(conf, im_rois, scales)\n    im_rois = single(im_rois);\n    \n    if length(scales) > 1\n        widths = im_rois(:, 3) - im_rois(:, 1) + 1;\n        heights = im_rois(:, 4) - im_rois(:, 2) + 1;\n        \n        areas = widths .* heights;\n        scaled_areas = bsxfun(@times, areas(:), scales(:)'.^2);\n        [~, levels] = min(abs(scaled_areas - 224.^2), [], 2); \n    else\n        levels = ones(size(im_rois, 1), 1);\n    end\n    \n    feat_rois = round(bsxfun(@times, im_rois-1, scales(levels))) + 1;\nend\n\nfunction boxes = clip_boxes(boxes, im_width, im_height)\n    % x1 >= 1 & <= im_width\n    boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);\n    % y1 >= 1 & <= im_height\n    boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);\n    % x2 >= 1 & <= im_width\n    boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);\n    % y2 >= 1 & <= im_height\n    boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);\nend", "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/functions/rfcn/rfcn_im_detect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.26284182582255894, "lm_q1q2_score": 0.1406462479750008}}
{"text": "function flat = rmVol2flat(gray,flat)\n% flat = rmVol2flat(gray,flat)\n%\n% sd 04/2008 wrote it\n\n% Don't do this unless gray is really a gray and flat is really a flat\nif ~strcmp(gray.viewType,'Gray') || ~strcmp(flat.viewType,'Flat')\n    myErrorDlg('vol2flatCorAnal can only be used to transform from gray to flat.');\nend\n\n% Check that both gray & flat are properly initialized\nif isempty(gray)\n  myErrorDlg('Gray view must be open.  Use \"Open Gray Window\" from the Window menu.');\nend\nif isempty(flat)\n  myErrorDlg('Flat view must be open.  Use \"Open Flat Window\" from the Window menu.');\nend\n\n% Check that dataType is the same for both views. If not, doesn't make sense to do the xform.\n% because for example the two dataTypes may have a different number of scans.\ncheckTypes(gray,flat);\n\n% get/load selected file\ntry\n  rmFile = viewGet(gray,'rmFile');\ncatch\n  disp(sprintf('[%s]:Please select file',mfilename));\n  gray    = rmSelect(gray);\n  rmFile  = viewGet(gray,'rmFile');\nend;\nload(rmFile,'model',  'params');\nmodelGray = model; %#ok<NODEF>\n\n% Mask image for masking the flat map away from where we have data\nmask = flat.ui.mask;\n\n% Put up wait bar\nwaitHandle = mrvWaitbar(0,'Transforming retModel.  Please wait...');\n% Intersect the coords from the gray view and the Flat view.\ngrayIndices=cell(1,2);\nflatIndices=cell(1,2);\nfor h=1:2\n    % Get the data corresponding to flat coordinates: coData,\n    % ampData, and phData are each of size nVoxels x nScans where\n    % nVoxels = size(flat.grayCoords,2).  First, find the\n    % intersection of gray.coords and flat.grayCoords.  Then make\n    % the data arrays by culling out the values from the\n    % intersecting voxels.\n    % Find gray nodes that are both in the inplanes and included\n    % in the unfold.\n    % gray.coords are the gray coords that lie in the inplanes.\n    % flat.grayCoords are the gray coords in the unfold.\n    % Note: this code segment is essentially identical to\n    % code in getFlatCoords.\n    [foo,grayIndicesTmp,flatIndicesTmp] = intersectCols(gray.coords,flat.grayCoords{h});\n    grayIndices{h}=grayIndicesTmp;\n    flatIndices{h}=flatIndicesTmp;\n    % Error check on flatIndices.  Because the above code segment\n    % is the same as that used to get the flat coords in\n    % getFlatCoords, all of the flatIndices should be in the\n    % intersection.  If not, something is busted.\n    if length(flatIndicesTmp)~=size(flat.grayCoords{h},2)\n        myWarnDlg('Ack!  Your flat maps do not appear to come from this segmentation!');\n    end\nend\n\nds = viewGet(flat,'datasize');\nfor m = 1:numel(model),  \n    % get all model fields \n    fnames = fieldnames(model{m});\n    for f = 1:numel(fnames),   % loop over model fields\n        mrvWaitbar(((m-1).*length(model)+f) ./ (length(model).*length(fnames)))\n        paramGray = rmGet(modelGray{m},fnames{f});\n        % only xfm model fields that have data of a certain size\n        if numel(paramGray)>1 && isnumeric(paramGray),  \n            % reshape both left and right\n            paramFlat = zeros(ds);\n            for h=1:2\n                % Corresponding coords on the flat map\n                coords = flat.coords{h}(:,flatIndices{h});            \n                switch lower(fnames{f})\n                    case {'b',  'beta'}\n                        for ii = 1:size(paramGray,1),  \n                            paramFlat(:,:,h,ii) = ...\n\t\t\t\t\t\t\t\tmyGriddata(coords, ...\n                                           paramGray(ii,grayIndices{h}).',  ...\n                                           mask(:,  :,h));\n                        end;\n                    otherwise,\n                        paramFlat(:,  :,h) = ...\n\t\t\t\t\t\t\tmyGriddata(coords, ...\n                                       paramGray(grayIndices{h}).', ...\n                                       mask(:, :,h));\n                end;\n            end\n            model{m} = rmSet(model{m},fnames{f},paramFlat); %#ok<AGROW>\n        end;\n    end;\nend;\nclose(waitHandle)\n\n% Now save output \n[p outputname] = fileparts(rmFile);\npathStr        = fullfile(dataDir(flat),outputname);\n\n% Overwrite?\nif exist(pathStr,'file')\n    saveFlag = questdlg([pathStr, ' already exists. Overwrite?'],  ...\n\t\t\t\t\t\t'Save model file?',  'Yes',  'No',  'No');\nelse\n    saveFlag = 'Yes';\nend\n\n% Save\nif strcmp(saveFlag, 'Yes')\n    save(pathStr, 'model', 'params');\n    flat = viewSet(flat, 'rmFile', pathStr);\n    fprintf(1, '[%s]:Saved %s.\\n', mfilename, pathStr);\nelse\n    fprintf(1, '[%s]:Model not saved.\\n', mfilename);\nend\n\n% If we transformed it, we probably want to view the data. Load the model.\nflat = rmSelect(flat, 1, [pathStr '.mat']);\nflat = rmLoadDefault(flat);\n\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Analysis/retinotopyModel/rmVol2flat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.14009138526944204}}
{"text": "function [ all_results ] = evaluate_average_precision_pascal( ...\n    all_bbox_gt, all_detected_bbox, classes, varargin)\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% 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\n%************************** OPTIONS *************************************\nip = inputParser;\nip.addParamValue('minoverlap', 0.5,   @isnumeric);\n\nip.parse(varargin{:});\nopts = ip.Results;\n\nminoverlap  = opts.minoverlap;\nall_results = compute_average_precision_of_detection(all_bbox_gt, all_detected_bbox, minoverlap);\n% fprintf('\\n~~~~~~~~~~~~~~~~~~~~\\n');\n% fprintf('Results:\\n');\n% aps = [all_results(:).ap]' * 100;\n% disp(mean(aps));\n% fprintf('~~~~~~~~~~~~~~~~~~~~\\n');\nend\n\nfunction [false_positives, true_positives] = find_detection_labels(bbox_detections, bbox_gt, is_difficult, minoverlap)\nfalse_positives = zeros(size(bbox_detections,1), 1);\ntrue_positives  = zeros(size(bbox_detections,1), 1);\noverlap         = zeros(size(bbox_detections,1), size(bbox_gt,1));\nnum_bbox_gt     = size(bbox_gt,1);\n\nfor j = 1:num_bbox_gt\n    overlap(:,j) = boxoverlap(bbox_detections(:,1:4), bbox_gt(j,1:4));\nend\n\noverlap(overlap==0) = -inf;\n[max_overlap, jmax] = max(overlap,[],2);\n\ndoes_overlap = max_overlap >= minoverlap;\n\nfalse_positives(~does_overlap) = 1; % false positive\n\ndoes_overlap = does_overlap & ~is_difficult(jmax); % dont care about the difficult ones\n\nif any(does_overlap) \n    bbox_indices = find(does_overlap);\n    jmax         = jmax(does_overlap);\n\n    for j = 1:num_bbox_gt\n        overlap_j = bbox_indices(jmax == j);\n        if ~isempty(overlap_j)\n            true_positives(overlap_j(1)) = 1; % true positive\n            if numel(overlap_j) > 1\n                false_positives(overlap_j(2:end)) = 1; % false positive - multiple detections\n            end\n        end      \n    end\nend\nend\n\nfunction all_results = compute_average_precision_of_detection(all_bbox_gt, all_detected_bbox, minoverlap)\nnum_imgs       = length(all_bbox_gt);\nnum_classes    = length(all_detected_bbox);\ntrue_positives   = cell(num_classes,1);\nfalse_positives  = cell(num_classes,1);\ndetection_scores = cell(num_classes,1);\n\nfor class_idx = 1:num_classes\n    true_positives{class_idx}   = cell(num_imgs,1);\n    false_positives{class_idx}  = cell(num_imgs,1);\n    detection_scores{class_idx} = cell(num_imgs,1);\nend\n\nnum_positives = zeros(num_classes, 1);\nfor img_idx = 1:num_imgs\n    for class_idx = 1:num_classes\n        ground_truth_idx = all_bbox_gt{img_idx}(:,5) == class_idx;\n        bbox_gt          = all_bbox_gt{img_idx}(ground_truth_idx,1:4);\n        is_difficult     = all_bbox_gt{img_idx}(ground_truth_idx,6) > 0;\n        num_positives(class_idx) = num_positives(class_idx) + sum(~is_difficult);\n\n        bbox_detections = all_detected_bbox{class_idx}{img_idx};\n        num_detections  = size(bbox_detections, 1);\n        if num_detections > 0\n            if isempty(bbox_gt)\n                false_positives{class_idx}{img_idx} = ones(num_detections, 1);\n                true_positives{class_idx}{img_idx}  = zeros(num_detections, 1);\n            else\n                [~, order]      = sort(bbox_detections(:,5), 'descend');\n                bbox_detections = bbox_detections(order, :);\n                \n                [false_positives{class_idx}{img_idx},...\n                    true_positives{class_idx}{img_idx}] = ...\n                        find_detection_labels(bbox_detections(:,1:4), ...\n                        bbox_gt, is_difficult, minoverlap);\n            end\n            detection_scores{class_idx}{img_idx} = double(bbox_detections(:,5));\n        end\n    end\nend\n\nall_results = compute_average_precision(true_positives, false_positives, ...\n    detection_scores, 1:num_classes, num_positives);\nend\n\nfunction res = compute_average_precision(true_positives, false_positives, detection_scores, class_indices, num_positives)\nfor class_idx = class_indices\n    all_true_positives  = cell2mat(true_positives{class_idx}(:));\n    all_false_positives = cell2mat(false_positives{class_idx}(:));\n    all_scores          = cell2mat(detection_scores{class_idx}(:));\n    [all_scores, order] = sort(all_scores, 'descend');\n    all_true_positives  = all_true_positives(order);\n    all_false_positives = all_false_positives(order);\n\n    % compute precision/recall\n    all_false_positives = cumsum(all_false_positives);\n    all_true_positives  = cumsum(all_true_positives);\n\n    recall    = all_true_positives  /  num_positives(class_idx);\n    precision = all_true_positives ./ (all_false_positives + all_true_positives);\n    f1_score  = 2 * (recall.*precision) ./ (recall + precision + eps);\n    [f1_score, max_idx] = max(f1_score);\n    f1_thresh    = all_scores(max_idx);\n    \n    % compute average precision\n    average_precion = 0;\n    for t=0:0.1:1\n        p = max(precision(recall>=t));\n        if ~isempty(p)\n            average_precion = average_precion + p/11;\n        end\n    end\n    ap_auc = xVOCap(recall, precision);\n    res(class_idx).recall    = recall;\n    res(class_idx).precision = precision;\n    res(class_idx).ap        = average_precion;\n    res(class_idx).ap_auc    = ap_auc;\n    res(class_idx).f1_score  = f1_score;\n    res(class_idx).f1_thresh = f1_thresh;\n%     fprintf('!!! %s : %.4f %.4f\\n', classes{class_idx}, average_precion, ap_auc);\nend\nend\n\nfunction ap = xVOCap(rec,prec)\nmrec=[0 ; rec ; 1];\nmpre=[0 ; prec ; 0];\nfor i=numel(mpre)-1:-1:1\n    mpre(i)=max(mpre(i),mpre(i+1));\nend\ni=find(mrec(2:end)~=mrec(1:end-1))+1;\nap=sum((mrec(i)-mrec(i-1)).*mpre(i));\nend\n", "meta": {"author": "gidariss", "repo": "mrcnn-object-detection", "sha": "2f355c0539961aa22f57d31971aa163a35f3152c", "save_path": "github-repos/MATLAB/gidariss-mrcnn-object-detection", "path": "github-repos/MATLAB/gidariss-mrcnn-object-detection/mrcnn-object-detection-2f355c0539961aa22f57d31971aa163a35f3152c/code/utils/evaluate_average_precision_pascal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.1397141409914883}}
{"text": "%-----------------------------------------------------------------------\n% Job saved on 08-Feb-2017 12:38:53 by cfg_util (rev $Rev: 7703 $)\n% spm SPM - SPM12 (12.3)\n% cfg_basicio BasicIO - Unknown\n%-----------------------------------------------------------------------\nmatlabbatch{1}.spm.meeg.source.headmodel.D = {''};\nmatlabbatch{1}.spm.meeg.source.headmodel.val = 1;\nmatlabbatch{1}.spm.meeg.source.headmodel.comment = '';\nmatlabbatch{1}.spm.meeg.source.headmodel.meshing.meshes.template = 1;\nmatlabbatch{1}.spm.meeg.source.headmodel.meshing.meshres = 2;\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(1).fidname = 'nas';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(1).specification.select = 'nas';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(2).fidname = 'lpa';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(2).specification.select = 'FIL_CTF_L';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(3).fidname = 'rpa';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.fiducial(3).specification.select = 'FIL_CTF_R';\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.useheadshape = 0;\nmatlabbatch{1}.spm.meeg.source.headmodel.forward.eeg = 'EEG BEM';\nmatlabbatch{1}.spm.meeg.source.headmodel.forward.meg = 'Single Shell';\nmatlabbatch{2}.spm.tools.beamforming.data.dir = '<UNDEFINED>';\nmatlabbatch{2}.spm.tools.beamforming.data.D(1) = cfg_dep('Head model specification: M/EEG dataset(s) with a forward model', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','D'));\nmatlabbatch{2}.spm.tools.beamforming.data.val = 1;\nmatlabbatch{2}.spm.tools.beamforming.data.gradsource = 'inv';\nmatlabbatch{2}.spm.tools.beamforming.data.space = 'MNI-aligned';\nmatlabbatch{2}.spm.tools.beamforming.data.overwrite = 0;\nmatlabbatch{3}.spm.tools.beamforming.sources.BF(1) = cfg_dep('Prepare data: BF.mat file', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{3}.spm.tools.beamforming.sources.reduce_rank = [2 3];\nmatlabbatch{3}.spm.tools.beamforming.sources.keep3d = 1;\nmatlabbatch{3}.spm.tools.beamforming.sources.plugin.grid.resolution = 10;\nmatlabbatch{3}.spm.tools.beamforming.sources.plugin.grid.space = 'MNI template';\nmatlabbatch{3}.spm.tools.beamforming.sources.visualise = 1;\nmatlabbatch{4}.spm.tools.beamforming.features.BF(1) = cfg_dep('Define sources: BF.mat file', substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{4}.spm.tools.beamforming.features.whatconditions.all = 1;\nmatlabbatch{4}.spm.tools.beamforming.features.woi = [-Inf Inf];\nmatlabbatch{4}.spm.tools.beamforming.features.modality = {'MEG'};\nmatlabbatch{4}.spm.tools.beamforming.features.fuse = 'no';\nmatlabbatch{4}.spm.tools.beamforming.features.plugin.cov.foi = [0 100];\nmatlabbatch{4}.spm.tools.beamforming.features.plugin.cov.taper = 'none';\nmatlabbatch{4}.spm.tools.beamforming.features.regularisation.manual.lambda = 5;\nmatlabbatch{4}.spm.tools.beamforming.features.bootstrap = false;\nmatlabbatch{5}.spm.tools.beamforming.inverse.BF(1) = cfg_dep('Covariance features: BF.mat file', substruct('.','val', '{}',{4}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{5}.spm.tools.beamforming.inverse.plugin.lcmv.orient = true;\nmatlabbatch{5}.spm.tools.beamforming.inverse.plugin.lcmv.keeplf = false;\nmatlabbatch{6}.spm.tools.beamforming.output.BF(1) = cfg_dep('Inverse solution: BF.mat file', substruct('.','val', '{}',{5}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.isdesign.custom.whatconditions.all = 1;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.isdesign.custom.contrast = [-1 1];\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.isdesign.custom.woi = [-100 0\n                                                                                   100 200];\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.datafeatures = 'sumpower';\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.foi = [5 15\n                                                                   15 30\n                                                                   30 60\n                                                                   60 90];\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.result = 'BIC';\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.sametrials = false;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_mv.modality = 'MEG';\nmatlabbatch{7}.spm.tools.beamforming.write.BF(1) = cfg_dep('Output: BF.mat file', substruct('.','val', '{}',{6}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{7}.spm.tools.beamforming.write.plugin.nifti.normalise = 'no';\nmatlabbatch{7}.spm.tools.beamforming.write.plugin.nifti.space = 'mni';\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/bf_pipeline_MVAR_two_conditions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.13971413797326923}}
{"text": "y = 17;\nx = (y + 3) / 2);", "meta": {"author": "101Hub", "repo": "Matlab101", "sha": "07273f68f1147a110443aeb121fa10962234f298", "save_path": "github-repos/MATLAB/101Hub-Matlab101", "path": "github-repos/MATLAB/101Hub-Matlab101/Matlab101-07273f68f1147a110443aeb121fa10962234f298/assets/\u300aMatlab\u7f16\u7a0b\u300b\u6e90\u7801/chap2/test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.13942465806836105}}
{"text": "\nfunction pass = example_graze_pair_filt(sicdmeta1, sicdmeta2)\n%EXAMPLE_GRAZE_PAIR_FILT An example image pair filter used by 'image_pair_search'\n% EXAMPLE_GRAZE_PAIR_FILT(sicdmeta1, sicdmeta) takes two SICD-compatible \n% structures and returns a boolean indicating pass/fail.  Any image/SICD\n% structure pair which yields a \"pass\" (boolean true) will be included in\n% the list returned by image_pair_search.\n%\n% Note: No this isn't a useful filter.  At all.  You should never use it.\n% We (i.e. you) should, of course, provide a filter specific to your\n% particular use.  This is meant to be a stub...\n%\n% Just FYI...  This filter will return images whos grazing angles are\n% within 5 degrees and have lat,lon locations within 0.001.  No.  There's\n% no real point to it.\n%\n% See Also:  example_graze_filt, write_SICD_KML_placemark, \n%            write_KML_header, write_KML_footer\n%\n% Author: Tom Krauss, NGA/IDT\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\n\n  pass = false;\n  \n  if isfield(sicdmeta1,'SCPCOA')  &&  ...\n     isfield(sicdmeta1.SCPCOA,'GrazeAng')  &&  ...\n     isfield(sicdmeta1, 'GeoData')  &&  ...\n     isfield(sicdmeta1.GeoData, 'SCP')  &&  ...\n     isfield(sicdmeta1.GeoData.SCP, 'LLH')  &&  ...\n     isfield(sicdmeta2,'SCPCOA')  &&  ...\n     isfield(sicdmeta2.SCPCOA,'GrazeAng')  &&  ...\n     isfield(sicdmeta2, 'GeoData')  &&  ...\n     isfield(sicdmeta1.GeoData, 'SCP')  &&  ...\n     isfield(sicdmeta2.GeoData.SCP, 'LLH')\n \n    if abs(sicdmeta1.SCPCOA.GrazeAng-sicdmeta2.SCPCOA.GrazeAng) < 5 && ...\n       abs(sicdmeta1.GeoData.SCP.LLH.Lat-sicdmeta2.GeoData.SCP.LLH.Lat) < 0.001 && ...\n       abs(sicdmeta1.GeoData.SCP.LLH.Lon-sicdmeta2.GeoData.SCP.LLH.Lon) < 0.001\n      pass = true;\n    end\n    \n  end\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED       ///\n% //////////////////////////////////////////\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/Visualization/image2kml/example_graze_pair_filt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.13863955954044932}}
{"text": "function [S,HDR,time] = sread(HDR,NoS,StartPos)\n% SREAD loads selected segments of signal file\n%\n% [S,HDR] = sread(HDR [,NoS [,StartPos]] )\n% NoS       Number of seconds, default = 1 (second)\n% StartPos  Starting position, if not provided the following data is read continously from the file. \n%                    no reposition of file pointer is performed\n%\n% HDR=sopen(Filename,'r',CHAN);\n% [S,HDR] = sread(HDR, NoS, StartPos)\n%      \treads NoS seconds beginning at StartPos\n% \n% [S,HDR] = sread(HDR, inf) \n%      \treads til the end starting at the current position \n% \n% [S,HDR] = sread(HDR, N*HDR.Dur) \n%\treads N trials of an BKR file \n% \n%\n% See also: fread, SREAD, SWRITE, SCLOSE, SSEEK, SREWIND, STELL, SEOF\n\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 3\n% of the License, or (at your option) any later version.\n\n%\t$Id: sread.m 2619 2011-02-14 10:25:07Z schloegl $\n%\t(C) 1997-2005,2007,2008 by Alois Schloegl <a.schloegl@ieee.org>\t\n%    \tThis is part of the BIOSIG-toolbox http://biosig.sf.net/\n\nS = [];\ntime = []; \n\nif nargin<2, \n        NoS = inf; \nend;\n\nif ~isnumeric(NoS) || (NoS<0),\n        fprintf(HDR.FILE.stderr,'Error SREAD: NoS must be non-negative number\\n');\n        return;\nend;\nif (nargin>=3) \n        if (StartPos<0),\n                fprintf(HDR.FILE.stderr,'Error SREAD: StartPos must be non-negative\\n');\n                return;\n        end;\n        tmp = HDR.SampleRate*StartPos;\n        if tmp ~= round(tmp),\n        %        fprintf(HDR.FILE.stderr,'Warning SREAD: StartPos yields non-integer position\\n');\n                StartPos = round(tmp)/HDR.SampleRate;\n        end;\nelse\n        StartPos = HDR.FILE.POS/HDR.SampleRate; \nend;\n\ntmp = HDR.SampleRate*NoS;\nif tmp ~= round(tmp),\n        fprintf(HDR.FILE.stderr,'Warning SREAD: NoS yields non-integer position [%f, %f]\\n',NoS,HDR.SampleRate);\n        NoS = round(tmp)/HDR.SampleRate;\nend;\n\n% define HDR.out.EVENT. This is used by EEGLAB. \nix = (HDR.EVENT.POS >= StartPos*HDR.SampleRate) & (HDR.EVENT.POS <= (StartPos+NoS)*HDR.SampleRate); \nHDR.out.EVENT.POS = HDR.EVENT.POS(ix)-StartPos;\nHDR.out.EVENT.TYP = HDR.EVENT.TYP(ix);\nif isfield(HDR.EVENT,'CHN')\n        if ~isempty(HDR.EVENT.CHN)\n                HDR.out.EVENT.CHN = HDR.EVENT.CHN(ix);\n        end;\nend;\nif isfield(HDR.EVENT,'DUR')\n        if ~isempty(HDR.EVENT.DUR)\n                HDR.out.EVENT.DUR = HDR.EVENT.DUR(ix);\n        end;\nend;\n\nSTATUS = 0; \nif isfield(HDR,'THRESHOLD')     % save THRESHOLD status (will be modified in BKR);\n        THRESHOLD = HDR.THRESHOLD; \nend\nFLAG_CALIB_DONE = 0; \n\nif 0, \nelseif strcmp(HDR.TYPE,'BDF'),\n        if nargin==3,\n                HDR.FILE.POS = round(HDR.SampleRate*StartPos);\n        end;\n\n        nr     = min(HDR.NRec*HDR.SPR-HDR.FILE.POS, NoS*HDR.SampleRate);\n\tblock1 = floor(HDR.FILE.POS/HDR.SPR);\n\tix1    = HDR.FILE.POS - block1*HDR.SPR;\t% starting sample (minus one) within 1st block \n\tnb     = ceil((HDR.FILE.POS+nr)/HDR.SPR)-block1;\n    \tfp     = HDR.HeadLen + block1*HDR.AS.bpb;\n    \tstatus = fseek(HDR.FILE.FID, fp, 'bof');\n\n\tcount  = 0;\n        if HDR.NS==0,\n\n        else\n                if (HDR.AS.spb*nb<=2^22), % faster access\n\t\t\tS  = repmat(NaN,HDR.SPR*nb,length(HDR.InChanSelect)); \n                        [s,c] = fread(HDR.FILE.FID,[3*HDR.AS.spb, nb],'uint8');\n                        s = reshape(2.^[0,8,16]*reshape(s(:),3,c/3),[HDR.AS.spb, nb]);\n                        c = c/3;\n                        for k = 1:length(HDR.InChanSelect),\n                               K = HDR.InChanSelect(k);\n                               if (HDR.AS.SPR(K)>0)\n                                       S(:,k) = rs(reshape(s(HDR.AS.bi(K)+1:HDR.AS.bi(K+1),:),HDR.AS.SPR(K)*nb,1),HDR.AS.SPR(K),HDR.SPR);\n                               else\n                                       S(:,k) = NaN;\n                               end;\n                        end;\n                        S = S(ix1+1:ix1+nr,:);\n                        count = nr;\n\n                        if HDR.FLAG.OVERFLOWDETECTION,  % BDF overflow detection is based on Status bit20\n\t                        K = HDR.BDF.Status.Channel;\n        \t                OVERFLOW = ~bitand(reshape(s(HDR.AS.bi(K)+1:HDR.AS.bi(K+1),:),HDR.AS.SPR(K)*nb,1),2^19);\n        \t                OVERFLOW = rs(OVERFLOW,HDR.AS.SPR(K),HDR.SPR);\n\t                        OVERFLOW = OVERFLOW(ix1+1:ix1+nr,:);\n        \t                S(OVERFLOW>0,:)=NaN; \n        \t        end;        \n                else\n\t\t\tS      = repmat(NaN,nr,length(HDR.InChanSelect)); \n                        while (count<nr);\n                                len   = ceil(min([(nr-count)/HDR.SPR,2^22/HDR.AS.spb]));\n                                [s,c] = fread(HDR.FILE.FID,[3*HDR.AS.spb, len],'uint8=>uint8');\n                                s1    = zeros(HDR.SPR*c/(3*HDR.AS.spb),length(HDR.InChanSelect));\n                                for k = 1:length(HDR.InChanSelect), \n                                        K = HDR.InChanSelect(k);\n                                        tmp = 2.^[0,8,16]*double(reshape(s(HDR.AS.bi(K)*3+1:HDR.AS.bi(K+1)*3,:),3,HDR.AS.SPR(K)*c/HDR.AS.bpb));\n                                        if (HDR.AS.SPR(K)>0)\n                                                s1(:,k) = rs(tmp',HDR.AS.SPR(K),HDR.SPR);\n                                        else\n                                                s1(:,k) = NaN;\n                                        end;\n                                end;\n\t                        if HDR.FLAG.OVERFLOWDETECTION,  % BDF overflow detection is based on Status bit20\n\t\t                        K = HDR.BDF.Status.Channel;\n                                        tmp = 2.^[0,8,16]*double(reshape(s(HDR.AS.bi(K)*3+1:HDR.AS.bi(K+1)*3,:),3,HDR.AS.SPR(K)*c/HDR.AS.bpb));\n                                        OVERFLOW = rs(~bitand(tmp',2^19),HDR.AS.SPR(K),HDR.SPR);\n\t        \t                s1(OVERFLOW>0,:)=NaN; \n\t        \t        end;        \n                                ix2   = min(nr-count, size(s1,1)-ix1);\n                                S(count+1:count+ix2,:) = s1(ix1+1:ix1+ix2,:);\n                                count = count+ix2;\n                                ix1   = 0; \n                        end;\t\n                end;\n                HDR.FILE.POS = HDR.FILE.POS + count;\n                S = S - 2^24*(S>=2^23);\n        end\n\nelseif strcmp(HDR.TYPE,'EDF') || strcmp(HDR.TYPE,'GDF') || strcmp(HDR.TYPE,'BDF') || strcmp(HDR.TYPE,'ACQ'),\n\t% experimental, might replace SDFREAD.M \n        if nargin==3,\n                HDR.FILE.POS = round(HDR.SampleRate*StartPos);\n        end;\n\n        nr     = min(HDR.NRec*HDR.SPR-HDR.FILE.POS, NoS*HDR.SampleRate);\n\tS      = repmat(NaN,nr,length(HDR.InChanSelect)); \n\n\tblock1 = floor(HDR.FILE.POS/HDR.SPR);\n\tix1    = HDR.FILE.POS- block1*HDR.SPR;\t% starting sample (minus one) within 1st block \n\tnb     = ceil((HDR.FILE.POS+nr)/HDR.SPR)-block1;\n    \tfp     = HDR.HeadLen + block1*HDR.AS.bpb;\n    \tSTATUS = fseek(HDR.FILE.FID, fp, 'bof');\n        count  = 0;\n        if HDR.NS==0,\n        elseif all(HDR.GDFTYP==HDR.GDFTYP(1)),\n                if (HDR.AS.spb*nb<=2^24), % faster access\n                        S = [];\n                        %[HDR.AS.spb, nb,block1,ix1,HDR.FILE.POS],\n                        [s,c] = fread(HDR.FILE.FID,[HDR.AS.spb, nb],gdfdatatype(HDR.GDFTYP(1)));\n                        for k = 1:length(HDR.InChanSelect),\n                               K = HDR.InChanSelect(k);\n                               if (HDR.AS.SPR(K)>0)\n                                       S(:,k) = rs(reshape(s(HDR.AS.bi(K)+1:HDR.AS.bi(K+1),:),HDR.AS.SPR(K)*nb,1),HDR.AS.SPR(K),HDR.SPR);\n                               else\n                                       S(:,k) = NaN;\n                               end;\n                        end;\n                        S = S(ix1+1:ix1+nr,:);\n                        count = nr;\n                else\n                        S = repmat(NaN,[nr,length(HDR.InChanSelect)]);\n                        while (count<nr);\n                                len   = ceil(min([(nr-count)/HDR.SPR,2^22/HDR.AS.spb]));\n                                [s,c] = fread(HDR.FILE.FID,[HDR.AS.spb, len],gdfdatatype(HDR.GDFTYP(1)));\n                                s1    = zeros(HDR.SPR*c/HDR.AS.spb,length(HDR.InChanSelect));\n                                for k = 1:length(HDR.InChanSelect), \n                                        K = HDR.InChanSelect(k);\n                                        if (HDR.AS.SPR(K)>0)\n                                                tmp = reshape(s(HDR.AS.bi(K)+1:HDR.AS.bi(K+1),:),HDR.AS.SPR(K)*c/HDR.AS.spb,1);\n                                                s1(:,k) = rs(tmp,HDR.AS.SPR(K),HDR.SPR);\n                                        end;\n                                end;\n                                ix2   = min(nr-count, size(s1,1)-ix1);\n                                S(count+1:count+ix2,:) = s1(ix1+1:ix1+ix2,:);\n                                count = count+ix2;\n                                ix1   = 0; \n                        end;\t\n                end;\n        else\n                fprintf(2,'SREAD (GDF): different datatypes - this might take some time.\\n');\n                \n                S = repmat(NaN,[nr,length(HDR.InChanSelect)]);\n                while (count<nr);\n                        s = [];\n                        for k=1:length(HDR.AS.TYP),\n                                [s0,tmp] = fread(HDR.FILE.FID,[HDR.AS.c(k), 1],gdfdatatype(HDR.AS.TYP(k)));\n                                s = [s;s0];\n                        end;\n                        \n                        s1    = repmat(NaN,[HDR.SPR,length(HDR.InChanSelect)]);\n                        for k = 1:length(HDR.InChanSelect), \n                                K = HDR.InChanSelect(k);\n                                if (HDR.AS.SPR(K)>0)\n                                        s1(:,k) = rs(s(HDR.AS.bi(K)+1:HDR.AS.bi(K+1),:),HDR.AS.SPR(K),HDR.SPR);\n                                end;\n                        end;\n                        ix2   = min(nr-count, size(s1,1)-ix1);\n                        S(count+1:count+ix2,:) = s1(ix1+1:ix1+ix2,:);\n                        count = count+HDR.SPR;\n                        ix1   = 0; \n                end;\t\n        end;\n        if strcmp(HDR.TYPE,'GDF')       % read non-equidistant sampling channels of GDF2.0 format\n                if (HDR.VERSION>1.94) %& isfield(HDR.EVENT,'VAL'),\n                        for k = 1:length(HDR.InChanSelect), \n                                ch = HDR.InChanSelect(k);\n                                if (HDR.AS.SPR(ch)==0),\n                                        ix = find((HDR.EVENT.TYP==hex2dec('7fff')) & (HDR.EVENT.CHN==ch));\n                                        pix= HDR.EVENT.POS(ix)-HDR.FILE.POS;\n                                        ix1= find((pix > 0) & (pix <= count));\n                                        S(pix(ix1),k)=HDR.EVENT.DUR(ix(ix1));\n                                end;\n                        end;\n                end;\n        end\n        HDR.FILE.POS = HDR.FILE.POS + count;\n        \n        \nelseif strcmp(HDR.TYPE,'AINF'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*StartPos*2*(HDR.NS+2),'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        %[S,count] = fread(HDR.FILE.FID,[HDR.NS+2,HDR.SampleRate*NoS],'int16');\n        nr = min(HDR.SampleRate*NoS, HDR.SPR*HDR.NRec-HDR.FILE.POS);\n        S  = []; \n\ttime = [];\n        count = 0; \n        while (count<nr),\n               \t[s,c] = fread(HDR.FILE.FID, [HDR.NS+2, min(nr-count,floor(2^24/HDR.NS))], 'int16');\n\t\tif nargout>2,\n\t\t\ttime  = [time; [s(1:2,:)'+2^16*(s(1:2,:)'<0)]*(2.^[16;0])];\n\t\tend;\t\n               \tS = [S; s(2+HDR.InChanSelect,:)'];\n              \tcount = count + c/(HDR.NS+2); \n\tend; \n        HDR.FILE.POS = HDR.FILE.POS + count;\n        \n        \nelseif strmatch(HDR.TYPE,{'BKR'}),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*HDR.NS*StartPos*2,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        [S,count] = fread(HDR.FILE.FID,[HDR.NS,HDR.SampleRate*NoS],'int16');\n        if ~isempty(S),\n                S = S(HDR.InChanSelect,:)';\n                HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n\telse\n\t\tS = zeros(0,length(HDR.InChanSelect));\t\t\n        end;\n        THRESHOLD(HDR.AS.TRIGCHAN,:)=NaN; % do not apply overflow detection for Trigger channel \n\n        \nelseif strmatch(HDR.TYPE,{'AIF','SND','WAV','Sigma'})\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*HDR.AS.bpb*StartPos,'bof');\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        maxsamples = min(HDR.SPR*HDR.NRec - HDR.FILE.POS, HDR.SampleRate*NoS);\n        [S,count] = fread(HDR.FILE.FID,[HDR.NS,maxsamples], gdfdatatype(HDR.GDFTYP));\n\n        S = S(HDR.InChanSelect,:)';\n        HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n        \n        if ~HDR.FLAG.UCAL,\n                if isfield(HDR.FILE,'TYPE')\n                        if HDR.FILE.TYPE==1,\n                                S = mu2lin(S);\n                        end;\n                end;\n        end;\n\n        \nelseif strmatch(HDR.TYPE,{'BLSC2','CFWB','CNT','DEMG','DDT','ET-MEG','ISHNE','Nicolet','RG64'}),\n\n\ttc = strcmp(HDR.TYPE,'CFWB') && isfield(HDR,'FLAG') && isfield(HDR.FLAG,'TimeChannel') && HDR.FLAG.TimeChannel;\n\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.AS.bpb*round(HDR.SampleRate*StartPos),'bof');\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        if strcmpi(HDR.FLAG.OUTPUT,'single'),\n\t\tDT = [gdfdatatype(HDR.GDFTYP),'=>single'];\n        elseif any(HDR.GDFTYP==[1:6,16]) && ~exist('OCTAVE_VERSION','builtin'),\n        \t% preserve data type\n\t\tDT = ['*',gdfdatatype(HDR.GDFTYP)];\n\telse\n\t\t% convert to double\n\t\tDT = [gdfdatatype(HDR.GDFTYP)];\n        end;\n        maxsamples = min(HDR.SampleRate*NoS, HDR.NRec*HDR.SPR-HDR.FILE.POS);\n\tS = []; count = 0;\n\twhile maxsamples>0,\n\t\t% the maximum block size of 2^23 is a heuristical value \n    \t\t[s,c] = fread(HDR.FILE.FID, [HDR.NS+tc,min(2^23/HDR.NS,maxsamples)], DT);\n    \t\tc = c/(HDR.NS+tc);\n\t\tcount = count + c;\n\t\tmaxsamples = maxsamples - c;\n        \tif c>0,\n            \t\tS = [S; s(HDR.InChanSelect+tc,:)'];\n            \telse \n\t\t        fprintf(HDR.FILE.stderr,'Warning SREAD(%s): could not read %i samples, only %i samples read\\n',HDR.TYPE,maxsamples+count,count);\n            \t\tbreak; \t\n    \t\tend;\n        end;\n\tHDR.FILE.POS = HDR.FILE.POS + count;\n\n\nelseif strcmp(HDR.TYPE,'EPL'),\n        if nargin==3,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        startblock = floor(HDR.FILE.POS/HDR.SPR);\n        STATUS   = fseek(HDR.FILE.FID, HDR.HeadLen + startblock*HDR.AS.bpb, 'bof'); % fseek needed because HDR.FILE.POS can be changed by SSEEK\n        curblock = startblock;\n        endpos   = min(HDR.FILE.POS+NoS*HDR.SampleRate, HDR.NRec*HDR.SPR);\n\n        [datablock,count] = fread(HDR.FILE.FID, [(1+HDR.NS)*HDR.SPR,ceil(endpos/HDR.SPR)-startblock], 'int16');\n        datablock = reshape(datablock(256+1:end,:),HDR.NS,HDR.SPR*size(datablock,2))'; % remove mark track, and reshape data  \n\n        S = datablock(HDR.FILE.POS-startblock*HDR.SPR+1:endpos-startblock*HDR.SPR,HDR.InChanSelect); \n        HDR.FILE.POS = HDR.FILE.POS + size(S,1);\n\n\nelseif strcmp(HDR.TYPE,'SMA'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*HDR.AS.bpb*StartPos,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        tmp = min(NoS*HDR.SampleRate,(HDR.NRec*HDR.SPR-HDR.FILE.POS));\n        [S,count] = fread(HDR.FILE.FID,[HDR.NS,tmp],'float32'); % read data frame\n        tmp = HDR.NS*tmp;\n        if count < tmp,\n                fprintf(HDR.FILE.stderr,'Warning SREAD SMA: only %i out of %i samples read\\n',count/HDR.NS,tmp/HDR.NS);\n        end;\n        S = S(HDR.InChanSelect,:)';\n        HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n        \n        HDR.SMA.events = diff(sign([HDR.Filter.T0',S(HDR.SMA.EVENT_CHANNEL,:)]-HDR.SMA.EVENT_THRESH))>0;\n        HDR.EVENT.POS = find(HDR.SMA.events);\n        HDR.EVENT.TYP = HDR.SMA.events(HDR.EVENT.POS);\n        \n        if size(S,2) > 0,\n                HDR.Filter.T0 = S(HDR.SMA.EVENT_CHANNEL,size(S,2))';\n        end;\n        \n        \nelseif strcmp(HDR.TYPE,'RDF'),\n        S = [];\n        if nargin>2,\n                HDR.FILE.POS = StartPos;\n        end;\n        POS = HDR.FILE.POS;\n        \n        NoSeg = min(NoS,length(HDR.Block.Pos)-HDR.FILE.POS);\n        count = 0;\n        S = zeros(NoSeg*HDR.SPR, length(HDR.InChanSelect));\n        \n        for k = 1:NoSeg,\n                STATUS = fseek(HDR.FILE.FID,HDR.Block.Pos(POS+k),-1);\n                \n                % Read nchans and block length\n                tmp = fread(HDR.FILE.FID,34+220,'uint16');\n                \n                %STATUS = fseek(HDR.FILE.FID,2,0);\n                nchans = tmp(2); %fread(HDR.FILE.FID,1,'uint16');\n                %fread(HDR.FILE.FID,1,'uint16');\n                block_size = tmp(4); %fread(HDR.FILE.FID,1,'uint16');\n                %ndupsamp = fread(HDR.FILE.FID,1,'uint16');\n                %nrun = fread(HDR.FILE.FID,1,'uint16');\n                %err_detect = fread(HDR.FILE.FID,1,'uint16');\n                %nlost = fread(HDR.FILE.FID,1,'uint16');\n                nevents = tmp(9); %fread(HDR.FILE.FID,1,'uint16');\n                %STATUS = fseek(HDR.FILE.FID,50,0);\n                \n                [data,c] = fread(HDR.FILE.FID,[nchans,block_size],'int16');\n                %S = [S; data(HDR.InChanSelect,:)']; \t% concatenate data blocks\n                S((k-1)*HDR.SPR+(1:c/nchans),:) = data(HDR.InChanSelect,:)';\n                count = count + c;\n        end;\n        HDR.FILE.POS = HDR.FILE.POS + NoSeg; \n        \n        \nelseif strcmp(HDR.TYPE,'LABVIEW'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*HDR.AS.bpb*StartPos,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        [S,count] = fread(HDR.FILE.FID,[HDR.NS,HDR.SampleRate*NoS],'int32');\n        if count,\n                S = S(HDR.InChanSelect,:)';\n                HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n        end;\n        \n        \nelseif strcmp(HDR.TYPE,'alpha'),\n        if nargin==3,\n                POS = HDR.SampleRate*StartPos*HDR.AS.bpb/HDR.SPR;\n                if POS~=ceil(POS),\n                        fprintf(HDR.FILE.stderr,'warning SREAD (alpha): starting position is non-integer (%f)\\n',POS);     \n                end\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen + POS,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        \n        nr = min(HDR.SampleRate*NoS, HDR.NRec*HDR.SPR-HDR.FILE.POS)*HDR.AS.bpb;\n        if (nr - round(nr)) < .01,\n    \t\tnr = round(nr);\n\telse\n\t        fprintf(HDR.FILE.stderr,'Error SREAD (alpha): can not deal with odd number of samples \\n');     \n                return;\n        end\n        \n        if HDR.Bits==12,\n                [s,count] = fread(HDR.FILE.FID,[3,nr/3],'uint8');\n                s(1,:) = s(1,:)*16 + floor(s(2,:)/16); \t\n                s(3,:) = s(3,:)+ mod(s(2,:),16)*256; \t\n                s = reshape(s([1,3],:),2*size(s,2),1);\n                s = s - (s>=2^11)*2^12;\n\t\tnr = floor(length(s)/HDR.NS);\n                S = reshape(s(1:nr*HDR.NS),HDR.NS,nr);\n                count = count*2/3;\n                \n        elseif HDR.Bits==16,\n                [S,count] = fread(HDR.FILE.FID,[HDR.NS,nr],'int16');\n                \n        elseif HDR.Bits==32,\n                [S,count] = fread(HDR.FILE.FID,[HDR.NS,nr],'int32');\n        end;        \n        \n        if count,\n                S = S(HDR.InChanSelect,:)';\n                HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n        end;\n\n                \nelseif strcmp(HDR.TYPE,'MIT'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.SampleRate*HDR.AS.bpb*StartPos,'bof');        \n                tmp = HDR.SampleRate*StartPos;\n                if HDR.FILE.POS~=tmp,\n                        HDR.mode8.accu = zeros(1,length(HDR.InChanSelect));\n                        HDR.mode8.valid= 0;\n                end;\n        end;\n\n        DataLen = NoS*HDR.SampleRate/HDR.SPR;\n        if HDR.VERSION == 212, \n                [A,count] = fread(HDR.FILE.FID, [1,DataLen*HDR.AS.bpb], 'uint8');  % matrix with 3 rows, each 8 bits long, = 2*12bit\n\t\tDataLen = floor(count/HDR.AS.bpb);\n\t\tif (count~= DataLen*HDR.AS.bpb) && isfinite(DataLen),\n\t\t\tfprintf(HDR.FILE.stderr,'Warning SREAD (MIT): non-integer block length %i,%f\\n',count, DataLen*HDR.AS.bpb);\n\t\t\t%HDR = sseek(HDR,HDR.FILE.POS,'bof');\n\t\t\t%return;\n                        A = A(1:DataLen*HDR.AS.bpb);\n\t\tend;\n                S = [A(1:3:end) + mod(A(2:3:end),16)*256; A(3:3:end) + floor(A(2:3:end)/16)*256]; \n                clear A;\n                S = S - 2^12*(S>=2^11);\t% 2-th complement\n                S = reshape(S,HDR.AS.spb,prod(size(S))/HDR.AS.spb)';\n                \n        elseif HDR.VERSION == 310, \n                [A,count] = fread(HDR.FILE.FID, [HDR.AS.bpb/2, DataLen], 'uint16'); \n                A = A'; DataLen = count/HDR.AS.bpb*2; \n                for k = 1:ceil(HDR.AS.spb/3),\n                        k1=3*k-2; k2=3*k-1; k3=3*k;\n                        S(:,3*k-2) = floor(mod(A(:,k*2-1),2^12)/2);\t\n                        S(:,3*k-1) = floor(mod(A(:,k*2),2^12)/2);\t\n                        S(:,3*k  ) = floor(A(:,k*2-1)*(2^-11)) + floor(A(:,k*2)*(2^-11))*2^5; \n                        S = mod(S(:,1:HDR.AS.spb),2^10);\n                        S = S - 2^10*(S>=2^9);\t% 2-th complement\n                end;\n\t\tS = S;\n                \n        elseif HDR.VERSION == 311, \n                [A,count] = fread(HDR.FILE.FID, [HDR.AS.bpb/4, DataLen], 'uint32');\n                A = A'; DataLen = count/HDR.AS.bpb*4;\n                for k = 1:ceil(HDR.AS.spb/3),\n                        S(:,3*k-2) = mod(A(:,k),2^10);\t\n                        S(:,3*k-1) = mod(floor(A(:,k)*2^(-11)),2^10);\t\n                        S(:,3*k)   = mod(floor(A(:,k)*2^(-22)),2^10);\t\n                        S = S(:,1:HDR.AS.spb);\n                        S = S - 2^10*(S>=2^9);\t% 2-th complement\n                end;\n\t\tS = S';\n                \n        elseif HDR.VERSION == 8, \n                [S,count] = fread(HDR.FILE.FID, [HDR.AS.spb,DataLen], 'int8');  \n                S = S'; DataLen = count/HDR.AS.spb          \n                \n        elseif HDR.VERSION == 80, \n                [S,count] = fread(HDR.FILE.FID, [HDR.AS.spb,DataLen], 'uint8');  \n                S = S'-128; DataLen = count/HDR.AS.spb;\n                \n        elseif HDR.VERSION == 160, \n                [S,count] = fread(HDR.FILE.FID, [HDR.AS.spb,DataLen], 'uint16');  \n                S = S'-2^15; DataLen = count/HDR.AS.spb;\n                \n        elseif HDR.VERSION == 16, \n                [S,count] = fread(HDR.FILE.FID, [HDR.AS.spb,DataLen], 'int16'); \n                S = S'; DataLen = count/HDR.AS.spb;\n                \n        elseif HDR.VERSION == 61, \n                [S,count] = fread(HDR.FILE.FID, [HDR.AS.spb,DataLen], 'int16'); \n                S = S'; DataLen = count/HDR.AS.spb;\n                \n        else\n                fprintf(2, 'ERROR MIT-ECG: format %i not supported.\\n',HDR.VERSION); \n                \n        end;\n        if any(HDR.AS.SPR>1),\n                A = S;\n                S = zeros(size(A,1)*HDR.SPR,length(HDR.InChanSelect));\n                for k = 1:length(HDR.InChanSelect),\n                        ch = HDR.InChanSelect(k);\n                        ix = HDR.AS.bi(ch)+1:HDR.AS.bi(ch+1);\n                        S(:,k)=rs(reshape(A(:,ix)',size(A,1)*HDR.AS.SPR(ch),1),HDR.AS.SPR(ch),HDR.SPR);\n                end\n        else\n                S = S(:,HDR.InChanSelect);\n        end\n        if HDR.VERSION == 8, \n                if HDR.FILE.POS==0,\n                        HDR.mode8.accu = zeros(1,length(HDR.InChanSelect));\n                        HDR.mode8.valid= 1;\n                end; \n                if ~HDR.mode8.valid;\n                        fprintf(2,'Warning SREAD: unknown offset (TYPE=MIT, mode=8) \\n');\n                else\n                        S(1,:) = S(1,:) + HDR.mode8.accu;\n                end;        \n                S = cumsum(S);\n                HDR.mode8.accu = S(size(S,1),:);\n\tend;\n        HDR.FILE.POS = HDR.FILE.POS + DataLen;   \t\n        \n        \nelseif strcmp(HDR.TYPE,'TMS32'),\n        if nargin==3,\n                HDR.FILE.POS = round(HDR.SampleRate*StartPos);\n        end;\n\n\tblockN = floor(HDR.FILE.POS/HDR.SPR);\n\tix1    = HDR.FILE.POS- blockN*HDR.SPR;\t% starting sample (minus one) within 1st block \n    \tfp     = HDR.HeadLen + blockN*HDR.AS.bpb;\n    \tstatus = fseek(HDR.FILE.FID, fp, 'bof');\n\n        nr     = min(HDR.AS.endpos-HDR.FILE.POS, NoS*HDR.SampleRate);\n\tS      = repmat(NaN,nr,length(HDR.InChanSelect)); \n\tcount  = 0;\n\n        fread(HDR.FILE.FID,86,'uint8');\n    \twhile (count<nr) && ~feof(HDR.FILE.FID),\n                if all(HDR.GDFTYP==HDR.GDFTYP(1))\n                        [s,c] = fread(HDR.FILE.FID,[HDR.NS,HDR.SPR],gdfdatatype(HDR.GDFTYP(1)));\n                else\n                        s = repmat(NaN,HDR.NS,HDR.SPR);\n\t\t\tc = 0;\n                        for k1 = 1:HDR.SPR,\n                                for k2 = 1:HDR.NS,\n                                        [s(k2,k1),c2] = fread(HDR.FILE.FID,1,gdfdatatype(HDR.GDFTYP(k2)));\n                                end;\n                        end;\n                end;\n\t\tix2 = min(nr-count, size(s,2)-ix1);\n\t\tS(count+1:count+ix2,:) = s(HDR.InChanSelect, ix1+1:ix1+ix2)';\n\t\tcount = count + ix2; \n\t\tix1 = 0;\t% reset starting index, \n                fread(HDR.FILE.FID,86,'uint8');\n        end;\n\tHDR.FILE.POS = HDR.FILE.POS + count;\n        \n        \nelseif strcmp(HDR.TYPE,'EGI'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.AS.bpb*StartPos,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        \n        if HDR.FLAG.TRIGGERED,\n                NoS = min(NoS,(HDR.NRec-HDR.FILE.POS));\n                S = zeros(NoS*HDR.SPR,length(HDR.InChanSelect))+NaN;\n                for i = (1:NoS),\n                        SegmentCatIndex(HDR.FILE.POS+i) = fread(HDR.FILE.FID,1,'uint16');\n                        SegmentStartTime(HDR.FILE.POS+i) = fread(HDR.FILE.FID,1,'uint32');\n                        \n                        [s,count] = fread(HDR.FILE.FID, [HDR.NS + HDR.EGI.N, HDR.SPR*HDR.NRec], gdfdatatype(HDR.GDFTYP));\n                        tmp = (HDR.NS + HDR.EGI.N) * HDR.SPR;\n\t                if isfinite(tmp) && (count < tmp),\n                                fprintf(HDR.FILE.stderr,'Warning SREAD EGI: only %i out of %i samples read\\n',count,tmp);\n                        end;\n                        HDR.FILE.POS = HDR.FILE.POS + count/tmp;\n                        \n                        if (HDR.EGI.N > 0),\n                                [HDR.EVENT.POS,HDR.EVENT.CHN,HDR.EVENT.TYP] = find(s(HDR.NS+1:size(s,1),:)');\n\t                        HDR.EVENT.DUR = ones(size(HDR.EVENT.POS)); \n                        end \n                        S((i-1)*HDR.SPR + (1:size(s,2)),:) = s(HDR.InChanSelect,:)';\n                end;\n        else\n                [S,count] = fread(HDR.FILE.FID,[HDR.NS + HDR.EGI.N, HDR.SampleRate*NoS],gdfdatatype(HDR.GDFTYP));\n                tmp = HDR.SampleRate * NoS;\n                if isfinite(tmp) && (count < tmp),\n                        fprintf(HDR.FILE.stderr,'Warning SREAD EGI: only %i out of %i samples read\\n',count,tmp);\n                end;\n                HDR.FILE.POS = HDR.FILE.POS + round(count/(HDR.NS + HDR.EGI.N));\n                S = S(HDR.InChanSelect,:)';\n        end;\n        \n        \nelseif strcmp(HDR.TYPE,'AVG'),\n        S = repmat(nan,HDR.SPR,HDR.NS);\n        count = 0;\n        for i = 1:HDR.NS, \n                [tmp,c]     = fread(HDR.FILE.FID,5,'uint8'); % no longer used \n                count = count + c;\n                [S(:,i), c] = fread(HDR.FILE.FID,HDR.SPR,'float');\n                count = count + c*4;\n        end\n        S = S(:,HDR.InChanSelect);\n        HDR.FILE.POS = HDR.FILE.POS + count/HDR.AS.bpb;\n        \n        \nelseif strcmp(HDR.TYPE,'COH'),\n        warning('.COH data not tested yet')\n        if (prod(size(NoS))==1) && (nargin>2), \n                rows = NoS; cols = StartPos;\n        elseif prod(size(NoS))==2\n                rows = NoS(1); cols = NoS(2);\n        else\n                fprintf(HDR.FILE.stderr,'Error SREAD mode=COH: invalid arguments.\\n');\n        end;\n        \n        STATUS = fseek(HDR.FILE.FID,HDR.COH.directory(rows,cols)+8,'bof'); % skip over a small unused header of 8 bytes \n        sr = fread(HDR.FILE.FID, HDR.SPR, 'float32');  % read real part of coherence    \n        si = fread(HDR.FILE.FID, HDR.SPR, 'float32');  % read imag part of coherence    \n        S = sr + i * si;\n        \n        \nelseif strcmp(HDR.TYPE,'CSA'),\n        warning('.CSA data not tested yet')\n        S = fread(HDR.FILE.FID, [HDR.NRec*(HDR.SPR+6)*HDR.NS], 'float32');\t        \n        \n        \nelseif strcmp(HDR.TYPE,'EEG'),\n        if nargin>2,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.AS.bpb*StartPos,'bof');        \n        end;\n        \n        NoS = min(NoS, HDR.NRec-HDR.FILE.POS);\n        S   = zeros(NoS*HDR.SPR, length(HDR.InChanSelect));\n        count = 0;\n        for i = 1:NoS, %h.compsweeps,\n                h.sweep(i).accept   = fread(HDR.FILE.FID,1,'uchar');\n                tmp\t\t    = fread(HDR.FILE.FID,2,'ushort');\n                h.sweep(i).ttype    = tmp(1);\n                h.sweep(i).correct  = tmp(2);\n                h.sweep(i).rt       = fread(HDR.FILE.FID,1,'float32');\n                tmp  \t\t    = fread(HDR.FILE.FID,2,'ushort');\n                h.sweep(i).response = tmp(1);\n                h.sweep(i).reserved = tmp(2);\n                \n                [signal,c] = fread(HDR.FILE.FID, [HDR.NS,HDR.SPR], gdfdatatype(HDR.GDFTYP));\n                \n                S(i*HDR.SPR+(1-HDR.SPR:0),:) = signal(HDR.InChanSelect,:)';\n                count = count + c;\n        end;\n        HDR.FILE.POS = HDR.FILE.POS + count/HDR.AS.spb;        \n        \n        \nelseif strcmp(HDR.TYPE,'MFER'),\n\tif (HDR.FRAME.N ~= 1),\n\t\tfprintf(2,'Warning MWFOPEN: files with more than one frame not implemented, yet.\\n');\n\t\treturn;\n\tend\n\t\n\tN = 1;\n\tif ~isfield(HDR,'data'),\n\t\tSTATUS = fseek(HDR.FILE.FID,HDR.FRAME.POS(N),'bof');\n\t\t[tmp,count] = fread(HDR.FILE.FID,HDR.FRAME.sz(N,1:2),gdfdatatype(HDR.FRAME.TYP(N)));\n        \tif isnan(HDR.NRec),\n        \t\tHDR.NRec = count/(HDR.SPR*HDR.NS);\n        \tend;\n\n        \tif count==(HDR.SPR*HDR.NS), %% alternate mode format\n        \t\ttmp = reshape(tmp,[HDR.SPR,HDR.NS]);\n        \telse\n        \t        tmp = reshape(tmp,[HDR.SPR,HDR.NS,HDR.NRec]);   % convert into 3-Dim\n        \t        tmp = permute(tmp,[1,3,2]);                     % re-order dimensions\n        \t        tmp = reshape(tmp,[HDR.SPR*HDR.NRec,HDR.NS]);   % make 2-Dim \n        \tend;\n\t\tHDR.data = tmp;\n\tend;\n\n\tif nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        \n        nr = min(HDR.SampleRate*NoS,size(HDR.data,1)-HDR.FILE.POS);\n\tS  = HDR.data(HDR.FILE.POS + (1:nr), HDR.InChanSelect);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n\t\n        \nelseif strcmp(HDR.TYPE,'BCI2000'),\n        if nargin==3,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.SampleRate*HDR.AS.bpb*StartPos,'bof');        \n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        [S,count] = fread(HDR.FILE.FID,[HDR.NS,HDR.SampleRate*NoS],HDR.BCI2000.GDFTYP,HDR.BCI2000.StateVectorLength);\n        if count,\n                S = S(HDR.InChanSelect,:)';\n                HDR.FILE.POS = HDR.FILE.POS + count/HDR.NS;\n        end;\n\n        \nelseif strcmp(HDR.TYPE,'native') || strcmp(HDR.TYPE,'SCP'),\n\tif nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        nr = min(round(HDR.SampleRate * NoS), size(HDR.data,1) - HDR.FILE.POS);\n\tS = HDR.data(HDR.FILE.POS+1:HDR.FILE.POS+nr,:);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n%\tFLAG_CALIB_DONE = 1; \n        \nelseif strcmp(HDR.TYPE,'NEX'),\n        %% hack: read NEX data once, and transform into \"native\"\n        for k = 1:HDR.NEX.NS,\n                fseek(HDR.FILE.FID, HDR.NEX.offset(k), 'bof');\n                if 0,  % elseif HDR.NEX.type(k)==1, \n                        \n                elseif HDR.NEX.type(k)==2,  % interval\n                        tmp = fread(HDR.FILE.FID, [HDR.NEX.nf(k),2], 'int32');\n                        HDR.EVENT.POS = [HDR.EVENT.POS; tmp(:,1)];\n                        HDR.EVENT.DUR = [HDR.EVENT.DUR; tmp(:,2)];\n                        HDR.EVENT.CHN = [HDR.EVENT.CHN; repmat(k,size(tmp,1),1)];\n                        \n                elseif HDR.NEX.type(k)==3,  % waveform \n                        HDR.HeadLen = HDR.NEX.offset(k);\n                        HDR.NEX6.ts{k} = fread(HDR.FILE.FID, [HDR.NEX.nf(k),1], 'int32');\n                        HDR.NEX6.data{k} = fread(HDR.FILE.FID, [HDR.NEX.SPR(k), HDR.NEX.nf(k)], 'int16');\n                        \n                elseif HDR.NEX.type(k)==5, % continous variable  \n                        HDR.NEX5.ts{k} = fread(HDR.FILE.FID, [HDR.NEX.nf(k), 2], 'int32')';\n                        HDR.data(:,HDR.AS.chanreduce(k)) = fread(HDR.FILE.FID, [HDR.NEX.SPR(k), 1], 'int16');\n                        \n                elseif HDR.NEX.type(k)==6,  % marker\n                        ts = fread(HDR.FILE.FID, [1,HDR.NEX.nf(k)], 'int32');\n                        names = zeros(1,64);\n                        m = zeros(HDR.NEX.SPR(k), nl, nm);\n                        for j=1:nm\n                                names(j, :) = fread(HDR.FILE.FID, [1 64], 'uint8');\n                                for p = 1:HDR.NEX.SPR(k)\n                                        m(p, :, j) = fread(HDR.FILE.FID, [1 nl], 'uint8');\n                                end\n                        end\n                        HDR.NEX.names = names;\n                        HDR.NEX.m = m;\n                else\n                        ts = fread(HDR.FILE.FID, [1,HDR.NEX.nf(k)], 'int32');\n                        HDR.NEX0.ts{k}=ts;\n                end;\n        end\n        fclose(HDR.FILE.FID);\n        HDR.FILE.OPEN = 0; \n        HDR.TYPE = 'native';\n\tHDR.data = HDR.data(:,HDR.InChanSelect);\n        \n        % sequence for reading \"native\" format\n\tif nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\t\t\n        nr = min([round(HDR.SampleRate * NoS), size(HDR.data,1) - HDR.FILE.POS]);\n        S  = HDR.data(HDR.FILE.POS + (1:nr), :);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n        \n        \nelseif strcmp(HDR.TYPE,'PLEXON'),\n        %% hack: read PLEXON data once, and transform into \"native\"\n        HDR.data = repmat(NaN,max(HDR.PLX.adcount),HDR.NS);\n        NRec = 0; \n        nET  = 0; \n        ET   = repmat(NaN,1024,6);\n        wav  = zeros(1024,HDR.PLX.wavlen); \n        \n        tscount=zeros(5,130);\n        wfcount=zeros(5,130);\n        evcount=zeros(1,300);\n        adcount=zeros(1,212);\n        \n        adpos = zeros(1,HDR.NS);\n        typ_ubyte = fread(HDR.FILE.FID,2,'int16');\n        while ~feof(HDR.FILE.FID),\n                TYP  = typ_ubyte(1);\n                ubyte= typ_ubyte(2);\n                POS  = fread(HDR.FILE.FID,1,'int32');\n                tmp  = fread(HDR.FILE.FID,4,'int16');\n                CHN  = tmp(1)+1; \n                unit = tmp(2);\n                nwf  = tmp(3); \n                DUR  = tmp(4);\n    \t        if nwf>0,\n\t\t        wf = fread(HDR.FILE.FID,[1,DUR],'int16');\n                end;\n\t\tif TYP<5,\n\t\t\tnET = nET + 1; \n    \t\t        if size(ET,1) < nET;       % memory allocation\n        \t                ET  = [ET ; repmat(NaN,size(ET))];\n        \t        end;\n        \t        ET(nET,:) = [TYP,ubyte*2^32+POS,CHN,DUR,unit,nwf];\n\t\tend;\n                if TYP==1, % spike\n                        tscount(unit+1,CHN) = tscount(unit+1,CHN)+1; \n                        if DUR>0,\n                                wfcount(unit+1,CHN) = wfcount(unit+1,CHN)+1; \n                        end;\n                elseif TYP==4, % events, \n                        evcount(CHN) = evcount(CHN) + 1; \n                elseif TYP==5,  % continous\n                        t1 = adpos(CHN) + 1;\n                        t2 = adpos(CHN) + DUR;\n                        HDR.data(t1:t2,CHN) = wf';\n                        adpos(CHN) = t2;\n                end;\n                NRec = NRec+1;\n                typ_ubyte = fread(HDR.FILE.FID,2,'int16');\n        end\n        fclose(HDR.FILE.FID);\n        HDR.FILE.OPEN = 0; \n        \n        HDR.PLX2.tscount = tscount; \n        HDR.PLX2.wfcount = wfcount; \n        HDR.PLX2.evcount = evcount; \n        HDR.PLX2.adcount = adcount; \n        \n        ET = ET(1:nET,:);\n        HDR.EVENT.ET  = ET; \n        HDR.EVENT.TYP = ET(:,1); \n        HDR.EVENT.POS = ET(:,2); \n        HDR.EVENT.CHN = ET(:,3); \n        HDR.EVENT.DUR = ET(:,4); \n        HDR.EVENT.unit= ET(:,5); \n\n        HDR.TYPE = 'native';\n\tHDR.data = HDR.data(:,HDR.InChanSelect);\n        \n        % sequence for reading \"native\" format\n\tif nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        nr = min(round(HDR.SampleRate * NoS), size(HDR.data,1) - HDR.FILE.POS);\n        S  = HDR.data(HDR.FILE.POS + (1:nr), :);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n        \n        \nelseif strcmp(HDR.TYPE,'SCP'),\n\t% this branch is not in use yet. \n\t% its experiemental to improve performance\n\n\t% decompress data in first call \n\tHT = HDR.Huffman.HT; \n        \n\tdd = [0:255]';\n        ACC = zeros(size(dd));\n        c = 0;\n        for k2 = 1:8,\n                ACC = ACC + (dd>127).*(2^c);\n                dd  = mod(dd*2, 256);\n                c   = c + 1;\n        end;\n        \n\tS2 = []; \n\tfor k3 = 5:6,\n\t\tif (k3==5) && isfield(HDR,'SCP5');\n\t\t\tSCP = HDR.SCP5;\n\t\telseif (k3==6) && isfield(HDR,'SCP6');\n\t\t\tSCP = HDR.SCP6;\n\t\telse \n\t\t\tSCP = []; \n\t\tend;\n\n\t\tif ~isempty(SCP),\n                        if ~isfield(HDR,'SCP2'),\n\t\t\t\tS2 = SCP.data(:,HDR.InChanSelect);                      \n        \n                        elseif HDR.SCP2.NHT==19999,\n                                HuffTab = HDR.Huffman.DHT;\n\t\t\t\tS2 = zeros(0,length(HDR.InChanSelect));\n                                for k0 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k0); %HDR.NS,\n                                        s2 = SCP.data{k};\n                                        s2 = [s2; repmat(0,ceil(max(HDR.SCP2.HT(:,4))/8),1)];\n\t\t\t\t\tk1 = 0;\t\n\t\t\t\t\tl2 = 0; \n\t\t\t\t\taccu = 0;\n\t\t\t\t\tc  = 0; \n\t\t\t\t\tx  = [];\n\t\t\t\t\tHT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==1),3:7);\n\t\t\t\t\twhile (l2 < HDR.LeadPos(k,2)),\n\t\t\t\t\t\twhile ((c < max(HT(:,2))) && (k1<length(s2)-1));\n\t\t\t\t\t\t\tk1 = k1 + 1;\n\t\t\t\t\t\t\tdd = s2(k1);\n\t\t\t\t\t\t\taccu = accu + ACC(dd+1)*(2^c);\n\t\t\t\t\t\t\tc = c + 8;\n\t\t\t\t\t\tend;\n\n                                                ixx = 1;\n\t\t\t\t\t\tacc = accu - 2^32*floor(accu*(2^(-32)));   % bitand returns NaN if accu >= 2^32\n\t\t\t\t\t\twhile (bitand(acc,2^HT(ixx,1)-1) ~= HT(ixx,5)),\n\t\t\t\t\t\t\tixx = ixx + 1;\n\t\t\t\t\t\tend;\n                                                \n                                                dd = HT(ixx,2) - HT(ixx,1);\n\t\t\t\t\t\tif HT(ixx,3)==0,\n\t\t\t\t\t\t\tHT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==HT(ixx,5)),3:7);\n\t\t\t\t\t\t\tfprintf(HDR.FILE.stderr,'Warning SCPOPEN: Switching Huffman Tables is not tested yet.\\n');\n\t\t\t\t\t\telseif (dd==0),\n\t\t\t\t\t\t\tl2 = l2 + 1;\n\t\t\t\t\t\t\tx(l2) = HT(ixx,4);\n\t\t\t\t\t\telse %if (HT(ixx,3)>0),\n\t\t\t\t\t\t\tl2 = l2 + 1;\n\t\t\t\t\t\t\t\n                                                        tmp = floor(accu*(2^(-HT(ixx,1))));       % \n\t\t\t\t\t\t\t%tmp = bitshift(accu,-HT(ixx,1));\n                                                        tmp = tmp - (2^dd)*floor(tmp*(2^(-dd)));  % \n\t\t\t\t\t\t\t%tmp = bitand(tmp,2^dd)\n                                                        \n                                                        % reverse bit-pattern\n                                                        if dd==8,\n                                                                tmp = ACC(tmp+1);\n                                                        else\n                                                                tmp = dec2bin(tmp);\n                                                                tmp = [char(repmat('0',1,dd-length(tmp))),tmp];\n                                                                tmp = bin2dec(tmp(length(tmp):-1:1));\n                                                        end\n                                                        x(l2) = tmp-(tmp>=(2^(dd-1)))*(2^dd);\n\t\t\t\t\t\tend;\n\t\t\t\t\t\taccu = floor(accu*2^(-HT(ixx,2)));\n\t\t\t\t\t\tc = c - HT(ixx,2); \n\t\t\t\t\tend;\n\n                                        if k0==1,\n                                                S2 = x';\n                                        elseif size(x,2)==size(S2,1),\n                                                S2(:,k0) = x';\n\t\t\t\t\telse\n\t                                        fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \\n',size(x,1));\n\t\t\t\t\t\treturn;\n                                        end;\n\t\t\t\tend;\n                                \n                                \n                        elseif (HDR.SCP2.NHT==19999), % alternative decoding algorithm. \n                                HuffTab = HDR.Huffman.DHT;\n\n                                for k0 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k0); %HDR.NS,\n                                        tmp  = SCP.data{k};\n                                        accu = [tmp(4)+256*tmp(3)+65536*tmp(2)+2^24*tmp(1)];\n                                        %accu = bitshift(accu,HDR.SCP2.prefix,32);\n                                        c  = 0; %HDR.SCP2.prefix;\n                                        l  = 4;\n                                        l2 = 0;\n                                        clear x;\n                                        Ntmp = length(tmp);\n                                        tmp = [tmp; zeros(4,1)];\n                                        while c <= 32, %1:HDR.SPR(k),\n                                                ixx = 1;\n                                                while (bitand(accu,HDR.Huffman.mask(ixx)) ~= HDR.Huffman.PREFIX(ixx)), \n                                                        ixx = ixx + 1;\n                                                end;\n\n                                                if ixx < 18,\n                                                        c = c + HDR.Huffman.prefix(ixx);\n                                                        %accu  = bitshift(accu, HDR.Huffman.prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^HDR.Huffman.prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        x(l2) = HuffTab(ixx,1);\n                                                        \n                                                elseif ixx == 18,\n                                                        c = c + HDR.Huffman.prefix(ixx) + 8;\n                                                        %accu = bitshift(accu, HDR.Huffman.prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^HDR.Huffman.prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        \n                                                        acc1  = mod(floor(accu*2^(-24)),256);\n                                                        %accu = bitshift(accu, 8, 32);\n                                                        accu  = mod(accu*256, 2^32);\n                                                        \n                                                        x(l2) = acc1-(acc1>=2^7)*2^8;\n                                                        acc2  = 0;\n                                                        for kk = 1:8,\n                                                                acc2 = acc2*2 + mod(acc1,2);\n                                                                acc1 = floor(acc1/2);\n                                                        end;\n                                                        \n                                                elseif ixx == 19,\n                                                        c = c + HDR.Huffman.prefix(ixx);\n                                                        %accu = bitshift(accu, HDR.Huffman.prefix(ixx),32);\n                                                        accu  = mod(accu.*(2^HDR.Huffman.prefix(ixx)),2^32);\n                                                        l2    = l2 + 1;\n                                                        while (c > 7) && (l < Ntmp),\n                                                                l = l+1;\n                                                                c = c-8;\n                                                                accu = accu + tmp(l)*2^c;\n                                                        end;\n                                                        \n                                                        acc1 = mod(floor(accu*2^(-16)),2^16);\n                                                        %accu = bitshift(accu, 16, 32);\n                                                        accu = mod(accu.*(2^16), 2^32);\n                                                        \n                                                        x(l2) = acc1-(acc1>=2^15)*2^16;\n                                                        acc2 = 0;\n                                                        for kk= 1:16,\n                                                                acc2 = acc2*2+mod(acc1,2);\n                                                                acc1 = floor(acc1/2);\n                                                        end;\n                                                        %x(l2) = acc2;\n                                                        c = c + 16;\n                                                end;\n                                                \n                                                while (c > 7) && (l < Ntmp),\n                                                        l = l+1;\n                                                        c = c-8;\n                                                        accu = accu + tmp(l)*(2^c);\n                                                end;\n                                        end;\n\n                                        x = x(1:end-1)';\n                                        if k==1,\n                                                S2=x;\n                                        elseif size(x,1)==size(S2,1),\n                                                S2(:,k0) = x;\n\t\t\t\t\telse\n\t                                        fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \\n',size(x,1));\n\t\t\t\t\t\treturn;\n                                        end;\n                                end;\n                        elseif (HDR.SCP2.NHT==1) && (HDR.SCP2.NCT==1) && (HDR.SCP2.prefix==0), \n\t\t\t\tS2 = SCP.data(:,HDR.InChanSelect);                      \n                                \n                        elseif HDR.SCP2.NHT~=19999,\n                                fprintf(HDR.FILE.stderr,'Warning SOPEN SCP-ECG: user specified Huffman Table not supported\\n');\n                                return;\n                        else\n                                HDR.SCP2,\n                        end;\n\n                        % Decoding of Difference encoding                  \n                        if SCP.FLAG.DIFF==2,\n                                for k1 = 3:size(S2,1);\n                                        S2(k1,:) = S2(k1,:) + [2,-1] * S2(k1-(1:2),:);\n                                end;\n                        elseif SCP.FLAG.DIFF==1,\n                                S2 = cumsum(S2);    \n                        end;\n                        S2 = S2 * SCP.Cal;\n\n\t\t\tif (k3==5) && isfield(HDR,'SCP5');\n\t\t\t%\tHDR.SCP5.data = S2; \n\n\t\t\telseif (k3==6) && isfield(HDR,'SCP6');\n                                if HDR.SCP6.FLAG.bimodal_compression,\n                                        F = HDR.SCP5.SampleRate/HDR.SCP6.SampleRate;\n                                        HDR.SampleRate = HDR.SCP5.SampleRate;\n                                        HDR.FLAG.F = F;\n                                        \n                                        tmp=[HDR.SCP4.PA(:,1);HDR.LeadPos(1,2)]-[1;HDR.SCP4.PA(:,2)+1];\n                                        if ~all(tmp==floor(tmp))\n                                                tmp,\n                                        end;\n                                        t  = (1:HDR.N) / HDR.SampleRate;\n                                        S1 = zeros(HDR.N, HDR.NS);\n                                        \n                                        \n                                        p = 1;\n                                        k2 = 1;\n                                        pa = [HDR.SCP4.PA;NaN,NaN];\n                                        flag = 1;\n                                        for k1 = 1:HDR.N,\n                                                if k1 == pa(p,2)+1,\n                                                        flag = 1;\n                                                        p    = p+1;\n                                                        accu = S2(k2,:);\n                                                elseif k1 == pa(p,1),\n                                                        flag = 0;\n                                                        k2 = ceil(k2);\n                                                end;\n                                                \n                                                if flag,\n                                                        S1(k1,:) = ((F-1)*accu + S2(floor(k2),:)) / F;\n                                                        k2 = k2 + 1/F;\n                                                else\t\n                                                        S1(k1,:) = S2(k2,:);\n                                                        k2 = k2 + 1;\n                                                end;\n                                        end;\t\n                                        \n                                        HDR.SCP.S2 = S2;\n                                        HDR.SCP.S1 = S1;\n                                        S2 = S1;\n                                end;\n                                \n                                if HDR.FLAG.ReferenceBeat,\n                                        for k = find(~HDR.SCP4.type(:,1)'),\n                                                t1 = (HDR.SCP4.type(k,2):HDR.SCP4.type(k,4));\n                                                t0 = t1 - HDR.SCP4.type(k,3) + HDR.SCP4.fc0;\n                                                S2(t1,:) = S2(t1,:) + HDR.SCP5.data(t0,:); \n                                        end;\n                                end;\n\t\t\tend;\n\t\tend;\n\tend;\n        HDR.data = S2;\n\tHDR.TYPE = 'native'; \t% decompression is already applied\n\n\tif nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        nr = min(round(HDR.SampleRate * NoS), size(HDR.data,1) - HDR.FILE.POS);\n        S  = HDR.data(HDR.FILE.POS + (1:nr), :);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n        \n\nelseif strcmp(HDR.TYPE,'SIGIF'),\n        if nargin==3,\n                HDR.FILE.POS = StartPos;\n        end;\n        \n        S = [];\n        for k = 1:min(NoS,HDR.NRec-HDR.FILE.POS),\n                HDR.FILE.POS = HDR.FILE.POS + 1;\n                STATUS = fseek(HDR.FILE.FID, HDR.Block.Pos(HDR.FILE.POS), 'bof');\n                if HDR.FLAG.TimeStamp,\n                        HDR.Frame(k).TimeStamp = fread(HDR.FILE.FID,[1,9],'uint8');\n                end;\n                \n                if HDR.FLAG.SegmentLength,\n                        HDR.Block.Length(k) = fread(HDR.FILE.FID,1,'uint16');  %#26\n                        STATUS = fseek(HDR.FILE.FID,HDR.Block.Length(k)*H1.Bytes_per_Sample,'cof');\n                else\n                        tmp = HDR.Segment_separator-1;\n                        [dat,c] = fread(HDR.FILE.FID,[HDR.NS,HDR.Block.Length/HDR.NS],gdfdatatype(HDR.GDFTYP));\n                        [tmpsep,c] = fread(HDR.FILE.FID,1,gdfdatatype(HDR.GDFTYP));\n                        \n                        if  (tmpsep~=HDR.Segment_separator);\n                                fprintf(HDR.FILE.stderr,'Error SREAD Type=SIGIF: blockseparator not found\\n');\n                        end;\n                end;\n                S = [S; dat(HDR.InChanSelect,:)'];\n        end;\n        \n        \nelseif strcmp(HDR.TYPE,'CTF'),\n        if nargin>2,\n                STATUS = fseek(HDR.FILE.FID,HDR.HeadLen+HDR.NS*HDR.SPR*4*StartPos,'bof');        \n                HDR.FILE.POS = StartPos;\n        end;\n\t\n\tnr = min(NoS, HDR.NRec - HDR.FILE.POS);\n\t\n        S = []; count = 0; \n\tfor k = 1:nr,\n\t        %[tmp,c] = fread(HDR.FILE.FID, 1, 'int32')\n\t        [s,c] = fread(HDR.FILE.FID, [HDR.SPR, HDR.NS], 'int32');\n\t\tS = [S; s(:,HDR.InChanSelect)];\n\t\tcount = count + c;\n\tend;\n\t\n        HDR.FILE.POS = HDR.FILE.POS + count/(HDR.SPR*HDR.NS);\n        \n        \nelseif strcmp(HDR.TYPE,'EEProbe-CNT'),\n        if nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        \n        nr = min(HDR.SampleRate*NoS, HDR.SPR*HDR.NRec-HDR.FILE.POS);\n\tif exist('read_eep_cnt','file')==3,\n                tmp = read_eep_cnt(HDR.FileName, HDR.FILE.POS+1, HDR.FILE.POS+nr);\n                sz  = size(tmp.data);\n                S   = tmp.data(HDR.InChanSelect,:)';\n                clear tmp; \n                if HDR.FLAG.UCAL,\n\t                S = S*diag(1./HDR.Cal(HDR.InChanSelect));\n\t        end;        \n                HDR.FILE.POS = HDR.FILE.POS + sz(2);\n\n        elseif exist('OCTAVE_VERSION','builtin')\n                fprintf(HDR.FILE.stderr,'ERROR SREAD (EEProbe): Reading EEProbe-file format is not supported.\\n');\n                return;\n\telse\n                fprintf(HDR.FILE.stderr,'ERROR SREAD (EEProbe): Cannot open EEProbe-file, because read_eep_cnt.mex not installed. \\n');\n                fprintf(HDR.FILE.stderr,'ERROR SREAD (EEProbe): You can downlad it from http://www.smi.auc.dk/~roberto/eeprobe/\\n');\n\t\t%% ftp://ftp.fcdonders.nl/pub/fieldtrip/external/eeprobe.zip\n                return;\n        end\n       \nelseif strcmp(HDR.TYPE,'EEProbe-AVR'),\n        if nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        nr = min(HDR.SPR-HDR.FILE.POS,NoS*HDR.SampleRate);\n\n        S = HDR.EEP.data(HDR.FILE.POS+(1:nr),:);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n\n        \nelseif strncmp(HDR.TYPE,'BrainVision',11),   %Brainvision\n        if strncmpi(HDR.BV.DataFormat, 'binary',5)\n\t\ttc = strcmp(HDR.TYPE,'BrainVisionVAmp');\n\t\tNS = HDR.NS+tc;\n                if strncmpi(HDR.BV.DataOrientation, 'multiplexed',6),\n                        if nargin>2,\n                                STATUS = fseek(HDR.FILE.FID,StartPos*HDR.SampleRate*HDR.AS.bpb,'bof');        \n                                HDR.FILE.POS = HDR.SampleRate*StartPos;\n                        end;\n\n\t\t\tnr = min(HDR.SampleRate*NoS, HDR.SPR*HDR.NRec - HDR.FILE.POS);\n\t\t\tif (length(HDR.InChanSelect)*2>HDR.NS)\n\t\t\t\t[s,c] = fread(HDR.FILE.FID, [NS, nr], ['*',gdfdatatype(HDR.GDFTYP)]);\n\t\t\t\tcount = c/NS;\n\t\t\t\tS = s(HDR.InChanSelect,:)';\n\t\t\telse\n\t\t\t\tS  = [];\n\t\t\t\tcount = 0;\n\t\t\t\twhile (count<nr),\n\t\t\t\t\t[s,c] = fread(HDR.FILE.FID, [NS, min(nr-count,floor(2^24/NS))], gdfdatatype(HDR.GDFTYP));\n\t\t\t\t\tif ~c, break; end; \n\t\t\t\t\tS = [S; s(HDR.InChanSelect,:)'];\n\t\t\t\t\tcount = count + c/NS; \n\t\t\t\tend; \n\t\t\tend;\n\t\t\tHDR.FILE.POS = HDR.FILE.POS + count;\n\t\telseif strncmpi(HDR.BV.DataOrientation, 'vectorized',6),\n\t\t\tS = [];\n\t\t\tnr = min(HDR.SampleRate*NoS, HDR.AS.endpos-HDR.FILE.POS);\n\n\t\t\tcount = 0; \n\t\t\tfor chan = 1:length(HDR.InChanSelect);\n                                STATUS = fseek(HDR.FILE.FID, HDR.HeadLen + HDR.FILE.POS + HDR.AS.bpb*HDR.SPR*(chan-1)/NS, 'bof');\n                                [s,count] = fread(HDR.FILE.FID, [nr,1], gdfdatatype(HDR.GDFTYP));\n                                if count ~= nr,\n                                        fprintf(2,'ERROR READ BV-bin-vec: \\n');\n                                        return;\n                                end;\n                                S(:,chan) = s;\n                        end\n                        HDR.FILE.POS = HDR.FILE.POS + count; \n                end;\n\n        elseif strncmpi(HDR.BV.DataFormat, 'ascii',5)  \n\t        %%%% OBSOLETE: supported by 'native' %%%%\n                if nargin>2,\n                        HDR.FILE.POS = HDR.SampleRate*StartPos;\n                end;\n                nr = min(HDR.SampleRate*NoS, HDR.AS.endpos-HDR.FILE.POS);\n                S  = HDR.BV.data(HDR.FILE.POS+(1:nr),HDR.InChanSelect);\n                \n        end\n                \n        \nelseif strcmp(HDR.TYPE,'SierraECG'),   %% SierraECG  1.03  *.open.xml from PHILIPS\n        if ~isfield(HDR,'data');\n                [HDR.data,status] = str2double(HDR.XML.waveforms.parsedwaveforms);\n                if any(status)\n                        error('SREAD: compressed SierraECG (Philips) format not supported')\n                end;\n                HDR.data = reshape(HDR.data,length(HDR.data)/HDR.NS,HDR.NS);\n                HDR.SPR = size(HDR.data,1);\n        else\n                % base64 - decoding \n                base64 = ['A':'Z','a':'z','0':'9','+','/'];\n                decode64 = repmat(nan,256,1);\n                decode64(abs(base64)) = 0:63;\n                tmp = decode64(HDR.XML.waveforms.parsedwaveforms);\n                tmp(isnan(tmp)) = [];\n                n   = length(tmp);\n                tmp = reshape([tmp;zeros(mod(n,4),1)], 4, ceil(n/4));\n                t1  = tmp(1,:)*4 + floor(tmp(2,:)/16);\n                t2  = mod(tmp(2,:),16)*16 + floor(tmp(3,:)/4);\n                t3  = mod(tmp(3,:),4)*64 + tmp(4,:);\n                tmp = reshape([t1,t2,t3], ceil(n/4)*3, 1);\n        end;\n        if nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        nr = min(HDR.SampleRate*NoS, HDR.SPR-HDR.FILE.POS);\n        S  = HDR.data(HDR.FILE.POS+(1:nr),HDR.InChanSelect);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n\n        \nelseif strcmp(HDR.TYPE,'ATF'); \n        if HDR.FILE.OPEN,\n                fseek(HDR.FILE.FID,HDR.HeadLen,-1);\n                t = fread(HDR.FILE.FID,[1,inf],'uint8');\n                fclose(HDR.FILE.FID);\n                HDR.FILE.OPEN=0; \n                [HDR.ATF.NUM,status,HDR.ATF.STR] = str2double(char(t));\n        end;\n        S = HDR.ATF.NUM;\n        \n        \nelseif strcmp(HDR.TYPE,'FEPI3'); \n        if nargin==3,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        Duration = min(NoS*HDR.SampleRate,(HDR.AS.endpos-HDR.FILE.POS));\n\n\tS = repmat(NaN,Duration,length(HDR.InChanSelect));\n\tix = find([HDR.FEPI.SEG(:,2) > HDR.FILE.POS] & [HDR.FEPI.SEG(:,1) <= HDR.FILE.POS+Duration]);\n\tfor k = 1:length(ix),\n\t\tfid = fopen(fullfile(HDR.FILE.Path,[HDR.FEPI.ListOfDataFiles{k},'.bin']));\n\t\tif k==1,\n\t\t\tfseek(fid,(HDR.FILE.POS-HDR.FEPI.SEG(ix(k),1))*2*HDR.NS,-1);\n\t\tend;\t\n\t\tdata= fread(fid,[HDR.NS,inf],'int16')'; \n\t\tix1 = HDR.FEPI.SEG(ix(k),1)-HDR.FEPI.SEG(ix(1),1);\n\t\tix2 = min(size(data,1),Duration+HDR.FILE.POS-HDR.FEPI.SEG(ix(k),1)+1);\n\t        S(ix1+1:ix1+ix2,:) = data(1:ix2,HDR.InChanSelect);\n\t\tfclose(fid); \n\tend; \n\tHDR.FILE.POS = HDR.FILE.POS+Duration; \n        \n        \nelseif strcmp(HDR.TYPE,'WG1'),   %walter-graphtek\n\t% code from Robert Reijntjes, Amsterdam, NL \n\t% modified by Alois Schloegl 19. Feb 2005 \n        if nargin==3,\n                HDR.FILE.POS = round(HDR.SampleRate*StartPos);\n        end;\n\n\tix1    = mod(HDR.FILE.POS, HDR.SPR);\t% starting sample (minus one) within 1st block \n    \tfp     = HDR.HeadLen + floor(HDR.FILE.POS/HDR.SPR)*HDR.AS.bpb;\n    \tstatus = fseek(HDR.FILE.FID, fp, 'bof');\n\n        nr     = min(HDR.AS.endpos-HDR.FILE.POS, NoS*HDR.SampleRate);\n\tS      = repmat(NaN,nr,length(HDR.InChanSelect)); \n\tcount  = 0;\n        endloop= 0;\n        c = 1; \n        offset = 0; \n    \twhile ~endloop & (c>0) && (offset(1)~=(hex2dec('AEAE5555')-2^32)) && (count<nr);\n\t        [offset,c] = fread(HDR.FILE.FID, HDR.WG1.szOffset, 'int32');\n\t\t[databuf,c] = fread(HDR.FILE.FID,[HDR.WG1.szBlock,HDR.NS+HDR.WG1.szExtra],'uint8');\n            \tdt = HDR.WG1.conv(databuf(:,1:HDR.NS)+1);\n            \tif any(dt(:)==HDR.WG1.unknownNr),\n            \t\t%dt(dt==HDR.WG1.unknownNr) = NaN; \n            \t\tdt(:) = NaN; \n            \t    \t%fprintf(HDR.FILE.stderr,'Warning SREAD (WG1): error in reading datastream');\n            \tend;\n\t\tdt(1,:) = dt(1,:) + offset(1:HDR.NS)';\n\t\tdt = cumsum(dt,1);\n\t\t\n\t\tix2 = min(nr-count, size(dt,1)-ix1);\n\t\tS(count+1:count+ix2,:) = dt(ix1+1:ix1+ix2, HDR.InChanSelect);\n\t\tcount = count + ix2; \n\t\tix1 = 0;\t% reset starting index, \n\n                k = 0; \n                while (k<HDR.WG1.szExtra) && ~endloop, \n                        endloop = ~isempty(strfind(databuf(:,HDR.NS+k)',[85,85,174,174]));\n                        k = k+1; \n                end;\n\tend;\t\n\t%S = S(1:count,:);\n\tHDR.FILE.POS = HDR.FILE.POS + count;\n\n\nelseif strcmp(HDR.TYPE,'XML-FDA'),   % FDA-XML Format\n        if ~isfield(HDR,'data');\n                tmp   = HDR.XML.component.series.derivation;\n                if isfield(tmp,'Series');\n                        tmp = tmp.Series.component.sequenceSet.component;\n                else    % Dovermed.CO.IL version of format\n                        tmp = tmp.derivedSeries.component.sequenceSet.component;\n                end;\n                for k = 1:length(HDR.InChanSelect);\n                        HDR.data(:,k) = str2double(tmp{HDR.InChanSelect(k)+1}.sequence.value.digits)';\n                end;\n                HDR.SPR = size(HDR.data,1);\n        end;\n        if nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n        nr = min(HDR.SampleRate*NoS, HDR.SPR-HDR.FILE.POS);\n        S  = HDR.data(HDR.FILE.POS+(1:nr),:);\n        HDR.FILE.POS = HDR.FILE.POS + nr;\n\n% using XML4MAT instead of XMLTREE\n% str2double(HDR.XML0{end}.component{1}.series{end}.derivation{:}.derivedSeries{5}.component{1}.sequenceSet{5}.component{1}.sequence{2}.value{3}.digits)'\n\n        \nelseif strcmp(HDR.TYPE,'FIF'),\n        % some parts of this code are from Robert Oostenveld, \n        if ~(exist('rawdata')==3 & exist('channames')==3)\n                error('cannot find Neuromag import routines on your Matlab path (see http://boojum.hut.fi/~kuutela/meg-pd)');\n        end\n        if nargin<3, \n                StartPos = HDR.FILE.POS/HDR.SampleRate;\n        end\n        if nargin>2,\n                HDR.FILE.POS = HDR.SampleRate*StartPos;\n        end;\n\n        t1  = rawdata('goto', HDR.FILE.POS/HDR.SPR);\n        t2  = t1;\n        dat = [];\n        count = 0;\n        status = 'ok';\n        \n        while (t2<(StartPos + NoS)) && ~strcmp(status,'eof'),\n                [buf, status] = rawdata('next');\n                if 0\n                elseif strcmp(status, 'ok')\n                        count = count + size(buf,2);\n                        dat = [dat; buf(HDR.InChanSelect,:)'];\n                elseif strcmp(status, 'eof')\n                elseif strcmp(status, 'skip')\n                elseif strcmp(status, 'error')\n                        error('error reading selected data from fif-file');\n                else\n                        error('undefined status code return from RAWDATA(FIF-file)');\n                end\n                t2 = rawdata('t');\n        end\n        t  = t1*HDR.SampleRate+1:t2*HDR.SampleRate;\n        ix = (t>StartPos*HDR.SampleRate) & (t<=(StartPos+NoS)*HDR.SampleRate);\n        S  = dat(ix,HDR.InChanSelect);\n        HDR.FILE.POS = t2*HDR.SampleRate;        \n\nelseif strcmp(HDR.TYPE,'EVENT'),\n        s = [];        \n\nelseif strncmp(HDR.TYPE,'IMAGE:',6),\n\t% forward call to IREAD\n        [S,HDR] = iread(HDR);\n\treturn;\n\nelse\n        fprintf(2,'Error SREAD: %s-format not supported yet.\\n', HDR.TYPE);        \n\treturn;\nend;\n\n\n%%% TOGGLE CHECK - checks whether HDR is kept consist %%% \nif 0,\nglobal SREAD_TOGGLE_CHECK\nif isfield(HDR.FLAG,'TOGGLE');\n        if HDR.FLAG.TOGGLE~=SREAD_TOGGLE_CHECK,\n                fprintf(HDR.FILE.stderr,'Warning SREAD: [s,HDR]=sread(HDR, ...) \\nYou forgot to pass HDR in %i call(s) of SREAD\\n',SREAD_TOGGLE_CHECK-HDR.FLAG.TOGGLE);\n        end;\nelse\n        HDR.FLAG.TOGGLE=0;\n        SREAD_TOGGLE_CHECK=0;\nend;\nSREAD_TOGGLE_CHECK = SREAD_TOGGLE_CHECK+1;\nHDR.FLAG.TOGGLE = HDR.FLAG.TOGGLE+1;\nend; \n\nif STATUS,\n        fprintf(HDR.FILE.stderr,'WARNING SREAD: something went wrong. Please send the files %s and BIOSIGCORE to <a.schloegl@ieee.org>',HDR.FileName);\n        save biosigcore.mat \nend;\n\nif isempty(S),\n\nelseif isfield(HDR,'THRESHOLD') && HDR.FLAG.OVERFLOWDETECTION,\n        ix = (S~=S);\n        for k=1:length(HDR.InChanSelect),\n                TH = THRESHOLD(HDR.InChanSelect(k),:);\n                %ix(:,k) = (S(:,k)<=TH(1)) | (S(:,k)>=TH(2));\n                ix = (S(:,k)<=TH(1)) | (S(:,k)>=TH(2));\n                S(ix,k)=NaN;\n        end\n        if exist('double','builtin')\n                S = double(S);\n        end;\n%        S(ix>0) = NaN;\nelseif HDR.FLAG.OVERFLOWDETECTION,\n        % no HDR.THRESHOLD defined\n        warning('no Threshold defined');\nelseif isfield(HDR,'THRESHOLD'),\n        % automated overflow detection has been turned off\nend;\n\nif ~HDR.FLAG.UCAL,\n        % S = [ones(size(S,1),1),S]*HDR.Calib; \n        % perform the previous function more efficiently and\n        % taking into account some specialities related to Octave sparse\n        % data. \n        if isempty(S),\t% otherwise Octave 2.1.64 could break below, \n\t\tif size(S,2)~=length(HDR.InChanSelect), \n\t\t\tfprintf(HDR.FILE.stderr,'Warning SREAD (%s): number of columns (%i) incorrect!\\n',HDR.TYPE,size(S,2));\n\t\tend;\t\n\t\tS = zeros(0,length(HDR.InChanSelect));\n\tend;\n\n        %if ~issparse(HDR.Calib); %\n        if FLAG_CALIB_DONE, \n\n        elseif strcmpi(HDR.FLAG.OUTPUT,'single')\n        \ttmp = single(zeros(size(S,1),size(HDR.Calib,2)));\n                for k = 1:size(S,1),\n                        tmp(k,:) = [1,S(k,:)] * HDR.Calib;\n                end;\n                S = tmp; \n                clear tmp;\n        \t\n        elseif 1, % exist('OCTAVE_VERSION','builtin')\n                % force octave to do a sparse multiplication\n                % the difference is NaN*sparse(0) = 0 instead of NaN\n                % this is important for the automatic overflow detection\n\t\tCalib = HDR.Calib;\n\t\ttmp   = S;\n                S     = zeros(size(S,1),size(Calib,2));   % memory allocation\n\n                for k = 1:size(Calib,2),\n                        chan = find(Calib(2:end,k));\n                        S(:,k) = double(tmp(:,chan)) * full(Calib(1+chan,k)) + Calib(1,k);\n                end;\n        else\n                % S = [ones(size(S,1),1),S]*HDR.Calib; \n                % the following is the same as above but needs less memory. \n                S = full(double(S) * HDR.Calib(2:end,:));\n                for k = 1:size(HDR.Calib,2),\n                        S(:,k) = S(:,k) + full(HDR.Calib(1,k));\n                end;\n        end;\nend;\n\n\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/external/biosig-partial/t200_FileAccess/sread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.13815443535082816}}
{"text": "%kClassify 'classifies a series of images according to a number of color vectors '\n% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros Classify.pane file\n%\n% Parameters: \n% InputFile: i1 'Images (along elements)', required: 'Series of images (also 3D) stacked along elment direction'\n% InputFile: i2 'Colors', required: 'Color vectors (along X) stacked along element direcition'\n% Double: t 'DAPI threshold', default: 10: 'Element 0 is assumed to contain the DAPI channel. Pixels below threshold are ignored.'\n% Double: minq 'Min Quality', default: 0.97: 'Defines the minimal quality for single channel matching. If not reached, method reverts to two channels'\n% Integer: co 'Color Optimize Iterations', default: 1: 'If selected, some iterations for finding the optimal color vectors are performed'\n% Double: mincq 'Min Color Quality', default: 0.8: 'Defines the minimum quality for adjusting the colors.'\n% OutputFile: o1 'Classified', required: 'Resulting classification image'\n% OutputFile: o2 'Quality Img', required: 'A classification quality is given for every pixel'\n% OutputFile: o3 'Output Colors', optional: 'The (eventually optimized) colors'\n%\n% Example: [o1, o2, o3] = kClassify({i1, i2}, {'i1','';'i2','';'t',10;'minq',0.97;'co',1;'mincq',0.8;'o1','';'o2','';'o3',''})\n%\n% Khoros helpfile follows below:\n%\n%  PROGRAM\n% Classify - classifies a series of images according to a number of color vectors\n%\n%  DESCRIPTION\n%\n%  \n%\n%  EXAMPLES\n%\n%  \"SEE ALSO\"\n%\n%  RESTRICTIONS \n%\n%  REFERENCES \n%\n%  COPYRIGHT\n% Copyright (C) 1996-2003, Rainer Heintzmann,  All rights reserved.\n% \n\n\nfunction varargout = kClassify(varargin)\nif nargin ==0\n  Inputs={};arglist={'',''};\nelseif nargin ==1\n  Inputs=varargin{1};arglist={'',''};\nelseif nargin ==2\n  Inputs=varargin{1}; arglist=varargin{2};\nelse error('Usage: [out1,..] = kClassify(Inputs,arglist).');\nend\nif size(arglist,2)~=2\n  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')\n end\nnarglist={'i1', '__input';'i2', '__input';'t', 10;'minq', 0.97;'co', 1;'mincq', 0.8;'o1', '__output';'o2', '__output';'o3', '__output'};\nmaxval={0,0,0,0,2,0,0,0,1};\nminval={0,0,0,0,2,0,0,0,1};\nistoggle=[0,0,1,1,1,1,0,0,1];\nwas_set=istoggle * 0;\nparamtype={'InputFile','InputFile','Double','Double','Integer','Double','OutputFile','OutputFile','OutputFile'};\n% identify the input arrays and assign them to the arguments as stated by the user\nif ~iscell(Inputs)\nInputs = {Inputs};\nend\nNumReqOutputs=2; nextinput=1; nextoutput=1;\n  for ii=1:size(arglist,1)\n  wasmatched=0;\n  for jj=1:size(narglist,1)\n   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments\n     wasmatched = 1;\n     was_set(jj) = 1;\n     if strcmp(narglist{jj,2}, '__input')\n      if (nextinput > length(Inputs)) \n        error(['Input ' narglist{jj,1} ' has no corresponding input!']); \n      end\n      narglist{jj,2} = 'OK_in';\n      nextinput = nextinput + 1;\n     elseif strcmp(narglist{jj,2}, '__output')\n      if (nextoutput > nargout) \n        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']); \n      end\n      if (isempty(arglist{ii,2}))\n        narglist{jj,2} = 'OK_out';\n      else\n        narglist{jj,2} = arglist{ii,2};\n      end\n\n      nextoutput = nextoutput + 1;\n      if (minval{jj} == 0)  \n         NumReqOutputs = NumReqOutputs - 1;\n      end\n     elseif isstr(arglist{ii,2})\n      narglist{jj,2} = arglist{ii,2};\n     else\n        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})\n            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);\n        end\n        if (minval{jj} ~= 0 | maxval{jj} ~= 0)\n          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);\n          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);\n          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)\n            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);\n          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)\n            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})\n            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);\n          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})\n            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);\n          end\n        end\n     end\n     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in') \n       narglist{jj,2} = arglist{ii,2};\n     end\n   end\n   end\n   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))\n        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);\n   end\nend\n% match the remaining inputs/outputs to the unused arguments and test for missing required inputs\n for jj=1:size(narglist,1)\n     if  strcmp(paramtype{jj}, 'Toggle')\n        if (narglist{jj,2} ==0)\n          narglist{jj,1} = ''; \n        end;\n        narglist{jj,2} = ''; \n     end;\n     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)\n          narglist{jj,1} = ''; \n          narglist{jj,2} = ''; \n     end;\n     if strcmp(narglist{jj,2}, '__input')\n      if (minval{jj} == 0)  % meaning this input is required\n        if (nextinput > size(Inputs)) \n           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']); \n        else\n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        end\n      else  % this is an optional input\n        if (nextinput <= length(Inputs)) \n          narglist{jj,2} = 'OK_in';\n          nextinput = nextinput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end;\n     else \n     if strcmp(narglist{jj,2}, '__output')\n      if (minval{jj} == 0) % this is a required output\n        if (nextoutput > nargout & nargout > 1) \n           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']); \n        else\n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n          NumReqOutputs = NumReqOutputs-1;\n        end\n      else % this is an optional output\n        if (nargout - nextoutput >= NumReqOutputs) \n          narglist{jj,2} = 'OK_out';\n          nextoutput = nextoutput + 1;\n        else \n          narglist{jj,1} = '';\n          narglist{jj,2} = '';\n        end;\n      end\n     end\n  end\nend\nif nargout\n   varargout = cell(1,nargout);\nelse\n  varargout = cell(1,1);\nend\nglobal KhorosRoot\nif exist('KhorosRoot') && ~isempty(KhorosRoot)\nw=['\"' KhorosRoot];\nelse\nif ispc\n  w='\"C:\\Program Files\\dip\\khorosBin\\';\nelse\n[s,w] = system('which cantata');\nw=['\"' w(1:end-8)];\nend\nend\n[varargout{:}]=callKhoros([w 'classify\"  -k'],Inputs,narglist);\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/matlab_tools/Converted/kClassify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.1381305748660648}}
{"text": "function prepare_voc12_imgs(img_set, output_img_dir, opts)\n% PREPARE_VOC12_IMGS\n%   prepare voc12 images (cropped from ground truth bboxes with jittering)\n% input:\n%   img_set: 'train' or 'val'\n%   output_img_dir: output folder names, final structure is <output_img_dir>/<category>/<imgs>\n%   opts: matlab struct with flip, aug_n, jitter_IoU, difficult, truncated, occluded fields\n%       if flip is 1, images will be flipped. \n%       if ang_n>1, images will be augmented by jittering bbox. jitter_IoU==1 means normal crop\n%       difficult, truncated, occluded \\in {0,1}, where 0 indicated that we do not \n%           want images with that property (e.g. 0,0,0 means we want easy images only)\n% output:\n%   cropped images according to ground-truth bounding boxes (with jittering) and image filelists\n%\n\naddpath(fullfile(mfilename('fullpath'), '../../'));\nglobal_variables;\ncls_names = g_cls_names;\n\n% paths\nannotation_path = fullfile(g_pascal3d_root_folder, 'Annotations');\nimage_path = fullfile(g_pascal3d_root_folder, 'Images');\naddpath(fullfile(g_pascal3d_root_folder, 'VDPM'));\naddpath(fullfile(g_pascal3d_root_folder, 'PASCAL/VOCdevkit/VOCcode'));\n\n% read ids of train/val set images\nVOCinit;\nids = textread(sprintf(VOCopts.imgsetpath, img_set), '%s');\nM = numel(ids);\n\n% avoid duplication\nassert(exist(output_img_dir,'dir')==0);\nmkdir(output_img_dir);\nfor cls_idx = 1:numel(cls_names)\n    mkdir([output_img_dir '/' cls_names{cls_idx}]);\nend\n\n\nfor cls_idx = 1:numel(cls_names)\n    cls = cls_names{cls_idx};\n    labelfile = fopen(fullfile(output_img_dir, sprintf('%s.txt',cls)),'w');\n     \n    for i = 1:M\n        if mod(i,100) == 0\n            fprintf('%s: %d/%d\\n', cls, i, M);\n        end\n        \n        anno_filename = fullfile(annotation_path, sprintf('%s_pascal/%s.mat', cls, ids{i}));\n        if ~exist(anno_filename,'file')\n            continue;\n        end\n        anno = load(anno_filename);\n        objects = anno.record.objects;\n\n        for k = 1:length(objects)\n            obj = objects(k);\n            \n            if ~isempty(obj.viewpoint) && strcmp(obj.class, cls)\n                try\n                    % write view annotation\n                    azimuth = mod(round(obj.viewpoint.azimuth), 360);\n                    elevation = mod(round(obj.viewpoint.elevation), 360);\n                    tilt = mod(round(obj.viewpoint.theta), 360);\n                    truncated = obj.truncated;\n                    occluded = obj.occluded;\n                    difficult = obj.difficult;\n                    % skip un-annotated image\n                    if azimuth == 0 && elevation == 0 && theta == 0\n                        fprintf('skip %s...', ids{i});\n                        continue;\n                    end\n                    % skip unwanted image\n                    if (difficult==1 && opts.difficult==0) || (truncated==1 && opts.truncated==0) || (occluded==1 && opts.occluded==0)\n                        fprintf('fliter skip %s...', ids{i});\n                        continue;\n                    end\n                    \n                    img_filename = fullfile(image_path, sprintf('%s_pascal/%s.jpg', cls, ids{i}));\n                    im = imread(img_filename);\n                    box = obj.bbox;\n                    w = box(3)-box(1)+1;\n                    h = box(4)-box(2)+1;\n                    rect = [box(1),box(2), w, h];\n                    \n                    for aug_i = 1:opts.aug_n\n                        % write cropped img\n                        if aug_i == 1\n                            cropped_im = imcrop(im, rect);\n                        else\n                            cropped_im = jitter_imcrop(im, rect, opts.jitter_IoU);\n                        end\n                        cropped_im_filename = sprintf('%s/%s/%s_%s_%s_%s.jpg', output_img_dir, cls, cls, ids{i}, num2str(k), num2str(aug_i)); \n                        imwrite(cropped_im, cropped_im_filename);\n                        fprintf(labelfile, '%s %d %d %d %d\\n', cropped_im_filename, cls_idx-1, azimuth, elevation, tilt);                    \n                        if opts.flip\n                            cropped_im_flip = fliplr(cropped_im); % flip the image horizontally\n                            cropped_im_flip_filename = sprintf('%s/%s/%s_%s_%s_%s_%s.jpg', output_img_dir, cls, cls, ids{i}, num2str(k), num2str(aug_i), 'flip');\n                            imwrite(cropped_im_flip, cropped_im_flip_filename);\n                            fprintf(labelfile, '%s %d %d %d %d\\n', cropped_im_flip_filename, cls_idx-1, mod(360-azimuth,360), elevation, mod(-1*tilt,360));                    \n                        end\n                    end\n                catch\n                end\n            end\n        end\n    end\n    fclose(labelfile);\nend\n\n\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/view_estimation/prepare_voc12_imgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.13762179400616564}}
{"text": "function ct = matRad_importDicomCt(ctList, resolution, dicomMetaBool, grid, visBool)\n% matRad function to import dicom ct data\n% \n% call\n%   ct = matRad_importDicomCt(ctList, resolution, dicomMetaBool)\n%   ct = matRad_importDicomCt(ctList, resolution, dicomMetaBool, grid)\n%   ct = matRad_importDicomCt(ctList, resolution, dicomMetaBool, visBool)\n%   ct = matRad_importDicomCt(ctList, resolution, dicomMetaBool, grid, visBool)\n%\n% input\n%   ctList:         list of dicom ct files\n%   resolution:   \tresolution of the imported ct cube, i.e. this function\n%                   will interpolate to a different resolution if desired\n%   dicomMetaBool:  store complete dicom information if true\n%   grid:           optional: a priori grid specified for interpolation\n%   visBool:        optional: turn on/off visualization\n%\n% output\n%   ct:             matRad ct struct. Note that this 3D matlab array \n%                   contains water euqivalent electron denisities.\n%                   Hounsfield units are converted using a standard lookup\n%                   table in matRad_calcWaterEqD\n%\n% References\n%   -\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nmatRad_cfg = MatRad_Config.instance();\n\nmatRad_cfg.dispInfo('\\nimporting ct-cube...');\n\n%% processing input variables\nif ~exist('visBool','var')\n  visBool = 0;\nend\n\n% creation of ctInfo list\nnumOfSlices = size(ctList,1);\nmatRad_cfg.dispInfo('\\ncreating info...')\n\nsliceThicknessStandard = true;\nfor i = 1:numOfSlices\n\n    if verLessThan('matlab','9')\n        tmpDicomInfo = dicominfo(ctList{i,1});\n    else\n        tmpDicomInfo = dicominfo(ctList{i,1},'UseDictionaryVR',true);\n    end\n    \n    % remember relevant dicom info - do not record everything as some tags\n    % might not been defined for individual files\n    ctInfo(i).PixelSpacing            = tmpDicomInfo.PixelSpacing;\n    ctInfo(i).ImagePositionPatient    = tmpDicomInfo.ImagePositionPatient;\n    ctInfo(i).SliceThickness          = tmpDicomInfo.SliceThickness;\n    ctInfo(i).ImageOrientationPatient = tmpDicomInfo.ImageOrientationPatient;\n    ctInfo(i).PatientPosition         = tmpDicomInfo.PatientPosition;\n    ctInfo(i).Rows                    = tmpDicomInfo.Rows;\n    ctInfo(i).Columns                 = tmpDicomInfo.Columns;\n    ctInfo(i).Width                   = tmpDicomInfo.Width;\n    ctInfo(i).Height                  = tmpDicomInfo.Height;\n    ctInfo(i).RescaleSlope            = tmpDicomInfo.RescaleSlope;\n    ctInfo(i).RescaleIntercept        = tmpDicomInfo.RescaleIntercept;\n    \n    %Problem due to some CT files using non-standard SpacingBetweenSlices\n    \n    if isempty(ctInfo(i).SliceThickness)\n        %Print warning ocne\n        if sliceThicknessStandard\n            matRad_cfg.dispWarning('Non-standard use of SliceThickness Attribute (empty), trying to overwrite with SpacingBetweenSlices');\n            sliceThicknessStandard = false;\n        end\n        ctInfo(i).SliceThickness = tmpDicomInfo.SpacingBetweenSlices;\n    end\n    \n    if i == 1\n        completeDicom = tmpDicomInfo;\n    end\n    \n    matRad_progress(i,numOfSlices);\nend\n\n% adjusting sequence of slices (filenames may not be ordered propperly....\n% e.g. CT1.dcm, CT10.dcm, CT100zCoordList = [ctInfo.ImagePositionPatient(1,3)]';.dcm, CT101.dcm,...\nCoordList = [ctInfo.ImagePositionPatient]';\n[~, indexing] = sort(CoordList(:,3)); % get sortation from z-coordinates\n\nctList = ctList(indexing);\nctInfo = ctInfo(indexing);\n\n%% check data set for consistency\nif size(unique([ctInfo.PixelSpacing]','rows'),1) > 1\n    matRad_cfg.dispError('Different pixel size in different CT slices');\nend\n\ncoordsOfFirstPixel = [ctInfo.ImagePositionPatient];\nif numel(unique(coordsOfFirstPixel(1,:))) > 1 || numel(unique(coordsOfFirstPixel(2,:))) > 1\n    matRad_cfg.dispError('Ct slices are not aligned');\nend\nif sum(diff(coordsOfFirstPixel(3,:))<=0) > 0\n    matRad_cfg.dispError('Ct slices not monotonically increasing');\nend\nif numel(unique([ctInfo.Rows])) > 1 || numel(unique([ctInfo.Columns])) > 1\n    matRad_cfg.dispError('Ct slice sizes inconsistent');\nend\n\n\n%% checking the patient position\n% As of now, the matRad treatment planning system is only valid for\n% patients in a supine position. Other orientations (e.g. prone, decubitus\n% left/right) are not supported.\n% Defined Terms:\n% HFP     Head First-Prone                  (not supported)\n% HFS     Head First-Supine                 (supported)\n% HFDR    Head First-Decubitus Right        (not supported)\n% HFDL    Head First-Decubitus Left         (not supported)\n% FFDR    Feet First-Decubitus Right        (not supported)\n% FFDL    Feet First-Decubitus Left         (not supported)\n% FFP     Feet First-Prone                  (not supported)\n% FFS     Feet First-Supine                 (supported)\n\nif isempty(regexp(ctInfo(1).PatientPosition,{'S','P'}, 'once'))\n    matRad_cfg.dispError(['This Patient Position is not supported by matRad.'...\n        ' As of now only ''HFS'' (Head First-Supine), ''FFS'''...\n        ' (Feet First-Supine), '...    \n        '''HFP'' (Head First-Prone), and ''FFP'''...\n        ' (Feet First-Prone) can be processed.'])    \nend\n\n%% creation of ct-cube\nmatRad_cfg.dispInfo('reading slices...')\norigCt = zeros(ctInfo(1).Height, ctInfo(1).Width, numOfSlices);\nfor i = 1:numOfSlices\n    currentFilename = ctList{i};\n    [currentImage, map] = dicomread(currentFilename);\n    origCt(:,:,i) = currentImage(:,:); % creation of the ct cube\n    \n    % draw current ct-slice\n    if visBool\n        if ~isempty(map)\n            image(ind2rgb(uint8(63*currentImage/max(currentImage(:))),map));\n            xlabel('x [voxelnumber]')\n            ylabel('y [voxelnumber]')\n            title(['Slice # ' int2str(i) ' of ' int2str(numOfSlices)])\n        else\n            image(ind2rgb(uint8(63*currentImage/max(currentImage(:))),bone));\n            xlabel('x [voxelnumber]')\n            ylabel('y [voxelnumber]')\n            title(['Slice # ' int2str(i) ' of ' int2str(numOfSlices)])\n        end\n        axis equal tight;\n        pause(0.1);\n    end\n    matRad_progress(i,numOfSlices);\nend\n\n%% correction if not lps-coordinate-system\n% when using the physical coordinates (ctInfo.ImagePositionPatient) to\n% arrange the  slices in z-direction, there is no more need for mirroring\n% in the z-direction\nmatRad_cfg.dispInfo('\\nz-coordinates taken from ImagePositionPatient\\n')\n\n% The x- & y-direction in lps-coordinates are specified in:\n% ImageOrientationPatient\nxDir = ctInfo(1).ImageOrientationPatient(1:3); % lps: [1;0;0]\nyDir = ctInfo(1).ImageOrientationPatient(4:6); % lps: [0;1;0]\nnonStandardDirection = false;\n\n% correct x- & y-direction\n% \n% if xDir(1) == 1 && xDir(2) == 0 && xDir(3) == 0\n%     matRad_cfg.dispInfo('x-direction OK\\n')\n% elseif xDir(1) == -1 && xDir(2) == 0 && xDir(3) == 0\n%     matRad_cfg.dispInfo('\\nMirroring x-direction...')\n%     origCt = flip(origCt,1);\n%     matRad_cfg.dispInfo('finished!\\n')\n% else\n%     nonStandardDirection = true;\n% end\n%     \n% if yDir(1) == 0 && yDir(2) == 1 && yDir(3) == 0\n%     matRad_cfg.dispInfo('y-direction OK\\n')\n% elseif yDir(1) == 0 && yDir(2) == -1 && yDir(3) == 0\n%     matRad_cfg.dispInfo('\\nMirroring y-direction...')\n%     origCt = flip(origCt,2);\n%     matRad_cfg.dispInfo('finished!\\n')\n% else\n%     nonStandardDirection = true;\n% end\n\nif nonStandardDirection\n    matRad_cfg.dispInfo(['Non-standard patient orientation.\\n'...\n        'CT might not fit to contoured structures\\n'])\nend\n\n%% interpolate cube\nmatRad_cfg.dispInfo('\\nInterpolating CT cube...');\nif exist('grid','var')\n    ct = matRad_interpDicomCtCube(origCt, ctInfo, resolution, grid);\nelse\n    ct = matRad_interpDicomCtCube(origCt, ctInfo, resolution);\nend\nmatRad_cfg.dispInfo('finished!\\n');\n\n%% remember some parameters of original dicom\nct.dicomInfo.PixelSpacing            = ctInfo(1).PixelSpacing;\n                                       tmp = [ctInfo.ImagePositionPatient];\nct.dicomInfo.SlicePositions          = tmp(3,:);\nct.dicomInfo.SliceThickness          = [ctInfo.SliceThickness];\nct.dicomInfo.ImagePositionPatient    = ctInfo(1).ImagePositionPatient;\nct.dicomInfo.ImageOrientationPatient = ctInfo(1).ImageOrientationPatient;\nct.dicomInfo.PatientPosition         = ctInfo(1).PatientPosition;\nct.dicomInfo.Width                   = ctInfo(1).Width;\nct.dicomInfo.Height                  = ctInfo(1).Height;\nct.dicomInfo.RescaleSlope            = ctInfo(1).RescaleSlope;\nct.dicomInfo.RescaleIntercept        = ctInfo(1).RescaleIntercept;\nif isfield(completeDicom, 'Manufacturer')\nct.dicomInfo.Manufacturer            = completeDicom.Manufacturer;\nend\nif isfield(completeDicom, 'ManufacturerModelName')\nct.dicomInfo.ManufacturerModelName   = completeDicom.ManufacturerModelName;\nend\nif isfield(completeDicom, 'ConvolutionKernel')\nct.dicomInfo.ConvolutionKernel       = completeDicom.ConvolutionKernel;\nend\n\n% store patientName only if user wants to\nif isfield(completeDicom,'PatientName') && dicomMetaBool == true\n    ct.dicomInfo.PatientName         = completeDicom.PatientName;\nend\nif dicomMetaBool == true\n    ct.dicomMeta                     = completeDicom;\nend\n\nct.timeStamp = datestr(clock);\n\n% convert to Hounsfield units\nmatRad_cfg.dispInfo('\\nconversion of ct-Cube to Hounsfield units...');\nct = matRad_calcHU(ct);\nmatRad_cfg.dispInfo('finished!\\n');\n\nend\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/dicom/matRad_importDicomCt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.1376217880093667}}
{"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 <http://www.gnu.org/licenses/>.\n\n% Source for TLD demo (CVPR'10)\n% Usage: \n%  1. Define input\n%     a) plug in your camera\n%     b) fill '/_input' with image sequence, define 'init.txt' (initial bounding box position)\n%  2. run demo.m\n%  3. Output of the TLD is written to 'log.txt', format [frame id; left col; top row; right col; bottom row]\n%   \n% \n% Control keys:\n%    n ... shows negative examples in online model (default on)\n%    p ... shows positive examples in online model (default on)\n%    i ... initialization of different target\n%    c ... show confidence score (default on)\n%    o ... show output as circle/dot/no output (default circle)\n%    d ... show detections (default on)\n%    t ... show target in top left corner (default off)\n%    r ... replace target with first patch (default off)\n%    # ... draw trajectory of target (default off)\n%    <space> ... svae current image\n%    1 ... mode without learning (fast, does not improve)\n%    2 ... mode with learning (slower, but can learn new appearances and discriminate)\n%    q ... quit application\n\naddpath(genpath('.')); init_workspace; \n\n% Input\nopt.source          = struct('camera',0,'input','_input/','bb0',[]);\nopt.debug           = 0;\nopt.name            = '_snapshots/'; mkdir(opt.name); % saves s snapshot every 100th frames\n\n% Parameters\nopt.model           = struct('ncc_thesame',0.95,'valid',0.5,'patchsize',[10 10],'min_win',20,'num_trees',10,'num_features',13,'thr_fern',0.5,'thr_nn',0.65,'thr_nn_valid',0.7,'fliplr',0);\nopt.p_par_init      = struct('num_closest',10,'num_warps',20,'noise',5,'angle',20,'shift',0.02,'scale',0.02);\nopt.p_par_update    = struct('num_closest',10,'num_warps',10,'noise',5,'angle',10,'shift',0.02,'scale',0.02);\nopt.n_par           = struct('overlap',0.2,'num_patches',100,'num_synthetic',0,'noise',1);\nopt.tracker         = struct('occlusion',10,'grid',10,'big_fb',10);\nopt.control         = struct('maxbbox',.9,'update_detector',1,'drop_img',1,'repeat',1,'rescale',1);\nopt.plot            = struct('pex',1,'nex',1,'save',0,'dt',0,'confidence',0,'target',0,'replace',0,'drawoutput',3,'draw',0,'pts',0,'help', 0,'patch_rescale',1);\n\n%  profile on;\nglobal tld;\ntldDemo(opt);\n%   profile off;\n%   profile viewer;", "meta": {"author": "zk00006", "repo": "OpenTLD", "sha": "953e2df96575ba9e3e0720b8f91e936c26c9b2e3", "save_path": "github-repos/MATLAB/zk00006-OpenTLD", "path": "github-repos/MATLAB/zk00006-OpenTLD/OpenTLD-953e2df96575ba9e3e0720b8f91e936c26c9b2e3/other/run_TLD_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2568319913875189, "lm_q1q2_score": 0.13743039501250479}}
{"text": "function filteredOutS = sitkWrapper(sitkLibPath, scan3M, filterType, paramS)\n%function filteredOutS = sitkWrapper(sitkLibPath, scan3M, filterType, paramS, planC)\n%Calculate image filters using the Simple ITK Python Library\n%--------------------------------------------------------------------------\n%sitkLibPath - location of sitk python wrappscan to be filtered\n%description - Short description string if desired.\n%filterType - name of sitk filter\n%             Supported options: 'GradientImageFilter','HistogramMatchingImageFilter',...\n%             'LaplacianRecursiveGaussianImageFilter',...\n%             'N4BiasFieldCorrectionImageFilter',\n%             'N4BiasAndHistogramCorrectionImageFilter'.\n%paramS: parameters required to calculate the filter\n%planC: to convert scan back to cerr\n%--------------------------------------------------------------------------\n% example usage:\n% filterType = 'GradientImageFilter';\n% paramS.useImageSpacing = false;\n% paramS.useImageDirection = true;\n% sitkLibPath = 'C:\\Python34\\Lib\\site-packages\\SimpleITK\\';\n% planC = loadPlanC(cerrFileName,tempdir);\n% planC = updatePlanFields(planC);\n% % Quality assure\n% planC = quality_assure_planC(cerrFileName,planC);\n% indexS = planC{end};\n%  % Get Scan\n%  scanNum  =1;\n%  scanM = double(planC{indexS.scan}(scanNum).scanArray) ...\n%      - planC{indexS.scan}(scanNum).scanInfo(1).CTOffset;%\n%\n% sitkWrapper(sitkLibPath, scanM, filterType, paramS)\n%\n%\n% Rutu Pandya, Dec, 16 2019.\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.\n\n\n% import python module SimpleITK\nsitkModule = 'SimpleITK';\nnumpyModule = 'numpy';\n%p = pyenv;\n\nP = py.sys.path;\ncurrentPath = pwd;\ncd(sitkLibPath);\nsitkFileName = fullfile(sitkLibPath,sitkModule);\nnumpyFileName = fullfile(sitkLibPath,numpyModule);\n\ntry\n    if count(P,numpyFileName) == 0\n        insert(P,int32(0),numpyFileName);\n    end\n    np = py.importlib.import_module(numpyModule);\n    if count(P,sitkFileName) == 0\n        insert(P,int32(0),sitkFileName);\n    end\n    sitk = py.importlib.import_module(sitkModule);\ncatch\n    disp('SimpleITK module could not be imported, check the path');\nend\n\ncd(currentPath);\n\n%origScanSize = size(scanM);\n% visualize original scan\n%slc = 50;\n%figure, imagesc(scanM(:,:,50)), title('orig Image')\n\n\n% % convert scan to numpy array and integer\n% scanPy = py.numpy.array(scanM(:).');\n% scanPy = scanPy.astype(py.numpy.int64);\n%\n% % get original shape of the scan\n% origShape = py.numpy.array(size(scanM));\n% origShape = origShape.astype(py.numpy.int64);\n\n\nswitch filterType\n    case 'GradientImageFilter'\n        % paramS inputs needed:\n        % useImageSpacing (bool), true by default\n        % useImageDirection (bool), true by default\n        \n        % convert scan to numpy array and integer\n        scanPy = np.array(scan3M);\n        scanPy = scanPy.astype(py.numpy.float32);\n        \n        % get original shape of the scan\n        %origShape = py.numpy.array(size(scanM));\n        %origShape = origShape.astype(py.numpy.int64);\n        \n        % reshape numpy array to original shape\n        %scanPy = reshape(scanPy,origShape);\n        \n        % Get image from the array\n        itkimg = sitk.GetImageFromArray(scanPy);\n        \n        % calculate gradient\n        gradient = sitk.GradientImageFilter();\n        \n        if(paramS.useImageSpacing == false)\n            gradient.SetUseImageSpacing(paramS.useImageSpacing);\n        end\n        if(paramS.useImageDirection == false)\n            gradient.SetUseImageDirection(paramS.useImageDirection);\n        end\n        gradImg = gradient.Execute(itkimg);\n        \n        % extract numpy array from resulting image\n        npGradImg = sitk.GetArrayFromImage(gradImg);\n        \n        % convert resulting numpy array to matlab array in required shape\n        %dblGradResultM = double(py.array.array('d',py.numpy.nditer(npGradImg)));\n        %gradMatM = reshape(dblGradResultM,[3,origScanSize]);\n        gradMatM = double(npGradImg);\n        gradMatM = permute(gradMatM,[2,3,4,1]);\n        \n        %             %visualize\n        %             size(gradMatM)\n        %             figure, imagesc(gradMatM(:,:,50,1))\n        %             figure, imagesc(gradMatM(:,:,50,2))\n        %             figure, imagesc(gradMatM(:,:,50,3))\n        \n        filteredOutS.xGradient = gradMatM(:,:,:,1);\n        filteredOutS.yGradient = gradMatM(:,:,:,2);\n        filteredOutS.zGradient = gradMatM(:,:,:,3);\n        \n        \n    case 'LaplacianRecursiveGaussianImageFilter'\n        \n        % convert scan to numpy array and integer\n        % scanPy = py.numpy.array(scanM(:).');\n        scanPy = np.array(scan3M);\n        scanPy = scanPy.astype(py.numpy.float32);\n        \n        % get original shape of the scan\n        %origShape = py.numpy.array(size(scanM));\n        %origShape = origShape.astype(py.numpy.int64);\n        \n        % reshape numpy array to original shape\n        %scanPy = reshape(scanPy,origShape);\n        \n        % Get image from the array\n        itkimg = sitk.GetImageFromArray(scanPy);\n        \n        % Set Image spacing\n        zSpacing = paramS.VoxelSize_mm.val(3);\n        xSpacing = paramS.VoxelSize_mm.val(1);\n        ySpacing = paramS.VoxelSize_mm.val(2);\n        itkimg.SetSpacing([zSpacing, ySpacing, xSpacing]);\n        \n        % calculate gradient\n        logRecursiveFilt = sitk.LaplacianRecursiveGaussianImageFilter();\n        \n        logRecursiveFilt.SetNormalizeAcrossScale(true)\n        \n        sigmaVal = paramS.Sigma_mm.val;\n        logRecursiveFilt.SetSigma(sigmaVal);\n        \n        % Execute the filter\n        logImg = logRecursiveFilt.Execute(itkimg);\n        \n        % extract numpy array from resulting image\n        npLogImg = sitk.GetArrayFromImage(logImg);\n        \n        % convert resulting numpy array to matlab array in required shape\n        %dblLogResultM = double(py.array.array('d',py.numpy.nditer(npLogImg)));\n        %logMatM = reshape(dblLogResultM,origScanSize);\n        \n        logMatM = double(npLogImg);\n        \n        filteredOutS.logImg3M = logMatM;\n        \n        \n    case 'HistogramMatchingImageFilter'\n        % paramS inputs needed:\n        % numHistLevel (int), paramS.numMatchPts (int),\n        % ThresholdAtMeanIntensityOn (bool),\n        % refImgPath (char vector)\n        \n        % convert scan to numpy array and integer\n        scan3M = permute(scan3M,[3,1,2]);\n        scanPy = np.array(scan3M);\n        scanPy = scanPy.astype(py.numpy.float32);\n        \n        % get original shape of the scan\n        %origShape = py.numpy.array(size(scanM(:)'));\n        %origShape = origShape.astype(py.numpy.int64);\n        \n        % reshape numpy array to original shape\n        %scanPy = reshape(scanPy,origShape);\n        \n        % Get image from the array\n        \n        srcItkImg = sitk.GetImageFromArray(scanPy);\n        \n        \n        %             srcItkImg = py.SimpleITK.ReadImage('E:\\data\\TumorAware_MR\\nrrdScanFormat.nrrd');\n        \n        % get ref image\n        maskImgPath = fullfile(getCERRPath,'ModelImplementationLibrary/SegmentationModels/referenceImages');\n        if isfield(paramS,'refImg') && ~isempty(paramS.refImg.val)\n            [refPath,~,~,] = fileparts(paramS.refImg.val);\n            if isempty(refPath)\n                maskImgPath = fullfile(maskImgPath,paramS.refImg.val);\n            else\n                maskImgPath = paramS.refImg.val;\n            end\n            refItkImg = sitk.ReadImage(maskImgPath);\n            refItkImg = sitk.Cast(refItkImg,py.SimpleITK.sitkFloat32);\n            \n            %Adjust to RTOG-compliant orientation \n            %maskPy = sitk.GetArrayFromImage(refItkImg);\n            %mask3M = single(maskPy);\n            %mask3M = flip(flip(permute(mask3M,[2,3,1]),1),3); % flip y and z dims to convert from RAS to CERR coordinate system\n            %mask3M = permute(mask3M,[3,1,2]);\n            %scanRefPy = np.array(mask3M);\n            %scanRefPy = scanRefPy.astype(py.numpy.float32);            \n            %refItkImg1 = sitk.GetImageFromArray(scanRefPy);\n            \n            %mask3M = flip(flip(mask3M,1),2);\n            %mask3M = flip(mask3M,3);\n            %maskPy = np.array(mask3M);\n            %refItkImg = py.extra.GetImageFromArray(maskPy);\n        elseif isfield(paramS,'refImgMat') && ~isempty(paramS.refImgMat.val)\n            maskPy = np.array(paramS.refImgMat.val);\n            maskPy = maskPy.astype(py.numpy.float32);   \n            % Get image from the array\n            refItkImg = sitk.GetImageFromArray(maskPy);\n        else\n            error('Reference image not specified for histogram matching')\n        end\n        \n        %refNumElems = int64(py.numpy.prod(refScanPy.shape));\n        %refShape = py.numpy.array([1,refNumElems]);\n        %refScanPy = refScanPy.astype(py.numpy.int64);        \n        % reshape numpy array to original shape\n        %refScanPy = reshape(refScanPy,refShape);\n        \n        \n        \n        %refItkImg = py.SimpleITK.reshape(refItkImg, scanPy);\n        % execute Histogram Matching\n        matcher = sitk.HistogramMatchingImageFilter();\n        matcher.SetNumberOfHistogramLevels(uint32(paramS.numHistLevel.val));\n        matcher.SetNumberOfMatchPoints(uint32(paramS.numMatchPts.val));\n        matcher.SetThresholdAtMeanIntensity(false)\n        if paramS.thresholdAtMeanIntensityOn.val\n            matcher.SetThresholdAtMeanIntensity(true);\n        end\n        matchedImg = matcher.Execute(srcItkImg,refItkImg);\n        \n        % extract numpy array from resulting image\n        npHistImg = sitk.GetArrayFromImage(matchedImg);\n        \n        % convert resulting numpy array to matlab array in required shape\n        %dblHistResultM = double(py.array.array('d',py.numpy.nditer(npHistImg)));\n        %histMatM = reshape(dblHistResultM,[origScanSize(1),origScanSize(2),origScanSize(3)]);\n        histMatM = double(npHistImg);\n        \n        filteredOutS.histMatchedImage = permute(histMatM,[2,3,1]);\n        \n        %             %visualize\n        %             size(histMatM)\n        %             figure, imagesc(histMatM(:,:,slc,1))\n        %             figure, imagesc(histMatM(:,:,slc,2))\n        %             figure, imagesc(histMatM(:,:,slc,3))\n        \n    case 'N4BiasFieldCorrectionImageFilter'\n\n        % Convert to sitk image   \n        scan3M = permute(scan3M,[3,1,2]);\n        scanPy = np.array(scan3M);\n        scanPy = scanPy.astype(py.numpy.float32);\n        srcItkImg = sitk.GetImageFromArray(scanPy);\n\n        % Get mask\n        if isfield(paramS,'maskImg') && ~isempty(paramS.maskImg.val)\n            maskImgPath = fullfile(paramS.maskImg.val);\n            maskImg = sitk.ReadImage(maskImgPath);\n            maskImg = sitk.Cast(maskImg,py.SimpleITK.sitkFloat32);\n            %Adjust to RTOG-compliant orientation \n            maskPy = sitk.GetArrayFromImage(maskImg);\n            mask3M = single(maskPy);\n            mask3M = permute(mask3M,[2,3,1]);\n            mask3M = flip(flip(mask3M,1),2);\n            mask3M = flip(mask3M,3);\n            maskPy = np.array(mask3M);\n            maskImg = sitk.GetImageFromArray(maskPy);\n        else\n            %Use defaults\n            %maskImg = py.SimpleITK.OtsuThreshold(srcItkImg,...\n            %    uint8(0),uint8(1),uint32(200));\n            maskImg = [];\n        end\n\n        corrector = sitk.N4BiasFieldCorrectionImageFilter();\n\n        % Get optional parameters\n        if isfield(paramS,'shrinkFactor') && paramS.shrinkFactor.val > 1\n            shrink = paramS.shrinkFactor.val;\n            srcItkImg = sitk.Shrink(srcItkImg,...\n                shrink*srcItkImg.GetDimension());\n            maskImg = sitk.Shrink(maskImg,...\n                shrink*srcItkImg.GetDimension());\n        end\n\n        if isfield(paramS,'numFittingLevels') \n            numFitLevels = paramS.numFittingLevels.val;\n        else\n            numFitLevels = 4;\n        end\n\n        if isfield(paramS,'numIterations')\n            numIterationsV = paramS.numIterations.val; %Vector of values per fit level\n            maxIterations = int32(numIterationsV);\n            corrector.SetMaximumNumberOfIterations(maxIterations);\n        end\n\n\n        % Apply bias correction\n        if ~isempty(maskImg)\n            outImg = corrector.Execute(srcItkImg, maskImg);\n        else\n            outImg = corrector.Execute(srcItkImg);\n        end\n        \n        logBiasFieldImg = corrector.GetLogBiasFieldAsImage(srcItkImg);\n        \n        % Convert to matlab array         \n        npLogBiasFieldImg = sitk.GetArrayFromImage(logBiasFieldImg);\n        logBiasFieldImg3M = double(npLogBiasFieldImg);\n        \n        correctedImageFullResolution = scan3M ./ exp(logBiasFieldImg3M);\n        \n        filteredOutS.biasCorrectedImage = permute(correctedImageFullResolution,[2,3,1]);\n        \n        %if isfield(paramS,'shrinkFactor') && paramS.shrinkFactor.val > 1\n        %  npCorrectedImg = py.extra.GetArrayFromImage(outImg);\n        %  correctedImgShrunk3M = double(npCorrectedImg);\n        %end\n\n\n    case 'N4BiasAndHistogramCorrectionImageFilter'\n        filteredOutS = sitkWrapper(sitkLibPath, scan3M, ...\n            'N4BiasFieldCorrectionImageFilter', paramS);\n        correctedScan3M = filteredOutS.biasCorrectedImage;\n        filteredOutS = sitkWrapper(sitkLibPath, correctedScan3M, ...\n            'HistogramMatchingImageFilter', paramS);\n\n    otherwise\n        \n        msgStr = [filterType,' not defined. Add it to sitkWrapper.m'];\n        error(msgStr)\nend\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/PlanMetrics/heterogenity_metrics/sitkWrapper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.25982564942392716, "lm_q1q2_score": 0.13701035427891575}}
{"text": "%                                                            y = bwdpr1(Lden, b)\n% BWDPR1  Solves \"PROD_k L(pk,betak)' * y = b\", where\n%     L(p,beta) = eye(n) + tril(p*beta',-1).\n%\n% **********  INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi, dpr1fact, fwdpr1\n\nfunction y = bwdpr1(Lden, b) %#ok\n%\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n%   Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n%   CRL, McMaster University, Canada.\n%   Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n%\n\ndisp('The SeDuMi binaries are not installed.')\ndisp('In Matlab, launch \"install_sedumi\" in the folder you put the SeDuMi files.')\ndisp('For more information see the file Install.txt.')\nerror(' ')", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/sedumi/bwdpr1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.25982563222951205, "lm_q1q2_score": 0.13701034907216433}}
{"text": "function trl = ft_trialfun_realtime(cfg)\n\n% FT_TRIALFUN_REALTIME can be used to segment a continuous stream of\n% data in real-time. Trials are defined as [begsample endsample offset\n% condition]\n%\n% The configuration structure can contain the following specifications\n%   cfg.minsample  = the last sample number that was already considered (passed from rt_process)\n%   cfg.blocksize  = in seconds. In case of events, offset is with respect to the trigger.\n%   cfg.offset     = the offset wrt the 0 point. In case of no events, offset is wrt\n%                    prevSample. E.g., [-0.9 1] will read 1 second blocks with\n%                    0.9 second overlap\n%   cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of\n%                    interest is read. Otherwise, all well-defined blocks are read (default = 'first')\n\n% Copyright (C) 2009, Marcel van Gerven\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 <http://www.gnu.org/licenses/>.\n%\n% $Id$\n\nif ~isfield(cfg,'minsample'),   cfg.minsample = 0;        end\nif ~isfield(cfg,'blocksize'),   cfg.blocksize = 0.1;  end\nif ~isfield(cfg,'offset'),      cfg.offset = 0; end\nif ~isfield(cfg,'bufferdata'),  cfg.bufferdata = 'first'; end\nif ~isfield(cfg,'triggers'),    cfg.triggers = [];        end\n\n% blocksize and offset in terms of samples\ncfg.blocksize = round(cfg.blocksize * cfg.hdr.Fs);\ncfg.offset = round(cfg.offset * cfg.hdr.Fs);\n\n% retrieve trials of interest\nif isempty(cfg.event) % asynchronous mode\n  trl = trialfun_asynchronous(cfg);\nelse % synchronous mode\n  trl = trialfun_synchronous(cfg);\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction trl = trialfun_asynchronous(cfg)\n\ntrl = [];\n\nprevSample = cfg.minsample;\n\nif strcmp(cfg.bufferdata, 'last') % only get last block\n  \n  % begsample starts blocksize samples before the end\n  begsample  = cfg.hdr.nSamples*cfg.hdr.nTrials - cfg.blocksize;\n  \n  % begsample should be offset samples away from the previous read\n  if begsample >= (prevSample + cfg.offset)\n    \n    endsample  = cfg.hdr.nSamples*cfg.hdr.nTrials;\n    \n    if begsample < endsample && begsample > 0\n      trl = [begsample endsample 0 nan];\n    end\n  end\n  \nelse % get all blocks\n  \n  while true\n    \n    % see whether new samples are available\n    newsamples = (cfg.hdr.nSamples*cfg.hdr.nTrials-prevSample);\n    \n    % if newsamples exceeds the offset plus length specified in blocksize\n    if newsamples >= (cfg.offset+cfg.blocksize)\n      \n      % we do not consider samples < 1\n      begsample  = max(1,prevSample+cfg.offset);\n      endsample  = max(1,prevSample+cfg.offset+cfg.blocksize);\n      \n      if begsample < endsample && endsample <= cfg.hdr.nSamples*cfg.hdr.nTrials\n        trl = [trl; [begsample endsample 0 nan]];\n      end\n      prevSample = endsample;\n      \n    else\n      break;\n    end\n  end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% SUBFUNCTION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction trl = trialfun_synchronous(cfg)\n\ntrl = [];\n\n% process all events\nfor j=1:length(cfg.event)\n  \n  if isempty(cfg.triggers)\n    curtrig = cfg.event(j).value;\n  else\n    [m1,curtrig] = ismember(cfg.event(j).value,cfg.triggers);\n  end\n  \n  if isempty(curtrig), curtrig = nan; end\n  \n  if isempty(cfg.triggers) || (~isempty(m1) && m1)\n    % catched a trigger of interest\n    \n    % we do not consider samples < 1\n    begsample = max(1,cfg.event(j).sample + cfg.offset);\n    endsample = max(1,begsample + cfg.blocksize);\n    \n    trl = [trl; [begsample endsample cfg.offset curtrig]];\n    \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/trialfun/ft_trialfun_realtime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.13685843721711904}}
{"text": "%\n%       HDR Toolbox demo 3:\n%\t   1) Load \"CS_Warwick.hdr\" HDR image\n%\t   2) Change the mapping from Longitude Latitude to Cube Map\n%\t   3) Show the new HDR image using gamma encoding\n%\t   4) Write the cube map on the disk\n%\t   5) Write on the disk each face of the cube map ready for OpenGL or\n%\t   Direct3D\n%\n%       Author: Francesco Banterle\n%       Copyright June 2012 (c)\n%\n%\n\nclear all;\n\ndisp('1) Load \"CS_Warwick.hdr\" HDR image');\nimg = hdrimread('demos/CS_Warwick.hdr');\n\ndisp('2) Change the mapping from Longitude Latitude to Cube Map');\nimgOut = ChangeMapping(img, 'LongitudeLatitude', 'CubeMap');\n\ndisp('3) Visualization of the new HDR image using gamma encoding');\nldr = GammaTMO(imgOut, 2.2, 0.0, 1);\n\ndisp('4) Write the cube map on the disk');\nhdrimwrite(imgOut, 'demos/output/CS_Warwick_CUBE_MAP_format.hdr');\n\ndisp('5) Write each face of the cube map on the disk');\nCrossCutter(imgOut, 'demos/output/CS_Warwick_CM', 'hdr');", "meta": {"author": "banterle", "repo": "HDR_Toolbox", "sha": "a2b45dc48b7169192fb633097a83879e71a0c0f2", "save_path": "github-repos/MATLAB/banterle-HDR_Toolbox", "path": "github-repos/MATLAB/banterle-HDR_Toolbox/HDR_Toolbox-a2b45dc48b7169192fb633097a83879e71a0c0f2/demos/demo_environment_maps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.13655193581555047}}
{"text": "function plotData(x, y)\n%PLOTDATA Plots the data points x and y into a new figure \n%   PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n%   population and profit.\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the training data into a figure using the \n%               \"figure\" and \"plot\" commands. Set the axes labels using\n%               the \"xlabel\" and \"ylabel\" commands. Assume the \n%               population and revenue data have been passed in\n%               as the x and y arguments of this function.\n%\n% Hint: You can use the 'rx' option with plot to have the markers\n%       appear as red crosses. Furthermore, you can make the\n%       markers larger by using plot(..., 'rx', 'MarkerSize', 10);\n\nfigure; % open a new figure window\n\nplot(x, y, 'rx', 'MarkerSize', 10);      % Plot the data\nylabel('Profit in $10,000s');            % Set the y-axis label\nxlabel('Population of City in 10,000s'); % Set the x-axis label\n\n% ============================================================\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex1_solution/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.13434127859733538}}
{"text": "%-----------------------------------------------------------------------\n% Job saved on 19-Jan-2014 14:08:03 by cfg_util (rev $Rev: 7703 $)\n% spm SPM - SPM12b (beta)\n% cfg_basicio BasicIO - Unknown\n%-----------------------------------------------------------------------\nmatlabbatch{1}.spm.meeg.source.headmodel.val = 1;\nmatlabbatch{1}.spm.meeg.source.headmodel.comment = '';\nmatlabbatch{1}.spm.meeg.source.headmodel.meshing.meshes.template = 1;\nmatlabbatch{1}.spm.meeg.source.headmodel.meshing.meshres = 2;\nmatlabbatch{1}.spm.meeg.source.headmodel.coregistration.coregspecify.useheadshape = 0;\nmatlabbatch{1}.spm.meeg.source.headmodel.forward.eeg = 'EEG BEM';\nmatlabbatch{1}.spm.meeg.source.headmodel.forward.meg = 'Single Shell';\nmatlabbatch{2}.spm.tools.beamforming.data.D(1) = cfg_dep('M/EEG head model specification: M/EEG dataset(s) with a forward model', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','D'));\nmatlabbatch{2}.spm.tools.beamforming.data.val = 1;\nmatlabbatch{2}.spm.tools.beamforming.data.gradsource = 'inv';\nmatlabbatch{2}.spm.tools.beamforming.data.space = 'MNI-aligned';\nmatlabbatch{2}.spm.tools.beamforming.data.overwrite = 1;\nmatlabbatch{3}.spm.tools.beamforming.sources.BF(1) = cfg_dep('Prepare data: BF.mat file', substruct('.','val', '{}',{2}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{3}.spm.tools.beamforming.sources.reduce_rank = [2 3];\nmatlabbatch{3}.spm.tools.beamforming.sources.keep3d = 1;\nmatlabbatch{3}.spm.tools.beamforming.sources.plugin.mesh.orient = 'original';\nmatlabbatch{3}.spm.tools.beamforming.sources.plugin.mesh.fdownsample = 1;\nmatlabbatch{3}.spm.tools.beamforming.sources.plugin.mesh.flip = false;\nmatlabbatch{3}.spm.tools.beamforming.sources.visualise = 1;\nmatlabbatch{4}.spm.tools.beamforming.features.BF(1) = cfg_dep('Define sources: BF.mat file', substruct('.','val', '{}',{3}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{4}.spm.tools.beamforming.features.whatconditions.all = 1;\nmatlabbatch{4}.spm.tools.beamforming.features.woi = [-Inf Inf];\nmatlabbatch{4}.spm.tools.beamforming.features.modality = {'MEG'};\nmatlabbatch{4}.spm.tools.beamforming.features.fuse = 'no';\nmatlabbatch{4}.spm.tools.beamforming.features.plugin.cov.foi = [0 Inf];\nmatlabbatch{4}.spm.tools.beamforming.features.plugin.cov.taper = 'none';\nmatlabbatch{4}.spm.tools.beamforming.features.regularisation.manual.lambda = 1;\nmatlabbatch{4}.spm.tools.beamforming.features.bootstrap = false;\nmatlabbatch{5}.spm.tools.beamforming.inverse.BF(1) = cfg_dep('Covariance features: BF.mat file', substruct('.','val', '{}',{4}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{5}.spm.tools.beamforming.inverse.plugin.eloreta.regularisation = 0.05;\nmatlabbatch{6}.spm.tools.beamforming.output.BF(1) = cfg_dep('Inverse solution: BF.mat file', substruct('.','val', '{}',{5}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.whatconditions.all = 1;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.sametrials = false;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.contrast = 1;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.result = 'singleimage';\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.scale = 2;\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.powermethod = 'trace';\nmatlabbatch{6}.spm.tools.beamforming.output.plugin.image_power.modality = 'MEG';\nmatlabbatch{7}.spm.tools.beamforming.write.BF(1) = cfg_dep('Output: BF.mat file', substruct('.','val', '{}',{6}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('.','BF'));\nmatlabbatch{7}.spm.tools.beamforming.write.plugin.gifti.normalise = 'no';\nmatlabbatch{7}.spm.tools.beamforming.write.plugin.gifti.space = 'mni';\nmatlabbatch{7}.spm.tools.beamforming.write.plugin.gifti.visualise = 2;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/DAiSS/bf_pipeline_eLORETA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.25386100132422423, "lm_q1q2_score": 0.1338651006399456}}
{"text": "function [TruePositives, FalseNegatives] = testAromaticAADegradation(model, microbeID, biomassReaction, database)\n% Performs an FVA and reports those AromaticAA pathway end reactions (exchange reactions)\n% that can carry flux in the model and should carry flux according to\n% data (true positives) and those AromaticAA pathway end reactions that\n% cannot carry flux in the model but should be secreted according to in\n% vitro data (false negatives).\n%\n% INPUT\n% model             COBRA model structure\n% microbeID         Microbe ID in carbon source data file\n% biomassReaction   Biomass objective functions (low flux through BOF\n%                   required in analysis)\n% database          Structure containing rBioNet reaction and metabolite\n%                   database\n%\n% OUTPUT\n% TruePositives     Cell array of strings listing all aromatic amino acid\n% degradation products\n% that can be secreted by the model and in comnparative genomic data.\n% FalseNegatives    Cell array of strings listing all aromatic amino acid\n% degradation products\n% that cannot be secreted by the model but should be secreted according to comparative genomic data.\n%\n% .. Author:\n%      Almut Heinken, Dec 2017\n%                     March  2022 - changed code to string-matching to make\n%                     it more robust\n\nglobal CBT_LP_SOLVER\nif isempty(CBT_LP_SOLVER)\n    initCobraToolbox\nend\n\n% read aromatic amino acid degradation product table\ndataTable = readInputTableForPipeline('AromaticAATable.txt');\n\ncorrRxns = {'Phenylpropanoate','EX_pppn(e)';'4-Hydroxyphenylpropanoate','EX_r34hpp(e)';'Indolepropionate','EX_ind3ppa(e)';'Isocaproate','EX_isocapr(e)'};\n\nTruePositives = {};  % true positives (uptake in vitro and in silico)\nFalseNegatives = {};  % false negatives (uptake in vitro not in silico)\n\n% find microbe index in data table\nmInd = find(strcmp(dataTable(:,1), microbeID));\nif isempty(mInd)\n    warning(['Microbe \"', microbeID, '\" not found in aromatic amino acid degradation data file.'])\nelse\n    % perform FVA to identify uptake metabolites\n    % set BOF\n    if ~any(ismember(model.rxns, biomassReaction)) || nargin < 3\n        error(['Biomass reaction \"', biomassReaction, '\" not found in model.'])\n    end\n    model = changeObjective(model, biomassReaction);\n    % set a low lower bound for biomass\n    %     model = changeRxnBounds(model, biomassReaction, 1e-3, 'l');\n    % list exchange reactions\n    exchanges = model.rxns(strncmp('EX_', model.rxns, 3));\n    % open all exchanges\n    model = changeRxnBounds(model, exchanges, -1000, 'l');\n    model = changeRxnBounds(model, exchanges, 1000, 'u');\n\n    % get the reactions to test\n    rxns = {};\n    for i=2:size(dataTable,2)\n        if contains(version,'(R202') % for Matlab R2020a and newer\n            if dataTable{mInd,i}==1\n                findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n                rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n            end\n        else\n            if strcmp(dataTable{mInd,i},'1')\n                findCorrRxns = find(strcmp(corrRxns(:,1),dataTable{1,i}));\n                rxns = union(rxns,corrRxns(findCorrRxns,2:end));\n            end\n        end\n    end\n\n    % flux variability analysis on reactions of interest\n    rxns = unique(rxns);\n    rxns = rxns(~cellfun('isempty', rxns));\n    rxnsInModel=intersect(rxns,model.rxns);\n    if ~isempty(rxnsInModel)\n        currentDir=pwd;\n        try\n            [minFlux, maxFlux, ~, ~] = fastFVA(model, 0, 'max', 'ibm_cplex', ...\n                rxnsInModel, 'S');\n        catch\n            warning('fastFVA could not run, so fluxVariability is instead used. Consider installing fastFVA for shorter computation times.');\n            cd(currentDir)\n            [minFlux, maxFlux] = fluxVariability(model, 0, 'max', rxnsInModel);\n        end\n\n        % active flux\n        flux = rxnsInModel(maxFlux > 1e-6);\n    else\n        flux = {};\n    end\n\n    % which reaction should carry flux according to in vitro data\n    for i=2:size(dataTable,2)\n        rxn={};\n        if contains(version,'(R202') % for Matlab R2020a and newer\n            if dataTable{mInd,i}==1\n                rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n            end\n        else\n            if strcmp(dataTable{mInd,i},'1')\n                rxn = corrRxns{find(strcmp(corrRxns(:,1),dataTable{1,i})),2};\n            end\n        end\n        if ~isempty(rxn)\n            % add any that are not in model/not carrying flux to the false negatives\n            if ~isempty(intersect(rxn,flux))\n                TruePositives = union(TruePositives,rxn);\n            else\n                FalseNegatives=union(FalseNegatives,rxn);\n            end\n        end\n    end\nend\n\n% replace reaction IDs with metabolite names\nif ~isempty(TruePositives)\n    TruePositives = TruePositives(~cellfun(@isempty, TruePositives));\n    TruePositives=strrep(TruePositives,'EX_','');\n    TruePositives=strrep(TruePositives,'(e)','');\n\n    for i=1:length(TruePositives)\n        TruePositives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),TruePositives{i})),2};\n    end\nend\n\n% warn about false negatives\nif ~isempty(FalseNegatives)\n    FalseNegatives = FalseNegatives(~cellfun(@isempty, FalseNegatives));\n    FalseNegatives=strrep(FalseNegatives,'EX_','');\n    FalseNegatives=strrep(FalseNegatives,'(e)','');\n    for i = 1:length(FalseNegatives)\n        FalseNegatives{i}=database.metabolites{find(strcmp(database.metabolites(:,1),FalseNegatives{i})),2};\n    end\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/demeter/suite/tests/testAromaticAADegradation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.25982562649804053, "lm_q1q2_score": 0.13295708740670992}}
{"text": "clear; clc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Add dependencies\ndir_lib_caffe = './fast-rcnn/caffe-fast-rcnn/matlab/caffe/';\ndir_lib_frcn = './fast-rcnn/matlab/';\ndir_lib_edgebox = './edges/';\ndir_lib_ptoolbox = './toolbox/';\n\naddpath(genpath(dir_lib_caffe));\naddpath(genpath(dir_lib_frcn));\naddpath(genpath(dir_lib_edgebox));\naddpath(genpath(dir_lib_ptoolbox));\n \n% Set directories\ndir_data = './data/';\nfile_input_img = [dir_data, 'input_img.jpg'];\n\nfile_model_edgebox = [dir_lib_edgebox, 'models/forest/modelBsds.mat'];\nfile_def_frcn = './models/fashion_detector.prototxt';\nfile_net_frcn = './models/fashion_detector.caffemodel';\n\ndir_results = './results/';\nfile_output_bbox = [dir_results, 'bbox_img.mat'];\n\n% Set hyper-parameters\nflag_visualize = true;\nsize_img_max = 227;\nid_category = 1; % '1' represents upper-body clothes, '2' represents lower-body clothes, '3' represents full-body clothes \n\n% Initialize EdgeBox model\nmodel_edgebox = load(file_model_edgebox);\nmodel_edgebox = model_edgebox.model;\nmodel_edgebox.opts.multiscale = 0;\nmodel_edgebox.opts.sharpen = 2;\nmodel_edgebox.opts.nThreads = 4;\n\nopts_edgebox = edgeBoxes;\nopts_edgebox.alpha = .65;      % step size of sliding window search\nopts_edgebox.beta  = .65;      % nms threshold for object proposals\nopts_edgebox.minScore = .01;   % min score of boxes to detect\nopts_edgebox.maxBoxes = 1e4;   % max number of boxes to detect\n\n% Initialize fast R-CNN model\ntic;\nuse_gpu = true;\nmodel_frcn = fast_rcnn_load_net(file_def_frcn, file_net_frcn, use_gpu);\ndisp('### Initialization completed: ');\ntoc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Read image\nimg_cur = imread(file_input_img);\nheight_img = size(img_cur, 1);\nwidth_img = size(img_cur, 2);\nchannel_img = size(img_cur, 3);\n\n% Resize image for speed-up\nif max([height_img, width_img]) > size_img_max\n\tratio = size_img_max ./ max([height_img, width_img]);\n\timg_resized = imresize(img_cur, ratio);\nelse\n\tratio = 1;\n\timg_resized = img_cur;\nend\n\n% Generate object proposals using EdgeBox\ntic;\ntry\n\tproposals_cur = edgeBoxes(img_resized, model_edgebox, opts_edgebox);\ncatch\n\tcontinue;\n\twarning('!!! error generating object proposals');\nend\nproposals_cur = proposals_cur(:, 1:4); % only keep coordinates\nproposals_cur(:, 3:4) = proposals_cur(:, 1:2) + proposals_cur(:, 3:4); % convert [x, y, w, h] to [x1, y1, x2, y2]\nproposals_cur = single(proposals_cur) + 1; % account for the 0-based indexing in EdgeBox\ndisp('### EdgeBox completed : ');\ntoc;\n\n% Sanity check proposals \nif isempty(proposals_cur)\n\tcontinue;\n\twarning('!!! no proposal generated');\nend\n\n% Detecting clothes using fast R-CNN \ntic;\ntry\n\tbbox_pred = fast_rcnn_im_detect(model_frcn, img_resized, proposals_cur);\ncatch\n\tcontinue;\n\twarning('!!! error running fast R-CNN');\nend\ndisp('### Fast R-CNN completed: ');\ntoc;\n\n% Transform bounding box back into original coordinates w.r.t input image\nbbox_img = cell(3, 1);\nfor id_category = 1:3\n\tbbox_img{id_category}(:, 1:4) = bbox_pred{id_category}(:, 1:4) ./ ratio;\n\tbbox_img{id_category}(:, 5) = bbox_pred{id_category}(:, 5);\nend\n\n% Visualize the most salient detection results for upper-body clothes, lower-body clothes and full-body clothes respectively\nif flag_visualize\n\tfigure(1);\n\tsubplot(1, 3, 1); showboxes(img_cur, bbox_img{1}(1, :)); title('Upper-body Clothes');\n\tsubplot(1, 3, 2); showboxes(img_cur, bbox_img{2}(1, :)); title('Lower-body Clothes');\n\tsubplot(1, 3, 3); showboxes(img_cur, bbox_img{3}(1, :)); title('Full-body Clothes');\nend\n\n% Save bounding box outputs\nsave(file_output_bbox, 'img_cur', 'bbox_img', '-v7.3');\n", "meta": {"author": "liuziwei7", "repo": "fashion-detection", "sha": "3181771369dd94b47f6d2a660d4a7da9f25cfe28", "save_path": "github-repos/MATLAB/liuziwei7-fashion-detection", "path": "github-repos/MATLAB/liuziwei7-fashion-detection/fashion-detection-3181771369dd94b47f6d2a660d4a7da9f25cfe28/demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.1318862059327537}}
{"text": "classdef geodata\n    %   GEODATA: Geographical data class\n    %   Handles geographical data describing coastlines or other features in\n    %   the form of a shapefile and topobathy in the form of a DEM\n    %   Copyright (C) 2018  Keith Roberts & William Pringle\n    %\n    %   The following inputs (with default values) are available for the\n    %   geodata method:\n    %     defval = 0; % placeholder value if arg is not passed.\n    %     addOptional(p,'bbox',defval);\n    %     addOptional(p,'shp',defval);\n    %     addOptional(p,'h0',defval);\n    %     addOptional(p,'dem',defval);\n    %     addOptional(p,'backupdem',defval);\n    %     addOptional(p,'fp',defval);\n    %     addOptional(p,'weirs',defval);\n    %     addOptional(p,'pslg',defval);\n    %     addOptional(p,'boubox',defval);\n    %     addOptional(p,'window',defval);\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 <http://www.gnu.org/licenses/>.\n    properties\n        bbox  % bounding coordinates\n        boubox % bbox coordinates as a CCW polygon\n        mainland % mainland boundary.\n        outer % outer boundary.\n        inner % island boundary(ies)\n        mainlandb % height of mainland\n        innerb    % height of inner\n        mainlandb_type % type of mainland (lake or river or ocean)\n        innerb_type    % type of inner (lake or river or ocean)\n        weirs % weir crestlines\n        weirPfix % boundaries of weir\n        weirEgfix % edges of weir\n        ibconn_pts % cell-array of paired weir nodes\n        inpoly_flip % reverse the notion of \"in\"\n        contourfile %  cell-array of shapefile\n        demfile % filename of dem\n        BACKUPdemfile % filename of dem\n        h0 % min. edgelength (meters)\n        window  % smoothing window on boundary (default 5 points)\n        fp % deprecated but kept for backwards capability\n        Fb % linear gridded interpolant of DEM\n        Fb2 % linear gridded interpolant of backup DEM\n        x0y0 % bottom left of structure grid or position (0,0)\n        pslg % piecewise liner straight line graph\n        spacing = 2.0 ; %Relative spacing along polygon, large effect on computational efficiency of signed distance.\n        gridspace\n        shapefile_3d % if the shapefile has a height attribute\n    end\n    \n    methods\n        \n        function obj = geodata(varargin)\n            % Class constructor to parse NetCDF DEM data, NaN-delimited vector,\n            % or shapefile that defines polygonal boundary of meshing\n            % domain.\n            % options\n            %addOptional(p,'bbox',defval);\n            %addOptional(p,'shp',defval);\n            %addOptional(p,'h0',defval);\n            %addOptional(p,'dem',defval);\n            %addOptional(p,'backupdem',defval);\n            %addOptional(p,'fp',defval);\n            %addOptional(p,'weirs',defval);\n            %addOptional(p,'pslg',defval);\n            %addOptional(p,'boubox',defval);\n            \n            % Check for m_map dir\n            M_MAP_EXISTS=0 ;\n            if exist('m_proj','file')==2\n              M_MAP_EXISTS=1 ;\n            end\n            if M_MAP_EXISTS~=1 \n              error('Where''s m_map? Please read the user guide')\n            end\n\n            % Check for utilties dir\n            UTIL_DIR_EXISTS=0  ;\n            if exist('inpoly.m','file')\n              UTIL_DIR_EXISTS=1; \n            end\n            if UTIL_DIR_EXISTS~=1 \n              error('Where''s the utilities directory? Please read the user guide')\n            end\n\n            % Check for dataset dir\n            DATASET_DIR_EXISTS=0 ;\n            if exist('datasets','dir')==7\n                DATASET_DIR_EXISTS=1 ;\n            end\n            if DATASET_DIR_EXISTS~=1\n                warning('We suggest you to place your files in a directory called \"datasets\". Please read the user guide')\n            end\n\n\n            p = inputParser;\n            \n            defval = 0; % placeholder value if arg is not passed.\n            % add name/value pairs\n            addOptional(p,'bbox',defval);\n            addOptional(p,'shp',defval);\n            addOptional(p,'h0',defval);\n            addOptional(p,'dem',defval);\n            addOptional(p,'backupdem',defval);\n            addOptional(p,'fp',defval);\n            addOptional(p,'weirs',defval);\n            addOptional(p,'pslg',defval);\n            addOptional(p,'boubox',defval);\n            addOptional(p,'window',defval);\n            addOptional(p,'shapefile_3d',defval);\n            \n            % parse the inputs\n            parse(p,varargin{:});\n            % store the inputs as a struct\n            inp=p.Results;\n            % get the fieldnames of the edge functions\n            fields = fieldnames(inp);\n            % loop through and determine which args were passed.\n            % also, assign reasonable default values if some options were\n            % not assigned.\n            obj.boubox = [] ;\n            for i = 1 : numel(fields)\n                type = fields{i};\n                switch type\n                    % parse aux options first\n                    case('bbox')\n                        obj.bbox = inp.(fields{i});\n                        if any(obj.bbox ~=0)\n                            obj.bbox = inp.(fields{i});\n                            %elseif ~ischar(inp.(fields{contains(fields,'dem')}))\n                            %    error('No bbox specified!');\n                        end\n                    case('h0')\n                        obj.h0= inp.(fields{i});\n                        if obj.h0 ~=0\n                            obj.h0 = inp.(fields{i});\n                        else\n                            error('No h0 specified!');\n                        end\n                    case('shp')\n                        obj.contourfile = inp.(fields{i});\n                        if ~iscell(obj.contourfile) && ~ischar(obj.contourfile)\n                            obj.contourfile = [];\n                        end\n                    case('dem')\n                        obj.demfile= inp.(fields{i});\n                        if obj.demfile ~=0\n                            obj.demfile = inp.(fields{i});\n                        else\n                            obj.demfile = [];\n                        end\n                    case('backupdem')\n                        obj.BACKUPdemfile= inp.(fields{i});\n                        if obj.BACKUPdemfile ~=0\n                            obj.BACKUPdemfile = inp.(fields{i});\n                        else\n                            obj.BACKUPdemfile = [];\n                        end\n                    case('fp')\n                        obj.fp= inp.(fields{i});\n                        if obj.fp ~=0\n                            obj.fp = inp.(fields{i});\n                        end\n                    case('outer')\n                        obj.outer = inp.(fields{i});\n                        if obj.outer(1) ~=0\n                            obj.outer = inp.(fields{i});\n                        end\n                    case('pslg')\n                        obj.pslg = inp.(fields{i});\n                        if obj.pslg(1) ~=0\n                            obj.pslg = inp.(fields{i});\n                        else\n                            obj.pslg = [];\n                        end\n                    case('mainland')\n                        obj.mainland = inp.(fields{i});\n                        if obj.mainland(1) ~=0\n                            obj.mainland = inp.(fields{i});\n                        end\n                    case('inner')\n                        obj.inner = inp.(fields{i});\n                        if obj.inner(1) ~=0\n                            obj.inner = inp.(fields{i});\n                        end\n                    case('boubox')\n                        obj.boubox = inp.(fields{i}) ;\n                    case('window')\n                        obj.window = inp.(fields{i}) ;\n                        if obj.window == 0\n                            % Default value\n                            obj.window = 5;\n                        end\n                    case('shapefile_3d')\n                         obj.shapefile_3d = inp.(fields{i}) ;\n                    case('weirs')\n                        if ~iscell(inp.(fields{i})) && ~isstruct(inp.(fields{i})) && inp.(fields{i})==0, continue; end\n                        if ~iscell(inp.(fields{i})) && ~isstruct(inp.(fields{i}))\n                            error('Data for weirs must be in a cell-array or struct. Please see the user guide.'); \n                        end\n                        obj.weirs = inp.(fields{i}) ;\n                        noWeirs   = length(obj.weirs) ;\n                        disp(['INFO: User has passed ',num2str(noWeirs),' weir crestlines.']) ;\n                        obj.weirPfix = [] ; obj.weirEgfix = [] ;\n                        if iscell(obj.weirs)\n                            ss = obj.weirs{1}(1);\n                        else\n                            ss = obj.weirs(1).X(1);\n                        end\n                        if ss ~= 0\n                            for ii = 1 : noWeirs\n                                if iscell(obj.weirs)\n                                    crestlines = obj.weirs{ii}(:,1:2) ;\n                                    width      = obj.weirs{ii}(1,3)/111e3 ;\n                                    weir_min_ele = obj.weirs{ii}(1,4)/111e3;\n                                else\n                                    crestlines = [obj.weirs(ii).X obj.weirs(ii).Y];\n                                    width      = obj.weirs(ii).width/111e3 ;\n                                    weir_min_ele = obj.weirs(ii).min_ele/111e3;\n                                end\n                                if width == 0 \n                                  error('Please specify non-zero width of weir in meters!');\n                                end\n                                % user-defined spacing along face of weir\n                                if weir_min_ele ~= 0\n                                    [tempPfix,tmpEgfix,obj.ibconn_pts{ii}] = GenerateWeirGeometry(crestlines,width,...\n                                          weir_min_ele,0) ;\n                                else\n                                % by default spacing along face of weir is\n                                % MIN_EL\n                                    [tempPfix,tmpEgfix,obj.ibconn_pts{ii}] = GenerateWeirGeometry(crestlines,width,...\n                                        2*(obj.h0/111e3),0) ;\n                                end\n                                [tmpEgfix]=renumberEdges(tmpEgfix) ;\n                                weirLength(ii) = length(tempPfix) ;\n                                if ii~=1\n                                    tmpEgfix = tmpEgfix + length(obj.weirPfix) ;\n                                end\n                                obj.weirPfix = [obj.weirPfix; tempPfix] ;\n                                obj.weirEgfix = [obj.weirEgfix; tmpEgfix] ;\n                            end\n                        end\n                end\n            end\n            % Basic error handling should go here.\n            % if not bbox and no dem, you're outta luck\n            if size(obj.bbox,1) == 1 && isempty(obj.demfile) && isempty(obj.pslg)\n                error('No DEM supplied and no bbox supplied, sorry pal');\n            end\n            obj.gridspace    = abs(obj.h0)/111e3; %point spacing along polygon,\n            % Get bbox information from demfile if not supplied\n            if size(obj.bbox,1) == 1 && isempty(obj.pslg)\n                obj = ParseDEM(obj,'bbox');\n            end\n            \n            if obj.bbox == 0\n                error('No bbox supplied. If you are using the pslg option then you need to supply a bbox.') \n            elseif size(obj.bbox,1) == 2\n                % Typical square bbox type\n                % Make the bounding box 5 x 2 matrix in clockwise order\n                obj.boubox = bbox_to_bou(obj.bbox);\n            else\n                % Handle non-square bbox type regions\n                obj.boubox = obj.bbox;\n                if ~isnan(obj.boubox(end,1))\n                    obj.boubox(end+1,:) = [NaN NaN];\n                end\n                obj.bbox = [min(obj.boubox(:,1)) max(obj.boubox(:,1))\n                    min(obj.boubox(:,2)) max(obj.boubox(:,2))] ;\n            end\n            \n            obj = ParseShoreline(obj) ;\n      \n            % kjr Add the weir faux islands to the inner geometry\n            if ~isempty(obj.weirPfix)\n                idx = [0; cumsum(weirLength)']+1 ;\n                tmp = [] ;\n                for ii = 1 : noWeirs\n                    tmp =  [tmp;\n                        [obj.weirPfix(idx(ii):idx(ii+1)-1,:)\n                        obj.weirPfix(idx(ii),:)]\n                        NaN NaN] ;\n                end\n                obj.inner = [obj.inner ; NaN NaN ;  tmp ] ;\n            end\n            \n            % Ensure inpoly flip is correct\n            obj = check_connectedness_inpoly(obj);\n            \n            disp(['Read in meshing boundary: ',obj.contourfile]);\n            \n            if obj.BACKUPdemfile~=0\n                obj = ParseDEM(obj,'BackUp') ;\n            end\n            \n            obj = ParseDEM(obj) ;\n            \n            \n            \n        end\n        \n        function obj = ParseShoreline(obj)\n            % Read in the geometric meshing boundary information from a\n            % ESRI-shapefile\n            if ~isempty(obj.contourfile)\n                if ~iscell(obj.contourfile)\n                    obj.contourfile = {obj.contourfile};\n                end\n                \n                polygon_struct = Read_shapefile( obj.contourfile, [], ...\n                    obj.bbox, obj.gridspace, obj.boubox, 0, obj.shapefile_3d);\n                \n                % Unpack data from function Read_Shapefile()s\n                obj.outer     = polygon_struct.outer;\n                obj.mainland  = polygon_struct.mainland;\n                obj.inner     = polygon_struct.inner;\n                obj.mainlandb = polygon_struct.mainlandb;\n                obj.innerb    = polygon_struct.innerb;\n                obj.mainlandb_type = polygon_struct.mainlandb_type;\n                obj.innerb_type    = polygon_struct.innerb_type;\n                \n                % Read in the geometric meshing boundary information from a\n                % NaN-delimited vector.\n            elseif ~isempty(obj.pslg)\n                \n                % Handle the case for user defined mesh boundary information\n                polygon_struct = Read_shapefile( [], obj.pslg, ...\n                    obj.bbox, obj.gridspace, obj.boubox, 0, obj.shapefile_3d);\n                \n                % Unpack data from function Read_Shapefile()s\n                obj.outer     = polygon_struct.outer;\n                obj.mainland  = polygon_struct.mainland;\n                obj.inner     = polygon_struct.inner;\n                obj.mainlandb = polygon_struct.mainlandb;\n                obj.innerb    = polygon_struct.innerb;\n                obj.mainlandb_type = polygon_struct.mainlandb_type;\n                obj.innerb_type    = polygon_struct.innerb_type;\n                \n            else\n                % set outer to the boubox\n                obj.outer = obj.boubox;\n            end\n            obj = ClassifyShoreline(obj) ;\n        end\n        \n        function obj = ClassifyShoreline(obj)\n            % Helper function to...\n            % 1) Read the data from supplied file\n            % 2) Classify segments as either inner, outer, or mainland.\n            % 3) Ensure point spacing is adequate to support mesh sizes\n            %    and ensure computational efficiency when calculating the\n            %    signed distance function.\n            \n            % Check if no mainland segments, set outer\n            % to the boubox.\n            if isempty(obj.mainland)\n                obj.outer = [ ];\n                obj.outer = obj.boubox;\n            end\n            \n            % Make sure the shoreline components have spacing of\n            % gridspace/spacing\n            [la,lo] = my_interpm(obj.outer(:,2),obj.outer(:,1),...\n                obj.gridspace/obj.spacing);\n            obj.outer = [];  obj.outer(:,1) = lo; obj.outer(:,2) = la;\n            outerbox = obj.outer(1:find(isnan(obj.outer(:,1)),1,'first'),:);\n            \n            if ~isempty(obj.mainland)\n                [la,lo] = my_interpm(obj.mainland(:,2),obj.mainland(:,1),...\n                    obj.gridspace/obj.spacing);\n                obj.mainland = []; obj.mainland(:,1) = lo; obj.mainland(:,2) = la;\n            end\n            \n            if ~isempty(obj.inner)\n                [la,lo]=my_interpm(obj.inner(:,2),obj.inner(:,1),...\n                    obj.gridspace/obj.spacing);\n                obj.inner = []; obj.inner(:,1) = lo; obj.inner(:,2) = la;\n            end\n            clearvars lo la\n            \n            % Smooth the coastline (apply moving average filter).\n            if obj.window > 1\n                disp(['Smoothing coastline with ' ...\n                    num2str(obj.window) ' point window'])\n                if ~isempty(obj.outer)\n                    obj.outer = smooth_coastline(obj.outer,obj.window,0);\n                end\n                if ~isempty(obj.mainland)\n                    obj.mainland = smooth_coastline(obj.mainland,obj.window,0);\n                end\n                if ~isempty(obj.inner)\n                    obj.inner = smooth_coastline(obj.inner,obj.window,0);\n                end\n            else\n                disp('No smoothing of coastline enabled')\n            end\n            \n            % KJR: Coarsen portions of outer, mainland\n            % and inner outside bbox.\n            iboubox = bbox_to_bou(obj.bbox);\n            iboubox(:,1) = 1.10*iboubox(:,1)+(1-1.10)*mean(iboubox(1:end-1,1));\n            iboubox(:,2) = 1.10*iboubox(:,2)+(1-1.10)*mean(iboubox(1:end-1,2));\n            \n            % Coarsen outer\n            obj.outer = coarsen_polygon(obj.outer,iboubox);\n            \n            % Coarsen inner and move parts that overlap with bounding box\n            % to mainland\n            if ~isempty(obj.inner)\n                obj.inner = coarsen_polygon(obj.inner,iboubox);\n            end\n            \n            % Coarsen mainland and remove parts that overlap with bounding\n            % box (note this doesn't change the polygon used for inpoly,\n            % only changes the distance function used for edgefx)\n            if ~isempty(obj.mainland)\n                obj.mainland = coarsen_polygon(obj.mainland,iboubox);\n            end\n            \n            \n        end\n        \n        function obj = ParseDEM(obj,varargin)\n            % obj = ParseDEM(obj,varargin)\n            % set 'BackUp' for reading backupdem\n            % set 'bbox' for reading only bbox\n            fname = obj.demfile ; backup = 0;\n            if any(strcmp(varargin,'BackUp'))\n                backup = 1;\n                fname = obj.BACKUPdemfile ;\n            end\n                                    \n            % Process the DEM for the meshing region.\n            if ~isempty(fname)\n                \n                % Find name of x, y (one that has 1 dimensions)\n                % z values (use one that has 2 dimensions)\n                [xvn, yvn, zvn] = getdemvarnames(fname);\n                \n                % Read x and y\n                x = double(ncread(fname,xvn));\n                y = double(ncread(fname,yvn));\n                                \n                if any(strcmp(varargin,'bbox'))\n                    obj.bbox = [min(x) max(x); min(y) max(y)];\n                    return;\n                end\n                \n                modbox = [0 0];\n                if obj.bbox(1,2) > 180 && obj.bbox(1,1) < 180 && min(x) < 0\n                    % bbox straddles 180/-180 line\n                    loop = 2;\n                else\n                    loop = 1;\n                    if max(x) > 180\n                        if obj.bbox(1,1) < 0; modbox(1) = 1; end\n                        if obj.bbox(1,2) < 0; modbox(2) = 1; end\n                    elseif min(x) < 0\n                        if obj.bbox(1,1) > 180; modbox(1) = -1; end\n                        if obj.bbox(1,2) > 180; modbox(2) = -1; end\n                    end\n                end\n                J = find(y >= obj.bbox(2,1) & y <= obj.bbox(2,2));\n                I = []; demz = [];\n                for nn = 1:loop\n                    bboxt = obj.bbox;\n                    bboxt(1,:) =  bboxt(1,:) + modbox.*360;\n                    if loop == 2\n                        if nn == 1\n                            bboxt(1,2) = 180;\n                        else\n                            bboxt(1,1) = -180;\n                            bboxt(1,2) = bboxt(1,2) - 360;\n                        end\n                    end\n                    It = find(x >= bboxt(1,1) & x <= bboxt(1,2));\n                    I = [I; It];\n                    \n                    % At this point, detect the memory footprint of the \n                    % DEM subset and compute the required stride necessary\n                    % to satisfy the memory requirements\n                    if nn == 1\n                        AVAILABLE_MEMORY=4; % 4 gb;\n                        mult = (obj.bbox(1,2) - obj.bbox(1,1))/...\n                                   (bboxt(1,2) - bboxt(1,1)); \n                        peak_mem = mult*length(I)*length(J)*4/1e9; % in GB assuming single\n                        STRIDE_MEM = ceil(sqrt(peak_mem/AVAILABLE_MEMORY));\n                        DEM_GRIDSPACE = (x(2)-x(1))*111e3; % in meters\n                        STRIDE_H0 = ceil(obj.h0/DEM_GRIDSPACE); % skip # of DEM entires\n                        STRIDE = max(STRIDE_H0, STRIDE_MEM); \n                        if STRIDE > 1\n                            if STRIDE_MEM > STRIDE_H0\n                                warning(['DEM would occupy ',num2str(peak_mem),...\n                                         'GB of RAM. DEM will be downsampled ' ...\n                                         'by a stride of ' num2str(STRIDE)])\n                            else\n                                warning(['DEM will be downsampled by a stride ' ...\n                                         'of ' num2str(STRIDE) ' to match h0'])\n                            end\n                        end\n                    \n                    end\n                    % grab only the portion that was requested \n                    if STRIDE > 1 && STRIDE_MEM > STRIDE_H0\n                        % with a stride to save memory \n                        LX = length(It(1:STRIDE:end));\n                        LY = length(J(1:STRIDE:end));\n                        demzt = single(ncread(fname,zvn,[It(1) J(1)],...\n                                       [LX LY],[STRIDE,STRIDE]));\n                    else\n                        % faster to read in with no stride if not memory\n                        % bound\n                        demzt = single(ncread(fname,zvn,[It(1) J(1)],...\n                                       [length(It) length(J)]));\n                        if STRIDE > 1\n                            demzt = demzt(1:STRIDE:end,1:STRIDE:end);\n                        end\n                    end\n                    if isempty(demz)\n                        demz = demzt;\n                    else\n                        demz = cat(1,demz,demzt);\n                    end\n                end\n                x = x(I(1:STRIDE:end)); y = y(J(1:STRIDE:end));\n                if obj.bbox(1,2) > 180\n                    x(x < 0) = x(x < 0) + 360;\n                    [x1,IA] = unique(x);\n                    if length(x) > length(x1)\n                        x = x1; demz = demz(IA,:);\n                    end\n                end\n                % handle DEMS from packed starting from the bottom left\n                if y(2) < y(1)\n                    y = flipud(y) ;\n                    demz = fliplr(demz) ;\n                end\n                % Determine bottom left corner of DEM \n                % (after possible flipping of DEM packing)\n                obj.x0y0 = [x(1),y(1)];\n                \n                % check for any invalid values\n                bad = isnan(demz); \n                if sum(bad(:)) > 0 && ~backup\n                    warning('ALERT: Invalid and/or missing DEM values detected..check DEM');\n                    if ~isempty(obj.BACKUPdemfile)\n                        disp('Replacing invalid values with back-up DEMfile');\n                        [demx,demy] = ndgrid(x,y) ;\n                        demz(bad) = obj.Fb2(demx(bad),demy(bad)) ;\n                    else\n                        % just replace it with NaNs\n                        demz(bad) = NaN ;\n                    end\n                end\n                \n                % creating back up interpolant\n                if backup\n                    obj.Fb2   = griddedInterpolant({x,y},demz,...\n                        'linear','nearest');\n                    % clear data from memory\n                    clear x y demz\n                else\n                    % main interpolant\n                    if obj.BACKUPdemfile~=0\n                        obj.Fb   = griddedInterpolant({x,y},demz,...\n                            'linear','none'); % no extrapolation (so use Fb2)\n                    else\n                        obj.Fb   = griddedInterpolant({x,y},demz,...\n                            'linear','nearest');\n                    end\n                    % clear data from memory\n                    clear x y demz\n                end\n                \n                disp(['Read in demfile ',fname]);\n            end\n            \n            % Handle the case of no dem\n            if isempty(obj.x0y0)\n                obj.x0y0 = [obj.bbox(1,1), obj.bbox(2,1)];\n            end\n            \n            function [xvn, yvn, zvn] = getdemvarnames(fname)\n                % Define well-known variables for longitude and latitude\n                % coordinates in Digital Elevation Model NetCDF file (CF\n                % compliant).\n                xvn = []; yvn = []; zvn = [];\n                wkv_x = {'x','Longitude','longitude','lon'} ;\n                wkv_y = {'y','Latitude', 'latitude','lat'} ;\n                finfo = ncinfo(fname);\n                for ii = 1:length(finfo.Variables)\n                    if ~isempty(xvn) && ~isempty(yvn) && ~isempty(zvn); break; end\n                    if length(finfo.Variables(ii).Size) == 1\n                        if isempty(xvn) && ...\n                                any(strcmp(finfo.Variables(ii).Name,wkv_x))\n                            xvn = finfo.Variables(ii).Name;\n                        end\n                        if isempty(yvn) && ...\n                                any(strcmp(finfo.Variables(ii).Name,wkv_y))\n                            yvn = finfo.Variables(ii).Name;\n                        end\n                    elseif length(finfo.Variables(ii).Size) == 2\n                        if isempty(zvn)\n                            zvn = finfo.Variables(ii).Name;\n                        end\n                    end\n                end\n                if isempty(xvn)\n                    error('Could not locate x coordinate in DEM') ;\n                end\n                if isempty(yvn)\n                    error('Could not locate y coordinate in DEM') ;\n                end\n                if isempty(zvn)\n                    error('Could not locate z coordinate in DEM') ;\n                end\n            end\n            \n        end\n        \n        \n        \n        function obj = check_connectedness_inpoly(obj)\n            % Check for connected polygons and if not connected,\n            %  whether to flip the inpoly result to ensure meshing\n            %  on the coastal side of the polygon.\n            \n            obj.inpoly_flip = 0;\n            % return if outer polygon is connected\n            shpEnd = find(isnan(obj.outer(:,1)));\n            [~,loc] = max(diff(shpEnd));\n            shpEnd = vertcat(0,shpEnd); loc = loc+1;\n            if abs(sum(obj.outer(shpEnd(loc)+1,:)) - ...\n                    sum(obj.outer(shpEnd(loc+1)-1,:))) > eps\n                disp('Warning: Shapefile is unconnected... continuing anyway')\n            end\n            \n            % check for inpoly goodness read the GSHHS checker\n            ps = Read_shapefile( {'GSHHS_l_L1'}, [], ...\n                obj.bbox, obj.gridspace, obj.boubox, 0, 0 );\n            \n            % make a \"fake\" tester grid\n            x = linspace(obj.bbox(1,1),obj.bbox(1,2),100);\n            y = linspace(obj.bbox(2,1),obj.bbox(2,2),100);\n            edges = Get_poly_edges( [ps.outer; ps.inner] );\n            in_Test = inpoly([x',y'],[ps.outer; ps.inner],edges);\n            polytester = [obj.outer; obj.inner];\n            edges = Get_poly_edges( polytester );\n            in_Shpf = inpoly([x',y'],polytester,edges);\n            % if more than half of thepoints disagree between Test and Shpf\n            % lets flip the inpoly\n            if length(find(xor(in_Shpf,in_Test))) > 50\n                obj.inpoly_flip = 1;\n                disp(['Shapefile inpoly is inconsistent ' ...\n                    'with GHSSS test file, flipping the inpoly test'])\n            end\n            \n            % if flooplaind meshing, flip the inpoly test\n            if obj.fp\n                obj.inpoly_flip = mod(1,obj.inpoly_flip);\n            end\n        end\n        \n        function obj = close(obj)\n            % Clips the mainland segment with the boubox.\n            % Performs a breadth-first search given a seed position\n            % of the piecewise-straight line graph (PSLG) that is used to define the meshing boundary.\n            % This returns back an updated geodata class instance with the outer boundary clipped with the boubox.\n            % kjr,und,chl 2018\n            \n            if isempty(obj.Fb)\n                warning('ALERT: Meshing boundary is not a polygon!')\n                warning('ALERT: DEM is required to clip line segment with polygon')\n                seed=input('Enter coordinate of seed location to clip: ');\n            else\n                % Guess seed location: submerged portion of domain within\n                % bbox?\n                [demx,demy] = ndgrid(obj.x0y0(1):obj.h0/111e3:obj.bbox(1,2), ...\n                    obj.x0y0(2):obj.h0/111e3:obj.bbox(2,2));\n                demz = obj.Fb(demx,demy);\n                [idx]=find(demz(:) < -10) ; % find points deeper than -10 m below sea level\n                allpts=[demx(:),demy(:)] ;\n                cands = allpts(idx,:);\n                if(isnan(obj.boubox(end,1)))\n                    edges=Get_poly_edges(obj.boubox) ;\n                    [in]=inpoly(cands,obj.boubox,edges) ; %  determine which of these points is in the domain\n                else\n                    [in]=inpoly(cands,obj.boubox) ;       %  determine which of these points is in the domain\n                end\n                cands2=cands(in,:) ;\n                seed = cands2(50,:) ;\n            end\n            \n            geom = [obj.mainland; obj.boubox] ;\n            \n            [NODE,PSLG]=getnan2(geom) ;\n            \n            [NODE2,PSLG2,PART2] = bfsgeo2(NODE,PSLG,seed) ;\n            \n            POLY = extdom_polygon(PSLG2(PART2{1},:),NODE2,-1) ;\n            \n            new_outer = cell2mat(POLY') ;\n            \n            [la,lo] = my_interpm(new_outer(:,2),new_outer(:,1),((obj.h0/2)/111e3))  ;\n            \n            new_outer = [lo la] ;\n            \n            obj.outer = new_outer ;\n            \n            % reset this to default\n            obj.inpoly_flip = 0 ;\n        end\n        \n        function obj = extractContour(obj,ilev)\n            % Extract a geometric contour from the DEM at elevation ilev.\n            % obj = extractContour(obj,ilev)\n            %\n            % Can use to get the mean sea level contour, e.g.;\n            % gdat = geodata('pslg',0,'h0',min_el,'dem',dem); % make the dummy gdat for the dem extents;\n            % lmsl = extractContour(gdat,0); %using the dummy gdat with dem info to get the 'lmsl' gdat with the 0-m contour.\n            \n            [node,edge] = ...\n                getiso2( obj.Fb.GridVectors{1},obj.Fb.GridVectors{2},...\n                double(obj.Fb.Values'),ilev) ;\n            \n            polyline = cell2mat(extdom_polygon(edge,node,-1,1,10)') ;\n            \n            obj = geodata('pslg',polyline,'bbox',obj.bbox,...\n                          'h0',obj.h0,'dem',obj.demfile) ;\n            \n        end\n        \n        function plot(obj,type,projection,holdon)\n            % plot(obj,type,projection,holdon)\n            % Plot geodata class info\n            % \n            % Inputs:\n            % obj  : geodata class object [required input]\n            %\n            % optional inputs =>....\n            % type : i) 'shp' [default] - plots the shapelines (shoreline) only\n            %       ii) 'dem' - plots the dem bathy in addition to shapelines\n            %      iii) 'omega' - hatches the meshing domain in addition to plotting shapelines\n            % projection : choose the projection type from m_map options\n            %              (default is Mercator)\n            % holdon : plot on a new (= 0 [default]) or existing (= 1) figure?\n            \n            if nargin == 1 || isempty(type)\n                type = 'shp';\n            end\n            if nargin < 3 || isempty(projection)\n                projection = 'Mercator';\n            end\n            if nargin < 4 || isempty(holdon)\n                holdon = 0;\n            end\n            \n            % plotting on new or existing figure?\n            if ~holdon\n                % setup the projection\n                bufx = 0.2*(obj.bbox(1,2) - obj.bbox(1,1));\n                bufy = 0.2*(obj.bbox(2,2) - obj.bbox(2,1));\n                if ~isempty(regexp(projection,'ste'))\n                    m_proj(projection,'lat',min(obj.bbox(2,:)),...\n                        'long',mean(obj.bbox(1,:)),'radius',...\n                        min(179.9,1.20*max(diff(obj.bbox(2,:)))));\n                else\n                    lmin = -180; lmax = +180;\n                    if obj.bbox(1,2) > 180; lmax = 360; lmin = 0; end \n                    lon1 = max(lmin,obj.bbox(1,1) - bufx);\n                    lon2 = min(lmax,obj.bbox(1,2) + bufx);\n                    lat1 = max(- 90,obj.bbox(2,1) - bufy);\n                    lat2 = min(+ 90,obj.bbox(2,2) + bufy);\n                    m_proj(projection,...\n                           'long',[lon1, lon2],'lat',[lat1, lat2]);\n                end\n                % plot on new figure\n                figure;\n                colori = 'g-'; % set island color\n                colorm = 'r-'; % set mainland color\n            else\n                colori = 'b-'; % set island color\n                colorm = 'm-'; % set mainland color\n            end\n            hold on\n            % select optional types\n            switch type\n                case('dem')\n                    % interpolate DEM's bathy linearly onto our \n                    % edgefunction grid (or a coarsened version of it for\n                    % memory considerations)\n                    mem = inf; stride = obj.h0/111e3;\n                    while mem > 1\n                        xx = obj.x0y0(1):stride:obj.bbox(1,2);\n                        yy = obj.x0y0(2):stride:obj.bbox(2,2);\n                        xs = whos('xx'); ys = whos('yy');\n                        mem = xs.bytes*ys.bytes/1e9;\n                        stride = stride*2;\n                    end\n                    [demx,demy] = ndgrid(xx,yy);\n                    demz = obj.Fb(demx,demy);\n                    m_fastscatter(demx(:),demy(:),demz(:));\n                    cb = colorbar; ylabel(cb,'topo-bathy depth [m]')\n                case('omega')\n                    % hatch the meshing domain, Omega\n                    [demx,demy] = ndgrid(obj.x0y0(1):obj.h0/111e3:obj.bbox(1,2), ...\n                        obj.x0y0(2):obj.h0/111e3:obj.bbox(2,2));\n                    edges = Get_poly_edges( [obj.outer; obj.inner] );\n                    in = inpoly([demx(:),demy(:)],[obj.outer; obj.inner], edges);\n                    long = demx(~in); lati = demy(~in);\n                    m_hatch(obj.boubox(1:end-1,1),...\n                        obj.boubox(1:end-1,2),'cross',45,0.05);\n                    m_plot(long,lati,'.','Color','white')\n            end\n            if ~isempty(obj.mainland) && obj.mainland(1) ~= 0\n                h1 = m_plot(obj.mainland(:,1),obj.mainland(:,2),...\n                    colorm,'linewi',1); hold on;\n            end\n            if ~isempty(obj.inner) && obj.inner(1) ~= 0\n                h2 = m_plot(obj.inner(:,1),obj.inner(:,2),...\n                    colori,'linewi',1); hold on;\n            end\n            if ~isempty(obj.weirs)\n                if isstruct(obj.weirs) ~= 0\n                    for ii =1 : length(obj.weirs)\n                        h3 = m_plot(obj.weirs.X,obj.weirs.Y,...\n                            'm-','linewi',1); hold on;\n                    end\n                else\n                    for ii =1 : length(obj.weirs)\n                        h3 = m_plot(obj.weirs{ii}(:,1),obj.weirs{ii}(:,2),...\n                            'm-','linewi',1); hold on;\n                    end\n                end\n            end\n            [la,lo] = my_interpm(obj.boubox(:,2),obj.boubox(:,1),...\n                0.5*obj.h0/111e3);\n            m_plot(lo,la,'k--','linewi',2);\n            if ~holdon\n                m_grid('xtick',10,'tickdir','out','yaxislocation','left','fontsize',10);\n            end\n            if exist('h1','var') && exist('h2','var') && exist('h3','var')\n                legend([h1 h2,h3],{'mainland' 'inner' 'weirs'},'Location','NorthWest')\n            elseif exist('h1','var') && exist('h2','var')\n                legend([h1 h2],{'mainland' 'inner'},'Location','NorthWest')\n            end\n        end\n        \n    end\n    \nend\n\n", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/@geodata/geodata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.13173324234525996}}
{"text": "%%\n% Copyright (c) 2019-present, Mahmoud Afifi\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% \n% Please, cite the following paper if you use this code:\n%\n% Mahmoud Afifi and Michael S. Brown. What else can fool deep learning? \n% Addressing color constancy errors on deep neural network performance.\n% ICCV, 2019\n%\n% Email: mafifi@eecs.yorku.ca | m.3afifi@gmail.com\n%%\n\n%% \n% This demo generates ten images from each image in the  given path. \n% Each generated file will be in the following format: \n% originalName_WB_CS.ext, where originalName is the original filename, WB \n% refers to white balance (WB) settings, and CS is the camera style. \n% WB settings are: \n%   - T: Tungsten WB [2850 Kelvin (K)]\n%   - F: Fluorescent WB [3800K]\n%   - D: Daylight WB [5500K] \n%   - C: Cloudy WB [6500K]\n%   - S: Shade WB [7500K]\n% Camera styes are:\n%   - AS: Adobe Standard\n%   - CS: Camera Standard\n% The generated images and a copy of the input image (optional) will be \n% saved in the output directory (output_dir)\n\n%%\nclear;\nclc;\n\nuse_GPU = 0; % to use GPU\ndatasetbase = fullfile('..','images'); % path of images directory\noutput_dir = fullfile('..','results'); % output directory (will contain \n% generated images and copy of original images\nNumOfImgs = 10; % should be less than or equal 10\nsaveOrig = true; % to save a copy of original images in output_dir\n\nif exist(output_dir, 'dir') == 0\n\tmkdir(output_dir)\nend\n\nif NumOfImgs > 10\n    error('Cannot generate more than 10 images for each input image');\nend\n\nimds = imageDatastore(datasetbase,'IncludeSubfolders' ,1);\nimages = {imds.Files{:}}'; % get all input filenames\n\nif use_GPU==1\n    load('synthWBmodel_GPU.mat'); % load WB_emulator GPU model\nelse\n    load('synthWBmodel.mat'); % load WB_emulator CPU model\nend\n\nfor i = 1 : length (images) % for each input image, do\n    fprintf('processing image: %s...\\n',images{i});\n    imgin = images{i};\n    I_in = imread(imgin); % read input image\n    [~,name,ext] = fileparts(imgin);\n    if saveOrig == true\n        imwrite(I_in,fullfile(output_dir,... % save a copy of it in output dir\n            sprintf('%s%s%s',name,'_original',ext)));\n    end\n    try\n        % generate images with synthetic WB effects\n        out = WB_emulator.generate_wb_srgb(I_in, NumOfImgs); \n        if use_GPU==1 % if GPU is used, \n            out = gather(out); % convert gpuArray to double tensor\n        end\n        for j =1 : size(out,4) % save generated images\n            imwrite(out(:,:,:,j),fullfile(output_dir,...\n                sprintf('%s%s%s',name,...\n                WB_emulator.wb_photo_finishing{j},ext)));\n        end\n    catch\n        fprintf('Error in image %s!\\n', imgin);\n    end\nend\n", "meta": {"author": "mahmoudnafifi", "repo": "WB_color_augmenter", "sha": "124b62b4ab864fdd3ff371b2e68594a4cf8c9c1e", "save_path": "github-repos/MATLAB/mahmoudnafifi-WB_color_augmenter", "path": "github-repos/MATLAB/mahmoudnafifi-WB_color_augmenter/WB_color_augmenter-124b62b4ab864fdd3ff371b2e68594a4cf8c9c1e/WBAugmenter_Matlab/demo_batch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.25683199707586785, "lm_q1q2_score": 0.1314251975230532}}
{"text": "function [influenceM] = getGlobalInfluenceM(IM, structsV)\n%function [influenceM] = getGlobalInfluenceM(IM, structsV)\n%   Get the global influence matrix (dose(:) = influenceM * weights(:)),\n%   for all given structures.  The output influenceM is sparse, and has\n%   rowNums equal to the number of voxels in the plan.\n%   The row coord is the same as would be gotten by retrieving the\n%   structure mask:\n%          [mask3D, planC] =getUniformStr(Str_Num, planC, optS);\n%\n%JOD, 17 Nov 03.\n%JRA, 27 Feb 04, cleanup.\n%JRA, 24 Mar 04, Supports multiple structs, preallocate inflM, kicked up\n%                the speed some.\n%JRA, 14 Apr 04, Added monteCarlo MCflag.\n%JOD, 19 Dec 05, comment mods.\n%JJW, 20 Jun 06, MCflag removed; added call of getSingleGlobalInfluenceM\n%APA, 10 Oct 06, updated to make compatible with changed location of beamlets field\n%\n%Usage:\n%   function [gInfluenceM] = getGlobalInfluenceM(IM, structsV);\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 <http://www.gnu.org/licenses/>.\n\nif length(structsV) == 1\n    \n    % this function is fast, but it works only for one structure at a time\n    [influenceM] = getSingleGlobalInfluenceM(IM, structsV);\n    \nelse\n\n   global planC;\n\n   beamlets = [IM.beams(:).beamlets];\n   \n   %get indices of structures stored under beamlets\n   structIndV = getAssociatedStr({beamlets(:,1).strUID});\n   \n   if ~all(ismember(structsV,structIndV))\n       influenceM = [];\n       error('Dose not computed on some of the input structures. Please compute dose on and try again')\n       return;\n   end\n   \n   numPBs = size(beamlets,2);\n\n   %Find minimum number of nonzero elements that need to be put in influenceM.\n   for structNum = structsV;\n       strBmletInd = find(structNum==structIndV);\n        count = 0;\n        for i=1:length(beamlets(strBmletInd,:))\n            count = count + length(beamlets(strBmletInd,i).influence);\n        end\n        nnzV(structNum) = count;\n   end\n    maxnnz = max(nnzV);\n\n    %Pre-initalize influence matrix, greatly speeds things up.\n    indexS = planC{end};\n    numVoxels = prod(getUniformScanSize(planC{indexS.scan}(getStructureAssociatedScan(structsV(1)))));\n    influenceM = spalloc(numVoxels, numPBs, maxnnz);\n\n    %Make sure structsV is a row vector, used in below for loop.\n    if size(structsV, 1) ~= 1\n        structsV = structsV';\n    end\n\n    %Loop over beamlets.\n    for PBNum = 1 : numPBs\n\n        %For each requested structure, add the effect of this beamlet to inflM.\n        %*** Loops are in this order to cut down on out of order inserts into\n        %*** sparse influence matrix. Greatly increases speed. Leave it!\n        for structNum = structsV\n            \n            strBmletInd = find(structNum==structIndV);\n            \n            if ~isempty(beamlets(strBmletInd,PBNum).influence)\n\n                doseV     = double(beamlets(strBmletInd,PBNum).influence);\n                indV      = beamlets(strBmletInd,PBNum).indexV;\n                maxVal    = beamlets(strBmletInd,PBNum).maxInfluenceVal;\n                sizeParam = beamlets(strBmletInd,PBNum).fullLength;\n\n                if isfield(beamlets, 'lowDosePoints')\n                    lowDosePoints = unpackLogicals(beamlets(strBmletInd,PBNum).lowDosePoints, size(indV));\n                    doseScaledV(~lowDosePoints) = doseV(~lowDosePoints) * (maxVal / (2^8 -1));\n                    doseScaledV(lowDosePoints) = doseV(lowDosePoints) * (maxVal / (2^8 -1) / (2^8 -1));\n                else\n                    doseScaledV = doseV * (maxVal / (2^8 -1));\n                end\n                \n                influenceM(indV,PBNum) = doseScaledV(:);\n                doseScaledV = [];\n\n            end\n\n        end\n\n    end\n\nend % if length(structsV)==1", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/getGlobalInfluenceM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.23934935817440722, "lm_q1q2_score": 0.1308614222315596}}
{"text": "function [any_scanevent_repaired, ons, dur, index] ...\n    = tapas_physio_repair_scan_events_PHILIPS(ons, sqpar, verbose)\n% repairs the temporal structure of the sequence of scan events\n% (time-stamps when slice was acquired) by filling up holes of missing\n% slice acquisition or volume acquisition starts\n% \n% USAGE\n%   [any_scanevent_repaired, ons, dur, index] ...\n%       = tapas_physio_repair_scan_events_PHILIPS(ons, sqpar, verbose)\n%\n% -------------------------------------------------------------------------\n% INPUT:\n%   ons         - ons_samples, as given by tapas_physio_read_physlog_PHILIPS_guess_scanevents.m\n%   sqpar       - sequence timing parameters\n%           .Nslices        - number of slices per volume in fMRI scan\n%           .NslicesPerBeat - usually equals Nslices, unless you trigger\n%                             with the heart beat\n%           .TR             - repetition time in seconds\n%           .Ndummies       - number of dummy volumes\n%           .Nscans         - number of full volumes saved (volumes in nifti file,\n%                             usually rows in your design matrix)   \n%\n%   verbose   - create informative plots (1= yes, 0 = no)\n%\n% -------------------------------------------------------------------------\n% OUTPUT:\n%   any_scanevent_repaired - flag, if function changed ons (1=yes, 0=no)\n%   ons         - ons_samples, corrected for missing slice and volume\n%                 scan events\n%\n% Note: The temporal unit of the output ons & dur corresponds to the input, \n% i.e. if acq_sliceevents is given in samples, the output unit will be 2 ms\n% usually, NOT 1 second!\n%\n% -------------------------------------------------------------------------\n% Lars Kasper, August 2011\n% Copyright (C) 2013, Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\nthrmin = 1.5; % gap between slices, if spacing >thrmin*min(slicegap)\nthrmax = 0.5; % gap is large, if gap > thrmax*max(slicegap)\n\n%% repair scan events: some scan event triggers were missed so we have to\n% fill up the holes\nons.acq_slice = ons.acq_slice_all(:);\ndur.acq_slice = diff(ons.acq_slice);\n\n%% =======================================================================\n%% Find and remove gaps of one missing slice trigger within one volume scan of Nslices\nindex.hugegaps = find(dur.acq_slice>thrmax*max(dur.acq_slice));\n\n%double gaps, think about it later...\nindex.doublegaps = setdiff(find(dur.acq_slice > (thrmin+1)*min(dur.acq_slice)),index.hugegaps);\nif ~isempty(index.doublegaps)\n    disp('There are double gaps or worse in scan events. I will not correct that!');\nend\n\n\n%one slice trigger missing in volume of NslicesPerBeat slices\nindex.gaps                  = find(dur.acq_slice>thrmin*min(dur.acq_slice) ...\n                                & dur.acq_slice<(thrmin+1)*min(dur.acq_slice));\nons.acq_slice_gaps          = floor((ons.acq_slice(index.gaps)+ons.acq_slice(index.gaps+1))/2);\nons.acq_slice_filled_gaps   = sort([ons.acq_slice; ons.acq_slice_gaps]);\n\n%% =======================================================================\n%% gaps at beginning or end of Nslices-volume block still possible\ndur.acq_most_slices = diff(ons.acq_slice_filled_gaps);\n\n%indices of ons.acq_slice which belong to start of new volume\n%ons.acq_vol=[1; find(dur.acq_most_slices>thrmin*min(dur.acq_most_slices))+1];\n\nind_vol = 1:sqpar.Nslices:length(ons.acq_slice_filled_gaps);%(length(ons.acq_slice_filled_gaps)-sqpar.Nslices*(Ndummies+Nscans)+1):sqpar.Nslices:length(ons.acq_slice_filled_gaps);\nons.acq_vol = ind_vol;%ons.acq_slice_filled_gaps(ind_vol); \n\n%here we have scan volume blocks with e.g. N-1 slices, scan event trigger\n%missed, e.g. for 3 slices: |||   ||  |||\nindex.gaps_startend_vol = find(diff(ons.acq_vol)<sqpar.NslicesPerBeat);\n\n%OK till here\n%is it |||   ||  ||| or |||  ||   ||| (larger gap before or after block\n%which is too short?)\ngapbefore   = ons.acq_slice_filled_gaps(ons.acq_vol(index.gaps_startend_vol))-ons.acq_slice_filled_gaps(ons.acq_vol(index.gaps_startend_vol)-1);\ngapafter    = ons.acq_slice_filled_gaps(ons.acq_vol(index.gaps_startend_vol+1))-ons.acq_slice_filled_gaps(ons.acq_vol(index.gaps_startend_vol+1)-1);\n\nons.acq_slice_all = ons.acq_slice_filled_gaps;\nons.acq_slice_larger_gaps = [];\nfor i = 1:length(gapbefore)\n    if (gapbefore(i) > gapafter(i))\n        targetons=(ons.acq_vol(index.gaps_startend_vol(i)));\n        ons.acq_slice_larger_gaps(i)=2*ons.acq_slice_filled_gaps(targetons)-ons.acq_slice_filled_gaps(targetons+1);\n    else\n        targetons=(ons.acq_vol(index.gaps_startend_vol(i)+1)-1);\n        ons.acq_slice_larger_gaps(i)=2*ons.acq_slice_filled_gaps(targetons)-ons.acq_slice_filled_gaps(targetons-1);\n    end\n    ons.acq_slice_all=[ons.acq_slice_all; ons.acq_slice_larger_gaps(i)];\nend\n\nons.acq_slice_all = sort(ons.acq_slice_all);\n% END of filling up start/end slice triggers in volume\n% update ons.acq_vol\ndur.acq_slice_all = diff(ons.acq_slice_all);\n\n%ons.acq_vol_all=[1; find(dur.acq_slice_all>thrmin*min(dur.acq_slice_all))+1];\nons.acq_vol_all = ons.acq_vol; \n\n%1st volume added manually\nons.acq_vol_all = [ons.acq_slice_all(ons.acq_vol_all)];\n\n\nany_scanevent_repaired = ~(length(ons.acq_slice)==length(ons.acq_slice_all) ...\n    && length(ons.acq_vol)==length(ons.acq_vol_all));\n\nif verbose && any_scanevent_repaired\n    figh{1} = plot_fix_missing_scan_events(ons, ...\n        dur, index);\nend\n\nend %repair_scan_events\n\n%%========================================================================\n%% auxiliary plot functions follow;\n\n\n%%=========================================================================\n%% plot fixing procedure in scantrigger-time-difference view\nfunction fh = plot_fix_missing_scan_events(ons, dur, index)\n\nfh = tapas_physio_get_default_fig_params();\nset(fh,'Name','Read-In: Time-difference view between events: Fix missing scan events');\nax(1) = subplot(3,1,1);\nhold off;\nplot(1:length(dur.acq_slice),dur.acq_slice);\nhold on;\nplot(index.hugegaps,dur.acq_slice(index.hugegaps),'bo')\nplot(index.doublegaps,dur.acq_slice(index.doublegaps),'go')\nplot(index.gaps,dur.acq_slice(index.gaps),'kx')\n\ntitle('As extracted from the logfile');\nxlabel('scan event + 1');\nylabel('\\Delta t (ms) from last event')\nwarning('off', 'MATLAB:legend:IgnoringExtraEntries');\nlegend(...\n    'dur.acq_slice (time diff between scan events', ...\n    'index.hugegaps (dur.acq\\_slice>thrmax*max(dur.acq\\_slice))', ...\n    'index.doublegaps (dur.acq\\_slice > (thrmin+1)*min(dur.acq\\_slice), but no hugegap)', ...\n    'index.gaps (roughly size of 2*sliceTR)'...\n    );\n\nax(2) = subplot(3,1,2);\nhold off;\nplot(1:length(dur.acq_most_slices),dur.acq_most_slices);\nhold on;\nplot(ons.acq_vol,dur.acq_most_slices(ons.acq_vol),'bx')\n\ntitle('After fixing the slice-trigger gaps within a volume');\nxlabel('scan event + 1');\nylabel('\\Delta t (ms) from last event')\nlegend(...\n    'dur.acq\\_most\\_slices', ...\n    'ons.acq\\_vol');\n\n\nax(3) = subplot(3,1,3);\nhold off;\nplot(1:length(dur.acq_slice_all),dur.acq_slice_all);\nhold on;\nplot(ons.acq_vol_all,dur.acq_slice_all(ons.acq_vol),'bx')\n\nlegend(...\n    'dur.acq\\_slice\\_all', ...\n    'ons.acq\\_vol\\_all');\n\ntitle('After inserting the slice triggers at the beginning or end of a volume');\nxlabel('scan event + 1');\nylabel('\\Delta t (ms) from last event')\n\nlinkaxes(ax,'x');\nend\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/readin/tapas_physio_repair_scan_events_PHILIPS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.13076786451609762}}
{"text": "%% load param\nparam.net_def_dir = 'model/ResNet_3b_s16_f2r';\nparam.init_model = fullfile(pwd, 'output/ResNet_3b_s16/tot_wometa_1epoch'); %fullfile(pwd, 'output/ResNet-101L/1000000');\nparam.solverfile = 'solver_test.prototxt';\nparam.gpu_id = 0;\nmins = 3;\nmaxs = 14;\n%% init caffe solver\ncaffe.reset_all;\ncaffe_solver = caffe.get_solver(fullfile(param.net_def_dir, param.solverfile), param.gpu_id);\nif ~isempty(param.init_model)\n    assert(exist(param.init_model)==2, 'Cannot find caffemodel.');\n    caffe_solver.use_caffemodel(param.init_model);\nend\ncaffe_solver.set_phase('test');\nnum = length(featmap_trans);\ncons = 0;\nhit = 0;\nsums = 0;\nmissed = cell(num, 1);\nrecall = 0;\nfor i = 1 : num\n    ti = tic();\n    drawnow;\n    fprintf('Step 3 rpn:  %d/%d...', i, num);\n    parsed(i) = detect_all_by_featmap( featmap_trans{i}, unique(min(scale{i}, 5)), param, caffe_solver, mins);\n    toc(ti);\nend\nfprintf('Modify scale...')\nfor i = 1 : num\n    s = max(size(imread(fullfile(param.test_root, list{i}))))/param.max_img;\n    parsed(i).box(:,1:4) = parsed(i).box(:,1:4) * s;\n    parsed(i).point = parsed(i).point * s;\nend\nfprintf('Done\\n');\n", "meta": {"author": "liuyuisanai", "repo": "RSA-for-object-detection", "sha": "626ad81172b260ecf8257a80731e5236fe41cb63", "save_path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection", "path": "github-repos/MATLAB/liuyuisanai-RSA-for-object-detection/RSA-for-object-detection-626ad81172b260ecf8257a80731e5236fe41cb63/predict/script_featmap_2_result.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.25091277568224823, "lm_q1q2_score": 0.12937562425110874}}
{"text": "function [c, r, t, cpulse, acq_codes] = tapas_physio_read_physlogfiles_brainproducts(log_files, ...\n    cardiac_modality, verbose)\n% reads out physiological time series (ECG, PMU, resp belt) and timing vector for BrainProducts .eeg file\n%\n%   [cpulse, rpulse, t, c, acq_codes] = tapas_physio_read_physlogfiles_brainproducts(logfiles, ...\n%                               verbose)\n%\n%\n% IN    log_files\n%       .cardiac        contains ECG or pulse oximeter time course\n%                           for BrainProducts: usually the same as respiration\n%       .respiration    contains breathing belt amplitude time course\n%                           for BrainProducts: usually the same as cardiac\n%       .sampling_interval  is ignored here, read from logfile\n%\n%   cardiac_modality\n%                       'ecg1_filtered'     filtered 1st ECG channel signal\n%                                           (Default)\n%                       'ecg2_filtered'     filteered 2nd ECG channel\n%                                           (sometimes less gradient artifacts)\n%                       'ecg1_raw'          raw 1st ECG channel\n%\n%       verbose\n%       .level              debugging plots are created if level >=3\n%       .fig_handles        appended by handle to output figure\n%\n% OUT\n%   r                   respiratory time series\n%   c                   cardiac time series (ECG or pulse oximetry)\n%   t                   vector of time points (in seconds)\n%   cpulse              time events of R-wave peak in cardiac time series (seconds)\n%                       for Biopac: usually empty, kept for compatibility\n%   acq_codes           slice/volume start events marked by number <> 0\n%                       for time points in t\n% EXAMPLE\n%   [ons_secs.cpulse, ons_secs.rpulse, ons_secs.t, ons_secs.c] =\n%       tapas_physio_read_physlogfiles_GE(logfiles);\n%\n%   See also tapas_physio_main_create_regressors\n\n% Author: Lars Kasper\n% Created: 2017-01-27\n% Copyright (C) 2017 Institute for Biomedical Engineering, ETH/Uni Zurich.\n%\n% This file is part of the PhysIO toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or <http://www.gnu.org/licenses/>.\n\n\n%% user input\n\n% volume trigger event\nevent_type = 'Response';\nevent_value = 'R128';\n\nswitch lower(cardiac_modality)\n    case {'ecg','ecg1_filtered'}\n        % chose one ecg channel (only for visualisation)\n        ecg_ch = 1;\n    case 'ecg2_filtered'\n       % chose one ecg channel (only for visualisation)\n        ecg_ch = 2;\nend\n \n% is ecg data flipped?\necg_is_flipped = 1;\n\n%% data\n\n% read data and header info using field trip (included in SPM)\nif ~exist('ft_read_header', 'file')\n   pathSpm = fileparts(which('spm'));\n   addpath(genpath(fullfile(pathSpm, 'external', 'fieldtrip')));\nend\n\nhdr = ft_read_header(log_files.cardiac);\ndata = ft_read_data(log_files.cardiac);\n\nfs = hdr.Fs; % sampling frequency in Hz\nN = hdr.nSamples; % number of samples\ndt = 1/fs; % sampling interval in seconds\nt = linspace(0,dt*(N-1), N); % time vector in seconds\n\nfh = [];\n\n% plot first 10 seconds of the raw data\nfh(end+1,1) = tapas_physio_get_default_fig_params(); \nplot_end = 10 * fs;\nplot(t(1:plot_end), data(:,(1:plot_end)));\nxlabel('time in seconds');\nylabel(hdr.chanunit);\nlegend(hdr.label);\n\n% extract ECG data\nif ecg_is_flipped\n    s = -data(ecg_ch,:);\nelse\n    s = data(ecg_ch,:);\nend\n\n% plot first 10 seconds again for check\nfh(end+1,1) = tapas_physio_get_default_fig_params(); \nplot_end = 10 * fs;\nplot(t(1:plot_end), s(:,(1:plot_end)));\nxlabel('time in seconds');\nylabel(hdr.chanunit{ecg_ch});\nlegend(hdr.label{ecg_ch});\n%% events\n% display all events in the data on the command line\ncfg = [];\ncfg.dataset = log_files.cardiac;\ncfg.trialdef.eventtype  = '?';\nft_definetrial(cfg);\n\n% define volume trigger\ncfg.trialdef.eventtype = event_type;\ncfg.trialdef.eventvalue = event_value;\ncfg = ft_definetrial(cfg);\ntrigger_pos = cfg.trl(:,1);\nn_trigger = length(trigger_pos);\n\n% plot raw data and events\nfh(end+1,1) = tapas_physio_get_default_fig_params(); \nmax_value = max(s);\nplot(t, s);\nhold all;\nstem(t(trigger_pos), max_value * ones(1,n_trigger));\n\n% find segments\n% compute the number of samples between each trigger (pos-1)\ndiff_trigger_pos = diff(trigger_pos);\n% find the positons where a change is happening\ndiff_diff_trigger_pos = find(diff(diff_trigger_pos));\n% add first and last event\nstart_segment = [1; diff_diff_trigger_pos(2:2:end)+1];\nend_segment = [diff_diff_trigger_pos(1:2:end)+1; n_trigger];\n% number of samples per trials\nn_trial_samples = diff_trigger_pos(start_segment);\n% position of start segment in samples\nsample_start_segment = trigger_pos(start_segment);\n% position of end segment in samples (not including the whole trial)\nsample_end_segment = trigger_pos(end_segment);\n% number of segments\nn_segments = length(start_segment);\n% number of trials per segment\nn_trials = end_segment - start_segment + 1;\n% TR per trial\nTR_trials = n_trial_samples*dt;\n\n% plot segments\nstem(t(sample_start_segment), max_value * ones(1,n_segments), '--', 'LineWidth', 5);\nstem(t(sample_end_segment), max_value * ones(1,n_segments), '--', 'LineWidth', 5);\nlegend('signal', 'all trigger', 'start segment', 'end segment');\n\n%% load only first segment for sanity check\ncfg = [];\ncfg.dataset = log_files.cardiac;\ncfg.trialdef.eventtype = event_type;\ncfg.trialdef.eventvalue = event_value;\ncfg.trialfun = 'ft_trialfun_segment';\ncfg.trialdef.prestim = 0;\ncfg.trialdef.poststim = TR_trials(1);\ncfg.trialdef.segment_start = start_segment(1);\ncfg.trialdef.segment_end = end_segment(1);\ncfg = ft_definetrial(cfg);\n\n% plot segments\nfh(end+1,1) = tapas_physio_get_default_fig_params(); \nmax_value = max(s);\nplot(t, s);\nhold all;\nstem(t(cfg.trl(:,1)), max_value * ones(1,n_trials(1)));\nstem(t(cfg.trl(:,2)), max_value * ones(1,n_trials(1)));\nlegend('signal', 'start trial', 'end trial');\n\n%% save results\n[~,name] = fileparts(file_name);\nsave_name = fullfile(file_path, [name, '_segments.mat']);\nsave(save_name, 'sample_start_segment', 'sample_end_segment', ...\n    'n_segments', 'n_trials', 'TR_trials', 'start_segment', 'end_segment', ...\n    'event_type', 'event_value', 'n_trial_samples', 'fs', ...\n    'ecg_is_flipped', 'ecg_ch', 'file_path', 'file_name');", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/PhysIO/code/readin/tapas_physio_read_physlogfiles_brainproducts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24508502416032485, "lm_q1q2_score": 0.12637071950251996}}
{"text": "%% Example of using KST class for interfacing with KUKA iiwa robots\n\n% Using the gamepad for controlling the end-effector of the KUKA\n% iiwa 7 R 800 robot.\n\n% 1- Left joystick of the game pad is used to control the X-Y motion of the end effector. \n%   a- Move the left joystick right and left to move the end-effector along the X axes. \n%   b- Move the left joystick up or down to move the end-effector along the Y axes. \n%   c- Combination is used to move the end-effector along X and Y\n%   simultaneously\n% ------------------------------------- \n% 2- Right joystick of the game pad is used to control the orientation of the end effector around the X and the Y axes. \n%   a- Move the right joystick right and left to rotate the end-effector around the X axes. \n%   b- Move the right joystick up or down to rotate the end-effector around the Y axes.\n%   c- Combination is used to rotate the end-effector around X and Y\n%   simultaneously\n% -------------------------------------\n\n% Warning: keep away from joint limits, and singularities they are not\n% yet taken into consideratio.\n% The Toolbox is a work in progress, other functionalities are going to be\n% added with time.\n\n% This example works with Sunrise application version KST_1.7  and higher.\n% Copyright: Mohammad SAFEEA, 25th of June 2018\n\nclose all;clear;clc;\nwarning('off')\n% Start the joystick, make sure that the joystick is connected\ninstrreset;\nID=1;\njoy=vrjoystick(ID);\n%% Add path of KST class to work space\ncDir = pwd;\ncDir=getTheKSTDirectory(cDir);\naddpath(cDir);\n\n%% Instantiate the KST object\nip='172.31.1.147'; % The IP of the controller\narg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820\narg2=KST.Medien_Flansch_elektrisch; % choose the type of flange\nTef_flange=eye(4); % transofrm matrix of EEF with respect to flange\niiwa=KST(ip,arg1,arg2,Tef_flange); % create the object\n\n%% Start a connection with the server\nflag=iiwa.net_establishConnection();\nif flag==0\n\tfprintf('Can not connect to KST \\n');\n    fprintf('Program terminated \\n');\n    return;\nend\n\n% Initial configuration\njPos={0, pi / 180 * 30, 0, -pi / 180 * 60, 0,...\n                        pi / 180 * 90, 0};\n% Move robot to initial configuration\nrelVel=0.15;\niiwa.movePTPJointSpace(jPos, relVel); % move to initial configuration\n \n% Start direct servo in joint space       \niiwa.realTime_startDirectServoJoints();\n\n% IK solver parameters\nnumberOfIterations=10;\nlambda=0.1;\nTefTool=eye(4);\n\n% Initial configuration vector\nqin=zeros(7,1);\nfor i=1:7\n    qin(i)=jPos{i};\nend\n\n% Ttransformation matrix at initial configurarion\n[Tt,j]=iiwa.directKinematics(qin); \n\n\n% max angular velocity, at which the end-effector can rotate.\nw=5*pi/180; % rad/sec\n% max linear velocity, at which the end-effector can move.\nv=0.05; % m/sec\n% Joint space control\nfirstExecution=0;\n\npause(0.1);\n\n% filtering buffer, value\nc=0.9;\njoyStatus=read(joy);\nfilter=zeros(size(joyStatus));\n\n% Control loop\nwhile true\n    joyStatus=read(joy);\n    % Remove the bias in the input analog signal\n    analogPrecission=1/20;\n    for i=1:4\n        if abs( joyStatus(i))<analogPrecission\n            joyStatus(i)=0;\n        end\n    end\n    filter=c*filter+(1-c)*joyStatus;\n    joyStatus=filter;\n    \n    % About the variable (joyStatus)\n    % joyStatus: is a 4x1 vector, the first and the second elements of this\n    % vector correspond to the analog values of the left analog-stick\n    % psoition. the third and the fourth elements of this\n    % vector correspond to the analog values of the right analog-stick\n    % psoition. \n    % \n    % All foour elemets of the analog signal of the vector  (joyStatus) are used for\n    % controlling the end-effector.\n    %\n    \n    % Calculate the elapsed time between updates\n    if(firstExecution==0)\n        firstExecution=1;\n        a=datevec(now);\n        timeNow=a(6)+a(5)*60+a(4)*60*60; % calculate time at this instant\n        dt=0; % elapsed is zero at first excution\n        time0=timeNow;\n    else\n        a=datevec(now);\n        timeNow=a(6)+a(5)*60+a(4)*60*60; % calculate time at this instant\n        dt=timeNow-time0; % calculate elapsed time interval\n        time0=timeNow;\n    end\n % Construct motion control command\n     n=[joyStatus(4);\n         joyStatus(3);\n         0];\n     k=[0;0;1];\n     w_control=w*cross(n,k);\n     v_control=v*[joyStatus(2);\n         joyStatus(1);\n         0];\n% Calculate target transform using command, and current transform\n     Tt=updateTransform(Tt,w_control,v_control,dt);\n\n     for i=1:7\n         qin(i)=jPos{i};\n     end\n     \n      qt=kukaDLSSolver( qin, Tt, TefTool,numberOfIterations,lambda );\n      \n      if(size(qt)==[7,1])\n          errorFlag=false;\n          for i=1:7\n              if abs(qt(i)-qin(i))>pi*0.5/180\n                  errorFlag=true;\n              end\n          end\n      % check joints limits\n     qt=iiwa.gen_InverseKinematics( qin, Tt,numberOfIterations,lambda );\n     flag=jointLimitReached(qt);\n     % if the motion causes joint limit violation, stay in the current configuration\n     if flag==true;\n         qt=qin;\n     end\n     \n          if errorFlag==false\n              for i=1:7\n                  jPos{i}=qt(i);\n              end\n          end\n      end\n      iiwa.sendJointsPositions(jPos);\n\n    \n     % A condition to break the loop, when x button of the gamepad is\n     % pressed\n     b=button(joy,1);\n     if(b==1)\n         break;\n     end\n       \nend\n% turn off the server\n% close connection\niiwa.net_turnOffServer();\n\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/realtimeControlOfEEFGamePad/KSTclass_Tutorial_gampade_EEFPosControl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2450850021044189, "lm_q1q2_score": 0.12637070813005558}}
{"text": "% Codes for CVPR-15 work `Face Alignment by Coarse-to-Fine Shape Searching'\n% Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com\n% Released on July 25, 2015\n\nif exist('config','var'), error('Please remove variable config mannally!'); end;\n\naddpath(genpath('./codes_release'));\naddpath(genpath('./external'));\n\nconfig.stageTot = 3;\nconfig.win_size = 250;\n\n% From Pr to sub-region center\nregsInfo.iterTot = [3 3 3];\nregsInfo.samplingOffset = [NaN,1500,100];\nregsInfo.trainSampleTot = [10 10 10]; \nregsInfo.testSampleTot = [10 10 10]; \nregsInfo.aug_eyes_id = [37 46];\nregsInfo.win_size = config.win_size;\nregsInfo.SIFTscale = [12 6 6 6];\nregsInfo.mirror = [17:-1:1 27:-1:18 28:31 36:-1:32 ...\n    46 45 44 43 48 47 40 39 38 37 42 41 ...\n    55:-1:49 60:-1:56 65:-1:61 68:-1:66];\nregsInfo.mirror = [regsInfo.mirror regsInfo.mirror+68];\nregsInfo.regressorInfo.trainMethod = @getLR_lcScale;\nregsInfo.regressorInfo.lambda = [50*25 50*30 50*20 50*20];\nregsInfo.regressorInfo.times = 20;\n\nregsInfo.dominantIterTot = [100 100 100];\n\nconfig.regs = regsInfo;\n\n% From sub-region center to Pr\nprobsInfo.semantic_id = [18 22 23 27 37 40 43 46 49 55 51 52 53 58 9];\nprobsInfo.fix_id = [3:7 11:15];\nprobsInfo.sigmaCutoff = [0.25 0.25];\n\nprobsInfo.SVCradius = [20 10];\nprobsInfo.SVCthre = {[0.3 0.6],[0.3 0.6]};\nprobsInfo.probSamplings = [5 5];\nprobsInfo.pyramidScale = [6 12 18];\nprobsInfo.representativeNum1 = [12 12]; \nprobsInfo.representativeNum2 = [8 8]; \n\nprobsInfo.acceptThre = 0.9;\nprobsInfo.gamma_current = 1/50;\nprobsInfo.gamma_search = 1/50;\nprobsInfo.gamma_fix = 1/50;\nprobsInfo.gamma_prior = [1/50,1];\n\nconfig.probs = probsInfo;\n\n% Prior model\npriorsInfo.augTimes = 10;\npriorsInfo.maxRoll = 45;\npriorsInfo.nose_id = 34;\npriorsInfo.noseUpLength = 15;\npriorsInfo.rotationCenter = [0.5 0.35]; %(x,y)\npriorsInfo.win_size = config.win_size;\npriorsInfo.rotatorLength = 15;\npriorsInfo.extractWindow = [0.2 0.8 0.1 0.7]; %(xX,xD,yX,yD)\npriorsInfo.extractCellNum = 3;\npriorsInfo.BaggerNum = 100;\n\nconfig.priors = priorsInfo;\n\nclear regsInfo probsInfo priorsInfo;\n\n%% Generate testConf\ntestConf.stageTot = config.stageTot;\ntestConf.win_size = config.win_size;\ntestConf.priors.win_size = config.win_size;\ntestConf.priors.rotationCenter = config.priors.rotationCenter;\ntestConf.priors.rotatorLength = config.priors.rotatorLength;\ntestConf.priors.extractWindow = config.priors.extractWindow;\ntestConf.priors.extractCellNum = config.priors.extractCellNum;\ntestConf.priors.predictedVoteThre = 10;\ntestConf.regs.samplingTot = [10 10 10];\ntestConf.regs.dominantIterTot = config.regs.dominantIterTot;\ntestConf.regs.SIFTscale = config.regs.SIFTscale;\ntestConf.regs.iterTot = config.regs.iterTot;\ntestConf.probs.probSamplings = config.probs.probSamplings;\ntestConf.probs.semantic_id = config.probs.semantic_id;\ntestConf.probs.fix_id = config.probs.fix_id;\ntestConf.probs.pyramidScale = config.probs.pyramidScale;\ntestConf.probs.acceptThre = config.probs.acceptThre;\ntestConf.probs.gamma_current = config.probs.gamma_current;\ntestConf.probs.gamma_search = config.probs.gamma_search;\ntestConf.probs.gamma_fix = config.probs.gamma_fix;\ntestConf.probs.gamma_prior = config.probs.gamma_prior;\n\n", "meta": {"author": "zhusz", "repo": "CVPR15-CFSS", "sha": "11b8d0b28a4a3e954741a4dae2f114df7b644d4e", "save_path": "github-repos/MATLAB/zhusz-CVPR15-CFSS", "path": "github-repos/MATLAB/zhusz-CVPR15-CFSS/CVPR15-CFSS-11b8d0b28a4a3e954741a4dae2f114df7b644d4e/addAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.23651623106411435, "lm_q1q2_score": 0.12563963889629073}}
{"text": "%%Ex. 2 The meaning of \"a = b\"\n\n\n%In Matlab and in any programming language, the statement \"a = b\" does not mean\n%\"a equals b\". Instead, it prompts the action of replacing the content of a by the\n%content of b.\na = 3;\nb = a;\nb\n\n%Output:3\n", "meta": {"author": "TheAlgorithms", "repo": "MATLAB-Octave", "sha": "e150b77ad256de46c1ce3815c3d7945ac4fc28dc", "save_path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave", "path": "github-repos/MATLAB/TheAlgorithms-MATLAB-Octave/MATLAB-Octave-e150b77ad256de46c1ce3815c3d7945ac4fc28dc/matlab_for_beginners/part_1(learn_basic_programing)/equal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.12537451212042813}}
{"text": "\nfunction ExecFlag=DoSARWatchExec(handles)\n\nglobal VObj;\nglobal VMag;\nglobal VCoi;\nglobal VCtl;\nglobal VSig;\nglobal VSeq;\nglobal VVar;\n\n%preserve VObj\nVTmpObj=VObj;\n\nhandles.Simuh=guidata(handles.Simuh.SimuPanel_figure);\n%% Do spin execution\ntry\n    % Read tab parameters\n    fieldname=fieldnames(handles.Attrh1);\n    for i=1:length(fieldname)/2\n        try\n            eval(['SW.' fieldname{i*2} '=[' get(handles.Attrh1.(fieldname{i*2}),'String') '];']);\n        catch me\n            TAttr=get(handles.Attrh1.(fieldname{i*2}),'String');\n            eval(['SW.' fieldname{i*2} '=''' TAttr{get(handles.Attrh1.(fieldname{i*2}),'Value')}  ''';']);\n        end\n    end\n    \n    if SW.N_Second<VCtl.TR\n        error('''N_Second'' needs to be no less than one TR.');\n    end\n    \n    % Prescan config\n    DoPreScan(handles.Simuh);\n    DoUpdateBar(handles.TimeBar_axes,10,40);\n    \n    if ~isequal(size(VCoi.TxE1x(:,:,:,1)),[max(max(sum(VMag.FRange,1))),max(max(sum(VMag.FRange,2))),max(max(sum(VMag.FRange,3)))])\n        error('E1+ map is not available or invalid.');\n    end\n    \n    % Create Executing Virtual Structure VOsw\n    VOsw=VObj;\n    VOsw.MassDen(VMag.FRange==0)=[];\n    VOsw.ECon(repmat(VMag.FRange,[1,1,1,3])==0)=[];\n    \n    % Kernel uses Mz to determine SpinMx size\n    VOsw.MassDen=reshape(VOsw.MassDen,[max(max(sum(VMag.FRange,1))),max(max(sum(VMag.FRange,2))),max(max(sum(VMag.FRange,3)))]);\n    VOsw.ECon=reshape(VOsw.ECon,[max(max(sum(VMag.FRange,1))),max(max(sum(VMag.FRange,2))),max(max(sum(VMag.FRange,3))),3]);\n    \n    % Spin execution\n    VObj=VOsw;\n\n    if sum(VObj.MassDen(VObj.MassDen~=0))*(VObj.XDimRes*VObj.YDimRes*VObj.ZDimRes)*0.01<SW.N_Gram/1000\n        error(['''N_Gram'' needs to be less than ' num2str(sum(VObj.MassDen(VObj.MassDen~=0))*(VObj.XDimRes*VObj.YDimRes*VObj.ZDimRes)*10) 'g (1% of the total mass).']);\n    end\n    \n    % Generate Pulse line\n    DoPulseGen(handles.Simuh);\n    DoUpdateBar(handles.TimeBar_axes,20,40);\n    \n    % Initialize SAR, Muts in VSig & VVar\n    seq=VSeq.utsLine;\n    dseq=diff(seq);\n    dseq(dseq<0)=0;\n    tSeqEnd=sum(dseq); % sequence end time point\n    if isinf(SW.N_Second)\n        tStart=0;\n        tEnd=tSeqEnd;\n        tSample=unique([tStart, tEnd]);\n    else\n        tEnd=max(0,SW.tStart):SW.dt:min(tSeqEnd,SW.tEnd); % prepare SAR sampling time point\n        tStart=tEnd-SW.N_Second;\n        tStart(tStart<0)=0;\n        tStart(tEnd==0)=[];\n        tEnd(tEnd==0)=[];\n        if isempty(tEnd) | isempty(tStart)\n            error('Input sample time is invalid.');\n        end\n        tSample=unique([tStart, tEnd]);\n    end\n    \n    [row,col,layer]=size(VObj.MassDen);\n    VSig.tSample=tSample;\n    VSig.tRealSample=zeros(size(tSample));\n    VSig.SAR=zeros([[row,col,layer] length(tSample)]);\n    VSig.Muts=zeros(max(size(VSeq.utsLine)),1);\n    VVar.SAR=zeros([[row,col,layer] 3]);\n    \n    % Simulation Process\n    fprintf('Calculating unaveraged local SAR...\\n');\n    try\n        % convert data type\n        DoDataTypeConv(handles.Simuh);\n        VObj.MassDen=single(VObj.MassDen);\n        VObj.ECon=single(VObj.ECon);\n        VCoi.TxE1x=single(VCoi.TxE1x);\n        VCoi.TxE1y=single(VCoi.TxE1y);\n        VCoi.TxE1z=single(VCoi.TxE1z);\n        VSig.SAR=single(VSig.SAR);\n        VVar.SAR=single(VVar.SAR);\n        \n        % calculate dissipated power\n        VCtl.MaxThreadNum=int32(handles.Simuh.CPUInfo.NumThreads);\n        VVar.SARi=int32(0);\n        DoCalSARAtCPU;\n        \n        % calculate unaveraged SAR\n        SAR=zeros([size(VObj.MassDen) length(tEnd)]);\n        Power=zeros([size(VObj.MassDen) length(tEnd)]);\n        tSARSample=zeros(size(tEnd));\n        tSARSecond=zeros(size(tEnd));\n        for i=1:length(tEnd)\n            if tEnd(i)>max(VSig.tRealSample)\n                SAR(:,:,:,i:end)=[];\n                tSARSample(i:end)=[];\n                break;\n            end\n            idx1 = find(tSample==tStart(i));\n            idx2 = find(tSample==tEnd(i));\n            tSARSecond(i) = VSig.tRealSample(idx2)-VSig.tRealSample(idx1);\n            % Collins et.al. MRM 2001 and Tang et.al. PIERS 2007\n            SAR(:,:,:,i)=((VSig.SAR(:,:,:,idx2) - VSig.SAR(:,:,:,idx1))/(VSig.tRealSample(idx2)-VSig.tRealSample(idx1)))./(2*VObj.MassDen);\n            Power(:,:,:,i)=((VSig.SAR(:,:,:,idx2) - VSig.SAR(:,:,:,idx1))/(VSig.tRealSample(idx2)-VSig.tRealSample(idx1)))*(VObj.XDimRes*VObj.YDimRes*VObj.ZDimRes/2);\n            tSARSample(i)=VSig.tRealSample(idx2);\n        end\n        SAR(isnan(SAR))=0;\n        fprintf('Calculating unaveraged local SAR completed.\\n');\n        DoUpdateBar(handles.TimeBar_axes,30,40);\n        \n    catch me\n        error_msg{1,1}='ERROR!!! SAR calculation process aborted.';\n        error_msg{2,1}=me.message;\n        errordlg(error_msg);\n        ExecFlag=0;\n        \n        %recover VObj\n        VObj=VTmpObj;\n        return;\n    end\n    \n    %N-gram average SAR\n    if SW.N_Gram~=0\n        fprintf('Calculating %f-gram local SAR...\\n', SW.N_Gram);\n%         aveSAR=zeros(size(SAR));\n%         avePower=zeros(size(Power));\n%         aveKGram=zeros(size(SAR));\n        % Carluccio et.al. TBME 2013\n        [aveSAR,avePower]=DoSARAverageAtCPU(SAR,Power,double(VObj.MassDen),VObj.XDimRes,VObj.YDimRes,VObj.ZDimRes,SW.N_Gram);\n%         for i=1:size(SAR,4)\n%             [aveSAR(:,:,:,i),avePower(:,:,:,i),aveKGram(:,:,:,i)]=DoSARAverage(SAR(:,:,:,i),Power(:,:,:,i),VObj.MassDen*(VObj.XDimRes*VObj.YDimRes*VObj.ZDimRes),SW.N_Gram/1000);\n%             fprintf('(%d/%d) %f-gram local SAR at time point %fs completed.\\n', i, size(SAR,4), SW.N_Gram, tSARSample(i));\n%             DoUpdateBar(handles.TimeBar_axes,i,size(SAR,4));\n%             pause(0.001);\n%         end\n    else\n        aveSAR=SAR;\n        avePower=Power;\n%         aveKGram=zeros(size(SAR));\n    end\n    \n    handles.SW = SW;\n    handles.aveSAR = aveSAR;\n    handles.avePower = avePower;\n%     handles.aveKGram = aveKGram;\n    handles.tSAR = tEnd; % prescribed sample point\n    handles.tSARSample = tSARSample; % actual sample point\n    handles.tSARSecond = tSARSecond; % actual N_Second\n    handles.MassDen = VObj.MassDen;\n    \n    DoUpdateBar(handles.TimeBar_axes,40,40);\ncatch me\n    error_msg{1,1}='ERROR!!! SAR calculation process aborted.';\n    error_msg{2,1}=me.message;\n    errordlg(error_msg);\n    ExecFlag=0;\n    \n    %recover VObj\n    VObj=VTmpObj;\n    return;\nend\n\n%recover VObj\nVObj=VTmpObj;\n\nguidata(handles.SARWatcherPanel_figure, handles);\nExecFlag=1;\n\nend", "meta": {"author": "leoliuf", "repo": "MRiLab", "sha": "5cdcf1f7b67759700685d3a26ffeb70e55325567", "save_path": "github-repos/MATLAB/leoliuf-MRiLab", "path": "github-repos/MATLAB/leoliuf-MRiLab/MRiLab-5cdcf1f7b67759700685d3a26ffeb70e55325567/Src/Main/DoSARWatchExec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.21733752611649487, "lm_q1q2_score": 0.12385036550927822}}
{"text": "function [net, info] = wsddn_train(varargin)\n% @author: Hakan Bilen\n% wsddn_train: training script for WSDDN\n\nopts.dataDir = fullfile(vl_rootnn, 'data') ;\nopts.expDir = fullfile(vl_rootnn, 'exp') ;\nopts.imdbPath = fullfile(vl_rootnn, 'data', 'imdbs', 'imdb-eb.mat');\nopts.modelPath = fullfile(vl_rootnn, 'models', 'imagenet-vgg-f.mat') ;\nopts.proposalType = 'eb' ;\nopts.proposalDir = fullfile(vl_rootnn, 'data', 'EdgeBoxes') ;\n\n\nopts.addBiasSamples = 1; % add Box Scores\nopts.addLossSmooth  = 1; % add Spatial Regulariser\nopts.softmaxTempCls = 1; % softmax temp for cls\nopts.softmaxTempDet = 2; % softmax temp for det\nopts.maxScale = 2000 ;\n\n% if you have limited gpu memory (<6gb), you can change the next 2 params\nopts.maxNumProposals = inf; % limit number (eg 1500)\nopts.imageScales = [480,576,688,864,1200]; % scales\nopts.minBoxSize = 20; % minimum bounding box size\nopts.train.gpus = [] ;\nopts.train.continue = true ;\nopts.train.prefetch = true ;\nopts.train.learningRate = 1e-5 * [ones(1,10) 0.1*ones(1,10)] ;\nopts.train.weightDecay = 0.0005;\nopts.train.numEpochs = 20;\nopts.train.derOutputs = {'objective', 1} ;\n\nopts.numFetchThreads = 1 ;\nopts = vl_argparse(opts, varargin) ;\n\ndisplay(opts);\n\nopts.train.batchSize = 1 ;\nopts.train.expDir = opts.expDir ;\nopts.train.numEpochs = numel(opts.train.learningRate) ;\n%% -------------------------------------------------------------------------\n%                                                   Database initialization\n% -------------------------------------------------------------------------\nfprintf('loading imdb...');\nif exist(opts.imdbPath,'file')==2\n  imdb = load(opts.imdbPath) ;\nelse\n  if strcmp(opts.proposalType,'ssw')\n    imdb = setup_voc07_ssw('dataDir',opts.dataDir, ...\n      'proposalDir',opts.proposalDir,'loadTest',1);\n  elseif strcmp(opts.proposalType,'eb')\n    imdb = setup_voc07_eb('dataDir',opts.dataDir, ...\n      'proposalDir',opts.proposalDir,'loadTest',1);\n  else\n    error('undefined proposal type %s\\n',opts.proposalType)\n  end\n  \n  imdbFolder = fileparts(opts.imdbPath);\n  \n  if ~exist(imdbFolder,'dir')\n    mkdir(imdbFolder);\n  end\n  save(opts.imdbPath,'-struct', 'imdb', '-v7.3');\nend\n\nfprintf('done\\n');\n\nimdb = fixBBoxes(imdb, opts.minBoxSize, opts.maxNumProposals);\n\n% use train + val for training\nimdb.images.set(imdb.images.set == 2) = 1;\ntrainIdx = find(imdb.images.set == 1);\n\n%% Compute image statistics (mean, RGB covariances, etc.)\nimageStatsPath = fullfile(opts.dataDir, 'imageStats.mat') ;\nif exist(imageStatsPath,'file')\n  load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nelse\n \n  images = imdb.images.name(imdb.images.set == 1) ;\n  images = strcat([imdb.imageDir filesep],images) ;\n  \n  [averageImage, rgbMean, rgbCovariance] = getImageStats(images, ...\n    'imageSize', [256 256], ...\n    'numThreads', opts.numFetchThreads, ...\n    'gpus', opts.train.gpus) ;\n  save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;\nend\n[v,d] = eig(rgbCovariance) ;\nrgbDeviation = v*sqrt(d) ;\nclear v d ;\n\n\n%% ------------------------------------------------------------------------\n%                                                    Network initialization\n% -------------------------------------------------------------------------\nnopts.addBiasSamples = opts.addBiasSamples; % add Box Scores (only with Edge Boxes)\nnopts.addLossSmooth  = opts.addLossSmooth; % add Spatial Regulariser\nnopts.softmaxTempCls = opts.softmaxTempCls; % softmax temp for cls\nnopts.softmaxTempDet = opts.softmaxTempDet; % softmax temp for det\n\nnopts.averageImage = reshape(rgbMean,[1 1 3]) ;\n% nopts.rgbVariance = 0.1 * rgbDeviation ;\nnopts.rgbVariance = [] ;\nnopts.numClasses = numel(imdb.classes.name) ;\nnopts.classNames = imdb.classes.name ;\n\nif ~exist(opts.modelPath,'file')\n  [pname,fname,ext]  = fileparts(opts.modelPath) ;\n  if ~exist(pname,'dir')\n    mkdir(pname) ;\n  end\n  fprintf('Downloading %s to %s\\n', [fname ext], pname) ;\n  urlwrite(sprintf('http://www.vlfeat.org/matconvnet/models/%s',[fname ext]),...\n    opts.modelPath) ;\nend\n\nnet = load(opts.modelPath);\nnet = wsddn_init(net,nopts);\n\nif nopts.addLossSmooth\n  opts.train.derOutputs = {'objective', 1, 'lossTopB', 1e-4} ;\nend\n\n\nif ~exist(opts.expDir,'dir')\n  mkdir(opts.expDir) ;\nend\n\n%% -------------------------------------------------------------------------\n%                                                   Database stats\n% -------------------------------------------------------------------------\nbopts = net.meta.normalization;\nnet.meta.augmentation.jitterBrightness = 0 ;\n% bopts.interpolation = 'bilinear';\nbopts.jitterBrightness = net.meta.augmentation.jitterBrightness ;\nbopts.imageScales = opts.imageScales;\nbopts.numThreads = opts.numFetchThreads;\nbopts.addLossSmooth = opts.addLossSmooth;\nbopts.addBiasSamples = opts.addBiasSamples;\nbopts.maxScale = opts.maxScale ;\nbopts.vgg16 = any(arrayfun(@(a) strcmp(a.name, 'relu5_1'), net.layers)==1) ;\n%% -------------------------------------------------------------------\n%                                                                Train\n% --------------------------------------------------------------------\n% avoid test data\nvalIdx = find(imdb.images.set == 3);\nvalIdx = valIdx(1:5:end) ;\n% valIdx = [];\n\n%% \nbopts.useGpu = numel(opts.train.gpus) >  0 ;\nbopts.prefetch = opts.train.prefetch;\n\ninfo = cnn_train_dag(net, imdb, @(i,b) ...\n  getBatch(bopts,i,b), ...\n  opts.train, 'train', trainIdx, ...\n  'val', valIdx) ;\n\n%% -------------------------------------------------------------------\n%                                                       Deploy network\n% --------------------------------------------------------------------\nif ~exist(fullfile(opts.expDir,'net.mat'),'file')\n  removeLoss = {'dagnn.Loss','dagnn.DropOut'};\n  for i=1:numel(removeLoss)\n    dagRemoveLayersOfType(net,removeLoss{i}) ;\n  end\n  \n  net.mode = 'test' ;\n  net_ = net ;\n  net = net_.saveobj() ;\n  save(fullfile(opts.expDir,'net.mat'), '-struct','net');\nend\n% --------------------------------------------------------------------\nfunction inputs = getBatch(opts, imdb, batch)\n% --------------------------------------------------------------------\nif isempty(batch)\n  inputs = {'input', [], 'label', [], 'rois', [], 'ids', []};\n  return;\nend\n\nopts.scale = opts.imageScales(randi(numel(opts.imageScales)));\nopts.flip = randi(2,numel(batch),1)-1; % random flip\nis_vgg16 = opts.vgg16 ;\nopts = rmfield(opts,'vgg16') ;\n\nimages = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;\nopts.prefetch = (nargout == 0);\n\n[im,rois] = wsddn_get_batch(images, imdb, batch, opts);\n\nif nargout>0\n  rois = single(rois') ;\n  labels = imdb.images.label(:,batch) ;\n  labels = reshape(labels,[1 1 size(labels,1) numel(batch)]);\n\n  if opts.useGpu > 0\n    im = gpuArray(im) ;\n    rois = gpuArray(rois) ;\n  end\n\n  if ~isempty(rois)\n   rois = rois([1 3 2 5 4],:) ;\n  end\n\n  ss = [16 16] ;\n\n  if is_vgg16\n    o0 = 8.5 ;\n    o1 = 9.5 ;\n  else\n    o0 = 18 ;\n    o1 = 9.5 ;\n  end\n\n  rois = [ rois(1,:); ...\n    floor((rois(2,:) - o0 + o1) / ss(1) + 0.5) + 1;\n    floor((rois(3,:) - o0 + o1) / ss(2) + 0.5) + 1;\n    ceil((rois(4,:) - o0 - o1) / ss(1) - 0.5) + 1;\n    ceil((rois(5,:) - o0 - o1) / ss(2) - 0.5) + 1];\n\n\n  inputs = {'input', im, 'label', labels, 'rois', rois, 'ids', batch} ;\n\n  if opts.addLossSmooth\n    inputs{end+1} = 'boxes' ;\n    inputs{end+1} = imdb.images.boxes{batch} ;\n  end\n\n  if opts.addBiasSamples==1\n    boxScore = reshape(imdb.images.boxScores{batch},[1 1 1 numel(imdb.images.boxScores{batch})]);\n    inputs{end+1} = 'boxScore';\n    inputs{end+1} = boxScore ;\n  end\nend\n\n% -------------------------------------------------------------------------\nfunction imdb = fixBBoxes(imdb, minSize, maxNum)\n% -------------------------------------------------------------------------\nfor i=1:numel(imdb.images.name)\n  bbox = imdb.images.boxes{i};\n  % remove small bbox\n  isGood = (bbox(:,3)>=bbox(:,1)+minSize) & (bbox(:,4)>=bbox(:,2)+minSize);\n  bbox = bbox(isGood,:);\n  % remove duplicate ones\n  [dummy, uniqueIdx] = unique(bbox, 'rows', 'first');\n  uniqueIdx = sort(uniqueIdx);\n  bbox = bbox(uniqueIdx,:);\n  % limit number for training\n  if imdb.images.set(i)~=3\n    nB = min(size(bbox,1),maxNum);\n  else\n    nB = size(bbox,1);\n  end\n  \n  if isfield(imdb.images,'boxScores')\n    imdb.images.boxScores{i} = imdb.images.boxScores{i}(isGood);\n    imdb.images.boxScores{i} = imdb.images.boxScores{i}(uniqueIdx);\n    imdb.images.boxScores{i} = imdb.images.boxScores{i}(1:nB);\n  end\n  imdb.images.boxes{i} = bbox(1:nB,:);\n  %   [h,w,~] = size(imdb.images.data{i});\n  %   imdb.images.boxes{i} = [1 1 h w];\n  \nend\n\n% -------------------------------------------------------------------------\nfunction layers = dagFindLayersOfType(net, type)\n% -------------------------------------------------------------------------\nlayers = [] ;\nfor l = 1:numel(net.layers)\n  if isa(net.layers(l).block, type)\n    layers{1,end+1} = net.layers(l).name ;\n  end\nend\n% -------------------------------------------------------------------------\nfunction dagRemoveLayersOfType(net, type)\n% -------------------------------------------------------------------------\nnames = dagFindLayersOfType(net, type) ;\nfor i = 1:numel(names)\n  layer = net.layers(net.getLayerIndex(names{i})) ;\n  net.removeLayer(names{i}) ;\n  net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;\nend\n", "meta": {"author": "hbilen", "repo": "WSDDN", "sha": "bfdaa3f9ffed45e52a11a1342fd7476e08dfac39", "save_path": "github-repos/MATLAB/hbilen-WSDDN", "path": "github-repos/MATLAB/hbilen-WSDDN/WSDDN-bfdaa3f9ffed45e52a11a1342fd7476e08dfac39/core/wsddn_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.2254166106314731, "lm_q1q2_score": 0.12237039799473567}}
{"text": "function colors = getColorSet(numObjs)\n% get rgb [0,1] values from id\ncolors=[\n        128 255 255;    % \n        255 0 0;        % red           1\n        0 255 0;        % green         2\n        0 0 255;        % blue          3\n        0 255 255;      % cyan          4\n        255 0 255;      % magenta       5\n        212 212 0;      % yellow        6\n        25 25 25;       % black         7\n        34,139,34;      % forestgreen   8\n        0,191,255;      % deepskyblue   9\n        139,0,0 ;       % darkred       10\n        218,112,214;    % orchid        11\n        244,164,96 ;]/255;  % sandybrown    12\ncolors = colors / 255;\nif(numObjs >= 13)\n    load colors.mat\n    %morecolors = rand(10000, 3);\n    %colors = cat(1,colors,morecolors);\nend", "meta": {"author": "VisDrone", "repo": "DroneCrowd", "sha": "3d25637f93f9476b4c949b6b9362287635b1a8c3", "save_path": "github-repos/MATLAB/VisDrone-DroneCrowd", "path": "github-repos/MATLAB/VisDrone-DroneCrowd/DroneCrowd-3d25637f93f9476b4c949b6b9362287635b1a8c3/STNNet/DroneCrowd-MOT-toolkit/display/getColorSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.23934934189686402, "lm_q1q2_score": 0.12154443552264721}}
{"text": "% Load far talk, close talk, and frame label. \nfunction [Data, para, vocab] = LoadParallelWavLabel_Reverb(para, step, dataset, datatype, distance)\nnCh = para.topology.useChannel;\nwavlist = []; wavlistClean = [];\n% note that training data do not contain real recordings. \n% real dev and eval data do not have clean version\nfor type_i = 1:length(datatype)\n    if strcmpi(datatype, 'real') || strcmpi(dataset, 'train')\n        nRoom = 1;    else; nRoom = 3; end\n    for dist_i = 1:length(distance)\n        for roomID = 1:nRoom\n            [tasklist, taskfile] = LoadTaskFile_Reverb([para.local.wavroot '/taskFiles'], dataset, datatype{type_i}, distance{dist_i}, nCh, roomID);\n            wavlist = [wavlist Tasklist2wavlist(para.local.wavroot, tasklist, dataset, datatype{type_i})];\n            \n            if strcmpi(dataset, 'train')\n                wavlistClean = findFiles([para.local.wsjcam0root '/data_wav/primary_microphone/si_tr'], para.local.wsjcam0ext);\n            elseif ~strcmpi(datatype, 'real')\n                [tasklistClean, taskfileClean] = LoadTaskFile_Reverb([para.local.wavroot '/taskFiles'], dataset, datatype{type_i}, 'cln', nCh, roomID);\n                wavlistClean = [wavlistClean Tasklist2wavlist(para.local.wavroot, tasklistClean, dataset, datatype{type_i})];\n            end\n        end\n        if strcmpi(dataset, 'train'); break; end    % For training data, far and near distances are in one list, so we can stop here.\n    end\nend\nfor i=1:length(wavlistClean)   % build an index of clean files so we can find them quickly by utterance ID\n    [~,curr_uttID] = fileparts(wavlistClean{i});\n    clean_struct.(['U_' curr_uttID]) = wavlistClean{i};\nend\n\n% Currently we don't support loading of frame label yet. \n% switch lower(dataset)\n%     case {'eval_simu'}\n%         ali_file = [para.local.aliDir '_' dataset '/ali.txt'];\n%     case 'tr05'\n%         ali_file = [para.local.aliDir '/ali.txt'];\n% end\n% [ali, vocab] = LoadKaldiFrameLabel(ali_file);\nvocab = [];\n\nwavlist = wavlist(:,step:step:end);\nwavlistClean = wavlistClean(:,step:step:end);\n\nwavreader.name = 'wavfile';\nwavreader.array = 1;\nwavreader.multiArrayFiles = 1;\n\nfs = 16000;   \nframe_size = fs*0.025;\nframe_shift = fs*0.01;\nif para.local.useFileName==0\n    seglen = para.local.seglen;\n    segshift = para.local.segshift;\nend\n\n% Load data file list\nwav_noisy = {};  label = {};  wav_clean = {};\nnUtt = size(wavlist,2);\nfor si = 1:nUtt\n    words = ExtractWordsFromString_v2(wavlist{1,si}, '/');\n    curr_uttID = words{end}(1:end-4);\n    PrintProgress(si, nUtt, 100, curr_uttID);\n    \n    words2 = ExtractWordsFromString_v2(curr_uttID, '_');\n    clean_uttID = words2{1};\n\n    [wav] = InputReader(wavlist(:,si), wavreader);\n    wav = StoreWavInt16(wav);\n    if strcmpi(datatype, 'real')    \n        wav_c = wav; % note that for real data, we don't have clean version. so just use the noisy version. This line will only be run at test time. \n    elseif strcmpi(dataset, 'train')\n        wavfileClean = clean_struct.(['U_' clean_uttID]);\n        wav_c = audioread(wavfileClean)';\n    else\n        [wav_c] = InputReader(wavlistClean(:,si), wavreader);\n    end\n    wav_c = StoreWavInt16(wav_c);\n    \n    % synchronize the length of label and wav\n    nFr_feat = enframe_decide_frame_number(size(wav,2), frame_size, frame_shift);\n    nFr_feat = min(nFr_feat, enframe_decide_frame_number(size(wav_c,2), frame_size, frame_shift));\n    nFr_label = 10000;\n    nFr = min([nFr_feat nFr_label]);\n    requiredLen = DecideWavLen4XFrames(nFr, frame_size, frame_shift);\n    wav(:,requiredLen+1:end) = [];\n    wav_c(:,requiredLen+1:end) = [];\n    \n    if para.local.useFileName\n        for i=1:nCh\n            wavfileArray{i} = sprintf('%s 0 %2.3f', wavlist{i,si}, size(wav,2)/fs);\n        end\n        wav_noisy{end+1} = wavfileArray;\n        if strcmpi(datatype, 'real')    \n            wav_clean{end+1} = wavfileArray{1};\n        elseif strcmpi(dataset, 'train')\n            wav_clean{end+1} = sprintf('%s 0 %2.3f', clean_struct.(['U_' clean_uttID]), size(wav,2)/fs);\n        else\n            wav_clean{end+1} = sprintf('%s 0 %2.3f', wavlistClean{1,si}, size(wav,2)/fs);\n        end\n    else    \n        if 1    % we use small segments rather than whole sentences as training examples\n            wav_c_seg = DivideSent2Segments(wav_c, (seglen-1)*frame_shift+frame_size, segshift*frame_shift, 1);\n            wav_seg = DivideSent2Segments(wav, (seglen-1)*frame_shift+frame_size, segshift*frame_shift, 1);\n            wav_noisy = [wav_noisy; wav_seg];\n            wav_clean = [wav_clean; wav_c_seg];\n        else\n            wav_noisy{end+1} = wav;\n            wav_clean{end+1} = wav_c;\n        end\n    end\n    if para.local.loadLabel\n        for j = length(label)+1:length(wav_noisy)\n            label{j} = [];\n        end\n    end\nend\n\nData(1).data = wav_noisy;\nData(2).data = wav_clean;\n\npara.IO.inputFeature = [1 1];\npara.IO.DataSyncSet{1} = [];\npara.IO.frame_rate = [16000 16000];\npara.IO.isTensor = [1 1];\nif para.local.useFileName\n    para.IO.inputFeature([1 2]) = 0;\n    wavreader.precision = 'int16';\n    if isfield(para.IO, 'fileReader')\n        para.IO = rmfield(para.IO, 'fileReader');\n    end\n    para.IO.fileReader(1) = wavreader;\n    para.IO.fileReader(2) = wavreader;\n    para.IO.fileReader(2).array = 0;\n    para.IO.fileReader(2).multiArrayFiles = 0;\nend\nif para.local.loadLabel\n    Data(3).data = label;\n    para.IO.inputFeature(3) = 1;\n    para.IO.frame_rate(3) = 100;\n    para.IO.isTensor(3) = 1;\n    para.IO.fileReader(3).name = '';\nend\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/dereverb/local/LoadParallelWavLabel_Reverb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2309197576365038, "lm_q1q2_score": 0.11816547433686046}}
{"text": "function events = in_events_kdf(sFile, EventFile)\n% IN_EVENTS_KDF: Read the events descriptions from a KRISS .trg file.\n%\n% USAGE:  events = in_events_kdf(sFile, EventFile)\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2014\n\n% Initialize returned variable\nevents = repmat(db_template('event'), 0);\n% Load trigger file\nEventDat = load(EventFile, '-ASCII');\nif isempty(EventDat)\n    return;\nend\n\n% Consider both the stim and responses as events of the same level\nAllEvt = [EventDat(:,1:2); EventDat(EventDat(:,4)~=0, 3:4)];\n% Get all the unique events\nuniqueEvt = unique(AllEvt(:,2));\n% Create events structures: one per category of event\nfor iEvt = 1:length(uniqueEvt)\n    % Find all the occurrences of event #iEvt\n    iMrk = find(AllEvt(:,2) == uniqueEvt(iEvt));\n    % Add event structure\n    events(iEvt).label      = num2str(uniqueEvt(iEvt));\n    events(iEvt).epochs     = ones(1, length(iMrk));\n    events(iEvt).times      = AllEvt(iMrk,1)' ./ sFile.prop.sfreq;\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_kdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.22541662103868043, "lm_q1q2_score": 0.11534942796179905}}
{"text": "\nfunction rezToPhy(rez, savePath, varargin)\n% pull out results from kilosort's rez to either return to workspace or to\n% save in the appropriate format for the phy GUI to run on. If you provide\n% a savePath it should be a folder, and you will need to have npy-matlab\n% available (https://github.com/kwikteam/npy-matlab)\n\n\n[~, Nfilt, Nrank] = size(rez.W);\nrez.Wphy = cat(1, zeros(1+rez.ops.nt0min, Nfilt, Nrank), rez.W); % for Phy, we need to pad the spikes with zeros so the spikes are aligned to the center of the window\n\n% spikeTimes will be in samples, not seconds\nrez.W = gather(single(rez.Wphy));\nrez.U = gather(single(rez.U));\nrez.mu = gather(single(rez.mu));\n\nif size(rez.st3,2)>4\n    rez.st3 = rez.st3(:,1:4);\nend\n\n[~, isort]   = sort(rez.st3(:,1), 'ascend');\nrez.st3      = rez.st3(isort, :);\nif ~isempty(rez.cProj)\n    rez.cProj    = rez.cProj(isort, :);\n    rez.cProjPC  = rez.cProjPC(isort, :, :);\nend\n\n% ix = rez.st3(:,4)>12;\n% rez.st3 = rez.st3(ix, :);\n% rez.cProj = rez.cProj(ix, :);\n% rez.cProjPC = rez.cProjPC(ix, :,:);\n\nfs = dir(fullfile(savePath, '*.npy'));\nfor i = 1:length(fs)\n   delete(fullfile(savePath, fs(i).name));\nend\nif exist(fullfile(savePath, '.phy'), 'dir')\n    rmdir(fullfile(savePath, '.phy'), 's');\nend\n\nspikeTimes = uint64(rez.st3(:,1));\n% account for ops.trange(1) to accomodate real time\nspikeTimes = spikeTimes - rez.ops.trange(1)*rez.ops.fs;\n% [spikeTimes, ii] = sort(spikeTimes);\nspikeTemplates = uint32(rez.st3(:,2));\nif size(rez.st3,2)>4\n    spikeClusters = uint32(1+rez.st3(:,5));\nend\namplitudes = rez.st3(:,3);\n\nNchan = rez.ops.Nchan;\n\nxcoords     = rez.xcoords(:);\nycoords     = rez.ycoords(:);\nchanMap     = rez.ops.chanMap(:);\nchanMap0ind = chanMap - 1;\n\nnt0 = size(rez.W,1);\nU = rez.U;\nW = rez.W;\n\nNfilt = size(W,2);\n\ntemplates = zeros(Nchan, nt0, Nfilt, 'single');\nfor iNN = 1:size(templates,3)\n   templates(:,:,iNN) = rez.mu(iNN,1) * squeeze(U(:,iNN,:)) * squeeze(W(:,iNN,:))';\nend\ntemplates = permute(templates, [3 2 1]); % now it's nTemplates x nSamples x nChannels\ntemplatesInds = repmat([0:size(templates,3)-1], size(templates,1), 1); % we include all channels so this is trivial\n\ntemplateFeatures = rez.cProj;\ntemplateFeatureInds = uint32(rez.iNeigh);\npcFeatures = rez.cProjPC;\npcFeatureInds = uint32(rez.iNeighPC);\n\n% whiteningMatrix = rez.Wrot/rez.ops.scaleproc;\nwhiteningMatrix = eye(size(rez.Wrot)) / rez.ops.scaleproc;\nwhiteningMatrixInv = whiteningMatrix^-1;\n\n% here we compute the amplitude of every template...\n\n% unwhiten all the templates\ntempsUnW = zeros(size(templates));\nfor t = 1:size(templates,1)\n    tempsUnW(t,:,:) = squeeze(templates(t,:,:))*whiteningMatrixInv;\nend\n\n% The amplitude on each channel is the positive peak minus the negative\ntempChanAmps = squeeze(max(tempsUnW,[],2))-squeeze(min(tempsUnW,[],2));\n\n% The template amplitude is the amplitude of its largest channel\ntempAmpsUnscaled = max(tempChanAmps,[],2);\n\n% assign all spikes the amplitude of their template multiplied by their\n% scaling amplitudes\nspikeAmps = tempAmpsUnscaled(spikeTemplates).*amplitudes;\n\n% take the average of all spike amps to get actual template amps (since\n% tempScalingAmps are equal mean for all templates)\nta = clusterAverage(spikeTemplates, spikeAmps);\ntids = unique(spikeTemplates);\ntempAmps = zeros(numel(rez.mu),1);\ntempAmps(tids) = ta; % because ta only has entries for templates that had at least one spike\ngain = getOr(rez.ops, 'gain', 1);\ntempAmps = gain*tempAmps'; % for consistency, make first dimension template number\n\n\ntemplateFeatures = [];\nif ~isempty(savePath)\n    fileID = fopen(fullfile(savePath, 'cluster_KSLabel.tsv'),'w');\n    fprintf(fileID, 'cluster_id%sKSLabel', char(9));\n    fprintf(fileID, char([13 10]));\n    \n    fileIDCP = fopen(fullfile(savePath, 'cluster_ContamPct.tsv'),'w');\n    fprintf(fileIDCP, 'cluster_id%sContamPct', char(9));\n    fprintf(fileIDCP, char([13 10]));\n    \n    fileIDA = fopen(fullfile(savePath, 'cluster_Amplitude.tsv'),'w');\n    fprintf(fileIDA, 'cluster_id%sAmplitude', char(9));\n    fprintf(fileIDA, char([13 10]));\n    \n    rez.est_contam_rate(isnan(rez.est_contam_rate)) = 1;\n    for j = 1:length(rez.good)\n        if rez.good(j)\n            fprintf(fileID, '%d%sgood', j-1, char(9));\n        else\n            fprintf(fileID, '%d%smua', j-1, char(9));\n        end\n        fprintf(fileID, char([13 10]));\n        \n        fprintf(fileIDCP, '%d%s%.1f', j-1, char(9), rez.est_contam_rate(j)*100);\n        fprintf(fileIDCP, char([13 10]));\n        \n        fprintf(fileIDA, '%d%s%.1f', j-1, char(9), tempAmps(j));\n        fprintf(fileIDA, char([13 10]));\n        \n    end\n    fclose(fileID);\n    fclose(fileIDCP);\n    fclose(fileIDA);\n    \n    \n    writeNPY(spikeTimes, fullfile(savePath, 'spike_times.npy'));\n    writeNPY(uint32(spikeTemplates-1), fullfile(savePath, 'spike_templates.npy')); % -1 for zero indexing\n    if size(rez.st3,2)>4\n        writeNPY(uint32(spikeClusters-1), fullfile(savePath, 'spike_clusters.npy')); % -1 for zero indexing\n    else\n        writeNPY(uint32(spikeTemplates-1), fullfile(savePath, 'spike_clusters.npy')); % -1 for zero indexing\n    end\n    writeNPY(amplitudes, fullfile(savePath, 'amplitudes.npy'));\n    writeNPY(templates, fullfile(savePath, 'templates.npy'));\n    writeNPY(templatesInds, fullfile(savePath, 'templates_ind.npy'));\n\n    %chanMap0ind = int32(chanMap0ind);\n    chanMap0ind = int32([1:rez.ops.Nchan]-1);\n    writeNPY(chanMap0ind, fullfile(savePath, 'channel_map.npy'));\n    writeNPY([xcoords ycoords], fullfile(savePath, 'channel_positions.npy'));\n\n    if ~isempty(templateFeatures)\n        writeNPY(templateFeatures, fullfile(savePath, 'template_features.npy'));\n        writeNPY(templateFeatureInds'-1, fullfile(savePath, 'template_feature_ind.npy'));% -1 for zero indexing\n        writeNPY(pcFeatures, fullfile(savePath, 'pc_features.npy'));\n        writeNPY(pcFeatureInds'-1, fullfile(savePath, 'pc_feature_ind.npy'));% -1 for zero indexing\n    end\n\n    writeNPY(whiteningMatrix, fullfile(savePath, 'whitening_mat.npy'));\n    writeNPY(whiteningMatrixInv, fullfile(savePath, 'whitening_mat_inv.npy'));\n\n    if isfield(rez, 'simScore')\n        similarTemplates = rez.simScore;\n        writeNPY(similarTemplates, fullfile(savePath, 'similar_templates.npy'));\n    end\n\n    % save a list of \"good\" clusters for Phy\n%     fileID = fopen(fullfile(savePath, 'channel_names.tsv'), 'w');\n%     fprintf(fileID, 'cluster_id%sKSLabel', char(9));\n%     for j = 1:Nchan\n%         fprintf(fileID, '%d%s%d', j-1,char(9),chanMap0ind(j));\n%         fprintf(fileID, char([13 10]));\n%     end\n%     fclose(fileID);\n\n    % Duplicate \"KSLabel\" as \"group\", a special metadata ID for Phy, so that\n    % filtering works as expected in the cluster view\n    KSLabelFilename = fullfile(savePath, 'cluster_KSLabel.tsv');\n    copyfile(KSLabelFilename, fullfile(savePath, 'cluster_group.tsv'));\n\n     %make params file\n    if ~exist(fullfile(savePath,'params.py'),'file')\n        fid = fopen(fullfile(savePath,'params.py'), 'w');\n\n%        [~, fname, ext] = fileparts(rez.ops.fbinary);\n%         fprintf(fid,['dat_path = ''',fname ext '''\\n']);\n%         fprintf(fid,'n_channels_dat = %i\\n',rez.ops.NchanTOT);\n        if ~isempty(varargin)\n            [root, fname, ext] = fileparts(rez.ops.fbinary);\n        else\n            [root, fname, ext] = fileparts(rez.ops.fproc);\n        end\n%         fprintf(fid,['dat_path = ''',fname ext '''\\n']);\n        fprintf(fid,['dat_path = ''', strrep(rez.ops.fproc, '\\', '/') '''\\n']);\n        \n        fprintf(fid,'n_channels_dat = %i\\n',rez.ops.Nchan);\n        \n        fprintf(fid,'dtype = ''int16''\\n');\n        fprintf(fid,'offset = 0\\n');\n        if mod(rez.ops.fs,1)\n            fprintf(fid,'sample_rate = %i\\n',rez.ops.fs);\n        else\n            fprintf(fid,'sample_rate = %i.\\n',rez.ops.fs);\n        end\n%         fprintf(fid,'hp_filtered = False');\n        fprintf(fid,'hp_filtered = True');\n        \n        fclose(fid);\n    end\nend\n", "meta": {"author": "MouseLand", "repo": "Kilosort", "sha": "d55179f4bed45d4f17e5481283bc3f260212c1c7", "save_path": "github-repos/MATLAB/MouseLand-Kilosort", "path": "github-repos/MATLAB/MouseLand-Kilosort/Kilosort-d55179f4bed45d4f17e5481283bc3f260212c1c7/utils/rezToPhy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2120688093369431, "lm_q1q2_score": 0.11430152986382801}}
{"text": "function val = get(w,prop_name)\n   %GET Get waveform properties\n   %   val = get(waveform,prop_name)\n   %\n   %   Valid property names:\n   %       CHANNELTAG, NETWORK, STATION, LOCATION, CHANNEL,\n   %       CHANNELINFO : (gets the info as a string 'Net.Sta.Loc.Cha')\n   %       FREQ, START_STR,\n   %       END_STR, DATA, NYQ, PERIOD\n   %     also:\n   %       START, END : return datenum format (MatLab's format)\n   %       START_EPOCH, END_EPOCH : return epoch format.\n   %\n   %       DATA_LENGTH : return number of elements in data\n   %\n   %       The following return time duration of data\n   %       DURATION_STR :  text format\n   %       DURATION: matlab (datenum) format\n   %       DURATION_EPOCH : antelope (epoch) format (just # of seconds)\n   %\n   %       TIMEVECTOR : return a vector of same length as data with\n   %                    matlab-formatted times.\n   %\n   %       MISC_FIELDS: gets a list of fields that were added to this waveform\n   %       UNITS : Find out what units the data is in (ex. counts, nm/s)\n   %\n   %   If waveform is N-dimensional, then VAL will be a cell of the same\n   %   dimensions.  If GET would return single-values for the property, then\n   %   VAL will be a matrix of type DOUBLE, arranged in the same dimensions.\n   %\n   %       If additional fields were added to waveform using ADDFIELD, then\n   %       values from these can be retrieved using the fieldname\n   %\n   %       Example: Create a waveform, add a field, then get the field\n   %           W = waveform;\n   %           W = addfield(W,'P-pick', datenum('1/5/2007 02:12:15'));\n   %           misc = get(W,'MISC_FIELDS'); %returns a cell with 'P-pick'\n   %           PickTime = get(W,'P-pick'); % (same as) PickTime = get(W,misc);\n   %\n   %\n   %   See also WAVEFORM/GETM, WAVEFORM/SET, WAVEFORM/ADDFIELD,\n   %   WAVEFORM/DELFIELD\n   \n   %  11/28/2008 added WAVEFORM_OBJECT_VERSION, which returns a single version\n   %  field from the waveform object.  This is set with the constructor, and\n   %  is used in load_obj.\n   \n   % AUTHOR: Celso Reyes, Geophysical Institute, Univ. of Alaska Fairbanks\n   % $Date$\n   % $Revision$\n   \n   \n   %global mep2dep\n   \n   %val_CELL = cell(size(w));\n   %val = val_CELL;\n   usedcell = false;\n   singleWave = isscalar(w);\n   switch upper(prop_name)\n      \n      % IDENTIFICATION PROPERTIES\n      case {'STATION','CHANNEL','NETWORK','LOCATION'} %type:CELL\n         val = get([w.cha_tag],prop_name);\n         usedcell = true;\n         \n      case {'COMPONENT'} %type:CELL   GRANDFATHERED IN...\n         val = get([w.cha_tag],'channel');\n         usedcell = true;\n         \n         % DATA DESCRIBING PROPERTIES\n         \n      case {'FS', 'FREQ'} %type:DOUBLE\n         val = [w.Fs];\n         \n      case 'DATA' %type:DOUBLE\n         if singleWave\n            val = w.data;\n         else\n            val = {w.data}; %cells of data values\n            usedcell = true;\n         end\n         \n      case 'NYQ' %type:DOUBLE\n         val = [w.Fs] ./ 2;\n         \n      case 'PERIOD' %type:DOUBLE\n         val = 1 ./ [w.Fs];\n         \n      case 'DATA_LENGTH' %type:DOUBLE\n         val = zeros(size(w));\n         for N = 1: numel(w)\n            val(N) = numel(w(N).data);\n         end\n         \n         % TIME PROPERTIES\n         \n      case {'START_STR'} %type:CELL\n         val = stringDate([w.start]);\n         usedcell = true;\n         \n      case {'START_EPOCH'} %type:DOUBLE\n         val = mep2dep([w.start]);\n         \n      case {'START_MATLAB', 'START'} %type:DOUBLE\n         val = [w.start];\n         \n      case {'END_STR'} %type:CELL\n         val = stringDate(grabEndTime(w));\n         usedcell = true;\n         \n      case {'END_EPOCH'} %type:DOUBLE\n         val = mep2dep(grabEndTime(w));\n         \n      case {'END_MATLAB', 'END'} %type:DOUBLE\n         val = grabEndTime(w);\n         \n      case {'DURATION_STR'} %type:CELL\n         endvec = grabEndTime(w(:)) - [w(:).start];\n         if numel(w) == 0\n            val = durationDate(nan);\n         elseif singleWave\n            val = durationDate(endvec);\n         else\n            val = cell(size(w));\n            for N = 1 : numel(w)\n               val(N) = {durationDate(endvec(N))};\n            end\n            usedcell = true;\n         end\n      case {'DURATION_EPOCH'} %type:DOUBLE\n         val = (grabEndTime(w) - [w.start]) * 86400;\n         %epoch time is # of seconds.\n         \n      case {'DURATION_MATLAB', 'DURATION'} %type:DOUBLE\n         val = grabEndTime(w) - [w.start];\n         \n      case {'TIMEVECTOR'} %type:CELL\n         val = cell(size(w));\n         for N = 1 : numel(w)\n            Xvalues = linspace(w(N).start,get(w(N),'end'),length(w(N).data)+1);\n            val{N} = Xvalues(1:end-1)';\n         end\n         usedcell = true;\n         \n      case {'MISC_FIELDS'} %type:CELL\n         val = {w.misc_fields};\n         usedcell = true;\n         \n      case {'UNITS'} %type : CELL\n         val = {w.units};\n         usedcell = true;\n         \n      case {'WAVEFORM_OBJECT_VERSION'}\n         val = w(1).version;\n         \n      case {'SCNLOBJECT'} % legacy only\n         % I'm making this whiny for now so it is obvious when things need to\n         % be changed.  This warning should probably be pulled out once we\n         % rerelease this.\n         warning('waveform:get:scnlobjectsAreDepricated',...\n            ['any usage of scnlobject should be replaced by ', ...\n            '''channelinfo'' which uses the new ChannelTag class']);\n         val = scnlobject([w.cha_tag]);\n         %must add network & location, too.\n         \n      case {'CHANNELTAG'}\n         val = [w.cha_tag];\n         \n      case {'CHANNELINFO'}\n         val = string([w.cha_tag]);\n         \n      case {'HISTORY'}\n         val = cell(size(w));\n         for n=1:numel(w)\n            val(n) = {w(n).history};\n         end\n         usedcell = true;\n         \n      otherwise\n         %perhaps we're trying to get at one of the miscelleneous fields?\n         val = cell(size(w));\n         for n = 1 : numel(w)\n            %loc is the position...\n            %w(n).misc_fields should ALWAYS already be in uppercase\n            mask = strcmp(upper(prop_name),w(n).misc_fields);\n            %fieldwasfound = any(mask);\n            %[fieldwasfound, loc] = ismember(prop_name, w(n).misc_fields);\n            if any(mask)\n               \n               val{n} = w(n).misc_values{mask};\n               %val{n} = w(n).misc_values{m};\n            else\n               error('Waveform:get:unrecognizedProperty',...\n                  'Unrecognized property name : %s',  prop_name);\n            end\n         end\n         %check to see if value can be returned as a numeric value instead\n         %of cell.  Only if all values are numeric AND scalar\n         numberize = true;\n         for n=1:numel(val)\n            if ~(isnumeric(val{n}) && isscalar(val{n}))\n               numberize = false;\n               usedcell = true;\n               break\n            end\n         end\n         if numberize,\n            Z = val;\n            val = nan(size(Z));\n            for n=1:numel(Z)\n               val(n) = Z{n};\n            end\n         end\n         \n   end;\n   if (numel(val) == numel(w)) %THIS TEST CONDITIONALIZED 4/16/2008\n      val = reshape(val,size(w)); %return values in proper shape\n   end\n   if usedcell && singleWave\n      if isa(val,'cell')\n         val = val{1}; % return the actual value, not a cell array\n      end\n   end;\nend\n%%%%%%%%%%%%%%%%\nfunction val = grabEndTime(w)\n   if isempty(w)\n      %val = [];\n      val = w.start;\n      return\n   end\n   dlens = get(w,'data_length');\n   dlens = dlens(:);\n   \n   myfrq = [w.Fs];\n   myfrq = myfrq(:);\n   \n   seclen = dlens ./ myfrq;\n   to_add = datenum([zeros(numel(w),5) seclen])';\n   svals = [w(:).start];\n   val = svals +  to_add;\n   \n   %endvec = datevec([w.start]) + [0 0 0 0 0 length(w.data)/w.Fs];\n   %endvec = datevec([w.start]) + [0 0 0 0 0 get(w,'data_length') ./ get(w,'Freq')];\n   %val = datenum(endvec);\n\nend\n%%%%%%%%%%%%%%%%\nfunction val = stringDate(myDate)\n   if isnan(myDate)\n      warning('waveform:get:undefinedDate','Undefined date');\n      val = 0;\n      return\n   end\n   val = datestr(myDate,'yyyy-mm-dd HH:MM:SS.FFF');\nend\n%%%%%%%%%%%%%%%%\nfunction val = durationDate(myDate)\n   \n   if isnan(myDate)\n      %this likely happened because the frequency was undefined (NaN)\n      val = '';\n      return;\n   end\n   \n   myDate = myDate(:);\n   [yr, mo, da] = datevec(myDate);\n   val = '';\n   %if yr, val = [val sprintf('%2d years ',yr)]; end\n   %if mo, val = [val sprintf('%2d months ',mo)]; end\n   if (yr+mo+da)>1,\n      val = [val sprintf('%4d days ',fix(myDate))];\n   end\n   val = [val datestr(myDate,'HH:MM:SS.FFF')];\nend\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/core/@waveform/get.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.22000710997428735, "lm_q1q2_score": 0.11344004750340626}}
{"text": "function events = in_events_oebin(sFile, EventFile)\n% IN_EVENTS_OEBIN: Import events from a Open Ephys flat binary event file (timestamps.npy)\n%\n% USAGE:  events = in_events_oebin(sFile, EventFile)\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\n% Read time stamps\nevtTime = reshape(readNPY(EventFile), 1, []);\nif isempty(evtTime)\n    events = [];\n    return\nend\n\n% Find other files, indicating the type of event\n[evtDir, fName] = bst_fileparts(EventFile);\nTextFile = bst_fullfile(evtDir, 'text.npy');\n% ChanFile = bst_fullfile(evtDir, 'channels.npy');\nChanStateFile = bst_fullfile(evtDir, 'channel_states.npy');\n\n% Get event labels\nif file_exist(TextFile)\n    disp('EOBIN> ERROR: Text events are not supported yet...');\n    evtGroupLabel = {'TEXT'};\n    evtGroupInd = {1:length(evtTime)};\n    evtChan = [];\n    \n%     evtLabels = readNPY(TextFile);\n%     % Create event groups\n%     evtGroupLabel = unique(evtLabels);\n%     evtGroupInd = cell(1, length(evtGroupLabel));\n%     for iUnique = 1:length(evtGroupLabel)\n%         evtGroupInd{iUnique} = find(strcmpi(evtLabels, evtGroupLabel{iUnique}));\n%     end\n%     % Read event channel\n%     if file_exist(ChanFile)\n%         evtChan = readNPY(ChanFile);\n%     else\n%         evtChan = [];\n%     end\nelseif file_exist(ChanStateFile)\n    evtVal = readNPY(ChanStateFile);\n    % Create event groups\n    uniqueVal = unique(evtVal);\n    evtGroupLabel = cell(1, length(uniqueVal));\n    evtGroupInd = cell(1, length(uniqueVal));\n    for iUnique = 1:length(uniqueVal)\n        evtGroupLabel{iUnique} = num2str(uniqueVal(iUnique));\n        evtGroupInd{iUnique} = find(evtVal == uniqueVal(iUnique));\n    end\n    % Do not get read channels\n    evtChan = [];\nelse\n    evtGroupLabel = {'Unknown'};\n    evtGroupInd = {1:length(evtTime)};\n    evtChan = [];\nend\n\n% Initialize list of events\nevents = repmat(db_template('event'), [1, length(evtGroupLabel)]);\n% Get occurrences for each event\nfor iEvt = 1:length(evtGroupLabel)\n    events(iEvt).label      = evtGroupLabel{iEvt};\n    events(iEvt).times      = double(evtTime(evtGroupInd{iEvt})) ./ sFile.prop.sfreq;\n    events(iEvt).epochs     = ones(1, length(events(iEvt).times));  % Epoch: set as 1 for all the occurrences\n    events(iEvt).reactTimes = [];\n    events(iEvt).select     = 1;\n    events(iEvt).notes      = [];\n    events(iEvt).channels   = [];\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_oebin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2068940537061185, "lm_q1q2_score": 0.1123151852637721}}
{"text": "function ni = niftiSet(ni,param,val,varargin)\n% Set data for various nifti data structures\n%   \n%     ni = niftiSet(ni,param,val,varargin)\n%\n% Parameter values\n%\n%  'pixdim'    - Voxel dimensions in millimeters (though settable)\n%  'dim'       - Number of pixels in each dimension (row,col, depth, time/orientation)\n%  'data'      - The data\n%  'voxelsize' - What is this?  Why isn't it pixdim?\n%\n%  'checkqto'\n%\n% Example:\n%  \n%   ni = niftiCreate;\n%   ni = niftiSet(ni,'voxel size',[0.375, 0.375, 2]);\n%\n%\n% EKA/BW Vistasoft Team, 2015\n\n%% Check the parameters\nif notDefined('ni'), error('Nifti data structure variable required'); end\nif notDefined('param'), error('Parameter field required.'); end\nif ~exist('val','var'), error('Val required'); end\n\n%% Squeeze spaces out, force lower case\nparam = mrvParamFormat(param);\n\n%TODO: Add a nifti paramaterMapField\nswitch param\n    case 'checkqto'\n        \n        sz = size(niftiGet(ni,'data'));\n        dim = niftiGet(ni,'dim');\n        \n        if(any(dim(1:3)~=sz(1:3)))\n            warning('[%s] NIFTI volume dim wrong- setting it to the actual data size.\\n',mfilename);\n            dim(1:3) = sz(1:3);\n            ni = niftiSet(ni,'dim',dim);\n        end\n        \n        if(ni.qform_code==0 && ni.sform_code~=0)\n            warning('[%s] ni.qform_code is zero and sform_code ~=0. Setting ni.qto_* from ni.sto_*...\\n',mfilename);\n            %ni = niftiSetQto(ni, ni.sto_xyz);\n            ni = niftiSet(ni,'qto',niftiGet(ni,'sto_xyz'));\n        end\n        \n        dim = niftiGet(ni,'dim');\n        qto_ijk = niftiGet(ni,'qto_ijk');\n        origin = [qto_ijk(1:3,:)*[0 0 0 1]']';\n        if(any(origin<2)||any(origin>dim(1:3)-2))\n            [~,r,s,k] = affineDecompose(niftiGet(ni, 'qto_ijk'));\n            t = ni.dim/2;\n            warning_string = [sprintf('[%s] Qto matrix defines an origin very far away from the isocenter.\\n',mfilename),...\n                              sprintf('This implies that the Qto matrix may be bad - please check qto_ijk. An automatic fix will be attempted.\\n'),...\n                              sprintf('Origin to the image center is at [%2.3f,%2.3f,%2.3f] pix.\\n',t(1),t(2),t(3))];\n            warning(warning_string);\n            %ni = niftiSetQto(ni, inv(affineBuild(t,r,s,k)));\n            ni = niftiSet(ni,'qto',inv(affineBuild(t,r,s,k)));\n            \n        end\n        \n    case 'data'\n        ni.data = val;\n        \n    case 'dim'\n        ni.dim = val;\n        \n    case 'filepath'\n        ni.fname = val;\n        \n    case 'freqdim'\n        ni.freq_dim = val;\n        \n    case 'nifti'\n        ni = val; %This means that we are passing in an entire Nifti!\n        \n    case 'phasedim'\n        ni.phase_dim = val;\n        \n    case 'pixdim'\n        ni.pixdim = val;\n        \n    case 'qfac'\n        ni.qfac= val;\n        \n    case 'qform_code'\n        ni.qform_code = val;\n        \n    case 'qoffset_x'\n        ni.qoffset_x = val;\n        \n    case 'qoffset_y'\n        ni.qoffset_y = val;\n        \n    case 'qoffset_z'\n        ni.qoffset_z = val;\n        \n    case 'qto'\n        xformXyz = val;\n        q = matToQuat(xformXyz);\n        ni = niftiSet(ni,'qform_code',2);\n        ni = niftiSet(ni,'qto_xyz',xformXyz);\n        ni = niftiSet(ni,'qto_ijk',inv(xformXyz));\n        ni = niftiSet(ni,'quatern_b',q.quatern_b);\n        ni = niftiSet(ni,'quatern_c ',q.quatern_c);\n        ni = niftiSet(ni,'quatern_d',q.quatern_d);\n        ni = niftiSet(ni,'qoffset_x',q.quatern_x);\n        ni = niftiSet(ni,'qoffset_y',q.quatern_y);\n        ni = niftiSet(ni,'qoffset_z',q.quatern_z);\n        ni = niftiSet(ni,'qfac',q.qfac);\n        \n        if length(varargin) < 1\n            setStoToo = '';\n        else\n            setStoToo = varargin{1};\n        end\n        \n        if(~isempty(setStoToo)&&setStoToo)\n            ni = niftiSet(ni,'sto_xyz',niftiGet(ni,'qto_xyz'));\n            ni = niftiSet(ni,'sto_ijk',niftiGet(ni,'qto_ijk'));\n        end\n        \n    case 'qto_ijk'\n        ni.qto_ijk = val;\n        \n    case 'qto_xyz'\n        ni.qto_xyz = val;\n        \n    case 'quatern_b'\n        ni.quatern_b = val;\n        \n    case 'quatern_c'\n        ni.quatern_c = val;\n        \n    case 'quatern_d'\n        ni.quatern_d = val;\n        \n    case 'slicedim'\n        ni.slice_dim = val;\n        \n    case 'sto_ijk'\n        ni.sto_ijk = val;\n        \n    case 'sto_xyz'\n        ni.sto_xyz = val;\n        \n    case 'voxelsize'\n        ni.voxelSize = val;\n        \n    otherwise\n        error('Unknown parameter %s\\n',param);\n        \nend %switch\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/Nifti/niftiSet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.21733751090819795, "lm_q1q2_score": 0.10951771283407229}}
{"text": "function events = in_events_array(sFile, EventFile, format, EventName, isInteractive)\n% IN_EVENTS_ARRAY: Read events information from a .mat or text file \n%\n% USAGE:  events = in_events_array(sFile, EventFile, 'times',   EventName=[ask], isInteractive=1)\n%         events = in_events_array(sFile, EventFile, 'samples', EventName=[ask], isInteractive=1)\n%         events = in_events_array(sFile, EventMat, ...)  \n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, Elizabeth Bock, 2012-2023\n\n% Parse inputs\nif (nargin < 5) || isempty(isInteractive)\n    isInteractive = 1;\nend\nif (nargin < 4) || isempty(EventName)\n    EventName = [];\nend\n\n% ===== READ FILE =====\nif ischar(EventFile)\n    % Can read ASCII or .mat\n    EventsMat = load(EventFile);\n    if isstruct(EventsMat)\n        fields = fieldnames(EventsMat);\n        EventsMat = EventsMat.(fields{1});\n        if isstruct(EventsMat)\n            fields = fieldnames(EventsMat);\n            EventsMat = EventsMat.(fields{1});\n        end\n    end\nelse\n    EventsMat = EventFile;\nend\n% Force to be double\nEventsMat = double(EventsMat);\n% Check orientation\nif (size(EventsMat,2) < size(EventsMat,1))\n    EventsMat = EventsMat';\nend\n\n% ===== FORMAT EVENTS =====\n% Create [samples; times] array\nswitch (format)\n    case 'times'\n        evtTimes = round(EventsMat .* sFile.prop.sfreq) ./ sFile.prop.sfreq;\n    case 'samples'\n        evtTimes = round(EventsMat) ./ sFile.prop.sfreq;\nend\n\n% ===== TIME OFFSET =====\nif isInteractive\n    % Check for offset (typical of FIF files)\n    isAddOffset = 0;\n    if (sFile.prop.times(1) ~= 0)\n        res = java_dialog('question', ['The raw data file starts at ' num2str(sFile.prop.times(1)) ' sec.' 10 10 ...\n                                      'Is this offset already added to these events?' 10 10],...\n                                      'Import events', [], {'Yes', 'Add Offset','Cancel'},'Yes');\n        if isempty(res) || strcmpi(res, 'Cancel')\n            bst_progress('stop');\n            return;\n        elseif strcmpi(res, 'Add Offset')\n            isAddOffset = 1;\n        end\n    end\n    % Add a column for time\n    if isAddOffset\n        evtTimes = evtTimes + sFile.prop.times(1);\n    end\nend\n\n% ===== CONVERT TO BRAINSTORM STRUCTURE =====\n% Initialize list of events\nevents = db_template('event');\n% Ask for a label\nif ~isempty(EventName)\n    events.label = EventName;\nelse\n    res = java_dialog('input', 'Please enter a label for this event:', 'Event Label');\n    if isempty(res)\n        events.label = '1';\n    else\n        events.label = res;\n    end\nend\nevents.color      = [];\nevents.reactTimes = [];\nevents.select     = 1;\nevents.times      = evtTimes;\nevents.epochs     = ones(1, length(evtTimes));  % Epoch: set as 1 for all the occurrences\nevents.channels   = [];\nevents.notes      = [];\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/in_events_array.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.1895210844630953, "lm_q1q2_score": 0.10581473745146062}}
{"text": "function plotData(x, y)\n%PLOTDATA Plots the data points x and y into a new figure \n%   PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n%   population and profit.\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the training data into a figure using the \n%               \"figure\" and \"plot\" commands. Set the axes labels using\n%               the \"xlabel\" and \"ylabel\" commands. Assume the \n%               population and revenue data have been passed in\n%               as the x and y arguments of this function.\n%\n% Hint: You can use the 'rx' option with plot to have the markers\n%       appear as red crosses. Furthermore, you can make the\n%       markers larger by using plot(..., 'rx', 'MarkerSize', 10);\n\nfigure; % open a new figure window\n\nplot(x, y, 'rx', 'MarkerSize', 10); % Plot the data\nylabel('Profit in $10,000s'); % Set the y\udbc0\udc00axis label\nxlabel('Population of City in 10,000s'); % Set the x\udbc0\udc00axis label\n\n\n\n\n% ============================================================\n\nend\n", "meta": {"author": "vugsus", "repo": "coursera-machine-learning", "sha": "4c2d45cb729355593509abcd41779d19de5a1970", "save_path": "github-repos/MATLAB/vugsus-coursera-machine-learning", "path": "github-repos/MATLAB/vugsus-coursera-machine-learning/coursera-machine-learning-4c2d45cb729355593509abcd41779d19de5a1970/mlclass-ex1/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.10272190532701399}}
{"text": "function plotData(x, y)\n%PLOTDATA Plots the data points x and y into a new figure \n%   PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n%   population and profit.\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the training data into a figure using the \n%               \"figure\" and \"plot\" commands. Set the axes labels using\n%               the \"xlabel\" and \"ylabel\" commands. Assume the \n%               population and revenue data have been passed in\n%               as the x and y arguments of this function.\n%\n% Hint: You can use the 'rx' option with plot to have the markers\n%       appear as red crosses. Furthermore, you can make the\n%       markers larger by using plot(..., 'rx', 'MarkerSize', 10);\n\nfigure; % open a new figure window\nplot(x, y, 'rx','MarkerSize', 10);\nylabel('Profit in $10,000s');\nxlabel('Population of City in 10,000s');\n\n\n% ============================================================\n\nend\n", "meta": {"author": "anirudhjayaraman", "repo": "Machine-Learning", "sha": "084e9c67ac3853f78461f9d0e46c7b41364da481", "save_path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning", "path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning/Machine-Learning-084e9c67ac3853f78461f9d0e46c7b41364da481/Andrew Ng Stanford Coursera/Week 02/ex1/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.2538610182592984, "lm_q1q2_score": 0.10054626437104303}}
{"text": "function plotData(x, y)\n%PLOTDATA Plots the data points x and y into a new figure \n%   PLOTDATA(x,y) plots the data points and gives the figure axes labels of\n%   population and profit.\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Plot the training data into a figure using the \n%               \"figure\" and \"plot\" commands. Set the axes labels using\n%               the \"xlabel\" and \"ylabel\" commands. Assume the \n%               population and revenue data have been passed in\n%               as the x and y arguments of this function.\n%\n% Hint: You can use the 'rx' option with plot to have the markers\n%       appear as red crosses. Furthermore, you can make the\n%       markers larger by using plot(..., 'rx', 'MarkerSize', 10);\n\nfigure; % open a new figure window\n\n\nplot(x,y,'rx','MarkerSize',10);%rx means color is red and show symbol is x,and x's size is 10\nylabel=('Profit in $10,000s');\nxlabel=('Population of City in 10,000s');\n\n\n\n% ============================================================\n\nend\n", "meta": {"author": "lawlite19", "repo": "MachineLearningEx", "sha": "44be60fe4d639d18af5ea5011f069eed348e97b8", "save_path": "github-repos/MATLAB/lawlite19-MachineLearningEx", "path": "github-repos/MATLAB/lawlite19-MachineLearningEx/MachineLearningEx-44be60fe4d639d18af5ea5011f069eed348e97b8/machine-learning-ex1/ex1/plotData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.23091976822203988, "lm_q1q2_score": 0.10021489926517761}}
