{"text": "function c8vec_print_some ( n, x, max_print, title )\n\n%*****************************************************************************80\n%\n%% C8VEC_PRINT_SOME prints some of a C8VEC.\n%\n% Discussion:\n%\n% The user specifies MAX_PRINT, the maximum number of lines to print.\n%\n% If N, the size of the vector, is no more than MAX_PRINT, then\n% the entire vector is printed, one entry per line.\n%\n% Otherwise, if possible, the first MAX_PRINT-2 entries are printed,\n% followed by a line of periods suggesting an omission,\n% and the last entry.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 September 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries of the vector.\n%\n% Input, complex X(N), the vector to be printed.\n%\n% Input, integer MAX_PRINT, the maximum number of lines to print.\n%\n% Input, string TITLE, a title.\n%\n if ( max_print <= 0 )\n return\n end\n\n if ( n <= 0 )\n return\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n fprintf ( 1, '\\n' );\n\n if ( n <= max_print )\n\n for i = 1 : n\n fprintf ( 1, ' %6d: %s\\n', i, num2str ( x(i) ) );\n end\n\n elseif ( 3 <= max_print )\n\n for i = 1 : max_print-2\n fprintf ( 1, ' %6d: %s\\n', i, num2str ( x(i) ) );\n end\n fprintf ( 1, ' ...... ..............\\n' );\n i = n;\n fprintf ( 1, ' %6d: %s\\n', i, num2str ( x(i) ) );\n\n else\n\n for i = 1 : max_print - 1;\n fprintf ( 1, ' %6d: %s\\n', i, num2str ( x(i) ) );\n end\n i = max_print;\n fprintf ( 1, ' %6d: %s ...more entries...\\n', i, num2str ( x(i) ) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cyclic_reduction/c8vec_print_some.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.09947021254732229, "lm_q1q2_score": 0.04934655866088742}} {"text": "function sequence_streak_display ( file_name, direction )\n\n%*****************************************************************************80\n%\n%% SEQUENCE_STREAK_DISPLAY makes a \"streak plot\" of a sequence.\n%\n% Discussion:\n%\n% The sequence information is assumed to be available in\n% a text file, with one sequence entry per line.\n%\n% One reason for making plots this way is to try to\n% see the \"fill in\" pattern of a sequence. For instance,\n% the van der Corput sequence has the property that all\n% entries lie in [0,1], and that it first eliminates all\n% gaps of size 1/2, then of size 1/4, then 1/8 and so on.\n%\n% Perhaps a second reason for looking at plots this way\n% is to notice patterns of convergence in a sequence.\n%\n% Example:\n%\n% The sequence 1, 3, 5, 7, 6, 2, 4 would plot as\n%\n% *---\n% *--\n% *----\n% *\n% *-----\n% *-\n% *------\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string FILE_NAME, the name of a text file containing\n% the sequence.\n%\n% Input, character DIRECTION, defines the direction of the sequence.\n% 'R', goes to the right;\n% 'L', goes to the left;\n% 'U', goes up;\n% 'D', goes down.\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SEQUENCE_STREAK_DISPLAY\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n\n y = load ( file_name );\n\n n = length ( y );\n x(1:n) = 1:n;\n\n if ( direction == 'R' | direction == 'r' )\n\n plot ( x, y, '*' );\n\n for i = 1 : n\n line ( [x(i), n], [y(i), y(i) ] )\n end\n\n xlabel ( 'Sequence Direction--->', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16 )\n\n ylabel ( 'Sequence Value', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16, 'Rotation', 90 );\n\n title ( 'Sequence \"Streak\" Plot', ...\n 'FontName', 'Helvetica', 'FontWeight', ...\n 'bold', 'FontSize', 16 );\n\n elseif ( direction == 'L' | direction == 'l' )\n\n plot ( x, y, '*' );\n\n for i = 1 : n\n line ( [1, x(i)], [y(i), y(i) ] )\n end\n\n xlabel ( 'Sequence Direction--->', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16 )\n\n ylabel ( 'Sequence Value', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16, 'Rotation', 90 );\n\n title ( 'Sequence \"Streak\" Plot', ...\n 'FontName', 'Helvetica', 'FontWeight', ...\n 'bold', 'FontSize', 16 );\n\n\n elseif ( direction == 'U' | direction == 'u' )\n\n plot ( y, x, '*' );\n\n for i = 1 : n\n line ( [y(i), y(i) ], [x(i), n] )\n end\n\n xlabel ( 'Sequence Value', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16 )\n\n ylabel ( 'Sequence Direction--->', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16, 'Rotation', 90 );\n\n title ( 'Sequence \"Streak\" Plot', ...\n 'FontName', 'Helvetica', 'FontWeight', ...\n 'bold', 'FontSize', 16 );\n\n elseif ( direction == 'D' | direction == 'd' )\n\n plot ( y, x, '*' );\n\n for i = 1 : n\n line ( [y(i), y(i) ], [1, x(i)] )\n end\n\n xlabel ( 'Sequence Value', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16 )\n\n ylabel ( 'Sequence Direction--->', ...\n 'FontName', 'Helvetica', 'FontWeight', 'bold', ...\n 'FontSize', 16, 'Rotation', 90 );\n\n title ( 'Sequence Streak Plot', ...\n 'FontName', 'Helvetica', 'FontWeight', ...\n 'bold', 'FontSize', 16 );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SEQUENCE_STREAK_DISPLAY\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1,'\\n' );\n timestamp ( );\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sequence_streak_display/sequence_streak_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.10818894449799439, "lm_q1q2_score": 0.04529837668776417}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% out.m 1993-12-28 % FORMATED OUTPUT OF MATRICES \n%% (c) M. Balda % updated on 2005-12-18\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% updated on 2006-02-10\n%\n% The function out.m outputs its first argument to screen or a file in a\n% default or required format. The argument can be either empty or a string,\n% integer, real or complex numbers or matrices. The format can be either\n% user defined or from a previous call of the function, or a default one.\n%\n% Prerequisity:\n% ~~~~~~~~~~~~~\n% function inp.m from http://www.mathworks.com/matlabcentral/\n%\n% Forms of calls:\n% ~~~~~~~~~~~~~~\n%\n% out; % Clear the format and close output file if any\n%\n% out(arg); % Display arg in formats '%s or '%e' or '%d' \n% % or any other used in the last call of out.m\n% arg = an argument \n%\n% out(arg,form); % Display arg in the format form\n% form = required format of the output (see help to fprintf).\n% A format for complex numbers is generated internally using\n% format for real numbers,\n% fid = file identifier - handle of the output file\n%\n% out(arg,fid); % Append arg to the open file of fid handle\n%\n% fid = out(arg,form,fname); % Open file, get handle fid, and write arg \n% fname = name of output file\n% fid = handle of the file if successfully opened,\n% -1 if not opened,\n% 0 if closed.\n%\n% out(arg,form,fid); % Append arg to fid file\n%\n% Examples:\n% ~~~~~~~~\n% out(rand(2,3)); % display matrix in the '%15.6e' format\n% Z = rand(3,2)+i*rand(3,2); % create complex matrix Z\n% h = out(Z,'','cmplxZ.dat'); % write Z in '%15.6e' format to the file\n% out('','%s\\n',h); % append new line into the file\n% out(Z,'%8.4f',h); % append Z once more in '%8.4f' format\n% out; % close the file 'cmplxZ.dat'\n% lf = char(10); % new line character\n% out(['This is a string' lf]);% display a string ending with new line\n% out(1:5,'%4i\\n'); % display a column of integers\n% out(char('='*ones(1,50)),'%s\\n');% display a line of 50 characters '='\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction fid = out(arg,form,fname)\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\npersistent fid_ frm_ \n\nif nargin<1 % Close file & return\n fid = 0;\n if ~isempty(fid_) && fid_~=1\n fid = fclose(fid_); \n end\n frm_ = [];\n return\nend\n\n% % Format test & reconstruction\nS = isempty(findstr('s',frm_));\nif (ischar(arg) && S) || (isnumeric(arg) && ~S)\n frm_ = []; \nend\n\n% % OUTPUT DESTINATION\nfid_ = 1; % screen\nif nargin>2 % write in a file?\n if ischar(fname) % file name\n if exist(fname,'file')\n if strcmp(inp(['Overwrite ' fname '?'],'no'),'no')\n fid=-1; \n return % without overwriting\n end\n end\n fid_ = fopen(fname, 'w+');% open file\n fid = fid_;\n if fid_<0, return, end\n else\n if isreal(fname) % file identifier\n fid_ = fname;\n end\n end\nend\n\n% % OUTPUT FORMAT\nif nargin>1\n if isempty(form)\n frm_ = [];\n elseif ischar(form) % format\n if isnumeric(arg) % for numeric arg\n if isempty(findstr(form,'-') + findstr(form,'+'))\n frmR_ = ['% ' form(2:end)]; % real\n frmI_ = ['%+' form(2:end)]; % imag\n else\n frmR_ = ['% ' form(3:end)]; % real\n frmI_ = ['%+' form(3:end)]; % imag\n end\n if ~isreal(arg)\n frm_ = [frmR_ frmI_ 'i ']; % complex\n else\n frm_ = frmR_;\n end\n else\n frm_ = form; % for string arg\n end\n else\n fid_ = form; % file identifier\n end\nend\n\nif isempty(frm_)\n if ischar(arg), frm_ = '%s '; \n elseif isinteger(arg), frm_ = '% d ';\n elseif isreal(arg), frm_ = '% e ';\n else frm_ = '% e %+ei ';\n end\nend\n% disp({arg, frm_, fid_})\n\n\n% % OUTPUT arg\nif ischar(arg)\n fprintf(fid_,frm_,arg); % text argument\nelse\n [m,n] = size(arg);\n if isreal(arg) % integer or real arg\n for k = 1:m\n for j = 1:n\n fprintf(fid_, frm_, arg(k,j));\n end\n fprintf(fid_,'\\n');\n end\n else % complex arg\n for k = 1:m\n Rc = real(arg(k,:));\n Ic = imag(arg(k,:));\n for j = 1:n\n fprintf(fid_, frm_, Rc(j), Ic(j));\n end\n fprintf(fid_,'\\n');\n end\n end\nend\nfid = fid_;\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/9954-simple-formatted-ascii-output/out.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.0888202960180265, "lm_q1q2_score": 0.04232994568364348}} {"text": "%EASY4 The ephemeris file is reformated by rinexe. The observation type\n% is selected and the observation files for master and rover are opened.\n% The preliminary (X,Y,Z) position of the master receiver is read from\n% the header.\n% The reading position in the file is moved to the first epoch and\n% sow is computed. sow in master and rover files are synchronized.\n% We test if all SVs have an ephemris and SVs and their\n% observations are sorted to match. Next we call the function\n% baseline which computes the components of the baseline.\n% Some results are printed in workspace and some figures are plotted.\n\n% The code could be shortened by introducing functions. However, for a\n% teaching situation I found it more illustrative to compile a script.\n\n%RINEX version 3.03\n\n%Kai Borre 27-07-2002\n%Copyright (c) by Kai Borre\n%$Revision: 1.0 $ $Date: 2002/07/27 $\n% Total revison 2.0, January 13, 2016\n\n% Read RINEX ephemerides file and convert to internal Matlab format\nrinexe('log_24h.15n','eph.dat');\nEph = get_eph('eph.dat');\n\n% Selection of observation type\nss = 'C1W'%;\n\n% Open the master observation file\nofile1 = 'log_24h.15o';\nfid1 = fopen(ofile1,'rt');\n\n% Open the rover observation file\nofile2 = 'log_r.15o'; % log_24h.15o\nfid2 = fopen(ofile2,'rt');\n\ncoo = [];\nant_delta = [];\nlinjer = 0;\n\n% Gobbling the master header, and collecting useful information\nwhile 1\n linjer = linjer +1;\n line = fgetl(fid1);\n answer = strfind(line,'END OF HEADER');\n if ~isempty(answer), break; end;\n if (line == -1), eof = 1; break; end;\n \n answer = strfind(line,'REC #');\n if ~isempty(answer)\n var = textscan(fid1,'%s %d14','Delimiter','\\n');\n var1 = var{1}{1};\n cox = str2double(var1(1:14));\n coy = str2double(var1(15:28));\n coz = str2double(var1(29:42));\n end\n \n answer = strfind(line,'ANT #');\n if ~isempty(answer)\n var = textscan(fid1,'%s %d14','Delimiter','\\n');\n var1 = var{1}{1};\n ax = str2double(var1(1:14));\n ay = str2double(var1(15:28));\n az = str2double(var1(29:42));\n end\n \n answer = strfind(line,'SYS / # / OBS TYPES');\n if ~isempty(answer)\n tline1 = strsplit(line);\n line = fgetl(fid1);\n tline2 = strsplit(line);\n tt1 = horzcat(tline1,tline2);\n i = strcmp(tt1,ss); % if tt equals ss, i =1, else 0\n ii = find(i == 1) ;\n ii = ii-2;\n if ii > 15, ii = ii-7, end;\n % the cell array of strings tline1 originally contains two strings\n % which describe the system and number of observation types.\n % Both tline1 and tline2 terminates with six additional strings.\n % An extra string appears at the start of tline2; it originates\n % from concatenation of the two lines. The indexing does not\n % change even if you empty the cells. They remain as empty\n % cells and keep a place\n obs_col = ii%;\n end;\n answer = strfind(line,'INTERVAL');\n if ~isempty(answer)\n interval = strtok(line);\n int = str2double(interval);\n end;\nend % end reading header\n\n% the string arrays for the tline1 and tline2 contain an integer after the\n% carrier phase observation. We must account for this by the following\n% correctional table\nif strcmp(ss(2:3), '1C'), obs_col = obs_col +1;\nelseif strcmp(ss(2:3), '1W'), obs_col = obs_col+2;\nelseif strcmp(ss(2:3), '2X'), obs_col = obs_col +3;\nelse strcmp(ss(2:3), '2W'), obs_col = obs_col +4;\nend\n\nPos = [];\ndt1 = [];\ndt2 = [];\nGdop = [];\nOmc = [];\nbases = [];\nepoch = 0;\n\nwhile 1\n epoch = epoch +1;\n time1 = 0;\n sats1 = [];\n time2 = 0;\n sats2 = [];\n \n % Reading first observation record in master file.\n \n % We read the first line in every epoch in the master file.\n % Output is sow nd number of SVs: NoSvs1.\n [time,~] = textscan(fid1,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n % static = str2double(tid(31:32));\n NoSvs1 = str2double(tid(34:36));\n dt1 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time1 = sec_of_week; % sow1\n \n Obs1 = zeros(NoSvs1,length(obs_col));\n % Reading NoSvs1 lines of observations in the master file\n for i = 1:NoSvs1\n [obs1,~] = textscan(fid1,'%s %d8','Delimiter','\\n');\n obs1x = obs1{1}{1} ;\n obs1y = strsplit(obs1x);\n sat1 = obs1y{1} ;\n sats1(i) = str2double(sat1(2:3));\n Obs1(i,:) = str2double(obs1y(obs_col));\n end\n \n % Next we test if all observed SVs have an ephemeris.\n % sats1 contains the SVs as read in the observation lines.\n % The intersect command delivers Sats in sorted order!\n % Therefore we must be careful in the follwing manipulations\n Sats = intersect(sats1,Eph(1,:));\n \n %The command ismember does not change the sequence of entries in sats1\n lia = ismember(sats1,Sats);\n % A 0 (zero) in lia indicates that a SV has been deleted. We delete the\n % corresponding row in the observations\n sats1(lia==0) = [];\n Obs1(lia==0) = [];\n NoSV1 = length(sats1);\n \n % dimensions\n % time1 % 1 x 1\n % NoSV1 % 1 x 1\n % sats1 % NoSV1 x 1\n % Obs1 % NoSV1 x 1\n \n % the whole story repated for the rover with index 2\n % we start by gobbeling the header\n if epoch == 1\n for qq = 1:linjer+ 3\n fgetl(fid2);\n end\n end\n \n % We read the header line for the first epoch in the rover file.\n % It gives us sow and number of SVs.\n [time,~] = textscan(fid2,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n % static = str2double(tid(31:32));\n NoSvs2 = str2double(tid(34:36));\n dt2 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time2 = sec_of_week; % sow2\n \n % Reading the observations in the first epch in the rover file\n Obs2 = zeros(NoSvs2,length(obs_col));\n for i = 1:NoSvs2\n [obs2,~] = textscan(fid2,'%s %d8','Delimiter','\\n');\n obs2y = obs2{1}{1};\n obs2 = strsplit(obs2y);\n sat2 = obs2{1};\n sats2(i,:) = str2double(sat2(2:3));\n Obs2(i,:) = str2double(obs2(obs_col));\n end\n \n % Next we test if all observed sats have an ephemeris.\n % sats contains the SVs as read in the observation lines\n % The intersect command delivers Sats in sorted order!\n % Therefore we must be careful in the follwing manipulations\n Sats = intersect(sats2,Eph(1,:));\n \n % The command ismember does not change the sequence of entries in sats\n lia = ismember(sats2,Sats);\n % A 0 (zero) in lia indicates that a SV has been deleted. We delete the\n % corresponding row in the observations\n sats2(lia==0) = [];\n Obs2(lia==0) = [];\n NoSV2 = length(sats2);\n \n % dimensions\n % time2 % 1 x 1\n % NoSV2 % 1 x 1\n % sats2 % NoSV2 x 1\n % Obs2 % NoSV2 x 1\n \n if epoch == 1\n % Establish synchronous reading of fid1 and fid2\n % The epoch interval is int seconds \n if time1 > time2\n for i = 1: round(time1-time2)\n [time,~] = textscan(fid2,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n %static = str2double(tid(31:32));\n NoSvs2 = str2double(tid(34:36));\n dt2 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time2 = sec_of_week; % sow2\n \n for qq = 1:NoSvs2\n fgetl(fid2);\n end\n end % i\n end % if time1 ...\n \n if time1 < time2\n for i = 1: round(time2-time1) \n [time, ~] = textscan(fid1,'%s %d8','Delimiter','\\n');\n tid = time{1}{1};\n year = str2double(tid(3:6));\n month = str2double(tid(8:9));\n day = str2double(tid(11:12));\n hour = str2double(tid(14:15));\n minute = str2double(tid(17:18));\n second = str2double(tid(20:29));\n static = str2double(tid(31:32));\n NoSvs1 = str2double(tid(34:36));\n dt1 = str2double(tid(38:56));\n h = hour+minute/60+second/3600;\n jd = julday(year, month, day, h);\n [~, sec_of_week] = gps_time(jd);\n time1 = sec_of_week; % sow1\n \n for qq = 1:NoSvs1\n fgetl(fid1);\n end\n end % i\n end % if time1\n fprintf('First Common Epoch Time1 : %8.0f\\n', time1)\n fprintf('First Common Epoch Time2 : %8.0f\\n', time2)\n end % synchronization\n \n % By chance sats1 and sats 2 are the same. Otherwise we need to establish\n % a matching between sats1 and sats2 and likewise for Obs1 and Obs2\n \n % master observations: obs1, and rover observations: obs2\n [omc,base] = baseline([cox;coy;coz],Obs1,Obs2,sats1,time1,Eph);\n Omc = [Omc, omc];\n bases = [bases base];\n \n [pos, el, gdop] = recpo_ls(Obs1,sats1,time1,Eph);\n Gdop = [Gdop gdop];\n Pos = [Pos pos];\n if feof(fid1) == 1, break, end;\n if feof(fid2) == 1, break; end;\nend % while\nfclose all;\n\nme1 = mean(bases,2);\nspread1 = std(bases,1,2);\nfprintf('\\nBaseline Components as Computed From %2.0f Epochs:', epoch)\nfprintf('\\n\\nX: %12.3f Y: %12.3f Z: %12.3f\\n\\n', me1(1,1),me1(2,1),me1(3,1))\n\nfigure(1);\nplot((bases(:,2:end)-bases(:,2)*ones(1,epoch-1))','linewidth',.25)\ntitle(['Variation of Baseline Components Over ',int2str(epoch),' Epochs'],'fontsize',14)\nlegend('X','Y','Z')\nxlabel(['Epochs ', int2str(int), ' s interval'], 'fontsize',14)\nylabel('[m]','fontsize',14)\nset(gca,'fontsize',14)\nlegend\nprint -dpdf easy41\n\nfigure(2);\nplot(Omc(:,2:end)')\nxlabel('Epochs')\nylabel('[m]','fontsize',14)\ntitle({'Observed minus Computed Values'; 'for All SVs in Each Epoch'},'fontsize',14)\nset(gca,'fontsize',14)\nprint -dpdf easy42\n\nfigure(3);\nplot(Gdop,'linewidth',1)\naxis([1 length(Gdop) 0 5])\ntitle('GDOP')\nprint -dpdf easy43\n\n%%%%%%%%%%%%%% end easy4.m %%%%%%%%%%%%%%%\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/easy4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07921033226026337, "lm_q1q2_score": 0.039295757064657974}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: binopdf_01ok.m\n% The regular binopdf returns NaN whenever x=0 and p=0 or whenever \n% x=n and p=1. The correct value for binopdf to return in both cases is 1.0.\n% This corrects that bug.\n% This also avoids calling binopdf when it would give an inappropriate warning\n% about taking the log of zero.\n% This could more easily be fixed within binopdf.m, but that for MathWorks\n%\n% 022400 tdr created\n% 033100 tdr added check for binopdf returning NaN or Inf, which it may for n > 1000, e.g., x=500, n=1030, p=0.1\n\nfunction y = binopdf_01ok(x,n,p)\n\nif nargin < 3, \n error('Requires three input arguments (x,n,p)');\nend\n\n[errorcode x n_bar p] = distchck(3,x,n,p);\n\nif errorcode > 0\n error('Requires non-scalar arguments to match in size.');\nend\n\ny = zeros(size(x));\n\nk = find(~((p == 0) | (p == 1)));\nif any(k),\n y(k) = binopdf(x(k),n,p(k));\n if ~isfinite(y),\n error('NaN or Inf value returned from binopdf.m')\n end;\nend\n\nk = find((x ~= 0 & p == 0) | (x ~= n & p == 1));\nif any(k),\n y(k) = 0;\nend\n\nk = find((x == 0 & p == 0) | (x == n & p == 1));\nif any(k),\n y(k) = 1;\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3031-accurate-confidence-intervals/ci_tool/binopdf_01ok.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.07696084363512665, "lm_q1q2_score": 0.037278299926010464}} {"text": "function hydro = combineBEM(hydro)\n% Combines multiple BEM outputs into one hydrodynamic ‘system.’ This function\n% requires that all BEM outputs have the same water depth, wave frequencies,\n% and wave headings. This function would be implemented following multiple\n% readWAMIT, readNEMOH, readCAPYTAINE, or readAQWA and before radiationIRF,\n% radiationIRFSS, excitationIRF, writeBEMIOH5, or plotBEMIO function calls.\n%\n% See ``WEC-Sim\\examples\\BEMIO\\NEMOH`` for examples of usage.\n% \n% Parameters\n% ----------\n% hydro : [1 x n] struct\n% Structures of hydro data that will be combined into a single\n% structure\n%\n% Returns\n% -------\n% hydro : [1 x 1] struct\n% Combined structure. \n\np = waitbar(0,'Combining multiple BEM results...'); % Progress bar\n\n[m,n] = size(hydro);\ntol = 1e-2;\nif n>1\n for i = 2:n\n if max(abs(hydro(i).h-hydro(i-1).h)) > tol\n error('Error: Inconsistent water depth');\n elseif (size(hydro(i).theta) ~= size(hydro(i-1).theta)) | ...\n (max(abs(sort(hydro(i).theta)-sort(hydro(i-1).theta))) > tol)\n error('Error: Inconsistent wave headings');\n elseif (size(hydro(i).T) ~= size(hydro(i-1).T)) | ...\n (max(abs(sort(hydro(i).T)-sort(hydro(i-1).T))) > tol)\n error('Error: Inconsistent wave frequencies');\n end\n end\n \n n = n+1;\n hydro(n).theta = hydro(1).theta;\n hydro(n).body = [];\n hydro(n).Khs = [];\n hydro(n).cb = [];\n hydro(n).cg = [];\n hydro(n).code = [];\n hydro(n).dof = [];\n hydro(n).ex_im = [];\n hydro(n).ex_ma = [];\n hydro(n).ex_ph = [];\n hydro(n).ex_re = [];\n hydro(n).fk_im = [];\n hydro(n).fk_ma = [];\n hydro(n).fk_ph = [];\n hydro(n).fk_re = [];\n hydro(n).sc_im = [];\n hydro(n).sc_ma = [];\n hydro(n).sc_ph = [];\n hydro(n).sc_re = [];\n hydro(n).file = [];\n hydro(n).g = 9.807;\n hydro(n).h = hydro(1).h;\n hydro(n).Nb = 0;\n hydro(n).Nf = hydro(1).Nf;\n hydro(n).Nh = hydro(1).Nh;\n hydro(n).rho = 1000;\n hydro(n).T = hydro(1).T;\n hydro(n).Vo = [];\n hydro(n).w = hydro(1).w;\n for i = 1:(n-1)\n hydro(n).body = [hydro(n).body, hydro(i).body];\n hydro(n).Khs = cat(3, hydro(n).Khs, hydro(i).Khs);\n hydro(n).cb = [hydro(n).cb, hydro(i).cb];\n hydro(n).cg = [hydro(n).cg, hydro(i).cg];\n hydro(n).code = [hydro(n).code, hydro(i).code];\n hydro(n).dof = [hydro(n).dof, hydro(i).dof];\n hydro(n).ex_im = cat(1, hydro(n).ex_im, hydro(i).ex_im);\n hydro(n).ex_ma = cat(1, hydro(n).ex_ma, hydro(i).ex_ma);\n hydro(n).ex_ph = cat(1, hydro(n).ex_ph, hydro(i).ex_ph);\n hydro(n).ex_re = cat(1, hydro(n).ex_re, hydro(i).ex_re);\n hydro(n).fk_im = cat(1, hydro(n).fk_im, hydro(i).fk_im);\n hydro(n).fk_ma = cat(1, hydro(n).fk_ma, hydro(i).fk_ma);\n hydro(n).fk_ph = cat(1, hydro(n).fk_ph, hydro(i).fk_ph);\n hydro(n).fk_re = cat(1, hydro(n).fk_re, hydro(i).fk_re);\n hydro(n).sc_im = cat(1, hydro(n).sc_im, hydro(i).sc_im);\n hydro(n).sc_ma = cat(1, hydro(n).sc_ma, hydro(i).sc_ma);\n hydro(n).sc_ph = cat(1, hydro(n).sc_ph, hydro(i).sc_ph);\n hydro(n).sc_re = cat(1, hydro(n).sc_re, hydro(i).sc_re);\n hydro(n).file = [hydro(n).file, hydro(i).file];\n hydro(n).Nb = hydro(n).Nb + hydro(i).Nb;\n hydro(n).Vo = [hydro(n).Vo, hydro(i).Vo];\n end\n hydro(n).Ainf = zeros(sum(hydro(n).dof),sum(hydro(n).dof));\n hydro(n).A = zeros(sum(hydro(n).dof),sum(hydro(n).dof),hydro(n).Nf);\n hydro(n).B = zeros(sum(hydro(n).dof),sum(hydro(n).dof),hydro(n).Nf);\n if isfield(hydro,'gbm')==1\n hydro(n).gbm = zeros(sum(hydro(n).dof),sum(hydro(n).dof),4);\n end\n k = 0;\n for i = 1:(n-1)\n j = sum(hydro(i).dof);\n hydro(n).Ainf((k+1):(k+j),(k+1):(k+j)) = hydro(i).Ainf;\n hydro(n).A((k+1):(k+j),(k+1):(k+j),:) = hydro(i).A;\n hydro(n).B((k+1):(k+j),(k+1):(k+j),:) = hydro(i).B;\n if isfield(hydro,'gbm')==1\n hydro(n).gbm((k+1):(k+j),(k+1):(k+j),:) = hydro(i).gbm;\n end\n k = k + j;\n end\n \n hydro(1) = hydro(n);\n hydro(2:n) = [];\n \nend\nclose(p);\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/BEMIO/combineBEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07055960302791833, "lm_q1q2_score": 0.035279801513959166}} {"text": "function varargout = newton_Raphson_GUI(varargin)\n% NEWTON_RAPHSON_GUI M-file for newton_Raphson_GUI.fig\n% NEWTON_RAPHSON_GUI, by itself, creates a new NEWTON_RAPHSON_GUI or raises the existing\n% singleton*.\n%\n% H = NEWTON_RAPHSON_GUI returns the handle to a new NEWTON_RAPHSON_GUI or the handle to\n% the existing singleton*.\n%\n% NEWTON_RAPHSON_GUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in NEWTON_RAPHSON_GUI.M with the given input arguments.\n%\n% NEWTON_RAPHSON_GUI('Property','Value',...) creates a new NEWTON_RAPHSON_GUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before newton_Raphson_GUI_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to newton_Raphson_GUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help newton_Raphson_GUI\n\n% Last Modified by GUIDE v2.5 09-Sep-2013 22:52:08\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @newton_Raphson_GUI_OpeningFcn, ...\n 'gui_OutputFcn', @newton_Raphson_GUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin & isstr(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before newton_Raphson_GUI is made visible.\nfunction newton_Raphson_GUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to newton_Raphson_GUI (see VARARGIN)\n\n% Choose default command line output for newton_Raphson_GUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes newton_Raphson_GUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = newton_Raphson_GUI_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes during object creation, after setting all properties.\nfunction f_CreateFcn(hObject, eventdata, handles)\n% hObject handle to f (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction f_Callback(hObject, eventdata, handles)\n% hObject handle to f (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of f as text\n% str2double(get(hObject,'String')) returns contents of f as a double\n\n\n% --- Executes on button press in plot.\nfunction plot_Callback(hObject, eventdata, handles)\nsyms x;\nfun=(x.^2)-1;\nezplot(fun);\n% hObject handle to plot (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction x0_CreateFcn(hObject, eventdata, handles)\n% hObject handle to x0 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction x0_Callback(hObject, eventdata, handles)\n% hObject handle to x0 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of x0 as text\n% str2double(get(hObject,'String')) returns contents of x0 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit5_Callback(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit5 as text\n% str2double(get(hObject,'String')) returns contents of edit5 as a double\n\n\n% --- Executes on button press in solve.\nfunction solve_Callback(hObject, eventdata, handles)\n\nxi=str2num(get(handles.x0,'string'));\n\nfor i=1:20\n \nxn=xi-(polyval([1 0 -1],[xi])/polyval(polyder([1 0 -1]),[xi]));\ndisp(xn);\nset(handles.r,'string',xn);\nxi=xn;\ni=i+1;\n\nend\n% hObject handle to solve (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n", "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/43471-newton-raphson-method-gui/Newton-rapsh0n/newton_Raphson_GUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.0705595893466682, "lm_q1q2_score": 0.03500417688488413}} {"text": "function [bcx,bcy] = specific_flow(xbd,ybd)\n%leakycavity_flow Reference problem 5.3 inflow condition \n% [bcx,bcy] = specific_flow(xbd,ybd);\n% input\n% xbd x coordinate vector\n% ybd y coordinate vector \n%\n% specifies leaky cavity flow boundary condition\n% IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbcx=0*xbd; bcy=0*xbd;\nk=find(ybd==1); bcx(k)=1;\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/test_problems/leakycavity_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.076960839930213, "lm_q1q2_score": 0.03488341253158466}} {"text": "function dy = scopy ( n, dx, incx, dy, incy )\n\n%*****************************************************************************80\n%\n%% SCOPY copies a vector X to a vector Y.\n%\n% Discussion:\n%\n% The routine uses unrolled loops for increments equal to one.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch and Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, 1979.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% Algorithm 539,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 3, September 1979, pages 308-323.\n%\n% Parameters:\n%\n% Input, integer N, the number of elements in DX and DY.\n%\n% Input, real DX(*), the first vector.\n%\n% Input, integer INCX, the increment between successive entries of DX.\n%\n% Input, real DY(*), the second vector, into which elements are copied.\n%\n% Input, integer INCY, the increment between successive entries of DY.\n%\n% Output, real DY(*), the second vector, with elements copied from DX.\n%\n if ( n <= 0 )\n dy = [];\n return\n end\n\n if ( incx == 1 & incy == 1 )\n\n m = mod ( n, 7 );\n\n if ( m ~= 0 )\n\n dy(1:m) = dx(1:m);\n\n end\n\n for i = m+1 : 7 : n\n dy(i) = dx(i);\n dy(i + 1) = dx(i + 1);\n dy(i + 2) = dx(i + 2);\n dy(i + 3) = dx(i + 3);\n dy(i + 4) = dx(i + 4);\n dy(i + 5) = dx(i + 5);\n dy(i + 6) = dx(i + 6);\n end\n\n else\n\n if ( 0 <= incx )\n ix = 1;\n else\n ix = ( -n + 1 ) * incx + 1;\n end\n\n if ( 0 <= incy )\n iy = 1;\n else\n iy = ( -n + 1 ) * incy + 1;\n end\n\n for i = 1 : n\n dy(iy) = dx(ix);\n ix = ix + incx;\n iy = iy + incy;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/blas1_s/scopy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.437823499114202, "lm_q2_score": 0.07477004136167943, "lm_q1q2_score": 0.0327360811378841}} {"text": "function x = rosser1_null_right ( )\n\n%*****************************************************************************80\n%\n%% ROSSER1_NULL_RIGHT returns a right null vector of the ROSSER1 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real X(8,1), the null vector.\n%\n x = [ ...\n 1.0; ...\n 2.0; ...\n -2.0; ...\n -1.0; ...\n 14.0; ...\n 14.0; ...\n 7.0; ...\n 7.0 ];\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/rosser1_null_right.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.07055959960760556, "lm_q1q2_score": 0.0322553837052834}} {"text": "function fd1d_display ( prefix )\n\n%*****************************************************************************80\n%\n%% FD1D_DISPLAY displays data for a 1D finite difference function.\n%\n% Discussion:\n%\n% The function is represented as the sum of piecewise linear functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Usage:\n%\n% fd1d_display ( 'prefix' )\n%\n% where\n%\n% 'prefix_nodes.txt' contains the point coordinates;\n% 'prefix_values.txt' contains the point values.\n%\n% Parameters:\n%\n% Input, string PREFIX, the prefix of the input files.\n%\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_DISPLAY\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read files defining a finite difference computatation,\\n' );\n fprintf ( 1, ' involving a set of nodes, and values of one or more\\n' );\n fprintf ( 1, ' functions at those nodes.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot the functions in a MATLAB graphics window.\\n' );\n%\n% First argument is the file prefix.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_DISPLAY:\\n' );\n prefix = input ( ' Enter the common prefix of the files (in ''quotes''!).\\n' );\n end\n%\n% Get the node coordinates.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n node_x = load ( node_filename );\n%\n% Get the function data.\n%\n value_filename = strcat ( prefix, '_values.txt' );\n node_value = load ( value_filename );\n%\n% Make the plot.\n%\n clf\n\n plot ( node_x, node_value )\n hold on\n plot ( node_x, node_value, '*' )\n\n grid\n\n title_string = s_escape_tex ( prefix );\n title ( title_string );\n xlabel ( 'X axis' );\n ylabel ( 'Function values' );\n\n hold off\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_DISPLAY\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction s2 = s_escape_tex ( s1 )\n\n%*****************************************************************************80\n%\n%% S_ESCAPE_TEX de-escapes TeX escape sequences.\n%\n% Discussion:\n%\n% In particular, every occurrence of the characters '\\', '_',\n% '^', '{' and '}' will be replaced by '\\\\', '\\_', '\\^',\n% '\\{' and '\\}'. A TeX interpreter, on seeing these character\n% strings, is then likely to return the original characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S1, the string to be de-escaped.\n%\n% Output, string S2, a copy of the string, modified to avoid TeX escapes.\n%\n s1_length = length ( s1 );\n\n s1_pos = 0;\n s2_pos = 0;\n s2 = [];\n\n while ( s1_pos < s1_length )\n\n s1_pos = s1_pos + 1;\n\n if ( s1(s1_pos) == '\\' | ...\n s1(s1_pos) == '_' | ...\n s1(s1_pos) == '^' | ...\n s1(s1_pos) == '{' | ...\n s1(s1_pos) == '}' )\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, '\\' );\n end\n\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, s1(s1_pos) );\n\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd1d_display/fd1d_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.07807817104433291, "lm_q1q2_score": 0.03209878589277788}} {"text": "%% Reference Frame Alignment\n%\n%%\n% The most important difference between MTEX and many other EBSD software\n% is that in MTEX the Euler angle reference is always the map reference\n% frame. This mean the $x$ and $z$ axes of the map are exactly the rotation\n% axes of the Euler angles. \n%\n% In case the map coordinates and the Euler angles in your data are with\n% respect to different reference frames it is highly recommended to correct\n% for this while importing the data into MTEX. This section explains in\n% detail how to do this.\n%\n%% On Sreen Orientation of the EBSD Map\n%\n% Many people are concerned when the images produced by MTEX are not\n% aligned exactly as they are in their commercial software. It is indeed\n% very important to understand exactly the alignment of your data. However,\n% the important point is not whether a map is upside down on your screen or\n% not. The important point is how your map aligns with the specimen, as we\n% want to use the map to describe properties of the specimen.\n%\n% There are basically two components in an EBSD data set that refer to the\n% specimen reference frame: the spatial coordinates $x$, $y$ and the Euler\n% angles $\\phi_1$, $\\Phi$, $\\phi_2$. To explain the difference have a look\n% at the EDAX export dialog\n% \n% <>\n% \n% Here we have the axes $x$ and $y$ which describe how the map coordinates\n% needs to be interpreted and the axes $A_1$, $A_2$, $A_3$ which describe\n% how the Euler angles, and in consequence, the pole figures needs to be\n% interpreted. We see that in none of these settings the map reference\n% system coincides with the Euler angle reference frame. \n%\n% This situation is not specific to EDAX but occurs as well with EBSD data\n% from Oxford or Bruker, all of them using different reference system\n% alignments. For that reason MTEX strongly recommends to transform the data\n% such that both map coordinates and Euler angles refer to the same\n% coordinate system. \n%\n% Doing this we have two choices:\n%\n% # transform everything to the reference system $x$, $y$ using the option\n% |'convertEuler2SpatialReferenceFrame'|. This will keep the map\n% coordinates while changing the Euler angles\n% # transform everything to the reference system $A_1$, $A_2$, $A_3$ using\n% the option |'convertSpatial2EulerReferenceFrame'|. This will keep the\n% Euler angles while changing the map coordinates.\n% \n% In the case of EDAX data imported from an |*.ang| file we still need to\n% specify the export option used by the EDAX software. This is done by the\n% options |'setting 1'|, |'setting 2'|, |'setting 3'| or |'setting 4'|.\n%\n% Since setting 2 is default for most EDAX exports a typical command for\n% importing data from an ang file would look like this\n\nebsd = EBSD.load([mtexEBSDPath filesep 'olivineopticalmap.ang'],...\n 'convertEuler2SpatialReferenceFrame','setting 2')\n\nplot(ebsd('olivine'),ebsd('olivine').orientations,'coordinates','on')\n\n%%\n% The plot does not yet fit the alignment of the map in the EDAX software\n% as it plots the x-axis be default to east and the z-axis into the plane.\n% This is only a plotting convention and can be set in MTEX by\n\nplotx2east\nplotzIntoPlane\n\nplot(ebsd('olivine'),ebsd('olivine').orientations,'coordinates','on')\n\n%%\n% Other plotting conventions are |plotx2north|, |plotx2west|, |plotx2south|\n% and |plotzOutOfPlane|. Note that these options only alter the orientation\n% of the EBSD map and the pole figures on the screen but does not change\n% any data.\n%\n%% Verify the reference system\n% One way of verifying the reference systems is to visualize crystal shapes\n% on top of the orientation map. To do this we proceed as follows\n\n% reconstruct grains\ngrains = calcGrains(ebsd('indexed'));\n\n% chose the correct crystal shape (cubic, hex are generic forms)\ncS = crystalShape.olivine;\n\n% select only large grains\nlargeGrains = grains(grains.grainSize>500)\n\n% and plot the crystal shapes\nhold on\nplot(largeGrains,cS)\nhold off\n\n%%\n% It may also be helpful to inspect pole figures \n\nh = Miller({1,0,0},{0,1,0},{0,0,1},ebsd('O').CS);\nplotPDF(ebsd('O').orientations,h,'contourf')\n\n%%\n% As pole figures display data relative to the specimen reference frame\n% MTEX automatically aligns them on the screen exactly as the spatial map\n% above, i.e., according to our last definition with x pointing towards\n% east and y to the south.\n%\n%% Change the map reference system\n% In order to manually change the map reference frame one may apply a\n% rotation to the map coordinates only. E.g. to flip the map left to right\n% while preserving the Euler angles one can do\n\nrot = rotation.byAxisAngle(yvector,180*degree);\nebsd_rot = rotate(ebsd,rot,'keepEuler');\n\n% reconstruct grains\ngrains = calcGrains(ebsd_rot('indexed'));\n\n% select only large grains\nlargeGrains = grains(grains.grainSize>500);\n\n\nplot(ebsd_rot('olivine'),ebsd_rot('olivine').orientations,'coordinates','on')\n\n% and plot the crystal shapes\nhold on\nplot(largeGrains,cS)\nhold off\n\n\n%% Change the Euler angle reference system\n% Analogously we may change the Euler angle reference frame while keeping\n% the map coordinates\n\nebsd_rot = rotate(ebsd,rot,'keepXY');\n\n% reconstruct grains\ngrains = calcGrains(ebsd_rot('indexed'));\n\n% select only large grains\nlargeGrains = grains(grains.grainSize>500);\n\n\nplot(ebsd_rot('olivine'),ebsd_rot('olivine').orientations,'coordinates','on')\n\n% and plot the crystal shapes\nhold on\nplot(largeGrains,cS)\nhold off\n\n\n%% Changing both reference system simultaneously\n%\n% Sometimes it is necessary to relate the EBSD data to a different external\n% reference frame, or to change the external reference frame from one to\n% the other, e.g. if one wants to concatenate several ebsd data sets where\n% the mounting was not done in perfect coincidence. In these cases the data\n% has to be rotated or shifted by the commands \n% and . The following commands rotate both reference\n% frames of the entire data set by 5 degree about the z-axis.\n\n% define a rotation\nrot = rotation.byAxisAngle(zvector,5*degree);\n\n% rotate the EBSD data\nebsd_rot = rotate(ebsd,rot);\n\n% reconstruct grains\ngrains = calcGrains(ebsd_rot('indexed'));\n\n% select only large grains\nlargeGrains = grains(grains.grainSize>500);\n\n\nplot(ebsd_rot('olivine'),ebsd_rot('olivine').orientations,'coordinates','on')\n\n% and plot the crystal shapes\nhold on\nplot(largeGrains,cS)\nhold off\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/EBSDAnalysis/EBSDReferenceFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.07585818211049715, "lm_q1q2_score": 0.03205043353026379}} {"text": "function [bcx,bcy] = specific_flow(xbd,ybd)\n%tightcavity_flow Reference problem 5.3 alternative inflow condition \n% [bcx,bcy] = specific_flow(xbd,ybd);\n% input\n% xbd x coordinate vector\n% ybd y coordinate vector \n%\n% specifies watertight cavity flow boundary condition\n% IFISS function: DJS; 6 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nbcx=0*xbd; bcy=0*xbd;\nk=find(ybd==1 & xbd>-1 & xbd<1); bcx(k)=1;\nreturn\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/stokes_flow/test_problems/tightcavity_flow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.0769608335789328, "lm_q1q2_score": 0.03163943518946729}} {"text": "function next = next_boundary_node_q9 ( node )\n\n%*****************************************************************************80\n%\n%% NEXT_BOUNDARY_NODE_Q9 returns the next boundary node in a Q9 element.\n%\n% Reference Element Q9:\n%\n% |\n% 1 4--7--3\n% | | |\n% | | |\n% S 8 9 6\n% | | |\n% | | |\n% 0 1--5--2\n% |\n% +--0--R--1-->\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE, the index of the current node. An input\n% value of 0 (or any \"unusual\" value\") indicates that the\n% first edge node is desired.\n%\n% Output, integer NEXT, the index of the next edge node.\n%\n if ( node == 1 )\n next = 5;\n elseif ( node == 5 )\n next = 2;\n elseif ( node == 2 )\n next = 6;\n elseif ( node == 6 )\n next = 3;\n elseif ( node == 3 )\n next = 7;\n elseif ( node == 7 )\n next = 4;\n elseif ( node == 4 )\n next = 8;\n else\n next = 1;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem2d_pack/next_boundary_node_q9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.0888202881792243, "lm_q1q2_score": 0.031600029782216946}} {"text": "function exact = p00_exact ( problem, dim_num )\n\n%*****************************************************************************80\n%\n%% P00_EXACT returns the exact integral for any problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the number of the desired test problem.\n%\n% Input, integer DIM_NUM, the dimension of the problem.\n%\n% Output, real EXACT, the exact value of the integral.\n%\n if ( problem == 1 )\n exact = p01_exact ( dim_num );\n elseif ( problem == 2 )\n exact = p02_exact ( dim_num );\n elseif ( problem == 3 )\n exact = p03_exact ( dim_num );\n elseif ( problem == 4 )\n exact = p04_exact ( dim_num );\n elseif ( problem == 5 )\n exact = p05_exact ( dim_num );\n elseif ( problem == 6 )\n exact = p06_exact ( dim_num );\n elseif ( problem == 7 )\n exact = p07_exact ( dim_num );\n elseif ( problem == 8 )\n exact = p08_exact ( dim_num );\n elseif ( problem == 9 )\n exact = p09_exact ( dim_num );\n elseif ( problem == 10 )\n exact = p10_exact ( dim_num );\n elseif ( problem == 11 )\n exact = p11_exact ( dim_num );\n elseif ( problem == 12 )\n exact = p12_exact ( dim_num );\n elseif ( problem == 13 )\n exact = p13_exact ( dim_num );\n elseif ( problem == 14 )\n exact = p14_exact ( dim_num );\n elseif ( problem == 15 )\n exact = p15_exact ( dim_num );\n elseif ( problem == 16 )\n exact = p16_exact ( dim_num );\n elseif ( problem == 17 )\n exact = p17_exact ( dim_num );\n elseif ( problem == 18 )\n exact = p18_exact ( dim_num );\n elseif ( problem == 19 )\n exact = p19_exact ( dim_num );\n elseif ( problem == 20 )\n exact = p20_exact ( dim_num );\n elseif ( problem == 21 )\n exact = p21_exact ( dim_num );\n elseif ( problem == 22 )\n exact = p22_exact ( dim_num );\n elseif ( problem == 23 )\n exact = p23_exact ( dim_num );\n elseif ( problem == 24 )\n exact = p24_exact ( dim_num );\n elseif ( problem == 25 )\n exact = p25_exact ( dim_num );\n elseif ( problem == 26 )\n exact = p26_exact ( dim_num );\n elseif ( problem == 27 )\n exact = p27_exact ( dim_num );\n elseif ( problem == 28 )\n exact = p28_exact ( dim_num );\n elseif ( problem == 29 )\n exact = p29_exact ( dim_num );\n elseif ( problem == 30 )\n exact = p30_exact ( dim_num );\n elseif ( problem == 31 )\n exact = p31_exact ( dim_num );\n elseif ( problem == 32 )\n exact = p32_exact ( dim_num );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_EXACT - Fatal error!\\n' );\n fprintf ( 1, ' Illegal problem number = %d\\n', problem );\n error ( 'P00_EXACT - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p00_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.06560483837252304, "lm_q1q2_score": 0.03152172601477647}} {"text": "function line = sphere_llq_grid_lines ( nlat, nlong, line_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLQ_GRID_LINES returns lines for an LLQ grid on a sphere.\n%\n% Discussion:\n%\n% A SPHERE LLQ grid imposes a grid of quadrilaterals on a sphere,\n% using latitude and longitude lines.\n%\n% The point numbering system is the same used in SPHERE_LLQ_GRID_POINTS,\n% and that routine may be used to compute the coordinates of the points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NLAT, NLONG, the number of latitude and longitude\n% lines to draw. The latitudes do not include the North and South\n% poles, which will be included automatically, so NLAT = 5, for instance,\n% will result in points along 7 lines of latitude.\n%\n% Input, integer LINE_NUM, the number of grid lines.\n%\n% Output, integer LINE(LINE_NUM,2), contains pairs of point indices for\n% line segments that make up the grid.\n%\n l = 0;\n line = zeros ( line_num, 2 );\n%\n% \"Vertical\" lines.\n%\n for j = 0 : nlong - 1\n\n old = 1;\n new = j + 2;\n l = l + 1;\n line(l,1:2) = [ old, new ];\n\n for i = 1 : nlat - 1\n\n old = new;\n new = old + nlong;\n l = l + 1;\n line(l,1:2) = [ old, new ];\n\n end\n\n old = new;\n l = l + 1;\n line(l,1:2) = [ old, 1 + nlat * nlong + 1 ];\n\n end\n%\n% \"Horizontal\" lines.\n%\n for i = 1 : nlat\n\n new = 1 + ( i - 1 ) * nlong + 1;\n\n for j = 0 : nlong - 2\n old = new;\n new = old + 1;\n l = l + 1;\n line(l,1:2) = [ old, new ];\n end\n\n old = new;\n new = 1 + ( i - 1 ) * nlong + 1;\n l = l + 1;\n line(l,1:2) = [ old, new ];\n\n end\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_llq_grid/sphere_llq_grid_lines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06371498936282499, "lm_q1q2_score": 0.030862271917272328}} {"text": "%% abaqusStruct2inp\n% Below is a demonstration of the features of the |abaqusStruct2inp| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[T]=abaqusStruct2inp(abaqus_spec,fileName,optionStruct);|\n\n%% Description\n% This function provides the basis for coding Abaqus .inp input files\n\n%%\n% See also: |abaqusStructTemplate|\n\n%% About Abaqus INP input files\n% Abaqus input files (.inp) are plain text files. \n\n%% Coding INP files in MATLAB\n\n%% \n% Specify file heading\n% Users may provide a heading which can be used to give a description of\n% the input file. \n\n% *Heading\n% ** Job name: ABAQUS inp file creation demo\n% ** Generated by: GIBBON\n\nabaqus_spec.Heading.COMMENT{1}='Job name: ABAQUS inp file creation demo';\nabaqus_spec.Heading.COMMENT{2}='Generated by: GIBBON';\n\n%% \n% The preprint section\n% \n\n% *Preprint, echo=NO, model=NO, history=NO, contact=NO\nabaqus_spec.Preprint.ATTR.echo='NO';\nabaqus_spec.Preprint.ATTR.model='NO';\nabaqus_spec.Preprint.ATTR.history='NO';\nabaqus_spec.Preprint.ATTR.contact='NO';\n\n%%\n% The part section\n\nV=[ 1 1 1; 1 0 1; 1 1 0; 1 0 0; 0 1 1; 0 0 1; 0 1 0; 0 0 0];\n\nnodeIds=(1:1:size(V,1));\nE=[5 6 8 7 1 2 4 3];\nelementIds=(1:1:size(E,1));\n\n% Node\nabaqus_spec.Part{1}.COMMENT='This section defines the part geometry in terms of nodes and elements';\nabaqus_spec.Part{1}.ATTR.name='Cube';\nabaqus_spec.Part{1}.Node={nodeIds(:),V};\n\n% Element\nabaqus_spec.Part{1}.Element{1}.ATTR.type='C3D8R';\nabaqus_spec.Part{1}.Element{1}.VAL={elementIds(:),E};\n\n%Element sets\nabaqus_spec.Part{1}.Elset{1}.ATTR.elset='Set-1';\nabaqus_spec.Part{1}.Elset{1}.VAL=1;\n\n%Node sets\nabaqus_spec.Part{1}.Nset{2}.ATTR.nset='Set-2';\nabaqus_spec.Part{1}.Nset{2}.VAL=1:1:size(V,1);\n\n%Node sets using \"generate\"\nabaqus_spec.Part{1}.Nset{1}.ATTR.nset='Set-1';\nabaqus_spec.Part{1}.Nset{1}.ATTR.generate='';\nabaqus_spec.Part{1}.Nset{1}.VAL=[1 size(V,1) 1];\n\n%Sections\nabaqus_spec.Part{1}.Solid_section.ATTR.elset='Set-1';\nabaqus_spec.Part{1}.Solid_section.ATTR.material='Elastic';\n\n% abaqus_spec.Part{1}.Shell_section.ATTR.elset='Set-1';\n% abaqus_spec.Part{1}.Shell_section.ATTR.material='Material-1';\n% % abaqus_spec.Part{1}.Shell_section.VAL=[10 5]; %Use numerical data\n% abaqus_spec.Part{1}.Shell_section.VAL='10., 5'; %Use custom text data\n\n%%\n% The assembly section\n\nabaqus_spec.Assembly.ATTR.name='Assembly-1';\n \nabaqus_spec.Assembly.Instance{1}.ATTR.name='Cube-1';\nabaqus_spec.Assembly.Instance{1}.ATTR.part='Cube';\n \n% abaqus_spec.Assembly.Instance{2}.ATTR.name='Clot-1';\n% abaqus_spec.Assembly.Instance{2}.ATTR.part='Clot';\n\n\nabaqus_spec.Assembly.Nset{1}.ATTR.nset='Set-1';\nabaqus_spec.Assembly.Nset{1}.ATTR.instance='Cube-1';\nabaqus_spec.Assembly.Nset{1}.ATTR.generate='';\nabaqus_spec.Assembly.Nset{1}.VAL=[1 4 1];\n\nabaqus_spec.Assembly.Nset{2}.ATTR.nset='Set-3';\nabaqus_spec.Assembly.Nset{2}.ATTR.instance='Cube-1';\nabaqus_spec.Assembly.Nset{2}.ATTR.generate='';\nabaqus_spec.Assembly.Nset{2}.VAL=[5 7 1];\n\nabaqus_spec.Assembly.Nset{3}.ATTR.nset='Set-4';\nabaqus_spec.Assembly.Nset{3}.ATTR.instance='Cube-1';\nabaqus_spec.Assembly.Nset{3}.ATTR.generate='';\nabaqus_spec.Assembly.Nset{3}.VAL=[2 6 2];\n\nabaqus_spec.Assembly.Nset{4}.ATTR.nset='Set-5';\nabaqus_spec.Assembly.Nset{4}.ATTR.instance='Cube-1';\nabaqus_spec.Assembly.Nset{4}.VAL=[3 4 7];\n\nabaqus_spec.Assembly.Nset{5}.ATTR.nset='origin';\nabaqus_spec.Assembly.Nset{5}.ATTR.instance='Cube-1';\nabaqus_spec.Assembly.Nset{5}.VAL=8;\n\nabaqus_spec.Assembly.Nset{6}.ATTR.nset='all';\nabaqus_spec.Assembly.Nset{6}.ATTR.instance='Cube-1';\n% abaqus_spec.Assembly.Nset{6}.ATTR.generate='';\nabaqus_spec.Assembly.Nset{6}.VAL=1:size(V,1);\n\nabaqus_spec.Assembly.Surface{1}.ATTR.type='ELEMENT';\nabaqus_spec.Assembly.Surface{1}.ATTR.name='innerSurface';\nelemSetsInner={[1 2 3 4],[4 5 6 7]};\nelemSetSideInner=[1 2];\nvalCell=cell(numel(elemSetsInner),1);\nfor qs=1:1:numel(elemSetsInner)\n surfaceElementSetName=['elementSetInnerSurface',num2str(qs)];\n abaqus_spec.Assembly.Elset{qs}.ATTR.elset=surfaceElementSetName;\n abaqus_spec.Assembly.Elset{qs}.ATTR.internal=''; %Remains hidden uppon import\n abaqus_spec.Assembly.Elset{qs}.ATTR.instance='Cube-1';\n abaqus_spec.Assembly.Elset{qs}.VAL=elemSetsInner{qs};\n \n sidePick=elemSetSideInner(qs);\n valCell{qs}={[surfaceElementSetName,', S',num2str(sidePick)]};\nend\nabaqus_spec.Assembly.Surface{1}.VAL=valCell;\n\n%% \n% Equation constraint\n\n% *Equation\n% 2\n% X(n-1), 1, 1.\n% XControlN, 1, -1.\n\n%%--> Constraints\nabaqus_spec.Assembly.COMMENT='Constraint 1';\nabaqus_spec.Assembly.Equation.VAL=['2' newline 'X(n-1), ', '1, 1.' newline 'XContN, ' '1, -1.'];\n\n%% \n% The material section\n\n% *Material, name=Material-1\n% *Hyperelastic, neo hooke\n% 0.03,1.\n\nabaqus_spec.Material.ATTR.name='Neo-Hooke';\nabaqus_spec.Material.Hyperelastic.VAL=[0.03 1];\nabaqus_spec.Material.Hyperelastic.ATTR.neo_hooke='';\nabaqus_spec.Material.ATTR.name='Elastic';\nabaqus_spec.Material.Elastic=[0.5 0.49];\n\n%%\n% Orientation\n\n% *Orientation, name=Ori-1, system=RECTANGULAR\n% Ori-1-DiscOrient\n% 2, 90.\nabaqus_spec.Orientation.ATTR.name='Ori-1';\nabaqus_spec.Orientation.ATTR.system='RECTANGULAR';\nabaqus_spec.Orientation.VAL=['Ori-1-DiscOrient' newline vec2strIntDouble([2 90],'%i')];\n\n%%\n% Contact pair\n\n%%--> Contact pair\nabaqus_spec.contact_pair{1}.ATTR.interaction='user-1';\nabaqus_spec.contact_pair{1}.ATTR.type='node to surface';\nabaqus_spec.contact_pair{1}.ATTR.adjust='0.0';\nabaqus_spec.contact_pair{1}.VAL='AORTA-ASSEMBLY.OUTER, AORTA1-ASSEMBLY.OUTERX';\n\n% surface interaction\nabaqus_spec.surface_interaction{1}.ATTR.name='user-1';\nabaqus_spec.surface_interaction{1}.ATTR.user='';\nabaqus_spec.surface_interaction{1}.ATTR.properties='7';\nabaqus_spec.surface_interaction{1}.ATTR.unsymm='';\nabaqus_spec.surface_interaction{1}.ATTR.DEPVAR='13';\nabaqus_spec.surface_interaction{1}.CSTM=', '; %Line with just comma\n\n%Wrap to max width of 8 entries\nt=vec2strIntDouble([0.2, 0.2, 0.05, 0.05,150,1000,0.0],'%6.7e');\nt=strwrap(t,8,', '); \nabaqus_spec.surface_interaction{1}.VAL=t;\n\n%%\n% The step section\n%\n\nabaqus_spec.Step.ATTR.name='Step-1';\nabaqus_spec.Step.ATTR.nlgeom='YES';\nabaqus_spec.Step.Static=[0.1 1 1e-5 0.1];\n\n% Boundary\nabaqus_spec.Step.Boundary{1}.VAL={'Set-1',[1 1],0.1};\nabaqus_spec.Step.Boundary{2}.VAL={repmat({'origin'},3,1) [1 1; 2 2; 3 3]};\nabaqus_spec.Step.Boundary{3}.VAL={'Set-3',[1,1]};\nabaqus_spec.Step.Boundary{4}.VAL={'Set-4',[2,2]};\nabaqus_spec.Step.Boundary{5}.VAL={'Set-5',[3,3]};\n\n% Loads\n% ** LOADS\n% ** \n% ** Name: Load-1 Type: Pressure\n% *Dsload\n% Surf-1, P, 0.00533\n% ** \nabaqus_spec.Step.Dsload{1}.VAL={'Surf-1','P',0.00533};\n\n%Output\nabaqus_spec.Step.Restart.ATTR.write='';\nabaqus_spec.Step.Restart.ATTR.frequency=0;\n\nabaqus_spec.Step.Output{1}.ATTR.field='';\nabaqus_spec.Step.Output{1}.ATTR.variable='PRESELECT';\nabaqus_spec.Step.Output{2}.ATTR.history='';\nabaqus_spec.Step.Output{2}.ATTR.variable='PRESELECT';\nabaqus_spec.Step.Node_print.ATTR.nset='all';\nabaqus_spec.Step.Node_print.ATTR.frequency = 1;\nabaqus_spec.Step.Node_print.VAL='COORD';\nabaqus_spec.Step.El_print.VAL='S';\n\n% * NODE SET, set=yoursetname, frequency = 1\n% U\n\n%% \n\n\n%% Creating the INP file\n% You can use |abaqusStruct2inp| to write the structure data to a file. \n\n%Create file name for INP file\ndefaultFolder = fileparts(fileparts(mfilename('fullpath')));\nsavePath=fullfile(defaultFolder,'data','temp');\nfileName=fullfile(savePath,'tempModel.inp');\n[~,fileNamePart,~]=fileparts(fileName);\n\n%%\n\n[T]=abaqusStruct2inp(abaqus_spec,fileName);\n\n%% View the inp file\n%\ntextView(fileName);\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_abaqusStruct2inp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.0715911930068287, "lm_q1q2_score": 0.02943191861948109}} {"text": "%% Copyright (C) 2014-2019, 2022 Colin B. Macdonald\n%% Copyright (C) 2016 Lagu\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @deftypeop Constructor @@sym {@var{x} =} sym (@var{y})\n%% @deftypeopx Constructor @@sym {@var{x} =} sym (@var{y}, @var{assumestr})\n%% @deftypeopx Constructor @@sym {@var{x} =} sym (@var{y}, @var{assumestr1}, @var{assumestr2}, @dots{})\n%% @deftypeopx Constructor @@sym {@var{x} =} sym (@var{A}, [@var{n}, @var{m}])\n%% @deftypeopx Constructor @@sym {@var{x} =} sym (@var{y}, @var{ratflag})\n%% @deftypeopx Constructor @@sym {@var{x} =} sym (@var{handle})\n%% Define symbols and numbers as symbolic expressions.\n%%\n%% @var{y} can be an integer, a string or one of several special\n%% double values. It can also be a double matrix or a cell\n%% array.\n%%\n%% Examples:\n%% @example\n%% @group\n%% x = sym ('x')\n%% @result{} x = (sym) x\n%% y = sym ('2')\n%% @result{} y = (sym) 2\n%% y = sym (3)\n%% @result{} y = (sym) 3\n%% y = sym (inf)\n%% @result{} y = (sym) ∞\n%% y = sym (pi)\n%% @result{} y = (sym) π\n%% y = sym (1i)\n%% @result{} y = (sym) ⅈ\n%% @end group\n%% @end example\n%%\n%% A sym of a sym is a sym (idempotence):\n%% @example\n%% @group\n%% sym (sym (pi))\n%% @result{} (sym) π\n%% @end group\n%% @end example\n%%\n%% A matrix of integers can be input:\n%% @example\n%% @group\n%% sym ([1 2; 3 4])\n%% @result{} (sym 2×2 matrix)\n%% ⎡1 2⎤\n%% ⎢ ⎥\n%% ⎣3 4⎦\n%% @end group\n%% @end example\n%%\n%% However, if the entries are not simply integers, its better to call\n%% @code{sym} inside the matrix:\n%% @example\n%% @group\n%% [sym(pi) sym(3)/2; sym(1) 0]\n%% @result{} (sym 2×2 matrix)\n%% ⎡π 3/2⎤\n%% ⎢ ⎥\n%% ⎣1 0 ⎦\n%% @end group\n%% @end example\n%% (Careful: at least one entry per row must be @code{sym} to workaround\n%% a GNU Octave bug @url{https://savannah.gnu.org/bugs/?42152}.)\n%% @c @example\n%% @c [sym(pi) 2; 1 0]\n%% @c @print{} ??? octave_base_value::map_value(): wrong type argument 'scalar'\n%% @c @end example\n%%\n%% Passing double values to sym is not recommended and will give a warning:\n%% @example\n%% @group\n%% sym(0.1)\n%% @print{} warning: passing floating-point values to sym is\n%% @print{} dangerous, see \"help sym\"...\n%% @result{} ans = (sym) 1/10\n%% @end group\n%% @end example\n%%\n%% In this particular case, the warning is easy to avoid:\n%% @example\n%% @group\n%% sym(1)/10\n%% @result{} (sym) 1/10\n%% @end group\n%% @end example\n%%\n%% The ``danger'' here is that typing @code{0.1} gives a double-precision\n%% floating-point value which differs slightly from the fraction\n%% @code{sym(1)/10} (and this is true for most decimal expressions).\n%% It is generally impossible to determine which exact symbolic value the\n%% user intended.\n%% The warning indicates that some heuristics have been applied\n%% (namely a preference for ``small'' fractions, small fractions\n%% of π and square roots of integers).\n%% Further examples include:\n%% @example\n%% @group\n%% y = sym(pi/100)\n%% @print{} warning: passing floating-point values to sym is\n%% @print{} dangerous, see \"help sym\"...\n%% @result{} y = (sym)\n%% π\n%% ───\n%% 100\n%% @end group\n%%\n%% @group\n%% y = sym(pi)/100\n%% @result{} y = (sym)\n%% π\n%% ───\n%% 100\n%% @end group\n%% @end example\n%% (@code{sym(pi)} is a special case; it does not raise the warning).\n%%\n%%\n%% There is an additional reason for the float-point warning,\n%% relevant if you are doing something like @code{sym(1.23456789012345678)}.\n%% In many cases, floating-point numbers should be thought of as\n%% approximations (with about 15 decimal digits of relative accuracy).\n%% This means that mixing floating-point values and symbolic computations\n%% with the goal of obtaining exact results is often a fool's errand.\n%% Compounding this, symbolic computations may not always use numerically\n%% stable algorithms (as their inputs are assumed exact) whereas a\n%% floating-point input is effectively perturbed in the 15th digit.\n%%\n%% If what you really want is higher-precision floating-point\n%% computations, @pxref{vpa}.\n%%\n%%\n%% If having read the above, you @emph{still} want to do something\n%% symbolic with floating-point inputs, you can use the @var{ratflag}\n%% argument; by setting it to @qcode{'f'}, you will obtain the precise\n%% rational number which is equal to the floating-point value:\n%% @example\n%% @group\n%% sym(0.1, 'f')\n%% @result{} (sym)\n%% 3602879701896397\n%% ─────────────────\n%% 36028797018963968\n%% @end group\n%% @end example\n%%\n%% The default heuristic rational behaviour can be obtained by passing\n%% @var{ratflag} as @qcode{'r'}; this avoids the floating-point warning:\n%% @example\n%% @group\n%% sym(0.1, 'r')\n%% @result{} (sym) 1/10\n%% @end group\n%% @end example\n%%\n%%\n%% For symbols, a second (and further) arguments can provide assumptions\n%% or restrictions on the type of the symbol:\n%% @example\n%% @group\n%% x = sym ('x', 'positive')\n%% @result{} x = (sym) x\n%% x = sym ('x', 'positive', 'integer')\n%% @result{} x = (sym) x\n%% @end group\n%% @end example\n%% @xref{assumptions}, for the list of supported assumptions.\n%%\n%% Caution: it is possible to create multiple variants of the\n%% same symbol with different assumptions.\n%% @example\n%% @group\n%% x1 = sym('x')\n%% @result{} x1 = (sym) x\n%% x2 = sym('x', 'positive')\n%% @result{} x2 = (sym) x\n%% x1 == x2\n%% @result{} (sym) x = x\n%% isAlways(x1 == x2)\n%% @result{} 0\n%% logical(x1 == x2)\n%% @result{} 0\n%% @end group\n%% @end example\n%%\n%% The second argument can also specify the size of a matrix:\n%% @example\n%% @group\n%% A = sym('a', [2 3])\n%% @result{} A = (sym 2×3 matrix)\n%% ⎡a₁₁ a₁₂ a₁₃⎤\n%% ⎢ ⎥\n%% ⎣a₂₁ a₂₂ a₂₃⎦\n%% @end group\n%% @end example\n%% or even with symbolic size:\n%% @example\n%% @group\n%% syms m n positive integer\n%% B = sym('B', [m n])\n%% @result{} B = (sym) B (m×n matrix expression)\n%% @end group\n%% @end example\n%%\n%% Anonymous functions can be converted to symbolic expressions by\n%% passing their function handle:\n%% @example\n%% @group\n%% f = @@(n, x) sin (pi*besselj (n, x)/2)\n%% @result{} f = @@(n, x) sin (pi * besselj (n, x) / 2)\n%% class (f)\n%% @result{} function_handle\n%% sym(f)\n%% @result{} (sym)\n%% ⎛π⋅besselj(n, x)⎞\n%% sin⎜───────────────⎟\n%% ⎝ 2 ⎠\n%% @end group\n%% @end example\n%%\n%% It is also possible to save sym objects to file and then load them when\n%% needed in the usual way with the @code{save} and @code{load} commands.\n%%\n%% The underlying SymPy string representation (``srepr'') can usually be passed\n%% directly to @code{sym}: @pxref{@@sym/char} for discussion of the details.\n%%\n%% @seealso{syms, assumptions, @@sym/assume, @@sym/assumeAlso}\n%% @end deftypeop\n\n\nfunction s = sym(x, varargin)\n\n if (nargin == 0)\n x = 0;\n end\n\n %% The actual class constructor\n % Tempting to make a 'private constructor' but we need to access\n % this from the python ipc stuff: outside the class. We identify\n % this non-user-facing usage by empty x and 6 inputs total. Note\n % that \"sym([])\" is valid but \"sym([], ...)\" is otherwise not.\n if (isempty (x) && nargin == 6)\n s.pickle = varargin{1};\n s.size = varargin{2};\n s.flat = varargin{3};\n s.ascii = varargin{4};\n s.unicode = varargin{5};\n s.extra = [];\n s = class (s, 'sym');\n return\n end\n\n %% User interface for defining sym\n % sym(1), sym('x'), etc.\n\n %if (strcmp (class (x), 'symfun') && nargin==1)\n % % FIXME: pass a symfun to sym() ctor; convert to pure sym\n % % (SMT does not do this in 2014a). bad idea?\n % s = x.sym;\n % return\n\n if (isa (x, 'sym'))\n if (nargin == 1)\n s = x;\n return\n else\n x = x.flat;\n end\n end\n\n if (iscell (x))\n %% Cell arrays are converted to sym arrays\n assert (isempty (varargin));\n s = cell2sym (x);\n return\n end\n\n if (isa (x, 'function_handle'))\n assert (nargin == 1)\n %% Need argnames of the handle. TODO: can do better than regex?\n vars = regexp (func2str (x), '^\\@\\(([\\w,\\s]*)\\)', 'tokens', 'once');\n assert (length (vars) == 1)\n vars = vars{1};\n if (isempty (vars))\n vars = {}; % empty char to empty cell\n else\n vars = strsplit (vars, {',' ' '});\n end\n for i = 1:length (vars)\n vars{i} = sym (sprintf ('Symbol(\"%s\")', vars{i}));\n end\n %% call the function with those arguments as symbolic inputs\n s = x (vars{:});\n if (~ isa (s, 'sym')) % e.g., for \"@(x) 7\"\n s = sym (s);\n end\n return\n end\n\n asm = {};\n isnumber = isnumeric (x) || islogical (x);\n ratwarn = true;\n ratflag = 'r';\n\n if (nargin >= 2)\n if (ismatrix (varargin{1}) && ~ischar (varargin{1}) && ~isstruct (varargin{1}) && ~iscell (varargin{1}))\n %% Handle MatrixSymbols\n assert (nargin < 3, 'MatrixSymbol do not support assumptions')\n s = make_sym_matrix (x, varargin{1});\n return\n elseif (nargin == 2 && isnumber && ischar (varargin{1}) && isscalar (varargin{1}))\n %% explicit ratflag given\n sclear = false;\n ratflag = varargin{1};\n switch ratflag\n case 'f'\n ratwarn = false;\n case 'r'\n ratwarn = false;\n case {'d' 'e'}\n error ('sym: RATFLAG ''%s'' is not implemented', ratflag)\n otherwise\n error ('sym: invalid RATFLAG ''%s''', ratflag)\n end\n elseif (nargin == 2 && ischar (varargin{1}) && strcmp (varargin{1}, 'clear'))\n sclear = true;\n varargin(1) = [];\n warning ('OctSymPy:deprecated', ...\n ['\"sym(x, ''clear'')\" is deprecated and will be removed in a future version;\\n' ...\n ' use \"assume(x, ''clear'')\" instead.'])\n else\n sclear = false;\n assert (~isnumber, 'Only symbols can have assumptions.')\n check_assumptions (varargin); % Check if assumptions exist - Sympy don't check this\n asm = varargin;\n end\n end\n\n if (~isscalar (x) && isnumber) % Handle octave numeric matrix\n s = numeric_array_to_sym (x);\n return\n\n elseif (isa (x, 'double')) % Handle double/complex\n iscmplx = ~isreal (x);\n if (iscmplx && isequal (x, 1i))\n s = pycall_sympy__ ('return S.ImaginaryUnit');\n return\n elseif (iscmplx)\n xx = {real(x); imag(x)};\n else\n xx = {x};\n end\n yy = cell(2, 1);\n for n = 1:numel (xx)\n x = xx{n};\n switch ratflag\n case 'f'\n y = double_to_sym_exact (x);\n case 'r'\n y = double_to_sym_heuristic (x, ratwarn, []);\n otherwise\n error ('sym: this case should not be possible')\n end\n yy{n} = y;\n end\n if (iscmplx)\n s = yy{1} + yy{2}*1i;\n else\n s = yy{1};\n end\n return\n\n elseif (isinteger (x)) % Handle integer vealues\n s = pycall_sympy__ ('return Integer(*_ins)', x);\n return\n\n elseif (islogical (x)) % Handle logical values\n if (x)\n s = pycall_sympy__ ('return S.true');\n else\n s = pycall_sympy__ ('return S.false');\n end\n return\n end\n\n if (isa (x, 'char'))\n %% Need to decide whether to use S() or Symbol()\n\n % TODO: tests pass without this? Is there a example where this is needed?\n %% sym('---1') -> '-' '1' Split first symbols to can search operators correctly.\n %r = 1;\n %xc = ''; % Used to check operators skipping first symbols\n %for i = 1:length (x)\n % if (strcmp (x (i), '-'))\n % r = r*-1;\n % elseif (~strcmp (x (i), '+'))\n % if (r == -1)\n % xc = x (i:end);\n % x = ['-' x(i:end)];\n % else\n % x = xc = x (i:end);\n % end\n % break\n % end\n %end\n\n y = detect_special_str (x);\n if (~ isempty (y))\n assert (isempty (asm), 'Only symbols can have assumptions.')\n s = pycall_sympy__ (['return ' y]);\n return\n end\n\n isnum = ~isempty (regexp (strtrim (x), ...\n '^[-+]*?[\\d_]*\\.?[\\d_]*(e[+-]?[\\d_]+)?$'));\n %% Use Symbol() for words, not numbers, not \"f(x)\".\n if ((~ isnum) && (~ isempty (regexp (strtrim (x), '^\\w+$'))))\n\n cmd = { 'd = dict()'\n 'x = _ins[0]'\n '_ins = _ins[1:]'\n 'for i in range(len(_ins)):'\n ' if isinstance(_ins[i], dict):'\n ' d.update(_ins[i])'\n ' #elif isinstance(_ins[i], list):' % TODO: allow a list?\n ' # for j in range(len(_ins[i])):'\n ' # d.update({_ins[i][j]:True})'\n ' elif isinstance(_ins[i], (str, bytes)):'\n ' d.update({_ins[i]:True})'\n ' else:'\n ' raise ValueError(\"something unexpected in assumptions\")'\n 'return Symbol(x, **d)' };\n s = pycall_sympy__ (cmd, x, asm{:});\n\n if (nargin == 2 && sclear)\n % ---------------------------------------------\n % Muck around in the caller's namespace, replacing syms\n % that match 'xstr' (a string) with the 'newx' sym.\n context = 'caller';\n S = evalin(context, 'whos');\n evalin(context, '[];'); % clear 'ans'\n for i = 1:numel(S)\n obj = evalin(context, S(i).name);\n [newobj, flag] = symreplace(obj, x, s);\n if flag, assignin(context, S(i).name, newobj); end\n end\n % ---------------------------------------------\n end\n\n return\n\n else % S() in other case\n\n assert (isempty (asm), 'Only symbols can have assumptions.')\n\n % TODO: future version might warn on expression strings\n % Check if the user try to execute operations from sym\n %if (~isempty (regexp (xc, '\\!|\\&|\\^|\\:|\\*|\\/|\\\\|\\+|\\-|\\>|\\<|\\=|\\~')))\n % warning ('Please avoid execute operations from sym function.');\n %end\n\n % Usually want rational output here (i.e., if input was \"1.2\").\n % But if input has words and parentheses it might be raw Sympy code.\n if (isempty (regexp (x, '\\w\\(.*\\)')))\n s = pycall_sympy__ (['return S(\"' x '\", rational=True)']);\n return\n end\n\n hint_symfun = false;\n %% distinguish b/w sym('ff(w)') and sym('ff(6, Symbol(\"w\"))')\n % regexp detects F()\n T = regexp (x, '^(\\w+)\\(([\\w,\\s]*)\\)$', 'tokens');\n if (length (T) == 1 && length (T{1}) == 2)\n hint_symfun = true;\n name = T{1}{1};\n varnamestr = T{1}{2};\n varnames = strtrim (strsplit (varnamestr, ','));\n\n %% Blocklist some strings for which srepr(x) == str(x)\n % Python code for this:\n % >>> ns = {}; exec('from sympy import *', ns)\n % ... for (k, v) in ns.items():\n % ... if not callable(v) and k not in ['__builtins__', 'C']:\n % ... if k == srepr(v):\n % ... print(k)\n var_blocklist = {'E' 'I' 'nan' 'oo' 'pi' 'zoo' 'Catalan' ...\n 'EulerGamma' 'GoldenRatio' 'true' 'false'};\n\n %% special case: if all (x,y,z) are in the blocklist, we should *not*\n % force symfun, thus preserving the identity sympy(sym(x)) == x\n if (all (cellfun (@(v) (any (strcmp (v, var_blocklist))), varnames)))\n hint_symfun = false;\n end\n\n %% special case some function names to always make a Function\n % Currently this is unused, but could be used if we want\n % different behaviour for the \"I\" in \"I(t)\" vs \"F(I, t)\".\n % SMT 2014 compat: does *not* have I, E here\n %function_allowlist = {'I', 'E', 'ff', 'FF'};\n %if (hint_symfun)\n % if (any (strcmp (name, function_allowlist)))\n % x = ['Function(\"' name '\")(' varnamestr ')'];\n % end\n %end\n end\n\n cmd = {'x, hint_symfun = _ins'\n 'if hint_symfun:'\n ' from sympy.abc import _clash1'\n ' myclash = {v: Function(v) for v in [\"ff\", \"FF\"]}'\n ' myclash.update(_clash1)'\n ' #myclash.pop(\"I\", None)' % remove for SMT compat\n ' #myclash.pop(\"E\", None)'\n 'else:'\n ' myclash = dict()'\n 'try:'\n ' return (0, 0, sympify(x, locals=myclash))'\n 'except Exception as e:'\n ' lis = set()'\n ' if \"(\" in x or \")\" in x:'\n ' x2 = split(\"\\(|\\)| |,\", x)'\n ' x2 = [p for p in x2 if p]'\n ' for i in x2:'\n ' try:'\n ' if eval(\"callable(\" + i + \")\"):'\n ' lis.add(i)'\n ' except:'\n ' pass'\n ' if len(lis) > 0:'\n ' return (str(e), 1, \"\\\", \\\"\".join(str(e) for e in lis))'\n ' return (str(e), 2, 0)' };\n\n [err flag s] = pycall_sympy__ (cmd, x, hint_symfun);\n\n switch (flag)\n case 1 % Bad call to python function\n error (['Python: %s\\n' ...\n 'Error occurred using \"%s\" Python function, perhaps use another variable name?'], ...\n err, s);\n case 2 % Something else\n error (['Python: %s\\n' ...\n 'Seems you cannot use \"%s\" for a variable name; perhaps this is a bug?'], ...\n err, x);\n end\n return\n\n end\n end\n\n error ('Conversion to symbolic with those arguments not (yet) supported')\n\nend\n\n\n%!test\n%! % integers\n%! x = sym ('2');\n%! y = sym (2);\n%! assert (isa (x, 'sym'))\n%! assert (isa (y, 'sym'))\n%! assert (isequal (x, y))\n\n%!test\n%! % infinity\n%! for x = {'inf', '-inf', inf, -inf, 'Inf'}\n%! y = sym (x{1});\n%! assert (isa (y, 'sym'))\n%! assert (isinf (double (y)))\n%! assert (isinf (y))\n%! end\n\n%!test\n%! % pi\n%! x = sym ('pi');\n%! assert (isa (x, 'sym'))\n%! assert (isequal (sin (x), sym (0)))\n%! assert (abs (double (x) - pi) < 2*eps )\n%! x = sym (pi);\n%! assert (isa (x, 'sym'))\n%! assert (isequal (sin (x), sym (0)))\n%! assert (abs (double (x) - pi) < 2*eps )\n\n%!test\n%! % rationals\n%! x = sym(1) / 3;\n%! assert (isa (x, 'sym'))\n%! assert (isequal (3*x - 1, sym (0)))\n%! x = 1 / sym (3);\n%! assert (isa (x, 'sym'))\n%! assert (isequal (3*x - 1, sym (0)))\n%! x = sym ('1/3');\n%! assert (isa (x, 'sym'))\n%! assert (isequal (3*x - 1, sym (0)))\n\n%!test\n%! % passing small rationals\n%! x = sym ('1/2');\n%! assert (double (x) == 1/2 )\n%! assert (isequal (2*x, sym (1)))\n\n%!warning x = sym (1/2);\n\n%!test\n%! % passing small rationals w/o quotes: despite the warning,\n%! % it should work\n%! s = warning ('off', 'OctSymPy:sym:rationalapprox');\n%! x = sym (1/2);\n%! warning (s)\n%! assert (double (x) == 1/2 )\n%! assert (isequal (2*x, sym (1)))\n\n%!test\n%! assert (isa (sym (pi), 'sym'))\n%! assert (isa (sym ('beta'), 'sym'))\n\n%!test\n%! % sym from array\n%! D = [0 1; 2 3];\n%! A = [sym(0) 1; sym(2) 3];\n%! assert (isa (sym (D), 'sym'))\n%! assert (isequal (size (sym (D)), size (D)))\n%! assert (isequal (sym (D), A))\n\n%!test\n%! % more sym from array\n%! syms x\n%! A = [x x];\n%! assert (isequal (sym (A), A))\n%! A = [1 x];\n%! assert (isequal (sym (A), A))\n\n%!test\n%! %% assumptions and clearing them\n%! clear variables % for matlab test script\n%! x = sym('x', 'real');\n%! f = {x {2*x}};\n%! asm = assumptions();\n%! assert ( ~isempty(asm))\n%! s = warning ('off', 'OctSymPy:deprecated');\n%! x = sym('x', 'clear');\n%! warning (s)\n%! asm = assumptions();\n%! assert ( isempty(asm))\n\n%!test\n%! %% matlab compat, syms x clear should add x to workspace\n%! x = sym('x', 'real');\n%! f = 2*x;\n%! clear x\n%! assert (~logical(exist('x', 'var')))\n%! s = warning ('off', 'OctSymPy:deprecated');\n%! x = sym('x', 'clear');\n%! warning (s)\n%! assert (logical(exist('x', 'var')))\n\n%!test\n%! %% assumptions should work if x is already a sym\n%! x = sym('x');\n%! x = sym(x, 'real');\n%! assert (~isempty(assumptions(x)))\n\n%!test\n%! %% likewise for clear\n%! x = sym('x', 'real');\n%! f = 2*x;\n%! s = warning ('off', 'OctSymPy:deprecated');\n%! x = sym(x, 'clear');\n%! warning (s)\n%! assert (isempty(assumptions(x)))\n%! assert (isempty(assumptions(f)))\n\n%!test\n%! % bool\n%! t = sym (false);\n%! t = sym (true);\n%! assert (logical (t))\n\n%!test\n%! % bool vec/mat\n%! a = sym (1);\n%! t = sym ([true false]);\n%! assert (isequal (t, [a == 1 a == 0]))\n%! t = sym ([true false; false true]);\n%! assert (isequal (t, [a == 1 a == 0; a == 0 a == 1]))\n\n%!test\n%! % symbolic matrix\n%! A = sym ('A', [2 3]);\n%! assert (isa (A, 'sym'))\n%! assert (isequal (size (A), [2 3]))\n%! A(1, 1) = 7;\n%! assert (isa (A, 'sym'))\n%! A = A + 1;\n%! assert (isa (A, 'sym'))\n\n%!test\n%! % symbolic matrix, symbolic but Integer size\n%! A = sym ('A', sym([2 3]));\n%! assert (isa (A, 'sym'))\n%! assert (isequal (size (A), [2 3]))\n\n%!test\n%! % symbolic matrix, subs in for size\n%! syms n m integer\n%! A = sym ('A', [n m]);\n%! B = subs (A, [n m], [5 6]);\n%! assert (isa (B, 'sym'))\n%! assert (isequal (size (B), [5 6]))\n\n%!error sym('2*a', [2 3])\n%!error sym(2*sym('a'), [2 3])\n%!error sym('1', [2 3])\n%!error sym(1, [2 3])\n\n%!error \n%! % TODO: symbolic tensor, maybe supported someday\n%! sym('a', [2 3 4])\n\n%!test\n%! % 50 shapes of empty\n%! a = sym (ones (0, 3));\n%! assert (isa (a, 'sym'))\n%! assert (isequal (size (a), [0 3]))\n%! a = sym (ones (2, 0));\n%! assert (isequal (size (a), [2 0]))\n%! a = sym ([]);\n%! assert (isequal (size (a), [0 0]))\n\n%!test\n%! % moar empty\n%! a = sym ('a', [0 3]);\n%! assert (isa (a, 'sym'))\n%! assert (isequal (size (a), [0 3]))\n%! a = sym ('a', [2 0]);\n%! assert (isa (a, 'sym'))\n%! assert (isequal (size (a), [2 0]))\n\n%!test\n%! % embedded sympy commands, various quotes, issue #143\n%! a = sym ('a');\n%! a1 = sym ('Symbol(\"a\")');\n%! a2 = sym ('Symbol(''a'')');\n%! assert (isequal (a, a1))\n%! assert (isequal (a, a2))\n%! % Octave only, and eval to hide from Matlab parser\n%! if exist ('OCTAVE_VERSION', 'builtin')\n%! eval( 'a3 = sym(\"Symbol(''a'')\");' );\n%! eval( 'a4 = sym(\"Symbol(\\\"a\\\")\");' );\n%! assert (isequal (a, a3))\n%! assert (isequal (a, a4))\n%! end\n\n%!test\n%! % complex\n%! x = sym(1 + 2i);\n%! assert (isequal (x, sym(1)+sym(2)*1i))\n\n%!test\n%! % doubles bigger than int32 INTMAX should not fail\n%! d = 4294967295;\n%! a = sym (d);\n%! assert (isequal (double (a), d))\n%! d = d + 123456;\n%! a = sym (d);\n%! assert (isequal (double (a), d))\n\n%!test\n%! % int32 integer types\n%! a = sym (100);\n%! b = sym (int32 (100));\n%! assert (isequal (a, b))\n\n%!test\n%! % int32 MAXINT integers\n%! a = sym ('2147483647');\n%! b = sym (int32 (2147483647));\n%! assert (isequal (a, b))\n%! a = sym ('-2147483647');\n%! b = sym (int32 (-2147483647));\n%! assert (isequal (a, b))\n%! a = sym ('4294967295');\n%! b = sym (uint32 (4294967295));\n%! assert (isequal (a, b))\n\n%!test\n%! % int64 integer types\n%! a = sym ('123456789012345');\n%! b = sym (int64(123456789012345));\n%! c = sym (uint64(123456789012345));\n%! assert (isequal (a, b))\n%! assert (isequal (a, c))\n\n%!test\n%! % integer arrays\n%! a = int64 ([1 2 100]);\n%! s = sym (a);\n%! assert (isequal (double (a), [1 2 100]))\n\n%!test\n%! % bigger int64 integer types\n%! q = int64 (123456789012345);\n%! w = 10000*q + 123;\n%! a = sym ('1234567890123450123');\n%! b = sym (w);\n%! assert (isequal (a, b))\n\n%!test\n%! % sym(double) heuristic\n%! s = warning ('off', 'OctSymPy:sym:rationalapprox');\n%! x = sym(2*pi/3);\n%! assert (isequal (x/sym(pi), sym(2)/3))\n%! x = sym(22*pi);\n%! assert (isequal (x/sym(pi), sym(22)))\n%! x = sym(pi/123);\n%! assert (isequal (x/sym(pi), sym(1)/123))\n%! warning (s)\n\n%!test\n%! % sym(double) with 'r': no warning\n%! a = 0.1;\n%! x = sym(a, 'r');\n%! assert (isequal (x, sym(1)/10))\n\n%!test\n%! % sym(double, 'f')\n%! a = 0.1;\n%! x = sym(a, 'f');\n%! assert (~isequal (x, sym(1)/10))\n%! assert (isequal (x, sym('3602879701896397')/sym('36028797018963968')))\n\n%!test\n%! x = sym(pi, 'f');\n%! assert (~isequal (x, sym('pi')))\n%! assert (isequal (x, sym('884279719003555')/sym('281474976710656')))\n\n%!test\n%! q = sym('3602879701896397')/sym('36028797018963968');\n%! x = sym(1 + 0.1i, 'f');\n%! assert (isequal (x, 1 + 1i*q))\n%! x = sym(0.1 + 0.1i, 'f');\n%! assert (isequal (x, q + 1i*q))\n\n%!test\n%! assert (isequal (sym(inf, 'f'), sym(inf)))\n%! assert (isequal (sym(-inf, 'f'), sym(-inf)))\n%! assert (isequaln (sym(nan, 'f'), sym(nan)))\n%! assert (isequal (sym(complex(inf, -inf), 'f'), sym(complex(inf, -inf))))\n%! assert (isequaln (sym(complex(nan, inf), 'f'), sym(complex(nan, inf))))\n%! assert (isequaln (sym(complex(-inf, nan), 'f'), sym(complex(-inf, nan))))\n\n%!test\n%! assert (isequal (sym (sqrt(2), 'r'), sqrt (sym (2))))\n%! assert (isequal (sym (sqrt(12345), 'r'), sqrt (sym (12345))))\n\n%!test\n%! % symbols with special sympy names\n%! syms Ei Eq\n%! assert (~isempty (regexp (sympy (Eq), '^Symbol')))\n%! assert (~isempty (regexp (sympy (Ei), '^Symbol')))\n\n%!test\n%! % more symbols with special sympy names\n%! x = sym('FF');\n%! assert (~isempty (regexp (x.pickle, '^Symbol')))\n%! x = sym('ff');\n%! assert (~isempty (regexp (x.pickle, '^Symbol')))\n\n%!test\n%! % E can be a sym not just exp(sym(1))\n%! syms E\n%! assert (~logical (E == exp(sym(1))))\n\n%!test\n%! % e can be a symbol, not exp(sym(1))\n%! syms e\n%! assert (~ logical (e == exp(sym(1))))\n\n%!test\n%! % double e\n%! x = sym (exp (1));\n%! y = exp (sym (1));\n%! assert (isequal (x, y))\n%! if (exist ('OCTAVE_VERSION', 'builtin'))\n%! x = sym (e);\n%! assert (isequal (x, y))\n%! end\n\n%!test\n%! x = sym (-exp (1));\n%! y = -exp (sym (1));\n%! assert (isequal (x, y))\n\n%!assert (~ isequal (sym (exp(1)), sym (exp(1), 'f')))\n\n%!warning sym (1e16);\n%!warning sym (-1e16);\n%!warning sym (10.33);\n%!warning sym (-5.23);\n%!warning sym (sqrt (1.4142135623731));\n\n%!error \n%! x = sym ('x', 'positive2');\n\n%!error \n%! x = sym ('x', 'integer', 'positive2');\n\n%!error \n%! x = sym ('x', 'integer2', 'positive');\n\n%!error \n%! x = sym ('-pi', 'positive')\n\n%!error \n%! x = sym ('pi', 'integer')\n\n%!test\n%! % multiple assumptions\n%! n = sym ('n', 'negative', 'even');\n%! a = assumptions (n);\n%! assert (strcmp (a, 'n: negative, even') || strcmp (a, 'n: even, negative'))\n\n%!error \n%! % multiple assumptions as a list\n%! % TODO: should this be allowed?\n%! n = sym ('n', {'negative', 'even'});\n%! a = assumptions (n);\n%! assert (strcmp (a, 'n: negative, even') || strcmp (a, 'n: even, negative'))\n\n%!error \n%! n = sym ('n', {{'negative', 'even'}});\n\n%!test\n%! % save/load sym objects\n%! syms x\n%! y = 2*x;\n%! a = 42;\n%! myfile = tempname ();\n%! save (myfile, 'x', 'y', 'a')\n%! clear x y a\n%! load (myfile)\n%! assert (isequal (y, 2*x))\n%! assert (a == 42)\n%! if (exist ('OCTAVE_VERSION', 'builtin'))\n%! assert (unlink (myfile) == 0)\n%! else\n%! delete ([myfile '.mat'])\n%! end\n\n%!test\n%! a = sym ('2.1');\n%! b = sym (21) / 10;\n%! %% https://github.com/sympy/sympy/issues/11703\n%! assert (pycall_sympy__ ('return _ins[0] == _ins[1] and hash(_ins[0]) == hash(_ins[1])', a, b))\n\n%!test\n%! % issue #706\n%! a = sym('Float(\"1.23\")');\n%! assert (~ isempty (strfind (char (a), '.')))\n\n% TODO: test that might be used in the future\n%%!warning sym ('1*2');\n\n%!assert (isequal (sym({1 2 'a'}), [sym(1) sym(2) sym('a')]));\n\n%!error sym({1 2 'a'}, 'positive');\n%!error sym({'a' 'b'}, 'positive');\n\n%!test\n%! a = sym ('--1');\n%! b = sym ('---1');\n%! assert (isequal (a, sym (1)))\n%! assert (isequal (b, sym (-1)))\n\n%!test\n%! % num2cell works on sym arrays\n%! syms x\n%! C1 = num2cell ([x 2 3; 4 5 6*x]);\n%! assert (iscell (C1))\n%! assert (isequal (size (C1), [2 3]))\n%! assert (isequal (C1{1,1}, x))\n%! assert (isequal (C1{2,3}, 6*x))\n%! assert (isequal (C1{1,3}, sym(3)))\n%! assert (isa (C1{1,3}, 'sym'))\n\n%!test\n%! % function_handle\n%! f = @(x, y) y*sin(x);\n%! syms x y\n%! assert (isequal (sym (f), y*sin(x)));\n%! f = @(x) 42;\n%! assert (isequal (sym (f), sym (42)));\n%! f = @() 42;\n%! assert (isequal (sym (f), sym (42)));\n\n%!error \n%! % function_handle\n%! f = @(x) A*sin(x);\n%! sym (f)\n\n%!test\n%! % Issue #885\n%! clear f x % if test not isolated (e.g., on matlab)\n%! syms x\n%! f(x) = sym('S(x)');\n%! f(x) = sym('I(x)');\n%! f(x) = sym('O(x)');\n\n%!test\n%! % sym(sympy(x) == x identity, Issue #890\n%! syms x\n%! f = exp (1i*x);\n%! s = sympy (f);\n%! g = sym (s);\n%! assert (isequal (f, g))\n\n%!test\n%! % sym(sympy(x) == x identity\n%! % Don't mistake \"pi\" (which is \"srepr(S.Pi)\") for a symfun variable\n%! f = sym ('ff(pi, pi)');\n%! s1 = sympy (f);\n%! s2 = 'FallingFactorial(pi, pi)';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % sym(sympy(x) == x identity\n%! % Don't mistake \"I\" (which is \"srepr(S.ImaginaryUnit)\") for a symfun variable\n%! f = sym ('sin(I)');\n%! g = 1i*sinh (sym (1));\n%! assert (isequal (f, g))\n%! s = sympy (f);\n%! assert (isempty (strfind (s, 'Function')))\n\n%!error\n%! % sym(sympy(x) == x identity\n%! % Don't mistake \"true/false\" (which is \"srepr(S.true)\") for a symfun variable\n%! % (Used to print as `S.true` but just `true` in sympy 1.2)\n%! sym ('E(true,false)')\n\n%!test\n%! % some variable names that are special to sympy but should not be for us\n%! f = sym ('f(S, Q, C, O, N)');\n%! s1 = sympy (f);\n%! s2 = 'Function(''f'')(Symbol(''S''), Symbol(''Q''), Symbol(''C''), Symbol(''O''), Symbol(''N''))';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % For SMT 2014 compatibilty, I and E would become ImaginaryUnit and Exp(1)\n%! % but I'm not sure this is by design. This test would need to change if\n%! % we want stricter SMT compatibilty.\n%! f = sym ('f(x, I, E)');\n%! s1 = sympy (f);\n%! s2 = 'Function(''f'')(Symbol(''x''), Symbol(''I''), Symbol(''E''))';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % not the identity, force symfun\n%! f = sym ('FF(w)');\n%! s1 = sympy (f);\n%! s2 = 'Function(''FF'')(Symbol(''w''))';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % not the identity, force symfun\n%! f = sym ('FF(w, pi)');\n%! s1 = sympy (f);\n%! s2 = 'Function(''FF'')(Symbol(''w''), pi)';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % not the identity, force symfun\n%! f = sym ('ff(x, y)');\n%! s1 = sympy (f);\n%! s2 = 'Function(''ff'')(Symbol(''x''), Symbol(''y''))';\n%! assert (strcmp (s1, s2))\n\n%!test\n%! % But this one should satisfy \"sym(sympy(x) == x\" identity\n%! % (OOTB, SymPy has ff -> FallingFactorial)\n%! f = sym ('FallingFactorial(x, y)');\n%! s1 = sympy (f);\n%! s2 = 'FallingFactorial(Symbol(''x''), Symbol(''y''))';\n%! assert (strcmp (s1, s2))\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.359364131437828, "lm_q2_score": 0.07807816246341381, "lm_q1q2_score": 0.028058491037926334}} {"text": "function [eigVec, eigVal, mmPerVox] = dtiLoadTensor(vectorsBasename, tensorBasename, b0Basename)\n% [eigVec, eigVal, mmPerVox] = dtiLoadTensor([vectorsBasename], [tensorBasename], [b0Basename])\n% \n% 'eigVec' is a 5d array- a 3d array of 3x3 eigenVectors. \n% To get the eigenVector for a particular voxel, use: v = eigVec(x,y,z,:,:);\n%\n% If you also provide the 'Tensor.float' file, then the eigen values are\n% also returned (eigVal).\n%\n% If you provide the B0 filename, then we can get some useful info from the\n% header, like the voxel dimensions.\n%\n% Loads the 3x3 matrix from the tensorcalc-format 'Vectors.float' file.\n% The Vectors.float files are 32-bit floating point arrays (raw data- no header) \n% with 9 images per file: \n% X1, Y1, Z1 = (signed) components of the eigenvector corresponding to the \n% largest eigenvalue. \n% X2, Y2, Z2 = (signed) components of the eigenvector corresponding to the \n% middle eigenvalue. \n% X3, Y3, Z3 = (signed) components of the eigenvector corresponding to the \n% smallest eigenvalue. \n% All vectors are unit vectors.\n%\n%\n% HISTORY:\n% 2002.08.16 RFD (bobd@stanford.edu) Wrote it.\n% 2003.11.13 RFD changed to return eigen vectors and values separately.\n% 2003.11.26 RFD- we now get some useful info from the B0 header, if it's available.\n%\n% TODO:\n%\n%\n% EXAMPLE:\n% [eigVec,eigVal] = dtiLoadTensor('Vectors.float','Tensor.float');\n% meanDiffusivity = sum(eigVal,4)/3;\n% stdevDiffusivity = sqrt(sum((eigVal-repmat(meanDiffusivity,[1,1,1,3])).^2,4));\n% normDiffusivity = sqrt(sum(eigVal.^2,4));\n% fa = sqrt(3/2).*(stdevDiffusivity./normDiffusivity);\n% \n\nif(~exist('vectorsBasename', 'var') | isempty(vectorsBasename))\n [f,p] = uigetfile({'*.001';'*.*'},'Select a slice from the Vectors file...');\n vectorsBasename = fullfile(p,f(1:end-3));\n tensorBasename = fullfile(p,'Tensor.float.');\n b0Basename = fullfile(p,'B0.');\nend\nif(~exist('tensorBasename', 'var') | isempty(tensorBasename))\n tensorBasename = fullfile(fileparts(vectorsBasename),'Tensor.float.');\nelse\n if(tensorBasename(end) ~= '.')\n tensorBasename = [tensorBasename '.'];\n end\nend\nif(~exist('b0Basename', 'var') | isempty(b0Basename))\n b0Basename = fullfile(fileparts(vectorsBasename),'B0.');\nelse\n if(b0Basename(end) ~= '.')\n b0Basename = [b0Basename '.'];\n end\nend\n\nif(vectorsBasename(end) ~= '.')\n vectorsBasename = [vectorsBasename '.'];\nend\n\nnSlices = length(dir([vectorsBasename,'*']));\nif(~isempty(b0Basename))\n [su,ex,se,im] = readIfileHeader([b0Basename,'001']);\n imdim = [im.imatrix_X, im.imatrix_Y, nSlices];\n mmPerVox = [im.pixsize_X, im.pixsize_Y, im.slthick];\nelse\n warning('B0 file not provided- guessing parameters!');\n mmPerVox = [260/128 260/128 3];\n % Now try to guess the image size\n d = dir([vectorsBasename,'001']);\n % OK- there are 9*4=36 bytes per voxel -> d.bytes/36 voxels. log2 tells us\n % how many bits this requires. We assume that the bits are divided equally\n % between X and Y (thus the /2), and then convert from bits to decimal (2^)\n xySize = 2^(log2(d.bytes./36)./2);\n imdim = [xySize,xySize,nSlices];\n disp(['I''m guessing that the image dimension is [',num2str(imdim),'].']);\nend\n\nnpix = imdim(1)*imdim(2);\neigVec = zeros([imdim,3,3]);\nif(~isempty(tensorBasename))\n eigVal = zeros([imdim,3]);\nelse\n eigVal = [];\nend\ndisp(['Reading ',num2str(nSlices),' slices...']);\nfor(ii=1:imdim(3))\n fname = sprintf('%s%03d', vectorsBasename, ii);\n fid = fopen(fname, 'rb', 'ieee-be');\n eigVec(:,:,ii,:,:) = reshape(fread(fid, inf, 'float32'),[imdim(1),imdim(2),1,3,3]);\n fclose(fid);\n % Unfortunately, tensorcalc stores only the unit vectors in the Vectors\n % file. So, we need to open up the corresponding Tensor file and get\n % the eigenvalues from there.\n if(~isempty(tensorBasename))\n fname = sprintf('%s%03d', tensorBasename, ii);\n % 2004.03.26 RFD: Data now in ieee-le format?\n fid = fopen(fname, 'rb', 'ieee-be');\n % The eigen values are in the 2:4 sections of the Tensor.float\n % file. Here, we just read the first four sections.\n tmp = fread(fid, npix*4, 'float32');\n % Drop the first section, since it's the mean diffusivity.\n tmp = tmp(npix+1:end);\n fclose(fid);\n eigVal(:,:,ii,1) = reshape(tmp(1:npix), imdim(1), imdim(2));\n eigVal(:,:,ii,2) = reshape(tmp(npix+1:npix*2), imdim(1), imdim(2));\n eigVal(:,:,ii,3) = reshape(tmp(npix*2+1:npix*3), imdim(1), imdim(2));\n end\nend\nreturn;\n\n% Genreal notes about tensorcalc data:\n% Each slice is in a separate file. Included are two different data file types,\n% Tensor.float and Vectors.float. Tensor.float contains most of the info that\n% you would need to do fiber tracing, except that it does not contain the \n% eigenvectors corresponding to the two smaller eigenvalues. Vectors.float \n% contains all 3 eigenvectors. (For more info about these files, see \n% http://sirl.stanford.edu/dwi/maj/)\n% \n% Tensor.float files are 32-bit floating point arrays (raw data- no header) \n% containing the following maps:\n% \n% 1. Mean diffusivity (or Trace/3, units x106 mm2/s)\n% 2. Maximum eigenvalue\n% 3. Medium eigenvalue \n% 4. Minimum eigenvalue \n% 5. X component of the maximum eigenvector (values between -1 and 1) \n% 6. Y component of the maximum eigenvector \n% 7. Z component of the maximum eigenvector \n% 8. Fractional Anisotropy, FA (multiplied by 1000) \n% 9. Lattice index, Add (if asked for via -Add option) \n% 10. Coherence index, CI (if asked for via -CI option) \n% 11. b=0 image (arbitrary units) \n% \n% Sample matlab code to read these files:\n% \n% baseName = 'Tensor.float.';\n% imDim = [128,128,38];\n% meanDiffusion = zeros(imDim);\n% maxEigVal = zeros(imDim);\n% medEigVal = zeros(imDim);\n% minEigVal = zeros(imDim);\n% maxEigValX = zeros(imDim);\n% maxEigValY = zeros(imDim);\n% maxEigValZ = zeros(imDim);\n% fa = zeros(imDim);\n% for(ii=1:imDim(3))\n% fname = sprintf('%s%03d', baseName, ii);\n% fid = fopen(fname, 'rb', 'ieee-be');\n% tmp = reshape(fread(fid, inf, 'float32'),[imDim(1),imDim(2),11]);\n% fclose(fid);\n% meanDiffusion(:,:,ii) = tmp(:,:,1);\n% maxEigVal(:,:,ii) = tmp(:,:,2);\n% medEigVal(:,:,ii) = tmp(:,:,3);\n% minEigVal(:,:,ii) = tmp(:,:,4);\n% maxEigValX(:,:,ii) = tmp(:,:,5);\n% maxEigValY(:,:,ii) = tmp(:,:,6);\n% maxEigValZ(:,:,ii) = tmp(:,:,7);\n% fa(:,:,ii) = tmp(:,:,8);\n% b0(:,:,ii) = tmp(:,:,11);\n% end\n\n\n\n\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/file/tensors/dtiLoadTensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05419873173281515, "lm_q1q2_score": 0.027099365866407574}} {"text": "function [stepsize newx storedb lsmem lsstats] = ...\n linesearch(problem, x, d, f0, df0, options, storedb, lsmem)\n% Standard line search algorithm (step size selection) for descent methods.\n%\n% function [stepsize newx storedb lsmem lsstats] = \n% linesearch(problem, x, d, f0, df0, options, storedb, lsmem)\n%\n% Base linesearch algorithm for descent methods, based on a simple\n% backtracking method. The search direction provided has to be a descent\n% direction, as indicated by a negative df0 = directional derivative of f\n% at x along d.\n%\n% The algorithm is invariant under positive scaling of the cost function\n% and under offsetting, that is: if the cost function f is replaced by\n% 8*f+3 for example, the returned step size will be the same. Furthermore,\n% the returned step size is independent of the norm of the search direction\n% vector d: only the direction of d is important.\n% \n% Below, the step will be constructed as alpha*d, and the step size is the\n% norm of that vector, thus: stepsize = alpha*norm_d. The step is executed\n% by retracting the vector alpha*d from the current point x, giving newx.\n%\n% Inputs\n%\n% problem : structure holding the description of the optimization problem\n% x : current point on the manifold problem.M\n% d : tangent vector at x (descent direction) -- its norm is irrelevant\n% f0 : cost value at x\n% df0 : directional derivative at x along d\n% options : options structure (see in code for usage)\n% storedb : store database structure for caching purposes\n% lsmem : a special memory holder to give the linesearch the opportunity\n% to \"remember\" what happened in the previous calls. See below.\n%\n% Outputs\n%\n% stepsize : norm of the vector retracted to reach newx from x.\n% newx : next iterate suggested by the line search algorithm, such that\n% the retraction at x of the vector alpha*d reaches newx.\n% storedb : the (possibly updated) store database structure.\n% lsmem : the (possibly updated) lsmem memory holder.\n% lsstats : statistics about the line search procedure (stepsize, number\n% of trials etc).\n% \n% About lsmem : It can be anything, and will typically be a matrix or a\n% structure. When first calling the line search, it should be\n% passed as the empty matrix []. For subsequent calls\n% (pertaining to the same solver call), the previously\n% returned lsmem should be passed as input. This memory\n% holder gives the line search a chance to exploit knowledge\n% of previous decisions to make new decisions.\n%\n% See also: steepestdescent conjugategradients linesearch_adaptive\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n% Sept. 13, 2013 (NB) : User control over the parameters of the\n% linesearch via the options\n% ls_contraction_factor, ls_optimism,\n% ls_suff_decr and ls_max_steps. See in code for\n% the effect of those.\n% Sept. 13, 2013 (NB) : The automatic direction reversal feature was\n% removed (it triggered when df0 > 0). Direction\n% reversal is a decision that needs to be made by\n% the solver, so it can know about it.\n% Sept. 13, 2013 (NB) : The linesearch is now invariant under rescaling\n% of the cost function f. That is, if f is\n% replaced by 8*f (and hence the directional\n% derivatives of f are scaled accordingly), the\n% stepsizes computed will not change.\n% Nov. 7, 2013 (NB) : The linesearch is now invariant under rescaling\n% of the search direction d. The meaning of\n% stepsize is also more clear in the comments.\n% Added a parameter ls_initial_stepsize to give\n% users control over the first step size trial.\n\n\n % Backtracking default parameters. These can be overwritten in the\n % options structure which is passed to the solver.\n default_options.ls_contraction_factor = .5;\n default_options.ls_optimism = 1/.5;\n default_options.ls_suff_decr = 1e-4;\n default_options.ls_max_steps = 25;\n default_options.ls_initial_stepsize = 1;\n \n options = mergeOptions(default_options, options);\n \n contraction_factor = options.ls_contraction_factor;\n optimism = options.ls_optimism;\n suff_decr = options.ls_suff_decr;\n max_ls_steps = options.ls_max_steps;\n initial_stepsize = options.ls_initial_stepsize;\n \n % Compute the norm of the search direction.\n % This is useful to make the linesearch algorithm invariant under the\n % scaling of d. The rationale is that the important information is the\n % search direction, not the size of that vector. The question of how\n % far we should go is precisely what the linesearch algorithm is\n % supposed to answer: the calling algorithm should not need to care.\n norm_d = problem.M.norm(x, d);\n \n % At first, we have no idea of what the step size should be.\n alpha = NaN;\n \n % If we know about what happened at the previous step, we can leverage\n % that to compute an initial guess for the step size, as inspired from\n % Nocedal&Wright, p59.\n if isstruct(lsmem) && isfield(lsmem, 'f0')\n % Pick initial step size based on where we were last time,\n alpha = 2*(f0-lsmem.f0)/df0;\n % and go look a little further (or less far), just in case.\n alpha = optimism*alpha;\n end\n \n % If we have no information about the previous iteration (maybe this is\n % the first one?) or if the above formula gave a too small step size\n % (perhaps it is even negative), then fall back to a user supplied\n % suggestion for the first step size (the \"a priori\").\n % At any rate, the choice should be invariant under rescaling of the\n % cost function f and of the search direction d, and it should be\n % bounded away from zero for convergence guarantees. We must allow it\n % to be close to zero though, for fine convergence.\n if isnan(alpha) || alpha*norm_d <= eps\n alpha = initial_stepsize/norm_d;\n end\n \n\n % Make the chosen step and compute the cost there.\n newx = problem.M.retr(x, d, alpha);\n [newf storedb] = getCost(problem, newx, storedb);\n cost_evaluations = 1;\n \n % Backtrack while the Armijo criterion is not satisfied\n while newf > f0 + suff_decr*alpha*df0\n \n % Reduce the step size,\n alpha = contraction_factor * alpha;\n \n % and look closer down the line\n newx = problem.M.retr(x, d, alpha);\n [newf storedb] = getCost(problem, newx, storedb);\n cost_evaluations = cost_evaluations + 1;\n \n % Make sure we don't run out of budget\n if cost_evaluations >= max_ls_steps\n break;\n end\n \n end\n \n % If we got here without obtaining a decrease, we reject the step.\n if newf > f0\n alpha = 0;\n newx = x;\n newf = f0; %#ok\n end\n \n % As seen outside this function, stepsize is the size of the vector we\n % retract to make the step from x to newx. Since the step is alpha*d:\n stepsize = alpha * norm_d;\n\n % Save the situtation faced now so that at the next iteration, we will\n % know something about the previous decision.\n lsmem.f0 = f0;\n lsmem.df0 = df0;\n lsmem.stepsize = stepsize;\n \n % Save some statistics also, for possible analysis.\n lsstats.costevals = cost_evaluations;\n lsstats.stepsize = stepsize;\n lsstats.alpha = alpha;\n \nend\n", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/Riemannian_DL_SC_SPD/manopt/manopt/solvers/linesearch/linesearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.054198728677407874, "lm_q1q2_score": 0.027099364338703937}} {"text": "%% Copyright (C) 2014-2016, 2018-2019, 2022 Colin B. Macdonald\n%% Copyright (C) 2014-2015 Andrés Prieto\n%% Copyright (C) 2020 Rafael Laboissière\n%% Copyright (C) 2020 Jing-Chen Peng\n%%\n%% This file is part of OctSymPy.\n%%\n%% OctSymPy is free software; you can redistribute it and/or modify\n%% it under the terms of the GNU General Public License as published\n%% by the Free Software Foundation; either version 3 of the License,\n%% or (at your option) any later version.\n%%\n%% This software is distributed in the hope that it will be useful,\n%% but WITHOUT ANY WARRANTY; without even the implied warranty\n%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\n%% the GNU General Public License for more details.\n%%\n%% You should have received a copy of the GNU General Public\n%% License along with this software; see the file COPYING.\n%% If not, see .\n\n%% -*- texinfo -*-\n%% @documentencoding UTF-8\n%% @deftypemethod @@sym {@var{sol} =} dsolve (@var{ode})\n%% @deftypemethodx @@sym {@var{sol} =} dsolve (@var{ode}, @var{IC})\n%% @deftypemethodx @@sym {@var{sol} =} dsolve (@var{ODEs}, @var{IC1}, @var{IC2}, @dots{})\n%% @deftypemethodx @@sym {@var{sol} =} dsolve (@var{ODEs}, @var{ICs})\n%% @deftypemethodx @@sym {[@var{sol}, @var{classify}] =} dsolve (@dots{})\n%% Solve ordinary differential equations (ODEs) symbolically.\n%%\n%% Basic example:\n%% @example\n%% @group\n%% syms y(x)\n%% DE = diff(y, x) - 4*y == 0\n%% @result{} DE = (sym)\n%% d\n%% -4⋅y(x) + ──(y(x)) = 0\n%% dx\n%% @end group\n%%\n%% @group\n%% sol = dsolve (DE)\n%% @result{} sol = (sym)\n%% 4⋅x\n%% C₁⋅ℯ\n%% @end group\n%% @end example\n%%\n%% You can specify initial conditions:\n%% @example\n%% @group\n%% sol = dsolve (DE, y(0) == 1)\n%% @result{} sol = (sym)\n%% 4⋅x\n%% ℯ\n%% @end group\n%% @end example\n%%\n%% In some cases, SymPy can return a classification of the\n%% differential equation:\n%% @example\n%% @group\n%% DE = diff(y) == y^2\n%% @result{} DE = (sym)\n%% d 2\n%% ──(y(x)) = y (x)\n%% dx\n%%\n%% [sol, classify] = dsolve (DE, y(0) == 1)\n%% @result{} sol = (sym)\n%% -1\n%% ─────\n%% x - 1\n%% @result{} classify = ... separable ...\n%% @end group\n%% @end example\n%%\n%% Many types of ODEs can be solved, including initial-value\n%% problems and boundary-value problem:\n%% @example\n%% @group\n%% DE = diff(y, 2) == -9*y\n%% @result{} DE = (sym)\n%% 2\n%% d\n%% ───(y(x)) = -9⋅y(x)\n%% 2\n%% dx\n%%\n%% dsolve (DE, y(0) == 1, diff(y)(0) == 12)\n%% @result{} (sym) 4⋅sin(3⋅x) + cos(3⋅x)\n%%\n%% dsolve (DE, y(0) == 1, y(sym(pi)/2) == 2)\n%% @result{} (sym) -2⋅sin(3⋅x) + cos(3⋅x)\n%% @end group\n%% @end example\n%%\n%% Some systems can be solved, including initial-value problems\n%% involving linear systems of first order ODEs with constant\n%% coefficients:\n%% @example\n%% @group\n%% syms x(t) y(t)\n%% ode_sys = [diff(x(t),t) == 2*y(t); diff(y(t),t) == 2*x(t)]\n%% @result{} ode_sys = (sym 2×1 matrix)\n%% ⎡d ⎤\n%% ⎢──(x(t)) = 2⋅y(t)⎥\n%% ⎢dt ⎥\n%% ⎢ ⎥\n%% ⎢d ⎥\n%% ⎢──(y(t)) = 2⋅x(t)⎥\n%% ⎣dt ⎦\n%% @end group\n%%\n%% @group\n%% soln = dsolve (ode_sys)\n%% @result{} soln = scalar structure containing ...\n%% x = ...\n%% y = ...\n%%\n%% @c doctest: +SKIP_IF(pycall_sympy__ ('return Version(spver) <= Version(\"1.5.1\")'))\n%% soln.x\n%% @result{} ans =\n%% (sym)\n%% -2⋅t 2⋅t\n%% - C₁⋅ℯ + C₂⋅ℯ\n%%\n%% @c doctest: +SKIP_IF(pycall_sympy__ ('return Version(spver) <= Version(\"1.5.1\")'))\n%% soln.y\n%% @result{} ans =\n%% (sym)\n%% -2⋅t 2⋅t\n%% C₁⋅ℯ + C₂⋅ℯ\n%% @end group\n%% @end example\n%%\n%% Note: The Symbolic Math Toolbox used to support strings like 'Dy + y = 0'; we\n%% are unlikely to support this so you will need to assemble a symbolic\n%% equation instead.\n%%\n%% @seealso{@@sym/diff, @@sym/int, @@sym/solve}\n%% @end deftypemethod\n\n\nfunction [soln,classify] = dsolve(ode,varargin)\n\n % Usually we cast to sym in the _cmd call, but want to be\n % careful here b/c of symfuns\n if (~ iscell (ode) && ~ all (isa (ode, 'sym')))\n error('Inputs must be sym or symfun')\n end\n\n % FIXME: might be nice to expose SymPy's \"sp.ode.classify_sysode\" and\n % \"sp.ode.classify_ode\" with their own commands\n if (isscalar(ode) && nargout==2)\n cmd = { 'from sympy.solvers import classify_ode'\n 'return classify_ode(_ins[0]),' };\n classify = pycall_sympy__ (cmd, ode);\n elseif(~isscalar(ode) && nargout==2)\n warning('Classification of systems of ODEs is currently not supported')\n classify='';\n end\n\n cmd = { 'ode=_ins[0]; ics=_ins[1:]'\n 'if len(ics) == 1:'\n ' ics = ics[0]'\n 'try:'\n ' ics = {ic.lhs: ic.rhs for ic in ics}'\n 'except TypeError:' % not iterable\n ' ics = {ics.lhs: ics.rhs}'\n 'sol = sp.dsolve(ode, ics=ics)'\n 'def convert_helper(sympy_obj):'\n ' if isinstance(sympy_obj, Eq) and sympy_obj.lhs.is_Function:'\n % y(t) = rhs to str \"y\", rhs expression\n ' return str(sympy_obj.lhs.func), sympy_obj.rhs'\n ' return None, None'\n % if just single equality with simple lhs, we return the rhs\n 'if isinstance(sol, Eq):'\n ' if sol.lhs.is_Function:'\n ' return sol.rhs'\n % If the solution set is iterable (system or multiple solutions),\n % we will try to convert to structure of {\"x\": expr, \"y\": expr2, ...}\n 'try:'\n ' return_data = dict()'\n ' for solution_part in sol:'\n ' key, rhs = convert_helper(solution_part)'\n ' if key is None:'\n ' raise ValueError(\"not of right form for extraction\")'\n ' if key in return_data.keys():'\n ' raise KeyError(f\"repeated key {key}\")'\n ' return_data[key] = rhs'\n ' return return_data'\n 'except (TypeError, ValueError, KeyError):'\n ' pass'\n % if nothing else worked, give back whatever form we have\n 'return sol' };\n soln = pycall_sympy__ (cmd, ode, varargin{:});\nend\n\n\n%!error dsolve (1, sym('x'))\n\n%!test\n%! syms y(x)\n%! de = diff(y, 2) - 4*y == 0;\n%! f = dsolve(de);\n%! syms C1 C2\n%! g1 = C1*exp(-2*x) + C2*exp(2*x);\n%! g2 = C2*exp(-2*x) + C1*exp(2*x);\n%! assert (isequal (f, g1) || isequal (f, g2))\n\n%!test\n%! % Not enough initial conditions\n%! syms y(x) C1\n%! de = diff(y, 2) + 4*y == 0;\n%! g = 3*cos(2*x) + C1*sin(2*x);\n%! try\n%! f = dsolve(de, y(0) == 3);\n%! waserr = false;\n%! catch\n%! waserr = true;\n%! expectederr = regexp (lasterr (), 'Perhaps.*under-specified');\n%! f = 42;\n%! end\n%! assert ((waserr && expectederr) || isequal (f, g))\n\n%!test\n%! % Solution in implicit form\n%! syms y(x) C1\n%! de = (2*x*y(x) - exp(-2*y(x)))*diff(y(x), x) + y(x) == 0;\n%! sol = dsolve (de);\n%! eqn = x*exp(2*y(x)) - log(y(x)) == C1;\n%! % could differ by signs\n%! sol = lhs (sol) - rhs (sol);\n%! eqn = lhs (eqn) - rhs (eqn);\n%! sol2 = subs (sol, C1, -C1);\n%! assert (isequal (sol, eqn) || isequal (sol2, eqn))\n\n%%!xtest\n%%! % system with solution in implicit form\n%%! % TODO: not implemented upstream?\n%%! syms y(x) z(x) C1\n%%! de1 = (2*x*y(x) - exp(-2*y(x)))*diff(y(x), x) + y(x) == 0;\n%%! de2 = diff(z, x) == 0;\n%%! sol = dsolve ([de1; de2]);\n\n%!test\n%! % Compute solution and classification\n%! syms y(x) C1\n%! de = (2*x*y(x) - exp(-2*y(x)))*diff(y(x), x) + y(x) == 0;\n%! [sol, classy] = dsolve (de);\n%! assert (any (strcmp (classy, '1st_exact')))\n\n%!test\n%! % initial conditions (first order ode)\n%! syms y(x)\n%! de = diff(y, x) + 4*y == 0;\n%! f = dsolve(de, y(0) == 3);\n%! g = 3*exp(-4*x);\n%! assert (isequal (f, g))\n\n%!test\n%! % initial conditions (second order ode)\n%! syms y(x)\n%! de = diff(y, 2) + 4*y == 0;\n%! f = dsolve(de, y(0) == 3, subs(diff(y,x),x,0)==0);\n%! g = 3*cos(2*x);\n%! assert (isequal (f, g))\n\n%!test\n%! % Dirichlet boundary conditions (second order ode)\n%! syms y(x)\n%! de = diff(y, 2) + 4*y == 0;\n%! f = dsolve(de, y(0) == 2, y(1) == 0);\n%! g = -2*sin(2*x)/tan(sym('2'))+2*cos(2*x);\n%! assert (isequal (simplify (f - g), 0))\n\n%!test\n%! % Neumann boundary conditions (second order ode)\n%! syms y(x)\n%! de = diff(y, 2) + 4*y == 0;\n%! f = dsolve(de, subs(diff(y,x),x,0)==1, subs(diff(y,x),x,1)==0);\n%! g = sin(2*x)/2+cos(2*x)/(2*tan(sym('2')));\n%! assert (isequal (simplify (f - g), 0))\n\n%!test\n%! % Dirichlet-Neumann boundary conditions (second order ode)\n%! syms y(x)\n%! de = diff(y, 2) + 4*y == 0;\n%! f = dsolve(de, y(0) == 3, subs(diff(y,x),x,1)==0);\n%! g = 3*sin(2*x)*tan(sym('2'))+3*cos(2*x);\n%! assert (isequal (simplify (f - g), 0))\n\n%!test\n%! % System of ODEs gives struct, Issue #1003.\n%! syms x(t) y(t)\n%! ode1 = diff(x(t),t) == 2*y(t);\n%! ode2 = diff(y(t),t) == 2*x(t);\n%! soln = dsolve([ode1, ode2]);\n%! assert (isstruct (soln))\n%! assert (numfields (soln) == 2)\n%! assert (isequal (sort (fieldnames (soln)), {'x'; 'y'}))\n\n%!test\n%! % System of ODEs\n%! syms x(t) y(t) C1 C2\n%! ode1 = diff(x(t),t) == 2*y(t);\n%! ode2 = diff(y(t),t) == 2*x(t);\n%! soln = dsolve([ode1, ode2]);\n%! soln = [soln.x, soln.y];\n%! g1 = [C1*exp(-2*t) + C2*exp(2*t), -C1*exp(-2*t) + C2*exp(2*t)];\n%! g2 = [C1*exp(2*t) + C2*exp(-2*t), C1*exp(2*t) - C2*exp(-2*t)];\n%! g3 = [-C1*exp(-2*t) + C2*exp(2*t), C1*exp(-2*t) + C2*exp(2*t)];\n%! g4 = [C1*exp(2*t) - C2*exp(-2*t), C1*exp(2*t) + C2*exp(-2*t)];\n%! % old SymPy <= 1.5.1 had some extra twos\n%! g5 = [2*C1*exp(-2*t) + 2*C2*exp(2*t), -2*C1*exp(-2*t) + 2*C2*exp(2*t)];\n%! g6 = [2*C1*exp(2*t) + 2*C2*exp(-2*t), 2*C1*exp(2*t) - 2*C2*exp(-2*t)];\n%! assert (isequal (soln, g1) || isequal (soln, g2) || ...\n%! isequal (soln, g3) || isequal (soln, g4) || ...\n%! isequal (soln, g5) || isequal (soln, g6))\n\n%!test\n%! % System of ODEs (initial-value problem)\n%! syms x(t) y(t)\n%! ode_1=diff(x(t),t) == 2*y(t);\n%! ode_2=diff(y(t),t) == 2*x(t);\n%! sol_ivp=dsolve([ode_1,ode_2],x(0)==1,y(0)==0);\n%! g_ivp=[exp(-2*t)/2+exp(2*t)/2,-exp(-2*t)/2+exp(2*t)/2];\n%! assert (isequal ([sol_ivp.x, sol_ivp.y], g_ivp))\n\n%!test\n%! syms y(x)\n%! de = diff(y, 2) + 4*y == 0;\n%! f = dsolve(de, y(0) == 0, y(sym(pi)/4) == 1);\n%! g = sin(2*x);\n%! assert (isequal (f, g))\n\n%!test\n%! % Nonlinear example\n%! syms y(x) C1\n%! e = diff(y, x) == y^2;\n%! g = -1 / (C1 + x);\n%! soln = dsolve(e);\n%! assert (isequal (soln, g))\n\n%!test\n%! % Nonlinear example with initial condition\n%! syms y(x)\n%! e = diff(y, x) == y^2;\n%! g = -1 / (x - 1);\n%! soln = dsolve(e, y(0) == 1);\n%! assert (isequal (soln, g))\n\n%!test\n%! % forcing, Issue #183, broken in older sympy\n%! if (pycall_sympy__ ('return Version(spver) >= Version(\"1.7.1\")'))\n%! syms x(t) y(t)\n%! ode1 = diff(x) == x + sin(t) + 2;\n%! ode2 = diff(y) == y - t - 3;\n%! soln = dsolve([ode1 ode2], x(0) == 1, y(0) == 2);\n%! X = soln.x;\n%! Y = soln.y;\n%! assert (isequal (diff(X) - (X + sin(t) + 2), 0))\n%! assert (isequal (diff(Y) - (Y - t - 3), 0))\n%! end\n\n%!test\n%! syms f(x) a b\n%! de = diff(f, x) == 4*f;\n%! s = dsolve(de, f(a) == b);\n%! assert (isequal (subs(s, x, a), b))\n\n%!test\n%! % array of ICs\n%! syms x(t) y(t)\n%! ode_1 = diff (x(t), t) == 2*y(t);\n%! ode_2 = diff (y(t), t) == 2*x(t);\n%! sol = dsolve([ode_1, ode_2], [x(0)==1 y(0)==0]);\n%! g = [exp(-2*t)/2+exp(2*t)/2, -exp(-2*t)/2+exp(2*t)/2];\n%! assert (isequal ([sol.x, sol.y], g))\n\n%!test\n%! % cell-array of ICs or ODEs, but not both\n%! % Note: to support both we'd need a wrapper outside of @sym\n%! syms x(t) y(t)\n%! ode_1 = diff (x(t), t) == 2*y(t);\n%! ode_2 = diff (y(t), t) == 2*x(t);\n%! sol = dsolve([ode_1, ode_2], {x(0)==1 y(0)==0});\n%! g = [exp(-2*t)/2+exp(2*t)/2, -exp(-2*t)/2+exp(2*t)/2];\n%! assert (isequal ([sol.x, sol.y], g))\n%! sol = dsolve({ode_1, ode_2}, [x(0)==1 y(0)==0]);\n%! g = [exp(-2*t)/2+exp(2*t)/2, -exp(-2*t)/2+exp(2*t)/2];\n%! assert (isequal ([sol.x, sol.y], g))\n\n%!test\n%! % array of ICs, Issue #1040.\n%! if (pycall_sympy__ ('return Version(spver) >= Version(\"1.7.1\")'))\n%! syms x(t) y(t) z(t)\n%! syms x_0 y_0 z_0\n%! diffEqns = [diff(x, t) == -x + 1, diff(y, t) == -y, diff(z, t) == -z];\n%! initCond = [x(0) == x_0, y(0) == y_0, z(0) == z_0];\n%! soln = dsolve (diffEqns, initCond);\n%! soln = [soln.x, soln.y, soln.z];\n%! exact_soln = [(x_0 - 1)*exp(-t) + 1 y_0*exp(-t) z_0*exp(-t)];\n%! assert (isequal (soln, exact_soln))\n%! end\n", "meta": {"author": "cbm755", "repo": "octsympy", "sha": "c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd", "save_path": "github-repos/MATLAB/cbm755-octsympy", "path": "github-repos/MATLAB/cbm755-octsympy/octsympy-c1ecd1e08f027d5101d0f4250dfc496aa98c8bcd/inst/@sym/dsolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3557748798522984, "lm_q2_score": 0.07585818785594478, "lm_q1q2_score": 0.026988437670261836}} {"text": "% MP_INTERFACE_HCURL: create a global numbering of basis functions in multipatch domains, assigning the correct orientation for tangential traces.\n%\n% [glob_num, glob_ndof, dofs_ornt] = mp_interface_hcurl (interfaces, sp);\n%\n% INPUT:\n%\n% interfaces: structure with the information of the interfaces between patches (see mp_geo_read_file)\n% sp: object representing the space of discrete functions, with the curl-preserving transform (see sp_vector)\n%\n% OUTPUT:\n%\n% glob_num: global numbering of the discrete basis functions\n% glob_ndof: total number of degrees of freedom\n% dofs_ornt: a cell-array with the orientation of the basis functions\n%\n% Copyright (C) 2010, 2011, 2015 Rafael Vazquez\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n\nfunction [glob_num, glob_ndof, dofs_ornt] = mp_interface_hcurl (interfaces, sp)\n\n npatch = numel (sp);\n \n ndim = size (sp{1}.ndof_dir, 2);\n\n if (~isempty (interfaces))\n glob_num = cell (npatch, 1);\n dofs_ornt = cell (npatch, 1);\n% patch_intrfc is only used for ndim == 3\n patch_intrfc = cell (npatch, 1);\n\n ttform = cell (ndim-1, npatch, numel (interfaces));\n ppnum = cell (ndim-1, numel (interfaces));\n\n for iptc = 1:npatch\n glob_num{iptc} = zeros (1, sp{iptc}.ndof);\n dofs_ornt{iptc} = ones (1, sp{iptc}.ndof);\n patch_intrfc{iptc} = union (find([interfaces.patch1] == iptc), ...\n find([interfaces.patch2] == iptc));\n end\n\n for intrfc = 1:numel(interfaces)\n iptc1 = interfaces(intrfc).patch1;\n iptc2 = interfaces(intrfc).patch2;\n iside1 = interfaces(intrfc).side1;\n iside2 = interfaces(intrfc).side2;\n for idim = 1:ndim-1\n ttform{idim,iptc1, intrfc} = sp{iptc1}.boundary(iside1).dofs(sp{iptc1}.boundary(iside1).comp_dofs{idim});\n nghbr_dofs{idim} = reshape (sp{iptc2}.boundary(iside2).dofs(sp{iptc2}.boundary(iside2).comp_dofs{idim}), ...\n\t\t\t\t [sp{iptc2}.boundary(iside2).ndof_dir(idim,:), 1]);\n end\n if (ndim == 2)\n if (interfaces(intrfc).ornt == -1)\n nghbr_dofs{1} = flipud (nghbr_dofs{1});\n end\n elseif (ndim == 3)\n if (interfaces(intrfc).flag == -1)\n aux = nghbr_dofs{1};\n nghbr_dofs{1} = nghbr_dofs{2}';\n nghbr_dofs{2} = aux';\n end\n if (interfaces(intrfc).ornt1 == -1)\n nghbr_dofs{1} = flipud (nghbr_dofs{1});\n nghbr_dofs{2} = flipud (nghbr_dofs{2});\n end\n if (interfaces(intrfc).ornt2 == -1)\n nghbr_dofs{1} = fliplr (nghbr_dofs{1});\n nghbr_dofs{2} = fliplr (nghbr_dofs{2});\n end\n end\n for idim = 1:ndim-1\n ttform{idim,iptc2, intrfc} = nghbr_dofs{idim}(:)';\n ppnum{idim,intrfc} = zeros (1, numel(sp{iptc1}.boundary(iside1).comp_dofs{idim}));\n end\n end\n\n glob_ndof = 0;\n% We start with the dofs that do not belong to any interface\n for iptc = 1:npatch\n non_intrfc_dofs = setdiff(1:sp{iptc}.ndof, [ttform{:,iptc,:}]);\n glob_num{iptc}(non_intrfc_dofs) = glob_ndof + (1:numel(non_intrfc_dofs));\n glob_ndof = glob_ndof + numel (non_intrfc_dofs);\n end\n\n% Then we set the interfaces\n for intrfc = 1:numel(interfaces)\n iptc = interfaces(intrfc).patch1;\n iptc2 = interfaces(intrfc).patch2;\n\n for idim = 1:ndim-1\n new_dofs{idim} = find (glob_num{iptc}(ttform{idim, iptc, intrfc}) == 0);\n new_dofs_number = glob_ndof + (1:numel (new_dofs{idim}));\n glob_num{iptc}(ttform{idim, iptc, intrfc}(new_dofs{idim})) = new_dofs_number;\n dofs_ornt{iptc}(ttform{idim, iptc, intrfc}(new_dofs{idim})) = 1;\n ppnum{idim,intrfc}(new_dofs{idim}) = new_dofs_number;\n glob_ndof = glob_ndof + numel (new_dofs{idim});\n end\n\n if (ndim == 2)\n glob_num{iptc2}(ttform{1, iptc2, intrfc}) = ...\n glob_num{iptc}(ttform{1, iptc, intrfc});\n dofs_ornt{iptc2}(ttform{1, iptc2, intrfc}) = ...\n interfaces(intrfc).ornt * dofs_ornt{iptc}(ttform{1, iptc, intrfc});\n elseif (ndim == 3)\n [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, intrfc, ...\n ttform, new_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);\n [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc, intrfc, ...\n ttform, new_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);\n\n end\n end\n\n else\n glob_ndof = 0;\n glob_num = cell (npatch, 1);\n dofs_ornt = cell (npatch, 1);\n for iptc = 1:npatch\n glob_num{iptc} = glob_ndof + (1:sp{iptc}.ndof);\n glob_ndof = glob_ndof + sp{iptc}.ndof;\n dofs_ornt{iptc} = ones (1, sp{iptc}.ndof);\n end\n end \n\nend\n\n\nfunction [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc, intrfc, ...\n ttform, new_dofs, interfaces, glob_num, ...\n dofs_ornt, ppnum, patch_intrfc);\n\n for idim = 1:size(ttform, 1)\n intrfc_dofs{idim} = ttform{idim, iptc, intrfc}(new_dofs{idim});\n end\n\n for ii = setdiff (patch_intrfc{iptc}, intrfc)\n for idim = 1:size(ttform, 1)\n jdim = mod (idim, 2) + 1;\n [~, pos1{idim}, pos2{idim}] = intersect (ttform{idim, iptc, ii}, intrfc_dofs{idim});\n not_set_p1{idim} = find (ppnum{idim,ii}(pos1{idim}) == 0);\n\n [~, pos1b{idim}, pos2b{jdim}] = ...\n intersect (ttform{idim, iptc, ii}, intrfc_dofs{jdim});\n not_set_p1b{idim} = find (ppnum{idim, ii}(pos1b{idim}) == 0);\n end\n\n if (~(all (cellfun (@isempty, not_set_p1))))\n for idim = 1:size(ttform, 1)\n ppnum{idim,ii}(pos1{idim}(not_set_p1{idim})) = ...\n ppnum{idim,intrfc}(new_dofs{idim}(pos2{idim}(not_set_p1{idim})));\n renew_dofs{idim} = pos1{idim}(not_set_p1{idim});\n end\n [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, ii, ...\n ttform, renew_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);\n elseif (~(all (cellfun (@isempty, not_set_p1b))))\n for idim = 1:size(ttform, 1)\n jdim = mod (idim, 2) + 1;\n ppnum{idim,ii}(pos1b{idim}(not_set_p1b{idim})) = ...\n ppnum{jdim,intrfc}(new_dofs{jdim}(pos2b{jdim}(not_set_p1b{idim})));\n renew_dofs{idim} = pos1b{idim}(not_set_p1b{idim});\n end\n [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, ii, ...\n ttform, renew_dofs, interfaces, glob_num, dofs_ornt, ppnum, patch_intrfc);\n end\n end\nend\n\n\n\nfunction [glob_num, dofs_ornt, ppnum] = set_same_interface (iptc, intrfc, ...\n ttform, new_dofs, interfaces, glob_num, ...\n dofs_ornt, ppnum, patch_intrfc)\n\n ornt(1) = interfaces(intrfc).ornt1;\n ornt(2) = interfaces(intrfc).ornt2;\n\n iptc2 = setdiff ([interfaces(intrfc).patch1 interfaces(intrfc).patch2], iptc);\n for idim = 1:size(ttform, 1)\n intrfc_dofs{idim} = ttform{idim, iptc, intrfc}(new_dofs{idim});\n glob_num{iptc2}(ttform{idim, iptc2, intrfc}(new_dofs{idim})) = ...\n glob_num{iptc}(intrfc_dofs{idim});\n dofs_ornt{iptc2}(ttform{idim, iptc2, intrfc}(new_dofs{idim})) = ...\n ornt(idim) * dofs_ornt{iptc}(intrfc_dofs{idim});\n% interfaces(intrfc).ornt(idim) * dofs_ornt{iptc}(intrfc_dofs{idim});\n end\n\n [glob_num, dofs_ornt, ppnum] = set_same_patch (iptc2, intrfc, ...\n ttform, new_dofs, interfaces, glob_num, ...\n dofs_ornt, ppnum, patch_intrfc);\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/multipatch/mp_interface_hcurl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.05184546481851975, "lm_q1q2_score": 0.025720215182519296}} {"text": "function [ node_coord, node_att, node_marker ] = triangle_node_data_read ( ...\n node_filename, node_num, node_dim, node_att_num, node_marker_num )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_NODE_DATA_READ reads the data from a node file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 October 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string NODE_FILENAME, the name of the node file.\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer NODE_DIM, the spatial dimension.\n%\n% Input, integer NODE_ATT_NUM, number of node attributes \n% listed on each node record.\n%\n% Input, integer NODE_MARKER_NUM, 1 if every node record \n% includes a final boundary marker value.\n%\n% Output, real NODE_COORD(NODE_DIM,NODE_NUM), the nodal \n% coordinates.\n%\n% Output, real NODE_ATT(NODE_ATT_NUM,NODE_NUM), the nodal \n% attributes.\n%\n% Output, integer NODE_MARKER(NODE_MARKER_NUM,NODE_NUM), the \n% node markers.\n%\n node = 0;\n\n input = fopen ( node_filename, 'rt' );\n\n if ( input < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_NODE_DATA_READ - Fatal error!\\n' );\n fprintf ( 1, ' Unable to open file.\\n' );\n error ( 'TRIANGLE_NODE_DATA_READ - Fatal error!' );\n end\n%\n% Create format.\n%\n format = '%d';\n for i = 1 : node_dim\n format = strcat ( format, '%g' );\n end\n for i = 1 : node_att_num\n format = strcat ( format, '%g' );\n end\n for i = 1 : node_marker_num\n format = strcat ( format, '%d' );\n end\n%\n% Create arrays.\n%\n node_coord = zeros ( node_dim, node_num );\n node_att = zeros ( node_att_num, node_num );\n node_marker = zeros ( node_marker_num, node_num );\n%\n% Read values and place in the arrays.\n%\n while ( 1 )\n\n text = fgets ( input );\n\n if ( text == -1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_NODE_DATA_READ - Fatal error!\\n' );\n fprintf ( 1, ' Unexpected end of file while reading.\\n' );\n error ( 'TRIANGLE_NODE_DATA_READ - Fatal error!' );\n end\n\n if ( s_len_trim ( text ) == 0 )\n continue\n end\n\n if ( text(1) == '#' )\n continue\n end\n%\n% Ignore the dimension line.\n%\n if ( node == 0 )\n\n else\n\n [ value, count ] = sscanf ( text, format );\n\n if ( count < 1 + node_dim + node_att_num + node_marker_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_NODE_DATA_READ - Fatal error!\\n' );\n fprintf ( 1, ' Line did not have enough data.\\n' );\n error ( 'TRIANGLE_NODE_DATA_READ - Fatal error!' );\n end\n\n j = 1;\n\n for i = 1 : node_dim\n j = j + 1;\n node_coord(i,node) = value(j);\n end\n\n for i = 1 : node_att_num\n j = j + 1;\n node_att(i,node) = value(j);\n end\n\n for i = 1 : node_marker_num\n j = j + 1;\n node_marker(i,node) = value(j);\n end\n\n end\n\n node = node + 1;\n\n if ( node_num < node )\n break\n end\n\n end\n\n fclose ( input );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/triangle_io/triangle_node_data_read.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.052618947405107266, "lm_q1q2_score": 0.024872106995553804}} {"text": "function [ varargout ] = Beam_Propagation_Method_GUI ( varargin )\n\n%% GUI for Beam Propagation Method (BPM)\n%\n%%\n% Author: Ido Schwartz (IS) \n% April 2011 (ver. 1.0.0)\n%\n%% build GUI\nfig = build_gui;\nh = guidata ( fig );\n\nswitch nargout %----------------------- check nargout\n case 0\n % do nothing\n case 1 % return a handle to GUI\n varargout(1) = {fig};\n otherwise\n error ('Invalid number of output arguments');\nend\n\ne = exist ('data_bpm_tmp.mat','file');\nif e==2\n delete('data_bpm_tmp.mat');\nend\n\nend\n\n\n%% uifunctions\nfunction fig = build_gui\n\nsetappdata(0,'UseNativeSystemDialogs',false);\n\nfig = figure;\n\nset (fig, 'Name', ' Beam Propagation Method GUI','NumberTitle', 'off', 'Visible','off');\nset (fig, 'deleteFcn', @close_figure_callback ); %%%%%%%%%%%%%%%\nset (fig, 'Color', get(0,'defaultUicontrolBackgroundColor') );\n\nback_color = get (fig,'Color');\nedit_box_back_color = [1 1 1]; % white\n\n%% ------------------------------------ draw tools panel\ntools_panel = uipanel('units', 'normalized', 'position' , [.005 .005 .99 .11] ,... %% draw panel\n 'parent' , fig, 'tag' , ' tools_panel' , 'TitlePosition', 'righttop', ...\n 'title' , 'tools');\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.003 0.1 0.12 0.8],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'simulation panel' ,'tag', 'graphs_pushbutton', 'callback', @graphs_pushbutton_callback, 'parent' , tools_panel );\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.126 0.1 0.12 0.8],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'set parameters' ,'tag', 'setparameters_pushbutton', 'callback', @setparameters_pushbutton_callback, 'parent' , tools_panel );\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.877 0.1 0.12 0.8],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'Exit' ,'tag', 'exit_pushbutton', 'callback', @exit_pushbutton_callback, 'parent' , tools_panel );\n\n\n%% ------------------------------------ draw graphs panel\ngraph_panel = uipanel('units', 'normalized', 'position' , [.005 .11 .99 .885] ,... %% draw panel\n 'parent' , fig, 'tag' , 'g_panel' , 'TitlePosition', 'righttop', ...\n 'title' , 'Graphs');\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.003 0.003 0.12 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'start' ,'tag', 'start_pushbutton', 'callback', @start_pushbutton_callback, 'parent' , graph_panel );\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.126 0.003 0.12 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,'enable','off',...\n 'string', 'stop' ,'tag', 'stop_pushbutton', 'callback', @stop_pushbutton_callback, 'parent' , graph_panel );\n\nuicontrol ('style', 'pushbutton', 'units', 'normalized', 'position', [0.875 0.003 0.12 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'bold','fontsize' , 12 ,'enable','on',...\n 'string', 'save' ,'tag', 'save_pushbutton', 'callback', @save_pushbutton_callback, 'parent' , graph_panel );\n\naxes('parent',graph_panel,'tag','ax1','Position', [.04 .125 .58 .83]'); %define the axes space\naxes('parent',graph_panel,'tag','ax2','Position',[.665 .4 .3 .5]); %define the axes space\n\n%% ------------------------------------ draw Set Parameters panel\nparameters_panel = uipanel('units', 'normalized', 'position' , [.005 .11 .99 .885] ,... %% draw panel\n 'parent' , fig, 'tag' , 'p_panel' , 'TitlePosition', 'righttop', ...\n 'title' , 'Set Parameters');\n% --------------------------------------------------------- Field parameters\nfield_panel = uipanel('units', 'normalized', 'position' , [.005 .005 .3 .99] ,... %% draw panel\n 'parent' , parameters_panel, 'tag' , 'field_panel' , 'TitlePosition', 'righttop', ...\n 'title' , 'Field Initial Parameters');\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.9 0.9 0.1],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'F(r,z=0)=A*exp(-0.5*(r/w)^2)' ,'tag', 'field_text', 'parent' , field_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.83 0.11 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', 'A = ' ,'tag', 'A_text', 'parent' , field_panel );\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.165 0.83 0.15 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '1' , 'backgroundcolor',[1 1 1],'tag', 'A_edit','enable','on', 'parent' , field_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.75 0.11 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', 'w = ' ,'tag', 'w_text', 'parent' , field_panel );\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.165 0.75 0.15 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '10' ,'backgroundcolor',[1 1 1],'tag', 'w_edit','enable','on', 'parent' , field_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.33 0.75 0.22 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', 'micrometer ' ,'tag', 'w_units_text', 'parent' , field_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.67 0.11 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', 'wave length' ,'tag', 'lambda_text', 'parent' , field_panel );\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.165 0.67 0.15 0.07],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '0.5' ,'backgroundcolor',[1 1 1],'tag', 'lambda_edit','enable','on', 'parent' , field_panel );\n\nuicontrol ('style', 'popupmenu', 'units', 'normalized', 'position', [0.33 0.67 0.3 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12,'backgroundcolor',[1 1 1] ,...\n 'string', {'micrometer','nanometer'} ,'tag', 'lambda_popup', 'callback', @lambda_popupmenu_callback, 'parent' , field_panel );\n\n% --------------------------------------------------------- Medium Parameters ---\nmedium_panel = uipanel('units', 'normalized', 'position' , [.305 .005 .3 .99] ,... %% draw panel\n 'parent' , parameters_panel, 'tag' , 'medium_panel' , 'TitlePosition', 'righttop', ...\n 'title' , 'Medium Parameters');\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.005 .98 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, '\\bfn=n_0+n_1exp(-\\alphar^m/w^m)', 'parent' , tex ,'FontSize',12);\n\nuicontrol ('style', 'popupmenu', 'units', 'normalized', 'position', [0.005 0.87 0.5 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,'backgroundcolor',[1 1 1],...\n 'string', {'uniform','linear','quadratic','customize'} ,'tag', 'medium_popup', 'callback', @medium_popupmenu_callback, 'parent' , medium_panel );\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.005 .8 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, 'n_0 =', 'parent' , tex ,'FontSize',12);\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.15 0.775 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '1' ,'backgroundcolor',[1 1 1],'tag', 'n0_edit','enable','on', 'parent' , medium_panel );\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.005 .73 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, 'n_1 =', 'parent' , tex ,'FontSize',12);\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.15 0.705 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '0' ,'backgroundcolor',[1 1 1],'tag', 'n1_edit','enable','off', 'parent' , medium_panel );\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.35 .74 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, '*10^-^4', 'parent' , tex ,'FontSize',12);\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.005 .66 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, '\\alpha =', 'parent' , tex ,'FontSize',12);\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.15 0.635 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '0.5' ,'backgroundcolor',[1 1 1],'tag', 'alpha_edit','enable','off', 'parent' , medium_panel );\n\ntex=axes('parent',medium_panel,'tag','tex','Position', [.005 .59 .0001 .0001],'XTick',[],'YTick',[]); %define the axes space\ntext( 1,1, 'm =', 'parent' , tex ,'FontSize',12);\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.15 0.565 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '0' ,'backgroundcolor',[1 1 1],'tag', 'm_edit','enable','off', 'parent' , medium_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.001 0.47 0.8 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'max value of r = 1000*(wave length)' ,'tag', 'r_max_text', 'parent' , medium_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.001 0.415 0.8 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'size of propagation step:' ,'tag', 'dz_size_text', 'parent' , medium_panel );\n\nuicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.365 0.15 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'dz =' ,'tag', 'dz_text', 'parent' , medium_panel );\n\n uicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.16 0.38 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '5' ,'backgroundcolor',[1 1 1],'tag', 'dz_edit','enable','on', 'parent' , medium_panel );\n \n uicontrol ('style', 'text', 'units', 'normalized', 'position', [0.35 0.365 0.3 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'micrometer' ,'tag', 'dz_unit_text', 'parent' , medium_panel );\n \n uicontrol ('style', 'text', 'units', 'normalized', 'position', [0.001 0.285 0.8 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'propagation distance:' ,'tag', 'z_distance_text', 'parent' , medium_panel );\n \n uicontrol ('style', 'text', 'units', 'normalized', 'position', [0.05 0.235 0.15 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'bold','fontsize' , 12 ,...\n 'string', 'z =' ,'tag', 'z_text', 'parent' , medium_panel );\n\nuicontrol ('style', 'edit', 'units', 'normalized', 'position', [0.16 0.25 0.15 0.06],...\n 'HorizontalAlignment','center', 'FontWeight', 'normal','fontsize' , 12 ,...\n 'string', '1000' ,'backgroundcolor',[1 1 1],'tag', 'steps_edit','enable','on', 'parent' , medium_panel );\n\nuicontrol ('style', 'popupmenu', 'units', 'normalized', 'position', [0.35 0.237 0.28 0.07],...\n 'HorizontalAlignment','left', 'FontWeight', 'normal','fontsize' , 12 ,'backgroundcolor',[1 1 1],...\n 'string', {'dz steps','micrometer'} ,'tag', 'steps_popup', 'callback', @steps_popupmenu_callback, 'parent' , medium_panel );\n\n%\n%% ------------------------------------ prepare gui_handles\nh = guihandles; % get handles of uicontrols\nh.fig = fig; % figures handle\nh.object = []; % instrument object\nh.back_color = back_color; % figure's background color\nh.edit_box_back_color = edit_box_back_color; % edit box background color\nh.start_itr = 1;\nh.Output = [];\n\nh.dir_path = fileparts(mfilename('fullpath')); % path of the gui mfile\n%\n%% ------------------------------------ show figure\n% update guidata\nguidata ( fig, h );\n\n% show figure\nhide_object(parameters_panel);\nshow_object(graph_panel);\nmovegui(fig,'center');\nset(gcf,'Visible','on');\n\n% focus on uicontrol\nfocus_on(h.start_pushbutton);\nend\n%\n%% ============================================== focus_on uicontrol ===\nfunction focus_on ( hObject )\n% focus on uicontrol only if figure is visible\nh = guidata (hObject);\nvisible_fig = findobj(h.fig,'flat','Visible','on');\nif ~isempty(visible_fig)\n uicontrol(hObject);\n drawnow expose;\nend\nend\n%\n%% ============================================== hide_object ===\nfunction hide_object (hObject)\nset ( hObject, 'Visible', 'off' );\nend\n%\n%% ============================================== show_object ===\nfunction show_object (hObject)\nset ( hObject, 'Visible', 'on' );\ndrawnow expose;\nend\n%\n%% ============================================== callbacks ===\n%\n%% ============================================== exit_pushbutton_callback ===\nfunction exit_pushbutton_callback (hObject,eventdata)\ne = exist ('data_bpm_tmp.mat','file');\nif e==2\n delete('data_bpm_tmp.mat');\nend\nclose; % close GUI and all open ports\n % (see close_figure_callback)\nend\n%\n%% ============================================== close_figure_callback ===\nfunction close_figure_callback (hObject,eventdata)\nstop_pushbutton_callback (hObject,eventdata);\nend\n%\n%% ============================================== stop_pushbutton_callback ===\nfunction stop_pushbutton_callback (hObject,eventdata)\nh = guidata(hObject);\nset(findobj('tag','stop_pushbutton'),'enable','off');\nset(findobj('tag','start_pushbutton'),'enable','on','BackGroundColor',h.back_color,'string','start');\nset(findobj('tag','setparameters_pushbutton'),'enable','on');\nset(findobj('tag','graphs_pushbutton'),'enable','on');\nend\n%\n%% ============================================== start_pushbutton_callback ===\nfunction flag = start_pushbutton_callback (hObject,flag)\nh = guidata(hObject);\nget(findobj('tag','start_pushbutton'),'string');\n\nset(findobj('tag','stop_pushbutton'),'enable','on');\nset(findobj('tag','setparameters_pushbutton'),'enable','off');\nset(findobj('tag','graphs_pushbutton'),'enable','off');\nset(findobj('tag','start_pushbutton'),'enable','off','string','running','BackGroundColor',[0 1 0]);\n% --------------------------------------------------------------------------\n\n[A w Lam n0 deltaN alpha m dz z]=get_data_from_gui(h);\n% Propagation of gaussian using BPM\n\nNR = 2^13; % Numerical Resolution\n\n%************Propagating Parameters ********%\nsteps=round(z/dz); % max value of z-axis\n%************Medium Parameters **********%\nx_max=1000*Lam; % maximum value of x-axis\n%........................................................................%\ndx = 2*x_max/(NR-1);\nx = -x_max : dx : x_max;\ndkx = pi/(x_max)*(NR-1)/NR;\nkx = ( (-NR/2):(NR/2-1) )*dkx;\nk0 = 2*pi/Lam;\n%........................................................................%\n\n%************Inpout Field Parameters****************%\n\nfz=A*exp(-0.5*(abs(x)/w).^2); % initial field distribution\n\nN=deltaN*exp(-alpha*(abs(x)/w).^m);\n\n start_itr = 1;\n Output = zeros(NR,steps);\n Output(:,1) = abs(fz).^2;\n\n%%%%%%%%%%%%%%%%%%%%%%%%\n%************PROPAGATION *****************%\n%%%%%%%%%%%%%%%%%%%%%%%%\n Fz=ifftshift(ifft(ifftshift(fz)));\n Fz_d=Fz.*exp(1i*(kx.^2)./(2*k0*(n0+N))*dz/2);\n fz=fftshift(fft(fftshift(Fz_d)));\n\nfor itr=start_itr:steps-1\n \n fz_N=fz.*exp(-1i*N*k0*dz);\n Fz=ifftshift(ifft(ifftshift(fz_N)));\n D=exp(1i*(kx.^2)./(2*k0*(n0+N))*dz);\n Fz_D=Fz.*D;\n fz=fftshift(fft(fftshift(Fz_D)));\n \n plot(h.ax1,x,abs(fz).^2);\n axis(h.ax1,[-0.5*10^-4 0.5*10^-4 0 4*A]);\n set(get(h.ax1,'XLabel'),'String','\\bfr [m]');\n set(get(h.ax1,'YLabel'),'String','\\bfI [r]');\n set(get(h.ax1,'Title'),'String','\\bfIntensity');\n \n Output(:,itr)=abs(fz).^2;\n \n imagesc((0:itr)*dz,x,Output(:,1:itr),'parent',h.ax2);\n colormap('hot');\n ylim(h.ax2,[-0.5*10^-4 0.5*10^-4]);\n set(get(h.ax2,'XLabel'),'String','\\bfz [m]');\n set(get(h.ax2,'YLabel'),'String','\\bfr [m]');\n set(get(h.ax2,'Title'),'String','\\bfIntensity Map');\n drawnow;\n \n val1 = get(findobj('tag','stop_pushbutton'),'enable');\n if strcmp(val1,'off')\n break\n end\n \nend\n\nFz=ifftshift(ifft(ifftshift(fz)));\nFz_d=Fz.*exp(1i*(kx.^2)./(2*k0*(n0+N))*dz/2);\nfz=fftshift(fft(fftshift(Fz_d)));\n\nOutput(:,itr+1)=abs(fz).^2;\nsave('data_bpm_tmp.mat','Output');\n\nplot(h.ax1,x,abs(fz).^2);\naxis(h.ax1,[-0.5*10^-4 0.5*10^-4 0 4*A]);\nset(get(h.ax1,'XLabel'),'String','\\bfr [m]');\nset(get(h.ax1,'YLabel'),'String','\\bfI [r]');\nset(get(h.ax1,'Title'),'String','\\bfIntensity');\n\nimagesc((0:itr)*dz,x,Output(:,1:itr+1),'parent',h.ax2);\ncolormap('hot');\nylim(h.ax2,[-0.5*10^-4 0.5*10^-4]);\nset(get(h.ax2,'XLabel'),'String','\\bfz [m]');\nset(get(h.ax2,'YLabel'),'String','\\bfr [m]');\nset(get(h.ax2,'Title'),'String','\\bfIntensity Map');\n\n% ---------------------------------------------\n set(findobj('tag','start_pushbutton'),'enable','on','string','running','BackGroundColor',h.back_color,'string','start');\n set(findobj('tag','stop_pushbutton'),'enable','off');\n set(findobj('tag','setparameters_pushbutton'),'enable','on');\n set(findobj('tag','graphs_pushbutton'),'enable','on');\nend\n%\n%% ============================================== save_pushbutton_callback ===\nfunction save_pushbutton_callback (hObject,eventdata)\nh = guidata(hObject);\ne = exist ('data_bpm_tmp.mat','file');\nif e==2\n load('data_bpm_tmp.mat');\nelse\n Output = [];\nend\nuisave('Output','BPM Simulation.mat');\nend\n%\n%% ============================================== graphs_pushbutton_callback ===\nfunction graphs_pushbutton_callback (hObject,eventdata)\nh=guidata(hObject);\nhide_object(h.p_panel);\nshow_object(h.g_panel);\nend\n%\n%% ============================================== setparameters_pushbutton_callback ===\nfunction setparameters_pushbutton_callback (hObject,eventdata)\nh=guidata(hObject);\nhide_object(h.g_panel);\nshow_object(h.p_panel);\n\n% focus on uicontrol\nfocus_on(h.start_pushbutton);\nend\n%\n%% ============================================== lambda_popupmenu_callback ===\nfunction lambda_popupmenu_callback (hObject,eventdata)\nh=guidata(hObject);\nval=get(h.lambda_popup,'value');\nlambda_edit=findobj('tag','lambda_edit');\nlambda=get(lambda_edit,'string');\n\nswitch val\n case 1\n new_lambda=num2str(str2double(lambda)/1000);\n set(lambda_edit,'string',new_lambda);\n case 2\n new_lambda=num2str(str2double(lambda)*1000);\n set(lambda_edit,'string',new_lambda);\nend\nend\n%\n%% ============================================== medium_popupmenu_callback ===\nfunction medium_popupmenu_callback (hObject,eventdata)\nh=guidata(hObject);\nval=get(h.medium_popup,'value');\nn0=findobj('tag','n0_edit');\nn1=findobj('tag','n1_edit');\nalpha=findobj('tag','alpha_edit');\nm=findobj('tag','m_edit');\n\nswitch val\n case 1\n set(n0,'enable','on');\n set(n1,'enable','off','string','0');\n set(alpha,'enable','off','string','0.5');\n set(m,'enable','off','string','0');\n case 2\n set(n0,'enable','on');\n set(n1,'enable','on','string','10');\n set(alpha,'enable','on');\n set(m,'enable','off','string','1');\n case 3\n set(n0,'enable','on');\n set(n1,'enable','on','string','10');\n set(alpha,'enable','on');\n set(m,'enable','off','string','2');\n case 4\n set(n0,'enable','on');\n set(n1,'enable','on');\n set(alpha,'enable','on');\n set(m,'enable','on');\nend\n\nend\n%\n%% ============================================== steps_popupmenu_callback ===\nfunction steps_popupmenu_callback (hObject,eventdata)\nh=guidata(hObject);\nval=get(h.steps_popup,'value');\nsteps_edit=findobj('tag','steps_edit');\nsteps=get(steps_edit,'string');\ndz=str2double(get(findobj('tag','dz_edit'),'string'));\n\nswitch val\n case 1\n new_steps=num2str(round(str2double(steps)/dz));\n set(steps_edit,'string',new_steps);\n case 2\n new_steps=num2str(round(str2double(steps)*dz));\n set(steps_edit,'string',new_steps);\nend\n\nend\n%\n%% ============================================== get_data_from_gui ===\nfunction [A w lambda n0 n1 alpha m dz z]=get_data_from_gui(h)\nA_text=get(h.A_edit,'string');\nA=str2double(A_text);\n\nw_text=get(h.w_edit,'string');\nw=str2double(w_text);\nw=w*10^(-6);\n\nlambda_text=get(h.lambda_edit,'string');\nlambda=str2double(lambda_text);\nw_val=get(h.lambda_popup,'value');\nswitch w_val\n case 1\n lambda=lambda*10^(-6);\n case 2 \n lambda=lambda*10^(-9);\nend\n\nn0_text=get(h.n0_edit,'string');\nn0=str2double(n0_text);\n\nn1_text=get(h.n1_edit,'string');\nn1=str2double(n1_text);\nn1=n1*10^(-4);\n\nalpha_text=get(h.alpha_edit,'string');\nalpha=str2double(alpha_text);\n\nm_text=get(h.m_edit,'string');\nm=str2double(m_text);\n\ndz_text=get(h.dz_edit,'string');\ndz=str2double(dz_text);\ndz=dz*10^(-6);\n\nz_text=get(h.steps_edit,'string');\nz=str2double(z_text);\nz_val=get(h.steps_popup,'value');\nswitch z_val\n case 1\n z=z*dz;\n case 2 \n z=z*10^(-6);\nend\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31006-beam-propagation-method-for-advancing-gaussian-beam-in-a-profiled-medium/Beam_Propagation_Method_GUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.06008665480259673, "lm_q1q2_score": 0.02447530139812785}} {"text": "function gpcf = gpcf_noise(varargin)\n%GPCF_NOISE Create a independent noise covariance function\n%\n% Description\n% GPCF = GPCF_NOISE('PARAM1',VALUE1,'PARAM2,VALUE2,...) creates\n% independent noise covariance function structure in which the\n% named parameters have the specified values. Any unspecified\n% parameters are set to default values.\n%\n% GPCF = GPCF_NOISE(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a covariance function structure with the named\n% parameters altered with the specified values.\n%\n% Parameters for independent noise covariance function [default]\n% noiseSigma2 - variance of the independent noise [0.1]\n% noiseSigma2_prior - prior for noiseSigma2 [prior_logunif]\n%\n% Note! If the prior is 'prior_fixed' then the parameter in\n% question is considered fixed and it is not handled in\n% optimization, grid integration, MCMC etc.\n%\n% See also\n% GP_SET, GPCF_*, PRIOR_*\n\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'GPCF_NOISE';\n ip.addOptional('gpcf', [], @isstruct);\n ip.addParamValue('noiseSigma2',0.1, @(x) isscalar(x) && x>0);\n ip.addParamValue('noiseSigma2_prior',prior_logunif, @(x) isstruct(x) || isempty(x));\n ip.parse(varargin{:});\n gpcf=ip.Results.gpcf;\n \n if isempty(gpcf)\n init=true;\n gpcf.type = 'gpcf_noise';\n else\n if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_noise')\n error('First argument does not seem to be a valid covariance function structure')\n end\n init=false;\n end\n \n % Initialize parameter\n if init || ~ismember('noiseSigma2',ip.UsingDefaults)\n gpcf.noiseSigma2=ip.Results.noiseSigma2;\n end\n \n % Initialize prior structure\n if init\n gpcf.p=[];\n end\n if init || ~ismember('noiseSigma2_prior',ip.UsingDefaults)\n gpcf.p.noiseSigma2=ip.Results.noiseSigma2_prior;\n end\n \n if init\n % Set the function handles to the subfunctions\n gpcf.fh.pak = @gpcf_noise_pak;\n gpcf.fh.unpak = @gpcf_noise_unpak;\n gpcf.fh.lp = @gpcf_noise_lp;\n gpcf.fh.lpg = @gpcf_noise_lpg;\n gpcf.fh.cfg = @gpcf_noise_cfg;\n gpcf.fh.ginput = @gpcf_noise_ginput;\n gpcf.fh.cov = @gpcf_noise_cov;\n gpcf.fh.trcov = @gpcf_noise_trcov;\n gpcf.fh.trvar = @gpcf_noise_trvar;\n gpcf.fh.recappend = @gpcf_noise_recappend;\n end \n\nend\n\nfunction [w, s] = gpcf_noise_pak(gpcf)\n%GPCF_NOISE_PAK Combine GP covariance function parameters into\n% one vector.\n%\n% Description\n% W = GPCF_NOISE_PAK(GPCF) takes a covariance function data\n% structure GPCF and combines the covariance function\n% parameters and their hyperparameters into a single row\n% vector W. This is a mandatory subfunction used for example \n% in energy and gradient computations.\n%\n% w = [ log(gpcf.noiseSigma2)\n% (hyperparameters of gpcf.magnSigma2)]'\n% \n%\n% See also\n% GPCF_NOISE_UNPAK\n\n\n w = []; s = {};\n if ~isempty(gpcf.p.noiseSigma2)\n w(1) = log(gpcf.noiseSigma2);\n s = [s 'log(noise.noiseSigma2)'];\n % Hyperparameters of noiseSigma2\n [wh sh] = gpcf.p.noiseSigma2.fh.pak(gpcf.p.noiseSigma2);\n w = [w wh];\n s = [s sh];\n end \n\nend\n\nfunction [gpcf, w] = gpcf_noise_unpak(gpcf, w)\n%GPCF_NOISE_UNPAK Sets the covariance function parameters\n% into the structure\n%\n% Description\n% [GPCF, W] = GPCF_NOISE_UNPAK(GPCF, W) takes a covariance\n% function data structure GPCF and a hyper-parameter vector W,\n% and returns a covariance function data structure identical\n% to the input, except that the covariance hyper-parameters\n% have been set to the values in W. Deletes the values set to\n% GPCF from W and returns the modified W. This is a mandatory \n% subfunction used for example in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = [ log(gpcf.noiseSigma2)\n% (hyperparameters of gpcf.magnSigma2)]'\n%\n% See also\n% GPCF_NOISE_PAK\n\n \n if ~isempty(gpcf.p.noiseSigma2)\n gpcf.noiseSigma2 = exp(w(1));\n w = w(2:end);\n \n % Hyperparameters of lengthScale\n [p, w] = gpcf.p.noiseSigma2.fh.unpak(gpcf.p.noiseSigma2, w);\n gpcf.p.noiseSigma2 = p;\n end\nend\n\n\nfunction lp = gpcf_noise_lp(gpcf)\n%GPCF_NOISE_LP Evaluate the log prior of covariance function parameters\n%\n% Description\n% LP = GPCF_NOISE_LP(GPCF) takes a covariance function\n% structure GPCF and returns log(p(th)), where th collects the\n% parameters. This is a mandatory subfunction used for example \n% in energy computations.\n%\n% See also\n% GPCF_NOISE_PAK, GPCF_NOISE_UNPAK, GPCF_NOISE_G, GP_E\n\n% Evaluate the prior contribution to the error. The parameters that\n% are sampled are from space W = log(w) where w is all the\n% \"real\" samples. On the other hand errors are evaluated in the\n% W-space so we need take into account also the Jacobian of\n% transformation W -> w = exp(W). See Gelman et.al., 2004,\n% Bayesian data Analysis, second edition, p24.\n \n lp = 0;\n gpp=gpcf.p;\n\n if ~isempty(gpcf.p.noiseSigma2)\n % Evaluate the prior contribution to the error.\n lp = gpp.noiseSigma2.fh.lp(gpcf.noiseSigma2, gpp.noiseSigma2) +log(gpcf.noiseSigma2);\n end\nend\n\nfunction lpg = gpcf_noise_lpg(gpcf)\n%GPCF_NOISE_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = GPCF_NOISE_LPG(GPCF) takes a covariance function\n% structure GPCF and returns LPG = d log (p(th))/dth, where th\n% is the vector of parameters. This is a mandatory subfunction \n% used for example in gradient computations.\n%\n% See also\n% GPCF_NOISE_PAK, GPCF_NOISE_UNPAK, GPCF_NOISE_LP, GP_G\n\n lpg = [];\n gpp=gpcf.p;\n \n if ~isempty(gpcf.p.noiseSigma2) \n lpgs = gpp.noiseSigma2.fh.lpg(gpcf.noiseSigma2, gpp.noiseSigma2);\n lpg = [lpg lpgs(1).*gpcf.noiseSigma2+1 lpgs(2:end)];\n end\nend\n\nfunction DKff = gpcf_noise_cfg(gpcf, x, x2, mask, i1)\n%GPCF_NOISE_CFG Evaluate gradient of covariance function\n% with respect to the parameters\n%\n% Description\n% DKff = GPCF_NOISE_CFG(GPCF, X) takes a covariance function\n% data structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to th (cell array with matrix elements). This is a \n% mandatory subfunction used in gradient computations.\n%\n% DKff = GPCF_NOISE_CFG(GPCF, X, X2) takes a covariance\n% function data structure GPCF, a matrix X of input vectors\n% and returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_NOISE_CFG(GPCF, X, [], MASK) takes a covariance\n% function data structure GPCF, a matrix X of input vectors\n% and returns DKff, the diagonal of gradients of covariance\n% matrix Kff = k(X,X2) with respect to th (cell array with\n% matrix elements). This subfunction is needed when using \n% sparse approximations (e.g. FIC).\n%\n% See also\n% GPCF_NOISE_PAK, GPCF_NOISE_UNPAK, GPCF_NOISE_E, GP_G\n\n DKff = {};\n\n if ~isempty(gpcf.p.noiseSigma2)\n gpp=gpcf.p;\n DKff{1}=gpcf.noiseSigma2;\n end\n if nargin==4\n % Use memory save option\n if i1==0\n % Return number of hyperparameters\n DKff=1;\n return\n end\n DKff=DKff{1};\n end\n \nend\n\nfunction DKff = gpcf_noise_ginput(gpcf, x, t, i1)\n%GPCF_NOISE_GINPUT Evaluate gradient of covariance function with \n% respect to x\n%\n% Description\n% DKff = GPCF_NOISE_GINPUT(GPCF, X) takes a covariance\n% function data structure GPCF, a matrix X of input vectors\n% and returns DKff, the gradients of covariance matrix Kff =\n% k(X,X) with respect to X (cell array with matrix elements).\n% This subfunction is needed when computing gradients with \n% respect to inducing inputs in sparse approximations.\n%\n% DKff = GPCF_NOISE_GINPUT(GPCF, X, X2) takes a covariance\n% function data structure GPCF, a matrix X of input vectors\n% and returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to X (cell array with matrix elements).\n% This subfunction is needed when computing gradients with \n% respect to inducing inputs in sparse approximations.\n%\n% See also\n% GPCF_NOISE_PAK, GPCF_NOISE_UNPAK, GPCF_NOISE_E, GP_G\n\nend\n\nfunction C = gpcf_noise_cov(gpcf, x1, x2)\n% GP_NOISE_COV Evaluate covariance matrix between two input vectors\n%\n% Description\n% C = GP_NOISE_COV(GP, TX, X) takes in covariance function of\n% a Gaussian process GP and two matrixes TX and X that contain\n% input vectors to GP. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i in TX\n% and j in X. This is a mandatory subfunction used for example in\n% prediction and energy computations.\n%\n% See also\n% GPCF_NOISE_TRCOV, GPCF_NOISE_TRVAR, GP_COV, GP_TRCOV\n\n\n if isempty(x2)\n x2=x1;\n end\n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n\n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n\n C = sparse([],[],[],n1,n2,0);\nend\n\nfunction C = gpcf_noise_trcov(gpcf, x)\n%GP_NOISE_TRCOV Evaluate training covariance matrix of inputs\n%\n% Description\n% C = GP_NOISE_TRCOV(GP, TX) takes in covariance function of a\n% Gaussian process GP and matrix TX that contains training\n% input vectors. Returns covariance matrix C. Every element ij\n% of C contains covariance between inputs i and j in TX. This is \n% a mandatory subfunction used for example in prediction and \n% energy computations.\n% \n%\n% See also\n% GPCF_NOISE_COV, GPCF_NOISE_TRVAR, GP_COV, GP_TRCOV\n\n [n, m] =size(x);\n n1=n+1;\n\n C = sparse([],[],[],n,n,0);\n C(1:n1:end)=C(1:n1:end)+gpcf.noiseSigma2;\n\nend\n\nfunction C = gpcf_noise_trvar(gpcf, x)\n% GP_NOISE_TRVAR Evaluate training variance vector\n%\n% Description\n% C = GP_NOISE_TRVAR(GPCF, TX) takes in covariance function \n% of a Gaussian process GPCF and matrix TX that contains\n% training inputs. Returns variance vector C. Every\n% element i of C contains variance of input i in TX. This is \n% a mandatory subfunction used for example in prediction and \n% energy computations.\n%\n%\n% See also\n% GPCF_NOISE_COV, GP_COV, GP_TRCOV\n\n\n\n [n, m] =size(x);\n C=ones(n,1)*gpcf.noiseSigma2;\n\nend\n\nfunction reccf = gpcf_noise_recappend(reccf, ri, gpcf)\n%RECAPPEND Record append\n%\n% Description\n% RECCF = GPCF_NOISE_RECAPPEND(RECCF, RI, GPCF) takes a\n% covariance function record structure RECCF, record index RI\n% and covariance function structure GPCF with the current MCMC\n% samples of the hyperparameters. Returns RECCF which contains\n% all the old samples and the current samples from GPCF.\n% This subfunction is needed when using MCMC sampling (gp_mc).\n%\n% See also\n% GP_MC and GP_MC -> RECAPPEND\n\n if nargin == 2\n % Initialize the record\n reccf.type = 'gpcf_noise';\n \n % Initialize parameters\n reccf.noiseSigma2 = []; \n \n % Set the function handles\n reccf.fh.pak = @gpcf_noise_pak;\n reccf.fh.unpak = @gpcf_noise_unpak;\n reccf.fh.e = @gpcf_noise_lp;\n reccf.fh.lpg = @gpcf_noise_lpg;\n reccf.fh.cfg = @gpcf_noise_cfg;\n reccf.fh.cov = @gpcf_noise_cov;\n reccf.fh.trcov = @gpcf_noise_trcov;\n reccf.fh.trvar = @gpcf_noise_trvar;\n % gpcf.fh.sampling = @hmc2;\n reccf.sampling_opt = hmc2_opt;\n reccf.fh.recappend = @gpcf_noise_recappend; \n reccf.p=[];\n reccf.p.noiseSigma2=[];\n if ~isempty(ri.p.noiseSigma2)\n reccf.p.noiseSigma2 = ri.p.noiseSigma2;\n end\n else\n % Append to the record\n gpp = gpcf.p;\n\n % record noiseSigma2\n reccf.noiseSigma2(ri,:)=gpcf.noiseSigma2;\n if isfield(gpp,'noiseSigma2') && ~isempty(gpp.noiseSigma2)\n reccf.p.noiseSigma2 = gpp.noiseSigma2.fh.recappend(reccf.p.noiseSigma2, ri, gpcf.p.noiseSigma2);\n end\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/external/dmlt/external/gpstuff/gp/gpcf_noise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.04813677026317784, "lm_q1q2_score": 0.023880354698221775}} {"text": "%DATE:21/04/2005\n%COFDM SIMULATOR\n%BY:Apurva Gupta\n%B.ENG,ELECTRONICs & COMMUNICATION ENGINEERING,\n%UNIVERSITY OF LEEDS,UK\n%SUPERVISOR:Prof.G.Markarian\n\nfunction varargout = final_simulator(varargin)\n% FINAL_SIMULATOR M-file for final_simulator.fig\n% FINAL_SIMULATOR, by itself, creates a new FINAL_SIMULATOR or raises the existing\n% singleton*.\n%\n% H = FINAL_SIMULATOR returns the handle to a new FINAL_SIMULATOR or the handle to\n% the existing singleton*.\n%\n% FINAL_SIMULATOR('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in FINAL_SIMULATOR.M with the given input arguments.\n%\n% FINAL_SIMULATOR('Property','Value',...) creates a new FINAL_SIMULATOR or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before final_simulator_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to final_simulator_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help final_simulator\n\n% Last Modified by GUIDE v2.5 24-Apr-2005 12:30:13\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @final_simulator_OpeningFcn, ...\n 'gui_OutputFcn', @final_simulator_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before final_simulator is made visible.\nfunction final_simulator_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to final_simulator (see VARARGIN)\n\n% Choose default command line output for final_simulator\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes final_simulator wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = final_simulator_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\nfunction [varargout] = code1(varargin)\nM=2;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo; % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(1,1e6);%message is a string of a thousand zeros.\n %t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n %code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(msg,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n %qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n %tblen = 48; delay = tblen; % Traceback length\n %decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decodmsg); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('code1', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('code1', varargin{:});\nend\n\n%--------------------------------------------------------------\nfunction [varargout] = code2(varargin)\nM=2;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo; % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(1,1e6);%message is a string of a thousand zeros.\n %t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n %code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(msg,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n %qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n %tblen = 48; delay = tblen; % Traceback length\n %decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decodmsg); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('code2', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('code2', varargin{:});\nend\n\n%-------16QAM-------------------------------------------\nfunction [varargout] = code3(varargin)\nbits=1e5;\nM=16;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo;%*0.5*log2(M);% Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(bits,1);%message is a string of a thousand zeros.\n txsig = qammod(msg,M); % Modulate.\n noise = awgn(txsig, snr,'measured'); % Add noise.\n decodmsg = qamdemod(noise,M); % Demodulate.\n newerrs = biterr(msg,decodmsg); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * bits),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%set(gcf,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1])\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\nif nargout == 0\n builtin('code3', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('code3', varargin{:});\nend\n\n%------64QAM------------------------------------------------\nfunction [varargout] = code4(varargin)\nbits=1e5;\nM=64;\nEbNomin = 5; EbNomax = 15; % EbNo range, in dB\nnumerrmin = 5; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo;%*0.5*log2(M);% Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(bits,1);%message is a string of a thousand zeros.\n txsig = qammod(msg,M); % Modulate.\n noise = awgn(txsig, snr,'measured'); % Add noise.\n decodmsg = qamdemod(noise,M); % Demodulate.\n newerrs = biterr(msg,decodmsg); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * bits),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%set(gcf,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1])\n%axes(handles.axes2);\nfor jj=1:numEbNos\n %legend('Emperical BER','64QAM','Poly Ratio fit');\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\nif nargout == 0\n builtin('code4', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('code4', varargin{:});\nend\n\n\nfunction [varargout] = conv_code1(varargin)\nM=2;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 5; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo; % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(1,1e6);%message is a string of a thousand zeros.\n t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(code,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('conv_code1', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('conv_code1', varargin{:});\nend\n%------------------------------------------------------------\nfunction [varargout] = conv_code2(varargin)\nM=4;\nEbNomin = 1; EbNomax = 10; % EbNo range, in dB\nnumerrmin = 5; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo; % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n msg= zeros(1,1e6);%message is a string of a thousand zeros.\n t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(code,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('conv_code2', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('conv_code2', varargin{:});\nend\n%-------------------------------------------------------------\nfunction [varargout] = conv_code3(varargin)\nM=2;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 10 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo;%*0.5*log2(M); % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n\n msg = zeros(1e6,1);%message is a string of a thousand zeros.\n t = poly2trellis(7,[171 133]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(code,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('conv_code3', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('conv_code3', varargin{:});\nend\n\n\n%-------------------------------------------------------\nfunction [varargout] = conv_code4(varargin)\nM=4;\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 10 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo*0.5*log2(M); % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n\n msg = zeros(1e6,1);%message is a string of a thousand zeros.\n t = poly2trellis(7,[171 133]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n txsig = pskmod(code,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n qcode = quantiz(decodmsg,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials * 1e6),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n%hold off;\nif nargout == 0\n builtin('conv_code4', varargin{:});\nelse\n [varargout{1:nargout}] = builtin('conv_code4', varargin{:});\nend\n\n% --- Executes on selection change in modulation.\nfunction modulation_Callback(hObject, eventdata, handles)\n% hObject handle to modulation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns modulation contents as cell array\n% contents{get(hObject,'Value')} returns selected item from modulation\n\n\n% --- Executes during object creation, after setting all properties.\nfunction modulation_CreateFcn(hObject, eventdata, handles)\n% hObject handle to modulation (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on selection change in popupmenu2.\nfunction popupmenu2_Callback(hObject, eventdata, handles)\n% hObject handle to popupmenu2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns popupmenu2 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from popupmenu2\n\n\n% --- Executes during object creation, after setting all properties.\nfunction popupmenu2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to popupmenu2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on selection change in coding.\nfunction coding_Callback(hObject, eventdata, handles)\n% hObject handle to coding (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns coding contents as cell array\n% contents{get(hObject,'Value')} returns selected item from coding\n\n\n% --- Executes during object creation, after setting all properties.\nfunction coding_CreateFcn(hObject, eventdata, handles)\n% hObject handle to coding (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on selection change in interleaving.\nfunction interleaving_Callback(hObject, eventdata, handles)\n% hObject handle to interleaving (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns interleaving contents as cell array\n% contents{get(hObject,'Value')} returns selected item from interleaving\n\n\n% --- Executes during object creation, after setting all properties.\nfunction interleaving_CreateFcn(hObject, eventdata, handles)\n% hObject handle to interleaving (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on button press in int.\nfunction int_Callback(hObject, eventdata, handles)\n% hObject handle to int (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\npopup_sel_index = get(handles.interleaving, 'Value');\nswitch popup_sel_index\n case 1\n\nbits =1e6\nM=2\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo; % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n % st1 = 27221; st2 = 4831; % States for random number generator\n msg= zeros(bits,1);%message is a string of a thousand zeros.\n t = poly2trellis(7,[171 133]); % Define trellis.\n %t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n nrows = 5; % Use 5 shift registers\n slope = 3; % Delays are 0, 3, 6, 9, and 12.\n inter = convintrlv(code,nrows,slope); % Interleave.\n txsig = pskmod(inter,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n deinter = convdeintrlv(decodmsg,nrows,slope); % Deinterleave.\n qcode = quantiz(deinter,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials *bits ),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%set(gcf,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1])\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\n\n case 2\n \nbits =1e6\nM=4\nEbNomin = 1; EbNomax = 5; % EbNo range, in dB\nnumerrmin = 10; % Compute BER only after 5 errors occur.\nEbNovec = EbNomin:1:EbNomax; % Vector of EbNo values\nnumEbNos = length(EbNovec); % Number of EbNo values\n% Preallocate space for certain data.\nber = zeros(1,numEbNos); % BER values\nintv = cell(1,numEbNos); % Cell array of confidence intervals\n% Loop over the vector of EbNo values.\nfor jj = 1:numEbNos\n EbNo = EbNovec(jj);\n snr = EbNo*0.5*log2(M); % Because of binary modulation\n ntrials = 0; % Number of passes through the while loop below\n numerr = 0; % Number of errors for this EbNo value\n % Simulate until numerrmin errors occur.\n while (numerr < numerrmin)\n % st1 = 27221; st2 = 4831; % States for random number generator\n msg= zeros(bits,1);%message is a string of a thousand zeros.\n t = poly2trellis(7,[171 133]); % Define trellis.\n %t = poly2trellis([4 3],[4 5 17;7 4 2]); % Define trellis.\n code = convenc(msg,t); % Encode a string of ones.\n nrows = 5; % Use 5 shift registers\n slope = 3; % Delays are 0, 3, 6, 9, and 12.\n inter = convintrlv(code,nrows,slope); % Interleave.\n txsig = pskmod(inter,M); % Modulate.\n rxsig = awgn(txsig, snr, 'measured'); % Add noise.\n decodmsg = pskdemod(rxsig,M); % Demodulate.\n deinter = convdeintrlv(decodmsg,nrows,slope); % Deinterleave.\n qcode = quantiz(deinter,[0.001,.1,.3,.5,.7,.9,.999]);% Quantize to prepare for soft-decision decoding.\n tblen = 48; delay = tblen; % Traceback length\n decoded = vitdec(qcode,t,tblen,'cont','soft',3); % Decode.\n newerrs = biterr(msg,decoded); % Errors in this trial\n numerr = numerr + newerrs; % Total errors for this EbNo value\n ntrials = ntrials + 1; % Update trial index.\n end\n % Error rate and 98% confidence interval for this EbNo value\n [ber(jj), intv1] = berconfint(numerr,(ntrials *bits ),.98);\n intv{jj} = intv1; % Store in cell array for later use.\n disp(['EbNo = ' num2str(EbNo) ' dB, ' num2str(numerr) ...\n ' errors, BER = ' num2str(ber(jj))])\nend\n% Use BERFIT to plot the best fitted curve,\n% interpolating to get a smooth plot.\nfitEbNo = EbNomin:0.25:EbNomax; % Interpolation values\nberfit(EbNovec,ber,fitEbNo);\n\n% Also plot confidence intervals.\nhold on;\ngrid on;\n%set(gcf,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1])\n%axes(handles.axes2);\nfor jj=1:numEbNos\n semilogy([EbNovec(jj) EbNovec(jj)],intv{jj},'g-+');\nend\nend\n\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\npopup_sel_index = get(handles.modulation, 'Value');\nswitch popup_sel_index\n case 1\npopup_sel_index = get(handles.coding, 'Value');\nswitch popup_sel_index\n case 1\n code1;\n case 2\n conv_code3;\n case 3\n conv_code1;\n\nend\n case 2\npopup_sel_index = get(handles.coding, 'Value');\nswitch popup_sel_index\n case 1\n code2;\n case 2\n conv_code4; \n case 3\n conv_code2;\nend\n case 3\n code3;\n case 4\n code4;\nend\n\n\n% --- Executes on button press in clr.\nfunction clr_Callback(hObject, eventdata, handles)\n% hObject handle to clr (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncla\n\n% --- Executes on button press in hlp.\nfunction hlp_Callback(hObject, eventdata, handles)\n% hObject handle to hlp (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nhelpPath = which('help.txt');\nweb(helpPath);\n\n\n\n\n% --------------------------------------------------------------------\nfunction close_Callback(hObject, eventdata, handles)\n% hObject handle to close (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nselection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...\n ['Close ' get(handles.figure1,'Name') '...'],...\n 'Yes','No','Yes');\nif strcmp(selection,'No')\n return;\nend\n\ndelete(handles.figure1)\n\n\n% --------------------------------------------------------------------\nfunction print_Callback(hObject, eventdata, handles)\n% hObject handle to print (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nprintdlg(handles.figure1)\n\n% --------------------------------------------------------------------\nfunction file_Callback(hObject, eventdata, handles)\n% hObject handle to file (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n", "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/7570-cofdm-simulator/final_simulator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04742587014823577, "lm_q1q2_score": 0.0233424506131967}} {"text": "function z = cvmgt(x, y, p)\n%CVMGT Conditional merge of two vectors\n%\n% Z = CVMGT(X, Y, P) return a vector Z whose elements are X if P is true\n% and Y otherwise. P, X, and Y should be the same shape except that X\n% and Y may be scalars. CVMGT stands for conditional vector merge true\n% (an intrinsic function for the Cray fortran compiler). It implements\n% the C++ statement\n%\n% Z = P ? X : Y;\n\n z = zeros(size(p));\n if isscalar(x)\n z(p) = x;\n else\n z(p) = x(p);\n end\n if isscalar(y)\n z(~p) = y;\n else\n z(~p) = y(~p);\n end\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39108-geodesics-on-an-ellipsoid-of-revolution/geographiclib-matlab/private/cvmgt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.06371499958557338, "lm_q1q2_score": 0.02266819719277837}} {"text": "function gpcf = gpcf_prod(varargin)\n%GPCF_PROD Create a product form covariance function\n%\n% Description\n% GPCF = GPCF_PROD('cf', {GPCF_1, GPCF_2, ...}) \n% creates a product form covariance function\n% GPCF = GPCF_1 .* GPCF_2 .* ... .* GPCF_N\n%\n% See also\n% GP_SET, GPCF_*\n%\n% Copyright (c) 2009-2010, 2018 Jarno Vanhatalo\n% Copyright (c) 2010 Aki Vehtari\n% Copyright (c) 2014 Arno Solin and Jukka Koskenranta\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'GPCF_PROD';\n ip.addOptional('gpcf', [], @isstruct);\n ip.addParamValue('cf',[], @iscell);\n ip.parse(varargin{:});\n gpcf=ip.Results.gpcf;\n\n if isempty(gpcf)\n init=true;\n gpcf.type = 'gpcf_prod';\n else\n if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_prod')\n error('First argument does not seem to be a valid covariance function structure')\n end\n init=false;\n end\n \n if init || ~ismember('cf',ip.UsingDefaults)\n % Initialize parameters\n gpcf.cf = {};\n cfs=ip.Results.cf;\n if ~isempty(cfs)\n for i = 1:length(cfs)\n gpcf.cf{i} = cfs{i};\n end\n else\n error('At least one covariance function has to be given in cf');\n end\n end\n \n if init\n % Set the function handles to the subfunctions\n gpcf.fh.pak = @gpcf_prod_pak;\n gpcf.fh.unpak = @gpcf_prod_unpak;\n gpcf.fh.lp = @gpcf_prod_lp;\n gpcf.fh.lpg = @gpcf_prod_lpg;\n gpcf.fh.cfg = @gpcf_prod_cfg;\n gpcf.fh.cfdg = @gpcf_prod_cfdg;\n gpcf.fh.cfdg2 = @gpcf_prod_cfdg2;\n gpcf.fh.ginput = @gpcf_prod_ginput;\n gpcf.fh.ginput2 = @gpcf_prod_ginput2;\n gpcf.fh.ginput3 = @gpcf_prod_ginput3;\n gpcf.fh.ginput4 = @gpcf_prod_ginput4;\n gpcf.fh.cov = @gpcf_prod_cov;\n gpcf.fh.trcov = @gpcf_prod_trcov;\n gpcf.fh.trvar = @gpcf_prod_trvar;\n gpcf.fh.recappend = @gpcf_prod_recappend;\n gpcf.fh.cf2ss = @gpcf_prod_cf2ss;\n end\n\nend\n\nfunction [w, s, h] = gpcf_prod_pak(gpcf)\n%GPCF_PROD_PAK Combine GP covariance function parameters into one vector\n%\n% Description\n% W = GPCF_PROD_PAK(GPCF, W) loops through all the covariance\n% functions and packs their parameters into one vector as\n% described in the respective functions. This is a mandatory \n% subfunction used for example in energy and gradient computations.\n%\n% See also\n% GPCF_PROD_UNPAK\n \n ncf = length(gpcf.cf);\n w = []; s = {}; h=[];\n \n for i=1:ncf\n cf = gpcf.cf{i};\n [wi, si, hi] = cf.fh.pak(cf);\n w = [w wi];\n s = [s; si];\n h = [h hi];\n end\nend\n\nfunction [gpcf, w] = gpcf_prod_unpak(gpcf, w)\n%GPCF_PROD_UNPAK Sets the covariance function parameters into\n% the structures\n%\n% Description\n% [GPCF, W] = GPCF_PROD_UNPAK(GPCF, W) loops through all the\n% covariance functions and unpacks their parameters from W to\n% each covariance function structure. This is a mandatory \n% subfunction used for example in energy and gradient computations.\n% \n% See also\n% GPCF_PROD_PAK\n%\n ncf = length(gpcf.cf);\n \n for i=1:ncf\n cf = gpcf.cf{i};\n [cf, w] = cf.fh.unpak(cf, w);\n gpcf.cf{i} = cf;\n end\n\nend\n\nfunction lp = gpcf_prod_lp(gpcf)\n%GPCF_PROD_LP Evaluate the log prior of covariance function parameters\n%\n% Description\n% LP = GPCF_PROD_LP(GPCF, X, T) takes a covariance function\n% structure GPCF and returns log(p(th)), where th collects the\n% parameters. This is a mandatory subfunction used for example \n% in energy computations.\n%\n% See also\n% GPCF_PROD_PAK, GPCF_PROD_UNPAK, GPCF_PROD_LPG, GP_E\n \n lp = 0;\n ncf = length(gpcf.cf);\n for i=1:ncf\n cf = gpcf.cf{i};\n lp = lp + cf.fh.lp(cf);\n end\n \nend\n\nfunction lpg = gpcf_prod_lpg(gpcf)\n%GPCF_PROD_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = GPCF_PROD_LPG(GPCF) takes a covariance function\n% structure GPCF and returns LPG = d log (p(th))/dth, where th\n% is the vector of parameters. This is a mandatory subfunction \n% used for example in gradient computations.\n%\n% See also\n% GPCF_PROD_PAK, GPCF_PROD_UNPAK, GPCF_PROD_LP, GP_G\n lpg = [];\n ncf = length(gpcf.cf);\n \n % Evaluate the gradients\n for i=1:ncf\n cf = gpcf.cf{i};\n lpg=[lpg cf.fh.lpg(cf)];\n end\n\nend\n\nfunction DKff = gpcf_prod_cfg(gpcf, x, x2, mask, i1)\n%GPCF_PROD_CFG Evaluate gradient of covariance function\n% with respect to the parameters.\n%\n% Description\n% DKff = GPCF_PROD_CFG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to th (cell array with matrix elements). This is a \n% mandatory subfunction used in gradient computations.\n%\n% DKff = GPCF_PROD_CFG(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_PROD_CFG(GPCF, X, [], MASK) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the diagonal of gradients of covariance matrix\n% Kff = k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_PROD_CFG(GPCF, X, X2, [], i) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2), or k(X,X) if X2 is empty, with respect to ith \n% hyperparameter. This subfunction is needed when using \n% memory save option in gp_set.\n%\n% See also\n% GPCF_PROD_PAK, GPCF_PROD_UNPAK, GPCF_PROD_LP, GP_G\n\n [n, m] =size(x);\n ncf = length(gpcf.cf);\n\n DKff = {};\n\n if nargin==5\n % Use memory save option\n savememory=1;\n i3=0;\n for k=1:ncf\n % Number of hyperparameters for each covariance function\n cf=gpcf.cf{k};\n i3(k)=cf.fh.cfg(cf,[],[],[],0);\n end\n if i1==0\n % Return number of hyperparameters\n DKff=sum(i3);\n return\n end\n % Help indices\n i3=cumsum(i3);\n ind=find(cumsum(i3 >= i1)==1);\n if ind>1\n i1=[ind i1-i3(ind-1)];\n else\n i1=[ind i1];\n end\n else\n savememory=0;\n end\n\n % Evaluate: DKff{1} = d Kff / d magnSigma2\n % DKff{2} = d Kff / d lengthScale\n % NOTE! Here we have already taken into account that the parameters are transformed\n % through log() and thus dK/dlog(p) = p * dK/dp\n\n % evaluate the gradient for training covariance\n if nargin == 2 || (isempty(x2) && isempty(mask))\n \n % evaluate the individual covariance functions\n for i=1:ncf\n cf = gpcf.cf{i};\n C{i} = cf.fh.trcov(cf, x);\n end\n \n % Evaluate the gradients\n ind = 1:ncf;\n DKff = {};\n if ~savememory\n i3=1:ncf;\n else\n i3=i1(1);\n end\n for i=i3\n cf = gpcf.cf{i};\n if ~savememory\n DK = cf.fh.cfg(cf, x);\n else\n DK = {cf.fh.cfg(cf,x,[],[],i1(2))};\n end\n \n CC = 1;\n for kk = ind(ind~=i)\n CC = CC.*C{kk};\n end\n for j = 1:length(DK)\n DKff{end+1} = DK{j}.*CC;\n end\n end\n \n % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)\n elseif nargin == 3 || isempty(mask)\n if size(x,2) ~= size(x2,2)\n error('gpcf_prod -> _ghyper: The number of columns in x and x2 has to be the same. ')\n end\n \n % evaluate the individual covariance functions\n for i=1:ncf\n cf = gpcf.cf{i};\n C{i} = cf.fh.cov(cf, x, x2);\n end\n \n % Evaluate the gradients\n ind = 1:ncf;\n DKff = {};\n if ~savememory\n i3=1:ncf;\n else\n i3=i1(1);\n end\n for i=i3\n cf = gpcf.cf{i};\n if ~savememory\n DK = cf.fh.cfg(cf, x,x2);\n else\n DK = {cf.fh.cfg(cf,x,x2,[],i1(2))};\n end\n \n CC = 1;\n for kk = ind(ind~=i)\n CC = CC.*C{kk};\n end\n \n for j = 1:length(DK)\n DKff{end+1} = DK{j}.*CC;\n end\n end\n\n \n \n % Evaluate: DKff{1} = d mask(Kff,I) / d magnSigma2\n % DKff{2...} = d mask(Kff,I) / d lengthScale\n elseif nargin == 4 || nargin == 5\n \n % evaluate the individual covariance functions\n for i=1:ncf\n cf = gpcf.cf{i};\n C{i} = cf.fh.trvar(cf, x);\n end\n \n % Evaluate the gradients\n ind = 1:ncf;\n DKff = {};\n if ~savememory\n i3=1:ncf;\n else\n i3=i1(1);\n end\n for i=i3\n cf = gpcf.cf{i};\n if ~savememory\n DK = cf.fh.cfg(cf, x, [], 1);\n else\n DK = {cf.fh.cfg(cf, x, [], 1, i1(2))};\n end\n \n CC = 1;\n for kk = ind(ind~=i)\n CC = CC.*C{kk};\n end\n \n for j = 1:length(DK)\n DKff{end+1} = DK{j}.*CC;\n end\n end\n end\n if savememory\n DKff=DKff{1};\n end\nend\n\nfunction DKff = gpcf_prod_cfdg(gpcf, x, x2, dims)\n%GPCF_SEXP_CFDG Evaluate gradient of covariance function, of\n% which has been taken partial derivative with\n% respect to x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SEXP_CFDG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of derivatived covariance matrix\n% dK(df,f)/dhyp = d(d k(X,X)/dx)/dhyp, with respect to the\n% parameters\n%\n% Evaluate: DKff{1:m} = d Kff / d magnSigma2\n% DKff{m+1:2m} = d Kff / d lengthScale_m\n% m is the dimension of inputs. If ARD is used, then multiple\n% lengthScales. This subfunction is needed when using derivative \n% observations.\n%\n% dims - is a vector of input dimensions with respect to which the\n% derivatives of the covariance function have been calculated\n% [by default dims=1:size(x,2)]\n%\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SEXP_GINPUT\n\n\n\nncf = length(gpcf.cf);\n\n[~, m] =size(x);\nif nargin <3 || isempty(x2)\n x2=x;\nend\nif nargin < 4 || isempty(dims)\n %dims1 = 1:m;\n error('dims1 needs to be given')\nend\n\n\n% check whether there are any covariance functions that depend on dims\n% covariate\nind = [];\nDKff = {};\nfor i1 = 1:ncf\n if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims)))\n ind(end+1) = i1;\n end\nend\nif ~isempty(ind)\n % Calculate derivative\n % calculate the individual covariance functions\n Ci = {};\n C = 1;\n for i1=1:ncf\n Ci{i1} = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n C = C.*Ci{i1};\n end\n \n if ncf==2\n if any(ind==1)\n DKdx1 = gpcf.cf{1}.fh.cfdg(gpcf.cf{1}, x, x2, dims);\n DKx1 = gpcf.cf{1}.fh.ginput4(gpcf.cf{1}, x, x2, dims);\n else\n DKdx1{1} = 0;\n DKx1{1} = 0;\n end\n DK1 = gpcf.cf{1}.fh.cfg(gpcf.cf{1}, x, x2);\n if any(ind==2)\n DKdx2 = gpcf.cf{2}.fh.cfdg(gpcf.cf{2}, x, x2, dims);\n DKx2 = gpcf.cf{2}.fh.ginput4(gpcf.cf{2}, x, x2, dims);\n else\n DKdx2{1} = 0;\n DKx2{1} = 0;\n end\n DK2 = gpcf.cf{2}.fh.cfg(gpcf.cf{2}, x, x2);\n \n for i2 = 1:length(DK1)\n DKff{end+1} = DKdx1{i2}.*C./Ci{1} + DK1{i2}.*DKx2{1};\n end\n for i2 = 1:length(DK2)\n DKff{end+1} = DKdx2{i2}.*C./Ci{2} + DK2{i2}.*DKx1{1};\n end\n \n else\n error('not implemented yet')\n for i1=1:ncf\n \n DKdx = gpcf.cf{i1}.fh.cfdg(gpcf.cf{i1}, x, x2, dims);\n DK = gpcf.cf{i1}.fh.cfg(gpcf.cf{i1}, x, x2);\n \n gpcftmp = gpcf;\n gpcftmp.cf = {gpcftmp.cf(1:ncf~=i1)};\n % continue from here\n %DKx2 =\n end\n end\nelse\n DK = gpcf.fh.lpg(gpcf);\n for i2 = 1:length(DK)\n DKff{end+1} = 0;\n end\nend\n\n\nend\n\n\nfunction DKff = gpcf_prod_cfdg2(gpcf, x, x2, dims1, dims2)\n%GPCF_SEXP_CFDG Evaluate gradient of covariance function, of\n% which has been taken partial derivative with\n% respect to x, with respect to parameters.\n%\n% Description\n% DKff = GPCF_SEXP_CFDG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of derivatived covariance matrix\n% dK(df,f)/dhyp = d(d k(X,X)/dx)/dhyp, with respect to the\n% parameters\n%\n% Evaluate: DKff{1:m} = d Kff / d magnSigma2\n% DKff{m+1:2m} = d Kff / d lengthScale_m\n% m is the dimension of inputs. If ARD is used, then multiple\n% lengthScales. This subfunction is needed when using derivative \n% observations.\n%\n% dims - is a vector of input dimensions with respect to which the\n% derivatives of the covariance function have been calculated\n% [by default dims=1:size(x,2)]\n%\n%\n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_SEXP_GINPUT\n\nncf = length(gpcf.cf);\n\n[~, m] =size(x);\nif nargin <3 || isempty(x2)\n x2=x;\nend\nif nargin < 4 || isempty(dims1)\n %dims1 = 1:m;\n error('dims1 needs to be given')\nend\nif nargin < 5 || isempty(dims2)\n %dims2 = 1:m;\n error('dims2 needs to be given')\nend\n\n% NOTICE. AS OF NOW we assume that dims1 and dims2 are scalars\n\n% check whether there are any covariance functions that depend on dims\n% covariate\nind = [];\nDKff = {};\nfor i1 = 1:ncf\n if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims1)) || any(ismember(gpcf.cf{i1}.selectedVariables,dims2)))\n ind(end+1) = i1;\n end\nend\nif ~isempty(ind)\n % Calculate derivative\n % calculate the individual covariance functions\n Ci = {};\n C = 1;\n for i1=1:ncf\n Ci{i1} = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n %C = C.*Ci{i1};\n end\n \n if ncf==2\n if any(ind==1)\n DKdx11 = gpcf.cf{1}.fh.cfdg(gpcf.cf{1}, x, x2, dims1);\n DKdx12 = gpcf.cf{1}.fh.cfdg(gpcf.cf{1}, x2, x, dims2);\n DKdx1_2 = gpcf.cf{1}.fh.cfdg2(gpcf.cf{1}, x, x2, dims1, dims2);\n DKx11 = gpcf.cf{1}.fh.ginput4(gpcf.cf{1}, x, x2, dims1);\n DKx12 = gpcf.cf{1}.fh.ginput4(gpcf.cf{1}, x2, x, dims2);\n else\n DKdx11{1} = 0;\n DKdx12{1} = 0;\n DKdx1_2{1} = 0;\n DKx11{1} = 0;\n DKx12{1} = 0;\n end\n if any(ind==2)\n DKdx21 = gpcf.cf{2}.fh.cfdg(gpcf.cf{2}, x, x2, dims1);\n DKdx22 = gpcf.cf{2}.fh.cfdg(gpcf.cf{2}, x2, x, dims2);\n DKdx2_2 = gpcf.cf{2}.fh.cfdg2(gpcf.cf{2}, x, x2, dims1, dims2);\n DKx21 = gpcf.cf{2}.fh.ginput4(gpcf.cf{2}, x, x2, dims1);\n DKx22 = gpcf.cf{2}.fh.ginput4(gpcf.cf{2}, x2, x, dims2);\n else\n DKdx21{1} = 0;\n DKdx22{1} = 0;\n DKdx2_2{1} = 0;\n DKx21{1} = 0;\n DKx22{1} = 0;\n end\n \n if dims1==dims2\n if any(ind==1)\n D2Kx1 = gpcf.cf{1}.fh.ginput2(gpcf.cf{1}, x, x2, dims1, dims2);\n else\n D2Kx1{1} = 0;\n end\n if any(ind==2)\n D2Kx2 = gpcf.cf{2}.fh.ginput2(gpcf.cf{2}, x, x2, dims1, dims2);\n else\n D2Kx2{1} = 0;\n end\n else\n% D2Kx1 = gpcf.cf{1}.fh.ginput3(gpcf.cf{1}, x, x2, dims1, dims2);\n% D2Kx2 = gpcf.cf{2}.fh.ginput3(gpcf.cf{2}, x, x2, dims1, dims2);\n if any(ind==1)\n D2Kx1 = gpcf.cf{1}.fh.ginput3(gpcf.cf{1}, x, x2, dims1, dims2);\n else\n D2Kx1{1} = 0;\n end\n if any(ind==2)\n D2Kx2 = gpcf.cf{2}.fh.ginput3(gpcf.cf{2}, x, x2, dims1, dims2);\n else\n D2Kx2{1} = 0;\n end\n end\n \n DK1 = gpcf.cf{1}.fh.cfg(gpcf.cf{1}, x, x2);\n DK2 = gpcf.cf{2}.fh.cfg(gpcf.cf{2}, x, x2);\n \n for i2 = 1:length(DK1)\n DKff{end+1} = DKdx1_2{i2}.*Ci{2} + DKdx11{i2}.*DKx22{1}' + DKdx12{i2}'.*DKx21{1} + DK1{i2}.*D2Kx2{1};\n end\n for i2 = 1:length(DK2)\n DKff{end+1} = DKdx2_2{i2}.*Ci{1} + DKdx21{i2}.*DKx12{1}' + DKdx22{i2}'.*DKx11{1} + DK2{i2}.*D2Kx1{1};\n end\n \n else\n error('not implemented yet')\n for i1=1:ncf\n \n DKdx = gpcf.cf{i1}.fh.cfdg(gpcf.cf{i1}, x, x2, dims);\n DK = gpcf.cf{i1}.fh.cfg(gpcf.cf{i1}, x, x2);\n \n gpcftmp = gpcf;\n gpcftmp.cf = {gpcftmp.cf(1:ncf~=i1)};\n % continue from here\n %DKx2 =\n end\n end\nelse\n DK = gpcf.fh.lpg(gpcf);\n for i2 = 1:length(DK)\n DKff{end+1} = 0;\n end\nend\n\n% [n, m] =size(x);\n% ncf = length(gpcf.cf);\n% \n% if nargin <3 || isempty(x2)\n% x2=x;\n% end\n% if nargin < 4 || isempty(dims1)\n% %dims1 = 1:m;\n% error('dims1 needs to be given')\n% end\n% if nargin < 5 || isempty(dims2)\n% %dims2 = 1:m;\n% error('dims2 needs to be given')\n% end\n% \n% \n% % check whether there are any covariance functions that depend on dims\n% % covariate\n% ind = [];\n% DKff = {};\n% for i1 = 1:ncf\n% if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims1)) || any(ismember(gpcf.cf{i1}.selectedVariables,dims2)))\n% ind(end+1) = i1;\n% end\n% end\n% if ~isempty(ind)\n% % Calculate derivative\n% \n% % calculate the individual covariance functions\n% Ci = {};\n% C = 1;\n% for i1=1:ncf\n% Ci{i1} = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n% C = C.*Ci{i1};\n% end\n% \n% for i1=1:ncf\n% if any(i1 == ind)\n% DK = gpcf.cf{i1}.fh.cfdg2(gpcf.cf{i1}, x, x2, dims1, dims2);\n% for i2 = 1:length(DK)\n% DKff{end+1} = DK{i2}.*C./Ci{i1};\n% end\n% else\n% DK = gpcf.cf{i1}.fh.lpg(gpcf.cf{i1});\n% for i2 = 1:length(DK)\n% DKff{end+1} = 0;\n% end\n% end\n% end\n% else\n% DK = gpcf.fh.lpg(gpcf);\n% for i2 = 1:length(DK)\n% DKff{end+1} = 0;\n% end\n% end\n\nend\n\n\n\nfunction DKff = gpcf_prod_ginput(gpcf, x, x2, i1)\n%GPCF_PROD_GINPUT Evaluate gradient of covariance function with \n% respect to x\n%\n% Description\n% DKff = GPCF_PROD_GINPUT(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to X (cell array with matrix elements). This subfunction \n% is needed when computing gradients with respect to inducing \n% inputs in sparse approximations.\n%\n% DKff = GPCF_PROD_GINPUT(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to X (cell array with matrix elements).\n% This subfunction is needed when computing gradients with \n% respect to inducing inputs in sparse approximations.\n%\n% DKff = GPCF_PROD_GINPUT(GPCF, X, X2, i) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2), or k(X,X) if X2 is empty, with respect to ith\n% covariate in X (cell array with matrix elements). This\n% subfunction is needed when using memory save option in\n% gp_set.\n%\n% See also\n% GPCF_PROD_PAK, GPCF_PROD_UNPAK, GPCF_PROD_LP, GP_G\n \n [n, m] =size(x);\n\n if nargin==4\n % Use memory save option\n savememory=1;\n if i1==0\n % Return number of covariates\n if isfield(gpcf,'selectedVariables')\n DKff=length(gpcf.selectedVariables);\n else\n DKff=m;\n end\n return\n end\n else\n savememory=0;\n end\n % evaluate the gradient for training covariance\n if nargin == 2 || isempty(x2)\n \n ncf = length(gpcf.cf);\n \n % evaluate the individual covariance functions\n for i=1:ncf\n cf = gpcf.cf{i};\n C{i} = cf.fh.trcov(cf, x);\n end\n \n % Evaluate the gradients\n ind = 1:ncf;\n if ~savememory\n DKff=cellfun(@(a) zeros(n,n), cell(1,numel(x)), 'UniformOutput', 0);\n else\n DKff=cellfun(@(a) zeros(n,n), cell(1,n), 'UniformOutput', 0);\n end\n for i=1:ncf\n cf = gpcf.cf{i};\n if ~savememory\n DK = cf.fh.ginput(cf, x);\n else\n DK = cf.fh.ginput(cf, x, [], i1);\n end\n\n CC = 1;\n for kk = ind(ind~=i)\n CC = CC.*C{kk};\n end\n \n for j = 1:length(DK)\n DKff{j} = DKff{j} + DK{j}.*CC;\n end\n end\n\n % Evaluate the gradient of non-symmetric covariance (e.g. K_fu)\n elseif nargin == 3 || nargin == 4\n if size(x,2) ~= size(x2,2)\n error('gpcf_prod -> _ghyper: The number of columns in x and x2 has to be the same. ')\n end\n \n ncf = length(gpcf.cf);\n \n % evaluate the individual covariance functions\n for i=1:ncf\n cf = gpcf.cf{i};\n C{i} = cf.fh.cov(cf, x, x2);\n end\n \n % Evaluate the gradients\n ind = 1:ncf;\n if ~savememory\n DKff=cellfun(@(a) zeros(n,n), cell(1,numel(x)), 'UniformOutput', 0);\n else\n DKff=cellfun(@(a) zeros(n,n), cell(1,n), 'UniformOutput', 0);\n end\n for i=1:ncf\n cf = gpcf.cf{i};\n if ~savememory\n DK = cf.fh.ginput(cf, x, x2);\n else\n DK = cf.fh.ginput(cf, x, x2, i1);\n end\n \n CC = 1;\n for kk = ind(ind~=i)\n CC = CC.*C{kk};\n end\n \n for j = 1:length(DK)\n DKff{j} = DKff{j} + DK{j}.*CC;\n end\n end\n end\n \nend\n\n\nfunction [DKff, DKff1, DKff2] = gpcf_prod_ginput2(gpcf, x, x2, dims, takeOnlyDiag)\n%GPCF_PROD_GINPUT2 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 (in\n% same dimension).\n%\n% Description\n% DKff = GPCF_PROD_GINPUT2(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). Input variable's dimensions are expected to be\n% same. The function returns also DKff1 and DKff2 which are\n% parts of DKff and needed with CFDG2. DKff = DKff1 -\n% DKff2. This subfunction is needed when using derivative \n% observations.\n% \n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_PROD_GINPUT, GPCF_PROD_GINPUT2, GPCF_PROD_CFDG2 \nif nargin < 5\n takeOnlyDiag=[];\nend\n\nncf = length(gpcf.cf);\n\n% check whether there are any covariance functions that depend on dims\n% covariate\nind = [];\nfor i1 = 1:ncf\n if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims)))\n ind(end+1) = i1;\n end\nend\n% Calculate derivative\nif ~isempty(ind)\n % evaluate the individual covariance functions\n C = 1;\n K = 0;\n for i1=1:ncf\n if ~isempty(takeOnlyDiag) && strcmp(takeOnlyDiag, 'takeOnlyDiag')\n Ci = gpcf.cf{i1}.fh.trvar(gpcf.cf{i1}, x);\n else\n Ci = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n end\n C = C.*Ci;\n if any(i1 == ind)\n Dt = gpcf.cf{i1}.fh.ginput2(gpcf.cf{i1}, x, x2, dims, takeOnlyDiag);\n if length(Dt)>1\n error('gpcf_prod->ginput2: something is wrong')\n end\n K = K+Dt{1}./Ci;\n end\n end\n DKff = {C.*K};\nelse\n DKff = {0};\nend\n\nend\n\n\nfunction DKff = gpcf_prod_ginput3(gpcf, x, x2, dims1, dims2)\n%GPCF_PROD_GINPUT3 Evaluate gradient of covariance function with\n% respect to both input variables x and x2 (in\n% different dimensions).\n%\n% Description\n% DKff = GPCF_PROD_GINPUT3(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the gradients of twice derivatived covariance\n% matrix K(df,df) = dk(X1,X2)/dX1dX2 (cell array with matrix\n% elements). The derivative is calculated in multidimensional\n% problem between input's observation dimensions which are not\n% same. This subfunction is needed when using derivative \n% observations.\n%\n% ---- !!note this help text needs to be corrected !! ---\n% DKff is a cell array with the following elements:\n% DKff{1} = dk(X1,X2)/dX1_1dX2_2\n% DKff{2} = dk(X1,X2)/dX1_1dX2_3\n% ... \n% DKff{m-1} = dk(X1,X2)/dX1_1dX2_m\n% DKff{m} = dk(X1,X2)/dX1_2dX2_3\n% ...\n% DKff{m} = dk(X1,X2)/dX1_(m-1)dX2_m\n% where _m denotes the input dimension with respect to which the\n% gradient is calculated.\n% ---- clip ---\n% \n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_PROD_GINPUT, GPCF_PROD_GINPUT2, GPCF_PROD_CFDG2 \n\nncf = length(gpcf.cf);\n\n% check whether there are any covariance functions that depend on dims\n% covariate\nind = [];\nfor i1 = 1:ncf\n if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims1)) || any(ismember(gpcf.cf{i1}.selectedVariables,dims2)) )\n ind(end+1) = i1;\n end\nend\n% Calculate derivative\nif ~isempty(ind)\n % evaluate the individual covariance functions\n C = 1;\n K = 0;\n for i1=1:ncf\n Ci{i1} = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n C = C.*Ci{i1};\n end\n for i1=1:ncf\n if any(i1 == ind)\n % double derivative of i'th covariance function\n Dt = gpcf.cf{i1}.fh.ginput3(gpcf.cf{i1}, x, x2, dims1, dims2);\n if length(Dt)>1\n error('gpcf_prod->ginput3: something is wrong')\n end\n K = K+Dt{1}./Ci{i1};\n % pairwise derivatives of i'th and j'th covariance functions\n Dti1 = gpcf.cf{i1}.fh.ginput4(gpcf.cf{i1}, x, x2, dims1);\n Dti2 = gpcf.cf{i1}.fh.ginput4(gpcf.cf{i1}, x2, x, dims2);\n for j1=i1+1:ncf\n if any(j1 == ind)\n Dtj1 = gpcf.cf{j1}.fh.ginput4(gpcf.cf{j1}, x, x2, dims1);\n Dtj2 = gpcf.cf{j1}.fh.ginput4(gpcf.cf{j1}, x2, x, dims2);\n \n K = K + (Dti1{1}.*Dtj2{1}' + Dtj1{1}.*Dti2{1}')./Ci{i1}./Ci{j1};\n end\n end\n end\n end\n DKff = {C.*K};\nelse\n DKff = {0};\nend\n\n\nend\n\nfunction DKff = gpcf_prod_ginput4(gpcf, x, x2, dims)\n%GPCF_PROD_GINPUT4 Evaluate gradient of covariance function with \n% respect to x. Simplified and faster version of\n% sexp_ginput, returns full matrices.\n%\n% Description\n% DKff = GPCF_PROD_GINPUT4takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to X (whole matrix). This subfunction is needed when \n% using derivative observations.\n% \n% Note! When coding the derivatives of the covariance function, remember\n% to double check them. See gp_cov for lines of code to check the\n% matrices\n%\n% See also\n% GPCF_PROD_GINPUT, GPCF_PROD_GINPUT2, GPCF_PROD_CFDG2 \n\nncf = length(gpcf.cf);\n\n% check whether there are any covariance functions that depend on dims\n% covariate\nind = [];\nfor i1 = 1:ncf\n if (~isfield(gpcf.cf{i1}, 'selectedVariables') || any(ismember(gpcf.cf{i1}.selectedVariables,dims)))\n ind(end+1) = i1;\n end\nend\n% Calculate derivative\nif ~isempty(ind)\n % evaluate the individual covariance functions\n C = 1;\n K = 0;\n for i1=1:ncf\n Ci = gpcf.cf{i1}.fh.cov(gpcf.cf{i1}, x, x2);\n C = C.*Ci;\n if any(i1 == ind) \n Dt = gpcf.cf{i1}.fh.ginput4(gpcf.cf{i1}, x, x2, dims);\n if length(Dt)>1\n error('gpcf_prod->ginput4: something is wrong')\n end\n K = K+Dt{1}./Ci;\n end\n end\n DKff = {C.*K};\nelse\n DKff = {0};\nend\n\n\nend\n\n\n\nfunction C = gpcf_prod_cov(gpcf, x1, x2)\n%GP_PROD_COV Evaluate covariance matrix between two input vectors\n%\n% Description \n% C = GP_PROD_COV(GP, TX, X) takes in covariance function of a\n% Gaussian process GP and two matrixes TX and X that contain\n% input vectors to GP. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i in TX\n% and j in X. This is a mandatory subfunction used for example in\n% prediction and energy computations.\n%\n%\n% See also\n% GPCF_PROD_TRCOV, GPCF_PROD_TRVAR, GP_COV, GP_TRCOV\n \n if isempty(x2)\n x2=x1;\n end\n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n\n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n\n ncf = length(gpcf.cf);\n \n % evaluate the individual covariance functions\n C = 1;\n for i=1:ncf\n cf = gpcf.cf{i};\n C = C.*cf.fh.cov(cf, x1, x2);\n end \nend\n\nfunction C = gpcf_prod_trcov(gpcf, x)\n%GP_PROD_TRCOV Evaluate training covariance matrix of inputs\n%\n% Description\n% C = GP_PROD_TRCOV(GP, TX) takes in covariance function of a\n% Gaussian process GP and matrix TX that contains training\n% input vectors. Returns covariance matrix C. Every element ij\n% of C contains covariance between inputs i and j in TX. This \n% is a mandatory subfunction used for example in prediction and \n% energy computations.\n%\n% See also\n% GPCF_PROD_COV, GPCF_PROD_TRVAR, GP_COV, GP_TRCOV\n ncf = length(gpcf.cf);\n \n % evaluate the individual covariance functions\n C = 1;\n for i=1:ncf\n cf = gpcf.cf{i};\n C = C.*cf.fh.trcov(cf, x);\n end\nend\n\nfunction C = gpcf_prod_trvar(gpcf, x)\n% GP_PROD_TRVAR Evaluate training variance vector\n%\n% Description\n% C = GP_PROD_TRVAR(GPCF, TX) takes in covariance function of\n% a Gaussian process GPCF and matrix TX that contains training\n% inputs. Returns variance vector C. Every element i of C\n% contains variance of input i in TX. This is a mandatory \n% subfunction used for example in prediction and energy computations.\n%\n% See also\n% GPCF_PROD_COV, GP_COV, GP_TRCOV\n\n\n ncf = length(gpcf.cf);\n \n % evaluate the individual covariance functions\n C = 1;\n for i=1:ncf\n cf = gpcf.cf{i};\n C = C.*cf.fh.trvar(cf, x);\n end\nend\n\nfunction reccf = gpcf_prod_recappend(reccf, ri, gpcf)\n%RECAPPEND Record append\n%\n% Description\n% RECCF = GPCF_PROD_RECAPPEND(RECCF, RI, GPCF) takes a\n% covariance function record structure RECCF, record index RI\n% and covariance function structure GPCF with the current MCMC\n% samples of the parameters. Returns RECCF which contains all\n% the old samples and the current samples from GPCF. This \n% subfunction is needed when using MCMC sampling (gp_mc).\n%\n% See also\n% GP_MC, GP_MC->RECAPPEND\n \n if nargin == 2\n % Initialize the record\n reccf.type = 'gpcf_prod';\n\n % Initialize parameters\n ncf = length(ri.cf);\n for i=1:ncf\n cf = ri.cf{i};\n reccf.cf{i} = cf.fh.recappend([], ri.cf{i});\n end\n \n % Set the function handles\n reccf.fh.pak = @gpcf_prod_pak;\n reccf.fh.unpak = @gpcf_prod_unpak;\n reccf.fh.lp = @gpcf_prod_lp;\n reccf.fh.lpg = @gpcf_prod_lpg;\n reccf.fh.cfg = @gpcf_prod_cfg;\n reccf.fh.cov = @gpcf_prod_cov;\n reccf.fh.trcov = @gpcf_prod_trcov;\n reccf.fh.trvar = @gpcf_prod_trvar;\n reccf.fh.recappend = @gpcf_prod_recappend;\n else\n % Append to the record\n \n % Loop over all of the covariance functions\n ncf = length(gpcf.cf);\n for i=1:ncf\n cf = gpcf.cf{i};\n reccf.cf{i} = cf.fh.recappend(reccf.cf{i}, ri, cf);\n end\n end\nend\n\nfunction [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = gpcf_prod_cf2ss(gpcf,x)\n%GPCF_PROD_CF2SS Convert the covariance function to state space form\n%\n% Description\n% Convert the sum of two covariance functions to the corresponding\n% sum of two state space models. Details on how this is done can\n% be found in the reference:\n%\n% References\n% Arno Solin and Simo Sarkka (2014). Explicit link between periodic \n% covariance functions and state space models. Accepted for \n% publication in Proceedings of the Seventeenth International \n% Conference on Artifcial Intelligence and Statistics (AISTATS 2014).\n%\n\n % Check arguments\n if nargin < 2, x = []; end\n\n % Vector of function handles of conversion functions \n % from covariance functions to state space \n cf2ssvect = cell(length(gpcf.cf),1);\n for k = 1:length(gpcf.cf)\n \n % Initial function handle \n fh = @(y) gpcf.cf{k}.fh.cf2ss(gpcf.cf{k},x);\n \n % Deal with the periodic (deterministic) covariance function\n % as a special case\n if isequal(gpcf.cf{k}.type,'gpcf_periodic') && gpcf.cf{k}.decay == 0\n cf2ssvect{k} = @(y) cf2ss_periodicprod(fh);\n else\n cf2ssvect{k} = fh;\n end\n \n end\n \n % Return model matrices, derivatives and parameter information\n [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = ...\n cf_prod_to_ss(cf2ssvect);\n \nend\n\nfunction [F,L,Pinf1,H,Pinf,dF,dPinf,dPinf1,params] = cf2ss_periodicprod(fh)\n% CF2SS_PERIODICPROD - Computes Qc values for periodic covariance production\n\n [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = fh();\n Pinf1 = Pinf; dPinf1 = dPinf;\nend\n\n\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/gp/gpcf_prod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.0495890189458586, "lm_q1q2_score": 0.02247680963619257}} {"text": "function exact = p00_exact ( prob )\n\n%*****************************************************************************80\n%\n%% P00_EXACT returns the exact integral for any problem.\n%\n% Discussion:\n%\n% This routine provides a \"generic\" interface to the exact integral\n% routines for the various problems, and allows a problem to be called\n% by number (PROB) rather than by name.\n%\n% In some cases, the \"exact\" value of the integral is in fact\n% merely a respectable approximation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROB, the number of the desired test problem.\n%\n% Output, real EXACT, the exact value of the integral.\n%\n if ( prob == 1 )\n exact = p01_exact ( );\n elseif ( prob == 2 )\n exact = p02_exact ( );\n elseif ( prob == 3 )\n exact = p03_exact ( );\n elseif ( prob == 4 )\n exact = p04_exact ( );\n elseif ( prob == 5 )\n exact = p05_exact ( );\n elseif ( prob == 6 )\n exact = p06_exact ( );\n elseif ( prob == 7 )\n exact = p07_exact ( );\n elseif ( prob == 8 )\n exact = p08_exact ( );\n elseif ( prob == 9 )\n exact = p09_exact ( );\n elseif ( prob == 10 )\n exact = p10_exact ( );\n elseif ( prob == 11 )\n exact = p11_exact ( );\n elseif ( prob == 12 )\n exact = p12_exact ( );\n elseif ( prob == 13 )\n exact = p13_exact ( );\n elseif ( prob == 14 )\n exact = p14_exact ( );\n elseif ( prob == 15 )\n exact = p15_exact ( );\n elseif ( prob == 16 )\n exact = p16_exact ( );\n elseif ( prob == 17 )\n exact = p17_exact ( );\n elseif ( prob == 18 )\n exact = p18_exact ( );\n elseif ( prob == 19 )\n exact = p19_exact ( );\n elseif ( prob == 20 )\n exact = p20_exact ( );\n elseif ( prob == 21 )\n exact = p21_exact ( );\n elseif ( prob == 22 )\n exact = p22_exact ( );\n elseif ( prob == 23 )\n exact = p23_exact ( );\n elseif ( prob == 24 )\n exact = p24_exact ( );\n elseif ( prob == 25 )\n exact = p25_exact ( );\n elseif ( prob == 26 )\n exact = p26_exact ( );\n elseif ( prob == 27 )\n exact = p27_exact ( );\n elseif ( prob == 28 )\n exact = p28_exact ( );\n elseif ( prob == 29 )\n exact = p29_exact ( );\n elseif ( prob == 30 )\n exact = p30_exact ( );\n elseif ( prob == 31 )\n exact = p31_exact ( );\n elseif ( prob == 32 )\n exact = p32_exact ( );\n elseif ( prob == 33 )\n exact = p33_exact ( );\n elseif ( prob == 34 )\n exact = p34_exact ( );\n elseif ( prob == 35 )\n exact = p35_exact ( );\n elseif ( prob == 36 )\n exact = p36_exact ( );\n elseif ( prob == 37 )\n exact = p37_exact ( );\n elseif ( prob == 38 )\n exact = p38_exact ( );\n elseif ( prob == 39 )\n exact = p39_exact ( );\n elseif ( prob == 40 )\n exact = p40_exact ( );\n elseif ( prob == 41 )\n exact = p41_exact ( );\n elseif ( prob == 42 )\n exact = p42_exact ( );\n elseif ( prob == 43 )\n exact = p43_exact ( );\n elseif ( prob == 44 )\n exact = p44_exact ( );\n elseif ( prob == 45 )\n exact = p45_exact ( );\n elseif ( prob == 46 )\n exact = p46_exact ( );\n elseif ( prob == 47 )\n exact = p47_exact ( );\n elseif ( prob == 48 )\n exact = p48_exact ( );\n elseif ( prob == 49 )\n exact = p49_exact ( );\n elseif ( prob == 50 )\n exact = p50_exact ( );\n elseif ( prob == 51 )\n exact = p51_exact ( );\n elseif ( prob == 52 )\n exact = p52_exact ( );\n elseif ( prob == 53 )\n exact = p53_exact ( );\n elseif ( prob == 54 )\n exact = p54_exact ( );\n elseif ( prob == 55 )\n exact = p55_exact ( );\n elseif ( prob == 56 )\n exact = p56_exact ( );\n elseif ( prob == 57 )\n exact = p57_exact ( );\n elseif ( prob == 58 )\n exact = p58_exact ( );\n elseif ( prob == 59 )\n exact = p59_exact ( );\n elseif ( prob == 60 )\n exact = p60_exact ( );\n elseif ( prob == 61 )\n exact = p61_exact ( );\n elseif ( prob == 62 )\n exact = p62_exact ( );\n elseif ( prob == 63 )\n exact = p63_exact ( );\n elseif ( prob == 64 )\n exact = p64_exact ( );\n elseif ( prob == 65 )\n exact = p65_exact ( );\n elseif ( prob == 66 )\n exact = p66_exact ( );\n elseif ( prob == 67 )\n exact = p67_exact ( );\n elseif ( prob == 68 )\n exact = p68_exact ( );\n elseif ( prob == 69 )\n exact = p69_exact ( );\n elseif ( prob == 70 )\n exact = p70_exact ( );\n elseif ( prob == 71 )\n exact = p71_exact ( );\n elseif ( prob == 72 )\n exact = p72_exact ( );\n elseif ( prob == 73 )\n exact = p73_exact ( );\n elseif ( prob == 74 )\n exact = p74_exact ( );\n elseif ( prob == 75 )\n exact = p75_exact ( );\n elseif ( prob == 76 )\n exact = p76_exact ( );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_EXACT - Fatal error!\\n' );\n fprintf ( 1, ' Illegal problem number = %d\\n', prob );\n error ( 'P00_EXACT - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p00_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.06008665522337757, "lm_q1q2_score": 0.02246494765923955}} {"text": "%% Intermediate Usage (for building complicated systems)\n% This document builds upon and explains how to\n% describe the problem in a more flexible way.\n\n%% Example Code\n% We examine a portion of the last code discussed in :\n[E, H, obj_array, src_array] = maxwell_run(...\n\t'OSC', 1e-9, 1550, ...\n\t'DOM', {'vacuum', 'none', 1.0}, [-1100 1100; -1100 2600; 0 10], 10, BC.p, [100 100 0],...\n\t'OBJ', {'CRC/Ag', 'k'}, ...\n\t\tBox([-1100 -80; 0 1000; 0 10]), ...\n\t\tBox([80 1100; 0 1000; 0 10]), ...\n\t'SRCJ', PlaneSrc(Axis.y, -500, Axis.x), ...\n\ttrue);\n\n%% Passing Variables as Arguments\n% You can store any arugments of <../comp/maxwell_run.html |maxwell_run|> in\n% variables and pass the variables instead of the arguments to |maxwell_run|.\n% This increases the readability of the code. For example, the meaning of the\n% last logical argument |true| in the above code is hard to figure out from the\n% code itself. We can define a variable |inspect_only| and modify the code as:\ninspect_only = true;\n[E, H, obj_array, src_array] = maxwell_run(...\n\t{PARAMETER GROUPS}, ...\n\tinspect_only);\n\n%%%\n% Now, it is more obvious that |inspect_only = true| makes |maxwell_run| inpect\n% the problem without solving it.\n%\n% Similarly, you can define a variable for the color code used for a material.\n% Because the actual color of silver is closer to gray than black, let's define\n% a RGB vector and substitute it for the color code 'k' used for the material\n% |'CRC/Ag'|:\ninspect_only = true;\ngray = [0.5 0.5 0.5]; % [r g b]\n[E, H, obj_array, src_array] = maxwell_run(...\n\t{OTHER PARAMETER GROUPS}, ...\n\t'OBJ', {'CRC/Ag', gray}, ...\n\t\tBox([-1100 -80; 0 1000; 0 10]), ...\n\t\tBox([80 1100; 0 1000; 0 10]), ...\n\tinspect_only);\n\n%%% \n% Upon execution, the above code generates the following figure describing the\n% simulation domain:\n%\n% <<../img/intermediate_01.png>>\n%\n% Compare this with the last figure in and note that\n% the two silver boxes are now drawn in gray.\n\n%% Building Shapes Beforehand\n% You can build the shapes of objects outside |maxwell_run|, store them in\n% variables, and pass the variables to |maxwell_run|:\ninspect_only = true;\nshape1 = Box([-1100 -80; 0 1000; 0 10]);\nshape2 = Box([80 1100; 0 1000; 0 10]);\ngray = [0.5 0.5 0.5]; % [r g b]\n[E, H, obj_array, src_array] = maxwell_run(...\n\t{OTHER PARAMETER GROUPS}, ...\n\t'OBJ', {'CRC/Ag', gray}, shape1, shape2, ...\n\tinspect_only);\n\n%%%\n% Defining shape variables before |maxwell_run| this way could be useful when,\n% for example, you want to calculate the size of the shapes using complicated\n% equations.\n%\n% You can even create an array of shapes and pass it as a single argument:\ninspect_only = true;\nshape1 = Box([-1100 -80; 0 1000; 0 10]);\nshape2 = Box([80 1100; 0 1000; 0 10]);\nshape_array = [shape1, shape2];\ngray = [0.5 0.5 0.5]; % [r g b]\n[E, H, obj_array, src_array] = maxwell_run(...\n\t{OTHER PARAMETER GROUPS}, ...\n\t'OBJ', {'CRC/Ag', gray}, shape_array, ...\n\tinspect_only);\n\n%%%\n% Passing an array of shapes as an argument can be useful when the number of\n% shapes is not fixed.\n\n%% Complete Code\n% As shown above, |maxwell_run| allows flexible ways to construct arguments. In\n% fact, you can construct most arguments outside |maxwell_run|, store them in\n% variables, and pass the variables to |maxwell_run|. Below is a complete\n% example that does so.\ninspect_only = true;\n\n% Geometric Parameters\nL0 = 1e-9; % length unit\nwvlen = 1550; % wavelength\ndL = 10; % grid size\nLpml = 10*dL; % PML thickness\nxn = -1000-Lpml; xp = 1000+Lpml; % x boundaries\nyn = -1000-Lpml; yp = 2500+Lpml; % y boundaries\nzn = 0; zp = dL; % z boundaries\nw = 160; % slit width\nh = 1000; % metal thickness\n\n% Materials and Shapes\nvacuum = Material('vacuum', 'none', 1.0);\nshape1 = Box([xn -w/2; 0 h; zn zp]);\nshape2 = Box([w/2 xp; 0 h; zn zp]);\nshape_array = [shape1, shape2];\ngray = [0.5 0.5 0.5]; % [r g b]\n\n% Source\ny_src = -500;\npolarization = Axis.x;\nsrc = PlaneSrc(Axis.y, y_src, polarization);\n\n% Solution\n[E, H, obj_array, src_array] = maxwell_run(...\n\t'OSC', L0, wvlen, ...\n\t'DOM', vacuum, [xn xp; yn yp; zn zp], dL, BC.p, [Lpml Lpml 0],...\n\t'OBJ', {'CRC/Ag', gray}, shape_array, ...\n\t'SRCJ', src, ...\n\tinspect_only);\n\n\n\n%%% See Also\n% \n\n\n\n\n\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/doc/src/intermediate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.045352580070439, "lm_q1q2_score": 0.02232200183499748}} {"text": "function value = p20_r8 ( action, name, value )\n\n%*****************************************************************************80\n%\n%% P20_R8 sets or gets R8 parameters for problem 20.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string ACTION,\n% 'D' sets the parameter to its default value;\n% 'G' gets a parameter.\n% 'R' sets the parameter to a random value.\n% 'S' sets a parameter,\n%\n% Input, string NAME, the name of the parameter.\n% 'A' is the value of all lower integral bounds.\n% 'B' is the value of all upper integral bounds.\n% 'P' is the value of the exponent in the integrand.\n%\n% Input/output, real VALUE.\n% * If ACTION = 'S', then VALUE is an input quantity, and is the\n% new value to be assigned to NAME.\n% * If ACTION = 'G' or 'R', then VALUE is an output quantity, \n% and is the current value of NAME.\n%\n persistent a;\n persistent b;\n persistent p;\n\n if ( action == 'D' | action == 'd' )\n\n if ( name == 'A' | name == 'a' | name == '*' )\n a = 0.0;\n end\n\n if ( name == 'B' | name == 'b' | name == '*' )\n b = 1.0;\n end\n\n if ( name == 'P' | name == 'p' | name == '*' )\n p = 2.0;\n end\n\n elseif ( action == 'G' | action == 'g' )\n\n if ( name == 'A' | name == 'a' )\n value = a;\n elseif ( name == 'B' | name == 'b' )\n value = b;\n elseif ( name == 'P' | name == 'p' )\n value = p;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P20_R8 - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized name = \"%s\".\\n', name );\n error ( 'P20_R8 - Fatal error!' );\n end\n\n elseif ( action == 'R' | action == 'r' )\n\n if ( name == 'A' | name == 'a' )\n a = rand ( 1, 1 );\n value = a;\n elseif ( name == 'B' | name == 'b' )\n b = rand ( 1, 1 );\n value = b;\n elseif ( name == 'P' | name == 'p' )\n p = rand ( 1, 1 );\n value = p;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P20_R8 - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized name = \"%s\".\\n', name );\n error ( 'P20_R8 - Fatal error!' );\n end\n\n elseif ( action == 'S' | action == 's' )\n\n if ( name == 'A' | name == 'a' )\n a = value;\n elseif ( name == 'B' | name == 'b' )\n b = value;\n elseif ( name == 'P' | name == 'p' )\n p = value;\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P20_R8 - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized name = \"%s\".\\n', name );\n error ( 'P20_R8 - Fatal error!' );\n end\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P20_R8 - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized action = \"%s\".\\n', action );\n error ( 'P20_R8 - Fatal error!' );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p20_r8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.045352576360788946, "lm_q1q2_score": 0.021614115016863514}} {"text": "function H=tricontour(tri,x,y,z,v,levels,color)\n%TRICONTOUR Contour plot for triangulated data.\n% TRICONTOUR(TRI,X,Y,Z,Levels) displays the contour plot based on\n% triangles defined in the M-by-3 face matrix TRI as a surface. A\n% row of TRI contains indexes into the X,Y, and Z vertex vectors\n% to define a single triangular face.\n%\n% TRICONTOUR(TRI,X,Y,Z,V,Levels) displays the contour plot based on\n% triangles defined in the M-by-3 face matrix TRI as a surface. A\n% row of TRI contains indexes into the X,Y, and Z vertex vectors\n% to define a single triangular face. The contours are determined\n% by the values V and the Levels.\n%\n% H = TRICONTOUR(...) a vector H of handles to LINE or PATCH objects,\n% one handle per line. TRICONTOUR is not compatible with CLABEL.\n%\n% The contours are normally colored based on the current colormap\n% and are drawn as PATCH objects. You can override this behavior\n% with the syntax CONTOUR(...,'LINESPEC') to draw the contours as\n% LINE objects with the color and linetype specified.\n%\n% Example:\n% x=rand(20); y=rand(20); z=rand(20); tri=delaunay(x,y);\n% tricontour(tri,x,y,z,.3:.1:1); colorbar\n%\n% See also CONTOUR, CONTOURF, TRICONTOURF\n\n%----- LGPL --------------------------------------------------------------------\n%\n% Copyright (C) 2011-2013 Stichting Deltares.\n%\n% This library is free software; you can redistribute it and/or\n% modify it under the terms of the GNU Lesser General Public\n% License as published by the Free Software Foundation version 2.1.\n%\n% This library 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 GNU\n% Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this library; if not, see .\n%\n% contact: delft3d.support@deltares.nl\n% Stichting Deltares\n% P.O. Box 177\n% 2600 MH Delft, The Netherlands\n%\n% All indications and logos of, and references to, \"Delft3D\" and \"Deltares\"\n% are registered trademarks of Stichting Deltares, and remain the property of\n% Stichting Deltares. All rights reserved.\n%\n%-------------------------------------------------------------------------------\n% http://www.deltaressystems.com\n% $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/trunk/src/tools_lgpl/matlab/quickplot/progsrc/tricontour.m $\n% $Id: tricontour.m 2498 2013-05-16 12:38:27Z jagers $\n\nerror(nargchk(5,7,nargin));\ngetdata=0;\nif nargin==7\n if strcmp(color,'getdata')\n getdata=1;\n lin = '*';\n col = '*';\n else\n [lin,col,mark,msg] = colstyle(color);\n if ~isempty(msg)\n error(msg)\n end\n end\nelseif nargin==6\n if ischar(levels)\n color=levels;\n levels=v;\n v=z;\n z=[];\n if strcmp(color,'getdata')\n getdata=1;\n lin = '*';\n col = '*';\n else\n [lin,col,mark,msg] = colstyle(color);\n if ~isempty(msg)\n error(msg)\n end\n end\n else\n lin = '';\n col = '';\n end\nelse\n levels=v;\n v=z;\n z=[];\n lin = '';\n col = '';\nend\n\nif ~getdata\n ax = newplot;\n if isempty(col) % no color spec was given\n colortab = get(ax,'colororder');\n ncol = size(colortab,1);\n end\nend\n\nx=transpose(x(:));\ny=transpose(y(:));\nzdef=~isempty(z);\nif zdef\n z=transpose(z(:));\nend\nv=transpose(v(:));\n\nPatches=1:size(tri,1);\nnlevels = length(levels);\nif getdata\n H=cell(1,nlevels);\nelse\n H=zeros(1,nlevels);\nend\nNonEmptyLevel=zeros(1,nlevels);\nfor LevelNr=1:nlevels\n level=levels(LevelNr);\n Nlarger=sum(v(tri)>level,2);\n Nsmaller=sum(v(tri)level,2);\n Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);\n % last element has elevation larger than level\n VTemp=v(Index);\n Lambda=min(1,(level-VTemp(:,[1 2]))./(VTemp(:,3)*ones(1,2)-VTemp(:,[1 2])));\n XPoint=transpose(x(Index(:,[1 2]))+Lambda.*(transpose(x(Index(:,3)))*ones(1,2)-x(Index(:,[1 2]))));\n XLevel(LvlIndex(:))=XPoint(:);\n YPoint=transpose(y(Index(:,[1 2]))+Lambda.*(transpose(y(Index(:,3)))*ones(1,2)-y(Index(:,[1 2]))));\n YLevel(LvlIndex(:))=YPoint(:);\n if zdef\n ZPoint=transpose(z(Index(:,[1 2]))+Lambda.*(transpose(z(Index(:,3)))*ones(1,2)-z(Index(:,[1 2]))));\n ZLevel(LvlIndex(:))=ZPoint(:);\n end\n LvlOffset=LvlOffset+3*length(Patch);\n end\n \n % patches with one equal and two larger or two smaller\n Patch=Patches((CLIndex==3) | (CLIndex==9));\n if ~isempty(Patch)\n LvlIndex=LvlOffset+(1:2:(2*length(Patch)));\n Index=tri(Patch,:);\n [Dummy,Permutation]=sort(v(Index)==level,2);\n Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);\n % third element has elevation equal to level\n Index=Index(:,3);\n XPoint=x(Index);\n XLevel(LvlIndex(:))=XPoint(:);\n YPoint=y(Index);\n YLevel(LvlIndex(:))=YPoint(:);\n if zdef\n ZPoint=z(Index);\n ZLevel(LvlIndex(:))=ZPoint(:);\n end\n LvlOffset=LvlOffset+2*length(Patch);\n end\n \n VLevel=level*ones(size(XLevel));\n \n NonEmptyLevel(LevelNr)=1;\n if getdata\n if zdef\n H{LevelNr}={XLevel YLevel ZLevel LevelNr};\n else\n H{LevelNr}={XLevel YLevel LevelNr};\n end\n elseif isempty(col) && isempty(lin)\n if ~zdef\n ZLevel=VLevel;\n end\n NewH = patch('XData',transpose([XLevel;XLevel]), ...\n 'YData',transpose([YLevel;YLevel]), ...\n 'ZData',transpose([ZLevel;ZLevel]), ...\n 'CData',transpose([VLevel;VLevel]), ...\n 'facecolor','none', ...\n 'edgecolor','flat',...\n 'userdata',level, ...\n 'parent',ax);\n H(LevelNr)=NewH;\n else\n if ~zdef\n ZLevel=VLevel;\n end\n NewH = line('XData',XLevel, ...\n 'YData',YLevel, ...\n 'ZData',ZLevel, ...\n 'userdata',level, ...\n 'parent',ax);\n H(LevelNr)=NewH;\n end\nend\n\nlevels=levels(logical(NonEmptyLevel));\n\nif getdata\n % do nothing\nelseif isempty(col) && ~isempty(lin)\n nlvl = length(levels);\n colortab = colortab(mod(1:nlvl,ncol)+1,:);\n for i = 1:length(H)\n set(H(i),'linestyle',lin,'color',colortab(i,:));\n end\nelse\n if ~isempty(lin)\n set(H,'linestyle',lin);\n end\n if ~isempty(col)\n set(H,'color',col);\n end\nend", "meta": {"author": "CHLNDDEV", "repo": "OceanMesh2D", "sha": "56222604a5c1fe897d10c8b08cb3380ef8b43740", "save_path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D", "path": "github-repos/MATLAB/CHLNDDEV-OceanMesh2D/OceanMesh2D-56222604a5c1fe897d10c8b08cb3380ef8b43740/utilities/tricontour.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.04272219495648557, "lm_q1q2_score": 0.02119421729936613}} {"text": "% 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 St, Fifth Floor, Boston, MA 02110-1301 USA\n%TFDEMO4 Cohen's class time-frequency distributions.\n%\tTime-Frequency Toolbox demonstration.\n%\n%\tSee also TFDEMO.\n\n%\tO. Lemoine - May 1996. \n%\tCopyright (c) CNRS.\n\nclc; zoom on; clf; \necho on;\n\n% The Wigner-Ville distribution\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% A time-frequency energy distribution which is particularly interesting \n% is the Wigner-Ville distribution (WVD),which satisfies a large number \n% of desirable mathematical properties. Let us see what we obtain on two \n% particular synthetic signals :\n% - the first signal is the academic linear chirp signal :\n\nsig=fmlin(128);\n\n% If we choose a 3-dimension plot to represent it, we can see that the WVD\n% can take negative values, and that the localization obtained in the\n% time-frequency plane for this signal is almost perfect.\n\ntfrwv(sig);\n% Press any key to continue...\n \npause ; clc;\n\n% - the second one illustrates the Doppler effect, which expresses the \n% dependence of the frequency received by an observer from a transmitter\n% on the relative speed between the observer and the transmitter : \n\n[fm,am,iflaw]=doppler(128,50,13,10,200);\nsig=am.*fm;\ntfrwv(sig);\n% Looking at this time-frequency distribution, we notice that the energy is\n% not distributed as we could expect for this signal. Although the signal\n% term is well localized in the time-frequency plane, numerous other terms\n% (the interference terms, due to the bilinearity of the WVD) are present at\n% positions in time and frequency where the energy should be null. \n%\n% Press any key to continue...\n \npause; clc; close\n\n% Interference geometry of the WVD\n%\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% The rule of interference construction of the WVD can be summarized as\n% follows : two points of the time-frequency plane interfere to create a\n% contribution on a third point which is located at their geometrical\n% midpoint. Besides, these interference terms oscillate perpendicularly to\n% the line joining the two points interfering, with a frequency\n% proportional to the distance between these two points.\n% This can be seen on the following example : we consider two atoms in\n% the time-frequency plane, analyzed by the WVD, whose relative distance \n% is increasing from one realization to the other, and then decreasing. \n% The WVDs were calculated and saved on the file movieat.mat. We load them \n% and run the sequence using the function movie :\n\nM=movwv2at(128,15); movie(M,10); clear M;\n\n% We can notice, from this movie, the evolution of the interferences\n% when the distance between the two interfering terms changes, and in\n% particular the change in the period and the direction of the oscillations.\n%\n% Press any key to continue...\n\npause; clc;\n \n% The pseudo-WVD\n%\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% As the analyzed signal is not known from -infinity to +infinity in\n% pratice, one often consider a windowed version of the WVD, called the\n% pseudo-WVD. The time-windowing operated has the effect of smoothing the\n% WVD in frequency. Thus, because of their oscillating nature, the \n% interferences will be attenuated in the pseudo-WVD compared to the WVD.\n% However, the consequence of this improved readability is that many \n% properties of the WVD are lost.\n% If we consider a signal composed of four gaussian atoms, each localized\n% at a corner of a rectangle,\n\nsig=atoms(128,[32,.15,20,1;96,.15,20,1;32,.35,20,1;96,.35,20,1]);\n\n% and compute its WVD\n\ntfrwv(sig);\n% we can see the four signal terms, along with six interference terms (two of\n% them are superimposed). If we now compute the pseudo-WVD,\n\nfigure\ntfrpwv(sig);\n% we can note the important attenuation of the interferences oscillating\n% perpendicularly to the frequency axis, and in return the spreading in\n% frequency of the signal terms.\n%\n% Press any key to continue...\n \npause; clc; close;\n \n% Importance of the analytic signal\n%\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% Due to the quadratic nature of the WVD, its discrete version may be \n% affected by a spectral aliasing, in particular if the signal x is \n% real-valued and sampled at the Nyquist rate. A solution to this problem \n% consists in using the analytic signal. Indeed, as its bandwidth is half the\n% one of the real signal, the aliasing will not take place in the useful\n% spectral domain [0,1/2] of this signal. This solution presents a second\n% advantage : since the spectral domain is divided by two, the number of\n% components in the time-frequency plane is also divided by two. \n% Consequently, the number of interference terms decreases significantly. \n% Here is an illustration : we first consider the WVD of the real part of \n% a signal composed of two atoms :\n\nsig=atoms(128,[32,0.15,20,1;96,0.32,20,1]);\ntfrwv(real(sig));\n% We can see that four signal terms are present instead of two, due to the\n% spectral aliasing. Besides, because of the components located at negative\n% frequencies (between -1/2 and 0), additional interference terms are\n% present. \n%\n% Press any key to continue...\n\npause; \n\n% If we now consider the WVD of the same signal, but in its complex\n% analytic form,\n\ntfrwv(sig);\n% the aliasing effect has disappeared, as well as the terms corresponding to\n% interferences between negative- and positive- frequency components.\n%\n% Press any key to continue...\n\npause; clc; \n\n% The Cohen's class\n%~~~~~~~~~~~~~~~~~~~\n% The Cohen's class gather all the time-frequency energy distributions which\n% are covariant by translations in time and in frequency. It can be expressed\n% as a 2-D correlation between a function PI(t,nu) and the WVD of the \n% analyzed signal. The WVD is the element of the Cohen's class for which PI \n% is a double Dirac, and the spectrogram is th element for which PI is the \n% WVD of the short time window h. We consider in the following other elements\n% of this class\n% \n% The smoothed pseudo-WVD\n%\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% If we consider a separable smoothing function PI(t,nu)=g(t)H(-nu) (where \n% H(nu) is the Fourier transform of a smoothing window h(t)), we allow a \n% progressive and independent control, in both time and frequency, of the \n% smoothing applied to the WVD. The obtained distribution is known as the \n% smoothed-pseudo WVD. \n% For example,let's consider a signal composed of two components : the first \n% one is a complex sinusoid (normalized frequency 0.15) and the second one \n% is a Gaussian signal shifted in time and frequency : \n\nsig=sigmerge(fmconst(128,.15),amgauss(128).*fmconst(128,0.4),5);\n \n% If we display the WVD, the pseudo-WV and the smoothed-pseudo-WVD of it,\n\ntfrwv(sig); \nfigure; tfrpwv(sig); \nfigure; tfrspwv(sig);\n% we can make the following remarks : from the WVD, we can see the two\n% signal terms located at the right positions in the time-frequency plane,\n% as well as the interference terms between them. As these interference \n% terms oscillate globally perpendicularly to the time-axis, the frequency\n% smoothing done by the pseudo-WVD degrades the frequency resolution without\n% really attenuating the interferences. On the other hand, the time-smoothing\n% carried out by the smoothed-pseudo-WVD considerably reduces these\n% interferences.\n%\n% Press any key to continue...\n\npause; clc; close; close; close\n\n\n% An interresting property of the smoothed-pseudo WVD is that it allows a\n% continuous passage from the spectrogram to the WVD, under the condition\n% that the smoothing functions g and h are gaussian. This is clearly \n% illustrated by the function movsp2wv.m, which considers different \n% transitions, on a signal composed of four atoms :\n\nM=movsp2wv(128,15); movie(M,10); clear M;\n\n% This movie shows the effect of a (time/frequency) smoothing on the\n% interferences and on the resolutions : the WVD gives the best resolutions\n% (in time and in frequency), but presents the most important interferences,\n% whereas the spectrogram gives the worst resolutions, but with nearly no\n% interferences ; and the smoothed-pseudo WVD allows to choose the best\n% compromise between these two extremes.\n%\n% Press any key to continue...\n\npause; clc; \n\n% The narrow-band ambiguity function\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% The narrow-band ambiguity function, often used in radar signal processing,\n% is the two-dimensional Fourier transform of the WVD. This property can be \n% used to attenuate some of the interference terms. Indeed, in the case of \n% a multi-component signal, the elements of the AF corresponding to the \n% signal components (denoted as the AF-signal terms) are mainly located \n% around the origin, whereas the elements corresponding to interferences \n% between the signal components (AF-interference terms) appear at a distance\n% from the origin which is proportional to the time-frequency distance\n% between the involved components. This can be noticed on a simple example :\n% We apply consider a signal composed of two linear FM signals with \n% gaussian amplitudes :\n\nN=64; sig1=fmlin(N,0.2,0.5).*amgauss(N);\nsig2=fmlin(N,0.3,0).*amgauss(N);\nsig=[sig1;sig2]; \n\n% Let us first have a look at the WVD :\n\ntfrwv(sig);\n% We have two distinct signal terms, and some interferences oscillating in\n% the middle. \n%\n% Press any key to continue...\n\npause;\n\n% If we look at the ambiguity function of this signal,\n\nclf; ambifunb(sig);\n\n% we have around the origin (in the middle of the image) the AF-signal \n% terms, whereas the AF-interference terms are located away from the origin.\n%\n% Press any key to continue...\n\npause; clc;\n\n% Other important energy distributions\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%\n% The Rihaczek and Margenau-Hill distributions\n% \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% The Rihaczek distribution, defined as\n%\tRx(t,nu)=x(t)X*(nu)e^{-j2pi nu t},\n% is a complex energy density at point (t,nu). This distribution, which \n% corresponds to the element of the Cohen's class for which \n% f(xi,tau)=e^{jpi xi tau}, verifies many good properties. However, it is \n% complex valued, which can be awkward in practice. The real part of the \n% Rihaczek distribution is also a time-frequency distribution of the \n% Cohen's class (f(xi,tau)=cos(pi xi tau)), known as the Margenau-Hill\n% distribution\n% The interference structure of the Rihaczek and Margenau-Hill\n% distributions is different from the Wigner-Ville one : the interference\n% terms corresponding to two points located on (t1,nu1) and (t2,nu2) are\n% positioned at the coordinates (t1,nu2) and (t2,nu1). This can be seen on\n% the following example :\n\nsig=atoms(128,[32,0.15,20,1;96,0.32,20,1]);\ntfrmh(sig);\n% Thus, the use of the Rihaczek (or Margenau-Hill) distribution for signals\n% composed of multi-components located at the same position in time or in\n% frequency is no advised, since the interference terms will then be\n% superposed to the signal terms.\n%\n% Press any key to continue...\n\npause; clc; close\n\n% The Choi-Williams distribution\n% \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% An example of reduced interference distribution is given by the\n% Choi-Williams distribution, defined as\n% CWx(t,nu)=sqrt(2/pi)\\int\\int sigma/|tau| e^{-2sigma^2(s-t)^2/tau^2} \n%\t x(s+tau/2)x*(s-tau/2) e^{-j2pi nu tau} ds dtau \n% Note that when sigma->+infty, we obtain the WVD. Inversely, the smaller\n% sigma, the better the reduction of the interferences. \n% The \"cross\"-shape of the parametrization function of the Choi-Williams\n% distribution implies that the efficiency of this distribution strongly\n% depends on the nature of the analyzed signal. For instance, if the signal\n% is composed of synchronized components in time or in frequency, the\n% Choi-Williams distribution will present strong interferences. This can be\n% observed on the following example : we analyze four gaussian atoms\n% positionned at the corners of a rectangle rotating around the center of \n% the time-frequency plane : \n\n\nM=movcw4at(128); movie(M,5); clear M;\n\n% When the time/frequency supports of the atoms overlap, some \n% AF-interference terms are not be completly attenuated (those present \n% around the axes of the ambiguity plane), and the efficiency of the \n% distribution is quite poor. \n%\n% Press any key to continue...\n\npause; clc;\n\n% Comparison of the parametrization functions\n% \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n% To illustrate the differences between some of the presented\n% distributions, we represent their weighting (parametrization) function in\n% the ambiguity plane, along with the result obtained by applying them on a\n% two-component signal embedded in white gaussian noise : the signal is the\n% sum of two linear FM signals, the first one with a frequency going from\n% 0.05 to 0.15, and the second one from 0.2 to 0.5. The signal to noise \n% ratio is 10 dB.\n\n% On the left-hand side of the figures, the parametrization functions are\n% represented in a schematic way by the bold contour lines (the weighting\n% functions are mainly non-zeros inside these lines), superimposed to the\n% ambiguity function of the signal. The AF-signal terms are in the middle of\n% the ambiguity plane, whereas the AF-interference terms are distant from the\n% center. On the right-hand side, the corresponding time-frequency\n% distributions are represented.\n\nparamfun\n\n% From these plots, we can conclude that the ambiguity plane is very\n% enlightening with regard to interference reduction in the case of\n% multicomponent signals. On this example, we notice that the\n% smoothed-pseudo-WVD is a particularly convenient and versatile\n% candidate. This is due to the fact that we can adapt independently the\n% time-width and frequency-width of its weighting function. But in the\n% general case, it is interesting to have several distributions at our\n% disposal since each one is well adapted to a certain type of\n% signal. Besides, for a given signal, as a result of the different\n% interference geometries, these distributions offer complementary\n% descriptions of this signal.\n%\n% Press any key to end this demonstration\n\npause; \necho off\n\nclose;\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tftb-0.2/demos/tfdemo4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.04813676770280703, "lm_q1q2_score": 0.021075407365488737}} {"text": "function s2 = s_escape_tex ( s1 )\n\n%*****************************************************************************80\n%\n%% S_ESCAPE_TEX de-escapes TeX escape sequences.\n%\n% Discussion:\n%\n% In particular, every occurrence of the characters '\\', '_',\n% '^', '{' and '}' will be replaced by '\\\\', '\\_', '\\^',\n% '\\{' and '\\}'. A TeX interpreter, on seeing these character\n% strings, is then likely to return the original characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string S1, the string to be de-escaped.\n%\n% Output, string S2, a copy of the string, modified to avoid TeX escapes.\n%\n s1_length = length ( s1 );\n\n s1_pos = 0;\n s2_pos = 0;\n s2 = [];\n\n while ( s1_pos < s1_length )\n\n s1_pos = s1_pos + 1;\n\n if ( s1(s1_pos) == '\\' || ...\n s1(s1_pos) == '_' || ...\n s1(s1_pos) == '^' || ...\n s1(s1_pos) == '{' || ...\n s1(s1_pos) == '}' )\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, '\\' );\n end\n\n s2_pos = s2_pos + 1;\n s2 = strcat ( s2, s1(s1_pos) );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/chrpak/s_escape_tex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2568319913875189, "lm_q2_score": 0.08151976043757422, "lm_q1q2_score": 0.020936882410615667}} {"text": "function [ colptr, rowind ] = hb_structure_read ( input_unit, ncol, mxtype, ...\n nnzero, neltvl, ptrcrd, ptrfmt, indcrd, indfmt )\n\n%*****************************************************************************80\n%\n%% HB_STRUCTURE_READ reads the structure of an HB matrix.\n%\n% Discussion:\n%\n% The user should already have opened the file, and positioned it\n% to just after the header records.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Iain Duff, Roger Grimes, John Lewis,\n% User's Guide for the Harwell-Boeing Sparse Matrix Collection,\n% October 1992.\n%\n% Parameters:\n%\n% Input, integer INPUT_UNIT, the unit from which data is read.\n%\n% Input, integer NCOL, the number of columns.\n%\n% Input, character ( len = 3 ) MXTYPE, the matrix type.\n% First character is R for Real, C for complex, P for pattern only.\n% Second character is S for symmetric, U for unsymmetric, H for\n% Hermitian, Z for skew symmetric, R for rectangular.\n% Third character is A for assembled and E for unassembled\n% finite element matrices.\n%\n% Input, integer NNZERO. In the case of assembled sparse matrices,\n% this is the number of nonzeroes. In the case of unassembled finite\n% element matrices, in which the right hand side vectors are also\n% stored as unassembled finite element vectors, this is the total\n% number of entries in a single unassembled right hand side vector.\n%\n% Input, integer NELTVL, the number of finite element matrix entries,\n% set to 0 in the case of assembled matrices.\n%\n% Input, integer PTRCRD, the number of pointer records.\n%\n% Input, character ( len = 16 ) PTRFMT, the format for reading pointers.\n%\n% Input, integer INDCRD, the number of index records.\n%\n% Input, character ( len = 16 ) INDFMT, the format for reading indices.\n%\n% Output, integer COLPTR(NCOL+1), COLPTR(I) points to the location of\n% the first entry of column I in the sparse matrix structure.\n%\n% Output, integer ROWIND(NNZERO) or ROWIND(NELTVL), the row index of\n% each item.\n%\n [ p, code, w, m ] = s_to_format ( ptrfmt );\n\n if ( mxtype(3) == 'A' )\n line_num = 1 + floor ( ( ( ncol + 1 ) - 1 ) / p );\n else\n line_num = 1 + floor ( ( ( ncol ) - 1 ) / p );\n end\n\n jhi = 0;\n\n for i = 1 : line_num\n line = fgetl ( input_unit );\n jlo = jhi + 1;\n if ( mxtype(3) == 'A' )\n jhi = min ( jlo + p - 1, ncol + 1 );\n else\n jhi = min ( jlo + p - 1, ncol );\n end\n\n khi = 0;\n\n for j = jlo : jhi\n klo = khi + 1;\n khi = min ( klo + w - 1, length ( line ) );\n s = line(klo:khi);\n colptr(j) = s_to_i4 ( s );\n end \n\n end\n\n if ( mxtype(3) == 'A' )\n\n [ p, code, w, m ] = s_to_format ( indfmt );\n\n line_num = 1 + floor ( ( nnzero - 1 ) / p );\n\n jhi = 0;\n\n for i = 1 : line_num\n line = fgetl ( input_unit );\n jlo = jhi + 1;\n jhi = min ( jlo + p - 1, nnzero );\n\n khi = 0;\n\n for j = jlo : jhi\n klo = khi + 1;\n khi = min ( klo + w - 1, length ( line ) );\n s = line(klo:khi);\n rowind(j) = s_to_i4 ( s );\n end \n\n end\n\n elseif ( mxtype(3) == 'E' )\n\n [ p, code, w, m ] = s_to_format ( indfmt );\n number = colptr(ncol) - colptr(1);\n line_num = 1 + floor ( ( number - 1 ) / p );\n\n jhi = 0;\n\n for i = 1 : line_num\n line = fgetl ( input_unit );\n jlo = jhi + 1;\n jhi = min ( jlo + p - 1, number );\n\n khi = 0;\n\n for j = jlo : jhi\n klo = khi + 1;\n khi = min ( klo + w - 1, length ( line ) );\n s = line(klo:khi);\n rowind(j) = s_to_i4 ( s );\n end \n\n end\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HB_STRUCTURE_READ - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of MXTYPE(3).\\n' );\n return\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hb_io/hb_structure_read.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.04885777394802062, "lm_q1q2_score": 0.020829123997845433}} {"text": "function varargout = inviscidChannelGUI(varargin)\n% INVISCIDCHANNELGUI MATLAB code for inviscidChannelGUI.fig\n% INVISCIDCHANNELGUI, by itself, creates a new INVISCIDCHANNELGUI or raises the existing\n% singleton*.\n%\n% H = INVISCIDCHANNELGUI returns the handle to a new INVISCIDCHANNELGUI or the handle to\n% the existing singleton*.\n%\n% INVISCIDCHANNELGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in INVISCIDCHANNELGUI.M with the given input arguments.\n%\n% INVISCIDCHANNELGUI('Property','Value',...) creates a new INVISCIDCHANNELGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before inviscidChannelGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to inviscidChannelGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help inviscidChannelGUI\n\n% Last Modified by GUIDE v2.5 20-Feb-2013 10:37:02\n\n% Copyright 2013 The MathWorks, Inc.\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @inviscidChannelGUI_OpeningFcn, ...\n 'gui_OutputFcn', @inviscidChannelGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before inviscidChannelGUI is made visible.\nfunction inviscidChannelGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to inviscidChannelGUI (see VARARGIN)\n\n% Initialize the GUI layout\nsketchplot(gcf);\nset(get(handles.plotstreamline,'XLabel'),'String','x (m)')\nset(get(handles.plotstreamline,'YLabel'),'String','y (m)')\nset(get(handles.plotstreamline,'Title'),'String','Normalized Stream Function \\Psi')\nset(get(handles.plotvector,'XLabel'),'String','x (m)')\nset(get(handles.plotvector,'YLabel'),'String','y (m)')\nset(get(handles.plotvector,'Title'),'String','Velocity Profile')\n% Create the help button on toolbar\n[X, map] = imread(fullfile(...\n matlabroot,'toolbox','matlab','icons','csh_icon.gif'));\nicon = ind2rgb(X,map);\nuipushtool(handles.uitoolbar1,'CData',icon,...\n 'TooltipString','Help',...\n 'ClickedCallback',@AppHelp);\n\n\n% Choose default command line output for inviscidChannelGUI\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n% UIWAIT makes inviscidChannelGUI wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = inviscidChannelGUI_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in start.\nfunction start_Callback(hObject, eventdata, handles)\n% hObject handle to start (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ninviscidchannel(handles);\n\nfunction handles = getpara(handles)\n% Get user input parameters from the GUI\nhandles.para.D1 = str2double(get(handles.D1,'String'));\nhandles.para.D2 = str2double(get(handles.D2,'String'));\nhandles.para.L1 = str2double(get(handles.L1,'String'));\nhandles.para.L2 = str2double(get(handles.L2,'String'));\nhandles.para.U1 = str2double(get(handles.U1,'String'));\nhandles.para.nx = str2double(get(handles.nx,'String'));\nhandles.para.ny = str2double(get(handles.ny,'String'));\nhandles.para.nmax = str2double(get(handles.nmax,'String'));\ncla(handles.plotstreamline),cla(handles.plotvector),\naxis([handles.plotstreamline handles.plotvector], [0 handles.para.L1+handles.para.L2 0 max(handles.para.D1,handles.para.D2)]),\n% Draw the channel shape according to input\nif handles.para.D1 < handles.para.D2 % converging channel\n cornerposition = [0 handles.para.D1 handles.para.L1 handles.para.D2-handles.para.D1];\nelseif handles.para.D1 > handles.para.D2 % diverging channel\n cornerposition = [handles.para.L1 handles.para.D2 handles.para.L2 handles.para.D1-handles.para.D2];\nelse\n cornerposition = [0 handles.para.D1 1 1]; % straight channel\nend\nrectangle('Parent',handles.plotstreamline,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])\nrectangle('Parent',handles.plotvector,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])\n\n\nfunction inviscidchannel(handles)\n%% Initialization\n% get input parameters\nhandles = getpara(handles);\n% store input parameters with shorter names\nD1 = handles.para.D1;\nD2 = handles.para.D2;\nL1 = handles.para.L1;\nL2 = handles.para.L2;\nU1 = handles.para.U1;\nnx = handles.para.nx;\nny = handles.para.ny;\nnmax = handles.para.nmax;\n% compute grid length\ndx = (L1+L2)/(nx-1);\ndy = max(D1,D2)/(ny-1);\n% nondimensionalization\ndX = dx/D1;\ndY = dy/D1;\nPSI = ones(ny,nx);\n%% Boundary conditions\nPSI(1,:) = 0; % bottom\nPSI(floor(D1/dy+1),1:floor(L1/dx+1)) = 1; % left part of top\nPSI(floor(D2/dy+1),floor(L1/dx+1):nx) = 1; % right part of top\nfor j = 1:floor(D1/dy+1)\n PSI(j,1) = (j-1)*dY; % inlet\nend\nfor j = 1:floor(D2/dy+1)\n PSI(j,nx) = D1/D2*(j-1)*dY; % outlet\nend\n%% Iteration to solve for stream function PSI\nerr = 1e-6; % convergence criteria\nn = 0;\nwhile n < nmax\n n = n + 1;\n tempPSI = PSI;\n % left part of the channel\n for i = 2:floor(L1/dx+1)\n for j = 2:(floor(D1/dy+1)-1)\n PSI(j,i) = 1/(2/dX^2+2/dY^2)*((tempPSI(j,i+1)+PSI(j,i-1))/dX^2+(tempPSI(j+1,i)+PSI(j-1,i))/dY^2);\n end\n end\n % right part of the channel\n for i = floor(L1/dx+1):nx-1\n for j = 2:(floor(D2/dy+1)-1)\n PSI(j,i) = 1/(2/dX^2+2/dY^2)*((tempPSI(j,i+1)+PSI(j,i-1))/dX^2+(tempPSI(j+1,i)+PSI(j-1,i))/dY^2);\n end\n end\n % checking for convergence\n if max(max(abs(PSI-tempPSI))) <= err\n break\n end\nend\n%% Prompt convergence result in a message box\nif n < nmax\n helpdlg({'Converged.';sprintf('Total number of iterations: %g\\n',n)},...\n 'Converged');\nelse\n warndlg({'NOT Converged!';sprintf('Change n_x, n_y, n_max or convergence criteria.\\n')},...\n 'NOT Converged');\nend\n%% Solve for velocity u and v from stream function\nu = zeros(ny,nx);\nv = zeros(ny,nx);\npsi = PSI*U1*D1; % dimentionalization\nfor j = 2:ny-1\n u(j,:) = (psi(j+1,:)-psi(j-1,:))/2/dy;\nend\nfor i = 2:nx-1\n v(:,i) = -(psi(:,i+1)-psi(:,i-1))/2/dx;\nend\n% velocity at boundaries (inviscid, so slip occurs)\nu(1,:) = u(2,:);\nu(ny,:) = u(ny-1,:);\nv(:,1) = v(:,2);\nv(:,nx) = v(:,nx-1);\n%% Plot results\n[X, Y] = meshgrid(0:dx:(L1+L2),0:dy:max(D1,D2));\n% contour plot of stream function\ncontourf(handles.plotstreamline,X,Y,PSI),colormap(handles.plotstreamline,'jet')\n% vector plot of velocity u and v\nquiver(handles.plotvector,X,Y,u,v),\naxis([handles.plotstreamline handles.plotvector],[0 L1+L2 0 max(D1,D2)]),\n% plot the shape of the channel based on input parameters\nif D1 < D2\n cornerposition = [0 D1 L1 D2-D1];\nelseif D1 > D2\n cornerposition = [L1 D2 L2 D1-D2];\nelse\n cornerposition = [0 D1 1 1];\nend\nrectangle('Parent',handles.plotstreamline,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])\nrectangle('Parent',handles.plotvector,'Position',cornerposition,'FaceColor',[0.94 0.94 0.94])\nset(get(handles.plotstreamline,'XLabel'),'String','x (m)')\nset(get(handles.plotstreamline,'YLabel'),'String','y (m)')\nset(get(handles.plotstreamline,'Title'),'String','Normalized Stream Function \\Psi')\nset(get(handles.plotvector,'XLabel'),'String','x (m)')\nset(get(handles.plotvector,'YLabel'),'String','y (m)')\nset(get(handles.plotvector,'Title'),'String','Velocity Profile')\n\nfunction sketchplot(h)\n%Sketch the plot of the channel to show geometric parameters\n% and governing equations. You can learn how to draw sketches\n% programmatically and write LaTeX. Don't worry about it otherwise,\n% since it has nothing to do with computation.\n\n% Create doublearrow\nd1 = annotation(h,'doublearrow',[0.06 0.06],...\n [0.6 0.8]);\n\n% Create doublearrow\nl1 = annotation(h,'doublearrow',[0.06 0.15],...\n [0.6 0.6]);\n\n% Create doublearrow\nl2 = annotation(h,'doublearrow',[0.15 0.3],...\n [0.6 0.6]);\n\n% Create doublearrow\nd2 = annotation(h,'doublearrow',[0.3 0.3],...\n [0.7 0.6]);\n\n% Create arrow U\nannotation(h,'arrow',[0.02 0.06],...\n [0.7 0.7],...\n 'HeadStyle','Plain',...\n 'HeadWidth',5);\n\n% Create textbox U\nannotation(h,'textbox',...\n [0.02 0.67 0.03 0.07],...\n 'String',{'U'},...\n 'FitBoxToText','off',...\n 'LineStyle','none');\n\n\n% Create textbox\nannotation(h,'textbox',...\n [0.06 0.65 0.03 0.07],...\n 'String',{'D1'},...\n 'FitBoxToText','off',...\n 'LineStyle','none');\n\n% Create textbox\nannotation(h,'textbox',...\n [0.1 0.58 0.03 0.07],...\n 'String',{'L1'},...\n 'FitBoxToText','off',...\n 'LineStyle','none');\n\n% Create textbox\nannotation(h,'textbox',...\n [0.22 0.58 0.03 0.07],...\n 'String',{'L2'},...\n 'FitBoxToText','off',...\n 'LineStyle','none');\n\n% Create textbox\nannotation(h,'textbox',...\n [0.25 0.61 0.03 0.07],...\n 'String',{'D2'},...\n 'FitBoxToText','off',...\n 'LineStyle','none');\n\n% Create channel\nannotation(h,'line',...\n [0.05 0.15],[0.8 0.8],...\n 'LineWidth',2);\n\n% Create channel\nannotation(h,'line',...\n [0.15 0.31],[0.7 0.7],...\n 'LineWidth',2);\n\n% Create channel\nannotation(h,'line',...\n [0.15 0.15],[0.7 0.8],...\n 'LineWidth',2);\n\n% Create channel\nannotation(h,'line',...\n [0.05 0.31],[0.58 0.58],...\n 'LineWidth',2);\n\n% Create textbox equations\nannotation(h,'textbox',[0.32 0.73 0.03 0.07],...\n 'String',{'\\partial^2\\psi/\\partialx^2 + \\partial^2\\psi/\\partialy^2 = 0','','u = \\partial\\psi/\\partialy','', 'v = -\\partial\\psi/\\partialx'},...\n 'FitBoxToText','on',...\n 'LineStyle','none');\n\nfunction AppHelp(varargin)\n% Create help message\ndlgname = 'About Inviscid Channel App';\ntxt = {'Inviscid flow in a channel (Laplace equation of stream function)';\n 'solved with explicit method';\n '';\n 'Start - Start the simulation';\n 'Solution Code - Open a pre-written script to show the solution code';\n '';\n '* Try D1 > D2, D1 < D2 or D1 = D2.';\n '* Use zoom, pan and data curser in the toolbar to interact with the';\n ' plots as usual';\n '* If result does not converge, try:';\n ' a) increasing n_max (total number of iterations)';\n ' b) decreasing n_x, n_y (number of grids in each direction)';\n '';\n 'Copyright 2013 The MathWorks, Inc.'};\nhelpdlg(txt,dlgname);\n\nfunction D1_Callback(hObject, eventdata, handles)\n% hObject handle to D1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ngetpara(handles);\n% Hints: get(hObject,'String') returns contents of D1 as text\n% str2double(get(hObject,'String')) returns contents of D1 as a double\n\n\n\nfunction D2_Callback(hObject, eventdata, handles)\n% hObject handle to D2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ngetpara(handles);\n% Hints: get(hObject,'String') returns contents of D2 as text\n% str2double(get(hObject,'String')) returns contents of D2 as a double\n\n\n\nfunction L1_Callback(hObject, eventdata, handles)\n% hObject handle to L1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ngetpara(handles);\n% Hints: get(hObject,'String') returns contents of L1 as text\n% str2double(get(hObject,'String')) returns contents of L1 as a double\n\n\n\nfunction L2_Callback(hObject, eventdata, handles)\n% hObject handle to L2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ngetpara(handles);\n% Hints: get(hObject,'String') returns contents of L2 as text\n% str2double(get(hObject,'String')) returns contents of L2 as a double\n\n\n% --- Executes on button press in solution.\nfunction solution_Callback(hObject, eventdata, handles)\n% hObject handle to solution (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nopen('inviscidChannelScript.m');\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/40751-inviscid-channel-flow/inviscidChannelGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33458945452352534, "lm_q2_score": 0.060975177878768765, "lm_q1q2_score": 0.02040165150593217}} {"text": "function [stop reason] = stoppingcriterion(problem, x, options, info, last)\n% Checks for standard stopping criteria, as a helper to solvers.\n%\n% function [stop reason] = stoppingcriterion(problem, x, options, info, last)\n%\n% Executes standard stopping criterion checks, based on what is defined in\n% the info(last) stats structure and in the options structure.\n%\n% The returned number 'stop' is 0 if none of the stopping criteria\n% triggered, and a (strictly) positive integer otherwise. The integer\n% identifies which criterion triggered:\n% 0 : Nothing triggered;\n% 1 : Cost tolerance reached;\n% 2 : Gradient norm tolerance reached;\n% 3 : Max time exceeded;\n% 4 : Max iteration count reached;\n% 5 : Maximum number of cost evaluations reached;\n% 6 : User defined stopfun criterion triggered.\n%\n% The output 'reason' is a string describing the triggered event.\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n\n\n stop = 0;\n reason = '';\n \n stats = info(last);\n\n % Target cost attained\n if isfield(stats, 'cost') && isfield(options, 'tolcost') && ...\n stats.cost <= options.tolcost\n reason = 'Cost tolerance reached. See options.tolcost.';\n stop = 1;\n return;\n end\n\n % Target gradient norm attained\n if isfield(stats, 'gradnorm') && isfield(options, 'tolgradnorm') && ...\n stats.gradnorm < options.tolgradnorm\n reason = 'Gradient norm tolerance reached. See options.tolgradnorm.';\n stop = 2;\n return;\n end\n\n % Alloted time exceeded\n if isfield(stats, 'time') && isfield(options, 'maxtime') && ...\n stats.time >= options.maxtime\n reason = 'Max time exceeded. See options.maxtime.';\n stop = 3;\n return;\n end\n\n % Alloted iteration count exceeded\n if isfield(stats, 'iter') && isfield(options, 'maxiter') && ...\n stats.iter >= options.maxiter\n reason = 'Max iteration count reached. See options.maxiter.';\n stop = 4;\n return;\n end\n \n % Alloted function evaluation count exceeded\n if isfield(stats, 'costevals') && isfield(options, 'maxcostevals') && ...\n stats.costevals >= options.maxcostevals\n reason = 'Maximum number of cost evaluations reached. See options.maxcostevals.';\n stop = 5;\n end\n\n % Check whether the possibly user defined stopping criterion\n % triggers or not.\n if isfield(options, 'stopfun')\n userstop = options.stopfun(problem, x, info, last);\n if userstop\n reason = 'User defined stopfun criterion triggered. See options.stopfun.';\n stop = 6;\n return;\n end\n end\n\nend\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/manopt/manopt/privatetools/stoppingcriterion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.051845463353511735, "lm_q1q2_score": 0.019955949212790237}} {"text": "function varargout = gsynsq(varargin)\n% function hgui = gsynsq()\n%\n% Runs the Synchrosqueezing toolbox GUI.\n% Does not require input parameters. Returns a handle to the GUI.\n%\n% This GUI tool can be used for speedy/rough Synchrosqueezing\n% analysis, filtering, component extraction of signals.\n% \n%\n%---------------------------------------------------------------------------------\n% Synchrosqueezing Toolbox\n% Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 0;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @gsynsq_OpeningFcn, ...\n 'gui_OutputFcn', @gsynsq_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n% --- Executes just before gsynsq is made visible.\nfunction gsynsq_OpeningFcn(hObj, eventdata, hs, varargin)\n% This function has no output args, see OutputFcn.\n% hObj handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n% varargin command line arguments to gsynsq (see VARARGIN)\n\n% Choose default command line output for gsynsq\nhs.output = hObj;\n\n% This sets up the initial plot - only do when we are invisible\n% so window can get raised using gsynsq.\nif strcmp(get(hObj,'Visible'),'off')\n set(hs.axesx, 'Visible', 'off');\n set(hs.axesTx, 'Visible', 'off');\n set(hs.axesrx, 'Visible', 'off');\n \n % Set up zoom\n zh = zoom;\n\n setAllowAxesZoom(zh, hs.axesx, true);\n setAllowAxesZoom(zh, hs.axesTx, true);\n setAllowAxesZoom(zh, hs.axesrx, true);\n\n % Link the axes w.r.t. zoom (just the t-axis component)\n linkaxes([hs.axesx hs.axesTx hs.axesrx], 'x');\n \n % Menu bar with \"reset axes\" does not work with linked axes\n set(zh, 'RightClickAction', 'InverseZoom');\n\n % Append any past ActionPostCallBack to run first\n %set(zh, 'ActionPostCallback', @postZoomUpdate);\n\n % Allow zoom\n set(zh, 'Enable', 'on');\n \n hs.zh = zh;\n \n % Initialize internal data structure placeholders\n hs = clear_data(hs);\nend\n\n% Update hs structure\nguidata(hObj, hs);\n\n% UIWAIT makes gsynsq wait for user response (see UIRESUME)\n% uiwait(hs.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = gsynsq_OutputFcn(hObj, eventdata, hs)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObj handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% Get default command line output from hs structure\nvarargout{1} = hs.output;\n\n% --------------------------------------------------------------------\nfunction FileMenu_Callback(hObj, eventdata, hs)\n% hObj handle to FileMenu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% --------------------------------------------------------------------\nfunction OpenMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to OpenMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfile = uigetfile('*.mat');\nif ~isequal(file, 0)\n try\n tx = load(file);\n assert(isfield(tx, 't'));\n assert(isfield(tx, 'x'));\n assert(length(tx.t) == length(tx.x));\n catch ME\n errordlg(sprintf('File load error: %s', ME.message), ...\n 'File Load Error');\n return;\n end\n \n load_data(hObj, eventdata, hs, file, tx);\nend\n\nfunction load_data(hObj, eventdata, hs, file, tx)\n% Do something here about old data, if any?\nif (hs.active && ~hs.saved)\nend\n \n% Load up the data. First clear old data\nhs = clear_data(hs);\nhs.data.t = tx.t;\nhs.data.x = tx.x - mean(tx.x);\n\n[fpath, fname] = fileparts(file);\nhs.prefix = fullfile(fpath, fname);\n\n% Plot axes\nplot(hs.axesx, hs.data.t, hs.data.x);\nset(hs.axesx, 'Visible', 'on');\ngrid(hs.axesx, 'on');\naxis(hs.axesx,'tight');\nsetAxesZoomMotion(hs.zh, hs.axesx, 'horizontal');\nset(hs.axesx,'FontSize',10);\n\n% Hide other axes and delete colorbars, if any\naxes(hs.axesTx);\ncolorbar('delete');\n\ncla(hs.axesTx);\nset(hs.axesTx, 'Visible', 'off');\ncla(hs.axesrx);\nset(hs.axesrx, 'Visible', 'off');\n\n% Save app data\nguidata(hObj, hs);\n\n\n% --------------------------------------------------------------------\nfunction PrintMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to PrintMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nprintdlg(hs.figure1)\n\n% --------------------------------------------------------------------\nfunction ExitMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to CloseMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfigure1_CloseRequestFcn(hObj, eventdata, hs);\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObj, eventdata, hs)\n% hObj handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% If the analysis has been modified but not been saved\nif (hs.active && ~hs.saved)\n selection = questdlg(['Unsaved Analysis. Close ' get(hs.figure1,'Name') '?'],...\n ['Close ' get(hs.figure1,'Name') '...'],...\n 'Yes','No','Yes');\n if strcmp(selection,'No')\n return;\n end\nend\n\n% Closes the figure\ndelete(hs.output);\n\n% Initializes / clears data from last job from hs\nfunction hs = clear_data(hs)\n% Is there an analysis active?\nhs.active = 0;\n% Has it been saved since the last change?\nhs.saved = 0;\n\n% What is the file prefix of the current analysis?\nhs.prefix = '';\n\n% Default parameters for the transforms\nhs.padtype = 'symmetric';\n% Number of voices\nhs.nv = 32;\n% Wavelet type and other options\nhs.opt = struct('disp', 1, 'bd', 1, 'gamma', sqrt(eps), 'type', 'morlet');\n\n% Placeholders for the input data\nhs.data = [];\n\n% Placeholders for the results of the analysis part\nhs.data.as = [];\nhs.data.fs = [];\nhs.data.Wx = [];\nhs.data.Tx = [];\n\n% Placeholders for the results of the synthesis part\nhs.data.rx = [];\n\n% Placeholder for the results of synthesis after removing padding\n%hs.data.rx0 = [];\n\n% Placeholder for the extracted curves\nhs.data.Cs = [];\nhs.data.xrs = [];\n\n% Attenuation filters\nif isfield(hs, 'filters')\n for hi = 1:length(hs.filters)\n delete(hs.filters(hi).f);\n end\nend\nhs.filters = [];\n\n% --------------------------------------------------------------------\nfunction openpush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to openpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nOpenMenuItem_Callback(hObj, eventdata, hs);\n\n\n% --------------------------------------------------------------------\nfunction savepush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to savepush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nSaveMenuItem_Callback(hObj, eventdata, hs);\n\n\n% --------------------------------------------------------------------\nfunction zoomtoggle_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to zoomtoggle (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% ZOOM\n\n\n% --------------------------------------------------------------------\nfunction zoomtoggle_OffCallback(hObj, eventdata, hs)\n% hObj handle to zoomtoggle (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% Disable zoom\nzoom_disable(hs);\n\nfunction zoom_disable(hs)\nset(hs.zoomtoggle, 'State', 'off');\nset(hs.ZoomMenuItem, 'Checked', 'off');\nset(hs.zh, 'Enable', 'off');\n\n% --------------------------------------------------------------------\nfunction zoomtoggle_OnCallback(hObj, eventdata, hs)\n% hObj handle to zoomtoggle (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% Allow zoom\n%if strcmp(get(hObj,'Visible'),'off')\nzoom_enable(hs);\n%end\n\nfunction zoom_enable(hs)\nset(hs.zoomtoggle, 'State', 'on');\nset(hs.zh, 'Enable', 'on');\nset(hs.ZoomMenuItem, 'Checked', 'on');\n\n\n%%% NOT USED %%%\nfunction postZoomUpdate(hObj, eventdata)\n% Get the new horizontal values of the updated axes\nXLim = get(eventdata.Axes, 'XLim');\n\n% Update the values for each of the axes\nhs = guidata(hObj);\n\nXLim(1) = max(XLim(1), min(hs.data.t));\nXLim(2) = min(XLim(2), max(hs.data.t));\nset(eventdata.Axes, 'XLim', XLim);\n\nif (eventdata.Axes ~= hs.axesTx), set(hs.axesTx, 'XLim', XLim); end\nif (eventdata.Axes ~= hs.axesx), set(hs.axesx, 'XLim', XLim); end\nif (eventdata.Axes ~= hs.axesrx), set(hs.axesrx, 'XLim', XLim); end\n\n% --------------------------------------------------------------------\nfunction SaveMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to SaveMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nif (~hs.active || hs.saved)\n return;\nend\n\nfile = uiputfile(sprintf('%s_r.mat', hs.prefix));\nif ~isequal(file, 0)\n try\n data = hs.data;\n save(file, '-struct', 'data');\n catch ME\n errordlg(sprintf('File save error: %s', ME.message), ...\n 'File Save Error');\n return;\n end\n \n hs.saved = 1;\n guidata(hObj, hs);\nend\n\n\n% --------------------------------------------------------------------\nfunction ExportMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to ExportMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nif (~hs.active), return; end\nlabels = {'Export t?', 'Export x(t)?', 'Export as?', 'Export Wx(a,t)?', ...\n 'Export fs?', 'Export Tx(f,t)?', 'Export rx(t) (reconstructed)?', ...\n 'Export filters?', 'Export identified contours?', ...\n 'Export extracted components?'};\nvarnames = {'t', 'x', 'as', 'Wx', 'fs', 'Tx', 'rx', ...\n 'filters', 'Cs', 'xrs'};\nfilters = hs.filters;\nfor fi=1:length(filters)\n filters(fi).bbox = filters(fi).f.getPosition();\n filters(fi).mask = filters(fi).f.createMask();\n % bbox = [tmin tmax fmin fmax]\n % filters(fi).bbox = [filters(fi).bbox([1 3])];\n tmin = filters(fi).bbox(1);\n tmax = tmin + filters(fi).bbox(3);\n flogmin = filters(fi).bbox(2);\n flogmax = flogmin + filters(fi).bbox(4);\n filters(fi).bbox = [tmin tmax 2^flogmin 2^flogmax];\nend\nif length(filters)>0, filters = rmfield(filters, 'f'); end\nvars = {hs.data.t, hs.data.x, hs.data.as, ...\n hs.data.Wx, hs.data.fs, hs.data.Tx, hs.data.rx, ...\n filters, hs.data.Cs, hs.data.xrs};\nselected = logical([0 0 0 0 0 0 0 0 0 0]);\nexport2wsdlg(labels, varnames, vars, 'Export to Workspace', selected);\n\n% TODO - export to a variable with proper prefix and name of choice\n\n% --------------------------------------------------------------------\nfunction AnalysisMenu_Callback(hObj, eventdata, hs)\n% hObj handle to AnalysisMenu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction AnalysisMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to AnalysisMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nrun_analysis(hObj, eventdata, hs);\n\nfunction run_analysis(hObj, eventdata, hs)\nif (isempty(hs.data))\n errordlg('Load a data file first', 'Error');\n return;\nend\n\nprompt = {'Wavelet [morlet,bump,hhhat,...]', ...\n 'Number of Voices (nv)', ...\n 'Pad type [symmetric, circular, replicate]', ...\n 'Gamma (\\gamma)'};\nname = 'Synchrosqueezing Analysis Parameters';\nanswers = {hs.opt.type, num2str(hs.nv), hs.padtype, num2str(hs.opt.gamma)};\nidata = inputdlg(prompt, name, 1, answers, struct('WindowStyle', 'normal'));\nif isempty(idata)\n return\nend\n\nhs.opt.type = idata{1};\nhs.nv = str2num(idata{2});\nhs.padtype = idata{3};\nhs.opt.gamma = str2num(idata{4});\n\n[hs.data.Tx, hs.data.fs, hs.data.Wx, hs.data.as] = ...\n synsq_cwt_fw(hs.data.t, hs.data.x, hs.nv, hs.opt);\n\naxes(hs.axesTx);\ncla(hs.axesTx);\ntplot(hs.data.Tx, hs.data.t, hs.data.fs, hs.opt);\nset(hs.axesTx, 'Visible', 'on');\ngrid(hs.axesTx, 'on');\nsetAxesZoomMotion(hs.zh, hs.axesTx, 'vertical');\nset(hs.axesTx,'FontSize',10);\nhs.filters = [];\n\nhs.active = 1;\n\n% Store application parameters\nguidata(hObj, hs);\n\n\n% --------------------------------------------------------------------\nfunction ReconMenuItem_Callback(hObj, eventdata, hs)\n% hObj handle to ReconMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nrun_recon(hObj, eventdata, hs);\n\nfunction run_recon(hObj, eventdata, hs);\n\nif (~hs.active)\n errordlg('Run Analysis First', 'Error');\n return;\nend\n\nTx = filter_Tx(hs);\n\nhs.data.rx = synsq_cwt_iw(Tx, hs.data.fs, hs.opt);\n\nplot(hs.axesrx, hs.data.t, hs.data.rx);\ngrid(hs.axesrx,'on');\nset(hs.axesrx, 'Visible', 'on');\nset(hs.axesrx,'FontSize',10);\naxis(hs.axesrx, [min(hs.data.t) max(hs.data.t) min(hs.data.x) max(hs.data.x)]);\n\nXLim = get(hs.axesx, 'XLim'); set(hs.axesrx, 'XLim', XLim);\nsetAxesZoomMotion(hs.zh, hs.axesrx, 'horizontal');\n%zoom_enable(hs);\n\nguidata(hObj, hs);\n\nfunction Tx = filter_Tx(hs)\n% Logic to see if any attenuation and/or passband filters are active\nTx = hs.data.Tx;\nif ~isempty(hs.filters)\n % Step 1: combine all pass-band filters\n maskp = zeros(size(hs.data.Tx));\n maska = ones(size(hs.data.Tx));\n nmp = 0;\n for fi=1:length(hs.filters)\n mask = hs.filters(fi).f.createMask();\n if strcmpi(hs.filters(fi).type, 'atten')\n maska = maska & ~mask;\n else\n maskp = maskp | mask;\n nmp = nmp + 1;\n end\n end\n \n % Mask via the filters\n if (nmp > 0)\n Tx = Tx .* maskp .* maska;\n else\n Tx = Tx .* maska;\n end\nend\n\n\n% --------------------------------------------------------------------\nfunction FiltersMenu_Callback(hObj, eventdata, hs)\n% hObj handle to FiltersMenu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction RectAtten_Callback(hObj, eventdata, hs)\n% hObj handle to RectAtten (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'recta')\n\n% --------------------------------------------------------------------\nfunction filter_enable(hObj, hs, type)\n\n% Check to make sure analysis is active\nif (~hs.active)\n return;\nend\n\n% Disable zoom icon\nset(hs.zoomtoggle, 'State', 'off');\n\n% Start filter selection - this disabled zoom\nfhs = filter_construct(hs, type);\n\n% Make sure that it's within the proper constraints at first\nfor fhi=1:length(fhs)\n fh = fhs(fhi);\n fh.setConstrainedPosition(fh.getPosition());\n \n if strcmpi(type(end), 'a')\n hs.filters = [hs.filters struct('type', 'atten', 'f', fh)];\n else\n hs.filters = [hs.filters struct('type', 'pass', 'f', fh)];\n end\nend\n\n% Save\nguidata(hObj, hs);\n\n\nfunction h = filter_construct(hs, type)\nswitch type\n case 'recta',\n h = imrect(hs.axesTx);\n case 'ellipsea',\n h = imellipse(hs.axesTx);\n case 'polya',\n h = impoly(hs.axesTx);\n case 'rectp',\n h = imrect(hs.axesTx);\n case 'bda',\n t = hs.data.t(:);\n fs = [hs.data.fs(1), hs.data.fs(2:hs.nv:end-1), hs.data.fs(end)]; % Subsample\n [Lbdi, Rbdi] = synsq_bd_loc(t, fs);\n fsbd = [fs(1); fs(:); fs(end)];\n Lbdi = [1; Lbdi(:); 1];\n Rbdi = [length(t); Rbdi(:); length(t)];\n\n hL = impoly(hs.axesTx, [t(Lbdi) log2(fsbd)]);\n hR = impoly(hs.axesTx, [t(Rbdi) log2(fsbd)]);\n h = [hL hR];\n otherwise,\n error('Unknown filter type');\nend\n\nfor j=1:length(h)\n hj = h(j);\n\n cstrstr = class(hj);\n\n % Set constraints\n constrfcn = makeConstrainToRectFcn(cstrstr, ...\n [min(hs.data.t)-sqrt(eps) max(hs.data.t)], ...\n [min(log2(hs.data.fs))-sqrt(eps) max(log2(hs.data.fs))]);\n hj.setPositionConstraintFcn(constrfcn);\n\n % Set color\n if strcmpi(type(end), 'a')\n hj.setColor('r');\n else\n hj.setColor('g');\n end\nend\n\n\n% --- Executes on mouse press over axes background.\nfunction axesTx_ButtonDownFcn(hObj, eventdata, hs)\n% hObj handle to axesTx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% Is not called due to axis ownership by zoom object\n\n\n% --------------------------------------------------------------------\nfunction EllipseAtten_Callback(hObj, eventdata, hs)\n% hObj handle to EllipseAtten (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'ellipsea')\n\n\n% --------------------------------------------------------------------\nfunction PolyAtten_Callback(hObj, eventdata, hs)\n% hObj handle to PolyAtten (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'polya')\n\n% --------------------------------------------------------------------\nfunction filterselector_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to filterselector (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n% FILTER SELECTOR\n\n% --------------------------------------------------------------------\nfunction filterselector_OffCallback(hObj, eventdata, hs)\n% hObj handle to filterselector (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n\n% FILTER SELECTOR\n\n% --------------------------------------------------------------------\nfunction filterselector_OnCallback(hObj, eventdata, hs)\n% hObj handle to filterselector (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\n\n\n% FILTER SELECTOR\n\n% --------------------------------------------------------------------\nfunction rectattenpush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to rectattenpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'recta')\n\n\n% --------------------------------------------------------------------\nfunction polyattenpush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to polyattenpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'polya')\n\n\n% --------------------------------------------------------------------\nfunction ellipseattenpush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to ellipseattenpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'ellipsea')\n\n\n% --------------------------------------------------------------------\nfunction analysispush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to analysispush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nrun_analysis(hObj, eventdata, hs);\n\n% --------------------------------------------------------------------\nfunction reconpush_ClickedCallback(hObj, eventdata, hs)\n% hObj handle to reconpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% hs structure with hs and user data (see GUIDATA)\nrun_recon(hObj, eventdata, hs);\n\n\n% --------------------------------------------------------------------\nfunction ZoomMenuItem_Callback(hObject, eventdata, handles)\n% hObject handle to ZoomMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nif strcmpi(get(handles.zh, 'Enable'), 'on'),\n zoomtoggle_OffCallback(hObject, eventdata, handles);\nelse\n zoomtoggle_OnCallback(hObject, eventdata, handles);\nend\n\n\n% --------------------------------------------------------------------\nfunction ToolsMenu_Callback(hObject, eventdata, handles)\n% hObject handle to ToolsMenu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction ImportMenuItem_Callback(hObject, eventdata, handles)\n% hObject handle to ImportMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nprompts = {'Import t variable: ', 'Import x(t) variable: ', 'Prefix: '};\nname = 'Import signal from workspace';\ndanswers = {'t', 'x', 'ws'};\nidata = inputdlg(prompts, name, 1, danswers, struct('WindowStyle', 'normal'));\n\n% Cancelled\nif isempty(idata),\n return;\nend\n\ntry\n tx = struct('t', evalin('base', idata{1}), ...\n 'x', evalin('base', idata{2}));\n assert(length(tx.t) == length(tx.x));\ncatch ME\n errordlg(sprintf('Import error: %s', ME.message), ...\n 'Import Error');\n return;\nend\n\n% Set some file prefix in the current directory\nfile = fullfile(pwd, idata{3});\n\nload_data(hObject, eventdata, handles, file, tx);\n\n\n% --------------------------------------------------------------------\nfunction rectpasspush_ClickedCallback(hObj, eventdata, hs)\n% hObject handle to rectpasspush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'rectp');\n\n\n% --------------------------------------------------------------------\nfunction RectPass_Callback(hObj, eventdata, hs)\n% hObject handle to RectPass (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'rectp');\n\n\n% --------------------------------------------------------------------\nfunction ExtractMenuItem_Callback(hObject, eventdata, handles)\n% hObject handle to ExtractMenuItem (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nextract_contour(hObject, handles);\n\n% Extract a contour\nfunction extract_contour(hObj, hs)\n\nif (~hs.active)\n errordlg('Run Analysis First', 'Error');\n return;\nend\n\nprompt = {'Number of Curves to Extract', ...\n 'Lambda (smoothness penalty)', ...\n 'Extraction window (n_w)'};\nname = 'Contour Extraction Parameters';\nnumlines = 1;\nanswers = {'2', '1e4', num2str(hs.nv/2)};\n\nidata = inputdlg(prompt, name, numlines, answers, struct('WindowStyle', 'normal'));\n\n% User cancelled\nif isempty(idata),\n return;\nend\n\nnc = str2num(idata{1});\nlambda = str2num(idata{2});\nnw = str2num(idata{3});\n\nTx = filter_Tx(hs);\n[na, N] = size(Tx);\n\n% Extract curves for plotting\n[hs.data.Cs,Es] = curve_ext_multi(Tx, log2(hs.data.fs), nc, lambda, nw);\n\n% Extract functions for export\nhs.data.xrs = curve_ext_recon(Tx, hs.data.fs, hs.data.Cs, hs.opt, nw);\n\n% Save\nguidata(hObj, hs);\n\nfigure;\nhc = plot_ext_curves(hs.data.t, hs.data.x, ...\n Tx, hs.data.fs, hs.data.Cs, Es, hs.opt);\n\n% --------------------------------------------------------------------\nfunction extractpush_ClickedCallback(hObject, eventdata, handles)\n% hObject handle to extractpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nextract_contour(hObject, handles);\n\n\n% --------------------------------------------------------------------\nfunction AttenBd_Callback(hObj, eventdata, hs)\n% hObject handle to AttenBd (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'bda');\n\n\n% --------------------------------------------------------------------\nfunction attenbdpush_ClickedCallback(hObj, eventdata, hs)\n% hObject handle to attenbdpush (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nfilter_enable(hObj, hs, 'bda');\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/synchrosqueezing/synchrosqueezing/gsynsq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04084572043430584, "lm_q1q2_score": 0.019625497758189656}} {"text": "function F = restrict(F, newDomain)\n%RESTRICT Restrict a CHEBFUN object to a subinterval.\n% G = RESTRICT(F, [S1, S2]) returns a CHEBFUN G defined on the interval [S1,\n% S2] which agrees with F on that interval. Any interior breakpoints in\n% F.DOMAIN within [S1, S2] are kept in G.DOMAIN.\n%\n% G = RESTRICT(F, S), where S is a row vector, will introduce additional\n% interior breakpoints at S(2:end-2).\n%\n% In both cases, if S(1) > S(end), S(1) < F.domain(1), or S(end) >\n% F.domain(end), then an error is returned. If S is empty or a scalar, then an\n% empty CHEBFUN G is returned.\n%\n% Note that G will not be 'simplified'. If this is required, call G =\n% SIMPLIFY(RESTRICT(F)), or G = F{S}.\n%\n% See also OVERLAP, SUBSREF, DEFINE, SIMPLIFY.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Tweak the domain of a quasimatrix input:\n[F, newDomain] = tweakDomain(F, newDomain);\n\n% Loop over the columns:\nfor k = 1:numel(F)\n F(k) = columnRestrict(F(k), newDomain);\nend\n\nend\n\nfunction f = columnRestrict(f, newDomain)\n\n% Ignore duplicate entries in newDomain:\nnewDomain([false, ~diff(newDomain)]) = [];\n\n% Empty case:\nif ( isempty(f) )\n return\nelseif ( isempty(newDomain) || numel(newDomain) == 1 )\n f = chebfun();\n return\nend\n\n% Cast a periodic chebfun to a regualr chebfun:\nif ( isPeriodicTech(f) )\n f = chebfun(f);\nend\n\n\n% Grab domain from f:\noldDomain = f.domain;\n\n% Trivial case:\nif ( (numel(newDomain) == 2) && domainCheck(f, newDomain([1, end])) ) \n % The domains are the same!\n return\nend\n\n% Check the domain is valid:\nif ( (newDomain(1) < oldDomain(1)) || (newDomain(end) > oldDomain(end)) || ...\n any(diff(newDomain) < 0) )\n % newDom is not a valid subinterval of oldDom!\n error('CHEBFUN:CHEBFUN:restrict:subdom', 'Not a valid subdomain.');\nend\n\n% Obtain FUN cell and pointValues from f:\nfuns = f.funs;\npointValues = f.pointValues;\n\n% Discard intervals to the left:\ndiscardIntsLeft = oldDomain(2:end) < newDomain(1);\noldDomain([discardIntsLeft, false]) = [];\nfuns(discardIntsLeft) = [];\npointValues([discardIntsLeft, false],:,:) = [];\n\n% Discard intervals to the right:\ndiscardIntsRright = oldDomain(1:end-1) > newDomain(end);\noldDomain([false, discardIntsRright]) = [];\nfuns(discardIntsRright) = [];\npointValues([false, discardIntsRright],:,:) = [];\n\n% Take the union of the new and old domains:\nif ( ~isempty( oldDomain(2:end-1) ) ) % Required due to Matlab union() behavior.\n % NB: the old endpoints will either be in newDomain or are not required.\n newDomain = union(oldDomain(2:end-1), newDomain);\nend\nnumFuns = numel(funs);\n\n% Initialise storage for new FUN objects and pointValues:\nnewFuns = cell(1, numel(newDomain)-1);\n\n% Loop through each fun and restrict as required:\nl = 0;\nfor k = 1:numFuns\n % Find the breaks which correspond to the kth fun:\n subsIdx = (newDomain >= oldDomain(k)) & (newDomain <= oldDomain(k+1));\n if ( sum(subsIdx) == 2 )\n % This interval is already a FUN: (i.e., no new breaks to introduce)\n newFuns{l+1} = restrict(funs{k}, newDomain(subsIdx));\n l = l + 1;\n else\n numSubs = sum(subsIdx)-1;\n if ( numSubs > 0 )\n % Restrict the FUN at the corresponding break points:\n newFuns(l+(1:numSubs)) = restrict(funs{k}, newDomain(subsIdx));\n l = l + numSubs;\n end\n end\nend\n\n% Update the pointValues:\nnewPointValues = chebfun.getValuesAtBreakpoints(newFuns);\n% Restore existing pointValues:\n[mask, locB] = ismember(oldDomain, newDomain);\nlocB(~logical(locB)) = [];\nnewPointValues(locB,:) = pointValues(mask,:);\n\n% Attach data to CHEBFUN to return as output:\nf.domain = newDomain;\nf.funs = newFuns;\nf.pointValues = newPointValues;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/restrict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.04885777412113743, "lm_q1q2_score": 0.018987011768196522}} {"text": "function [Lmk, Frm, Fac] = makeMeasFactor(Lmk, Obs, Frm, Fac)\n\n% MAKEMEASFACTOR Make measurement factor.\n% [Lmk, Frm, Fac] = MAKEMEASFACTOR(Lmk, Obs, Frm, Fac) creates a new\n% measurement factor Fac linking frame Frm to landmark Lmk, using the\n% observation informaiton in Obs.\n\n% Copyright 2015- Joan Sola @ IRI-UPC-CSIC\n\nFac.used = true; % Factor is being used ?\nFac.id = newId; % Factor unique ID\n\nFac.type = 'measurement'; % {'motion','measurement','absolute'}\nFac.rob = Frm.rob;\nFac.sen = Obs.sen;\nFac.lmk = Obs.lmk;\nFac.frames = Frm.frm;\n\n% Ranges\nFac.state.r1 = Frm.state.r;\nFac.state.r2 = Lmk.state.r;\n\n% Measurement is the straight data\nFac.meas.y = Obs.meas.y;\nFac.meas.R = Obs.meas.R;\nFac.meas.W = Obs.meas.R^-1; % measurement information matrix\n\n% Expectation has zero covariance -- and info in not defined\nFac.exp.e = Fac.meas.y; % expectation\nFac.exp.E = zeros(size(Obs.meas.R)); % expectation cov\n% Fac.exp.W = Fac.meas.W; % expectation information matrix\n\n% Error is zero at this stage, and takes covariance and info from measurement\nFac.err.z = zeros(size(Fac.meas.y)); % error or innovation (we call it error because we are on graph SLAM)\nFac.err.Z = Fac.meas.R; % error cov matrix\nFac.err.W = Fac.meas.W; % error information matrix\nFac.err.Wsqrt = chol(Fac.err.W);\n\n% Jacobians are zero at this stage. Just make size correct.\nFac.err.J1 = Obs.Jac.E_r; % Jac. of error wrt. node 1 - robot pose\nFac.err.J2 = Obs.Jac.E_l; % Jac. of error wrt. node 2 - lmk state\n\nFac.err.size = numel(Fac.err.z);\n\n% Append factor to Frame's and Lmk's factors lists.\nFrm.factors = [Frm.factors Fac.fac]; \nLmk.factors = [Lmk.factors Fac.fac];\n\n\n\n% ========== End of function - Start GPL license ==========\n\n\n% # START GPL LICENSE\n\n%---------------------------------------------------------------------\n%\n% This file is part of SLAMTB, a SLAM toolbox for Matlab.\n%\n% SLAMTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% SLAMTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with SLAMTB. If not, see .\n%\n%---------------------------------------------------------------------\n\n% SLAMTB is Copyright:\n% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,\n% Copyright (c) 2010-2013, Joan Sola,\n% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,\n% SLAMTB is Copyright 2009 \n% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol\n% @ LAAS-CNRS.\n% See on top of this file for its particular copyright.\n\n% # END GPL LICENSE\n\n", "meta": {"author": "joansola", "repo": "slamtb", "sha": "b4767f6bf38bceed205abb85f1aed12422c9a972", "save_path": "github-repos/MATLAB/joansola-slamtb", "path": "github-repos/MATLAB/joansola-slamtb/slamtb-b4767f6bf38bceed205abb85f1aed12422c9a972/InterfaceLevel/makeMeasFactor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.0378924251356822, "lm_q1q2_score": 0.018798198293500712}} {"text": "function mm_header_print ( input_filename, id, type, rep, field, symm )\n\n%*****************************************************************************80\n%\n%% MM_HEADER_PRINT prints header information from a Matrix Market file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character ( len = * ) INPUT_FILENAME, the input file name.\n%\n% Input, character ( len = 14 ) ID, the Matrix Market identifier.\n% This value must be '%%MatrixMarket'.\n%\n% Input, character ( len = 6 ) TYPE, the Matrix Market type.\n% This value must be 'matrix'.\n%\n% Input, character ( len = 10 ) REP, the Matrix Market 'representation'\n% indicator. Possible values include:\n% 'coordinate' (for sparse data)\n% 'array' (for dense data)\n% 'elemental' (to be added)\n%\n% Input, character ( len = 7 ) FIELD, the Matrix Market 'field'.\n% Possible values include:\n% 'real'\n% 'double'\n% 'complex'\n% 'integer'\n% 'pattern'\n%\n% Input, character ( len = 19 ) SYMM, the Matrix Market symmetry.\n% Possible values include:\n% 'symmetric'\n% 'hermitian'\n% 'skew-symmetric'\n% 'general'\n%\n fprintf ( 1, '\\n');\n fprintf ( 1, 'MM_HEADER_PRINT:\\n' );\n fprintf ( 1, ' Header information from Matrix Market file \"%s\".\\n', ...\n input_filename );\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Matrix Market ID = \"%s\".\\n', id );\n fprintf ( 1, ' \"%%%%MatrixMarket\" is only allowed value.\\n' );\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Matrix Market TYPE = \"%s\".\\n', type );\n fprintf ( 1, ' \"matrix\" is only allowed value.\\n' );\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Representation type REP = \"%s\".\\n', rep );\n fprintf ( 1, ' \"coordinate\" for sparse matrices,\\n' );\n fprintf ( 1, ' \"array\" for dense matrices,\\n' );\n fprintf ( 1, ' \"elemental\" for unassembled finite element matrices.\\n' );\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Numeric FIELD = \"%s\".\\n', field );\n fprintf ( 1, ' \"integer\" for integer values,\\n' );\n fprintf ( 1, ' \"real\" for real values,\\n' );\n fprintf ( 1, ' \"double\" for double precision real values,\\n' );\n fprintf ( 1, ' \"complex\" for complex values,\\n' );\n fprintf ( 1, ' \"pattern\" for nonzero pattern only.\\n' );\n fprintf ( 1, '\\n');\n fprintf ( 1, ' Symmetry type SYMM = \"%s\".\\n', symm );\n fprintf ( 1, ' \"general\" no symmetry,\\n' );\n fprintf ( 1, ' \"symmetric\" A(I,J) = A(J,I),\\n' );\n fprintf ( 1, ' input only lower triangle.\\n' );\n fprintf ( 1, ' \"skew-symmetric\" A(I,J) = - A(J,I),\\n' );\n fprintf ( 1, ' input only strict lower triangle.\\n' );\n fprintf ( 1, ' \"Hermitian\" A(I,J) = A*(J,I),\\n' );\n fprintf ( 1, ' input only lower triangle.\\n' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/mm_io/mm_header_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.0550052921662442, "lm_q1q2_score": 0.018788845180480573}} {"text": "classdef Scalar3d\n % SCALAR3D represents a 3D arary of scalar values. It can represents a single\n % directional component of a 3D vector field (e.g. Ex of E).\n\t% The fields are always evaluated at the primary grid points (grid kind =\n\t% GT.prim)\n \n properties (SetAccess = immutable)\n\t\t% numerical properties\n array % 3D array\n grid3d % instance of Grid3d\n\t\tgt_array % [x_gridtype y_gridtype z_gridtype]: array of instances of GT\n osc % instance of Oscillation\n\n\t\t% extra properties\n\t\tphysQcell % {PhysQ, int; PhysQ, int; ...}: representation of physical quanity\n\t\tunitvalue % unit value of physical quantity\n\t\tname % name of this quantity: \"E_x\", \"H_y\", etc. in LaTeX equation format\n\tend\n\t \n methods\n function this = Scalar3d(array, grid3d, gt_array, osc, physQcell, name)\n\t\t\tchkarg(istypesizeof(grid3d, 'Grid3d'), '\"grid3d\" should be instance of Grid3d.');\n\t\t\tthis.grid3d = grid3d;\n\t\t\t\n\t\t\tchkarg(istypesizeof(gt_array, 'GT', [1 Axis.count]), ...\n\t\t\t\t'\"gt_array\" should be length-%d row vector with GT as elements.', Axis.count);\n\t\t\tthis.gt_array = gt_array;\n\n\t\t\tN = grid3d.N + int(gt_array);\n\t\t\tchkarg(istypesizeof(array, 'complex', N), ...\n\t\t\t\t'\"array\" should be %d-by-%d-by-%d array with complex elements.', N(Axis.x), N(Axis.y), N(Axis.z));\n\t\t\tthis.array = array;\t\t\t\n\t\t\t\n\t\t\tchkarg(istypesizeof(osc, 'Oscillation'), '\"osc\" should be instance of Oscillation.');\n\t\t\tthis.osc = osc;\n\t\t\t\n\t\t\tif nargin < 5 % no physQ\n\t\t\t\tphysQcell = PhysQ.arbitrary;\n\t\t\tend\n\t\t\tchkarg(istypesizeof(physQcell, 'PhysQ') || isphysQcell(physQcell), ...\n\t\t\t\t'\"physQcell\" should be instance of PhysQ, or cell array {PhysQ, int; PhysQ, int; ...}.');\n\t\t\tif istypesizeof(physQcell, 'PhysQ')\n\t\t\t\tphysQcell = {physQcell, 1};\n\t\t\tend\n\t\t\tthis.physQcell = physQcell;\n\t\t\tthis.unitvalue = osc.unit.value(this.physQcell);\n\t\t\t\n\t\t\tif nargin < 6 % no name\n\t\t\t\tname = '';\n\t\t\tend\n\t\t\tchkarg(ischar(name), '\"name\" should be string.');\n this.name = name;\n\t\tend\n\t\t\n\t\tfunction l_cell = lall(this)\n\t\t\tl_cell = this.grid3d.lall(Axis.elems + Axis.count*subsindex(this.gt_array));\n\t\tend\n\t\t\n\t\tfunction l_cell = lg(this)\n\t\t\tl_cell = this.grid3d.lg(Axis.elems + Axis.count*subsindex(this.gt_array));\n\t\tend\n\t\t\n\t\tfunction l_cell = l(this)\n\t\t\tl_cell = this.grid3d.l(Axis.elems + Axis.count*subsindex(this.gt_array));\n\t\tend\n\n\t\tfunction [array, l_cell] = data_expanded(this)\n\t\t\tl_cell = this.lall;\n\t\t\tarray = this.array;\n\t\tend\n\t\t\n\t\tfunction [array, l_cell] = data_ghost_expanded(this)\n\t\t\tl_cell = this.lg;\n\t\t\tind = cell(1, Axis.count);\n\t\t\t\n\t\t\tfor w = Axis.elems\n\t\t\t\tind{w} = 1:(this.grid3d.N(w)+1);\n\t\t\tend\n\t\t\tarray = this.array(ind{:});\n\t\tend\n\t\t\n\t\tfunction [array, l_cell] = data_original(this)\n\t\t\tl_cell = this.l;\n\t\t\tind = cell(1, Axis.count);\n\t\t\t\n\t\t\tfor w = Axis.elems\n\t\t\t\tif this.gt_array(w) == GT.prim\n\t\t\t\t\tind{w} = 1:this.grid3d.N(w);\n\t\t\t\telse % this.gt_array(w) == GT.dual\n\t\t\t\t\tind{w} = 2:(this.grid3d.N(w)+1);\n\t\t\t\tend\n\t\t\tend\n\t\t\tarray = this.array(ind{:});\n\t\tend\n\t\t\n\t\tfunction [val, loc] = value(this, x, y, z)\n\t\t\t% Return the values of this Scalar3d along a line. The line should\n\t\t\t% be along one of the x, y, z directions, so at least two of the\n\t\t\t% given x, y, z should be scalar.\n\t\t\tloc = {x, y, z};\n\t\t\tlavail = this.l; % available locations\n\t\t\tnum_len1 = 0; % at least two of x, y, z should be scalar\n\t\t\tfor w = Axis.elems\n\t\t\t\tcoord_w = loc{w};\n\t\t\t\tchkarg(isempty(coord_w) || isvector(coord_w) && istypeof(coord_w, 'real'), ...\n\t\t\t\t'\"%s\" should be empty or real vector.', char(w));\n\t\t\t\tif isempty(coord_w)\n\t\t\t\t\tcoord_w = lavail{w}; % if empty, use all available locations\n\t\t\t\telse\n\t\t\t\t\tchkarg(this.grid3d.comp(w).contains(coord_w), '\"%s\" should be inside grid.', char(w));\n\t\t\t\t\tcoord_w = sort(coord_w);\n\t\t\t\tend\n\t\t\t\tloc{w} = coord_w;\n\t\t\t\tif length(coord_w) == 1\n\t\t\t\t\tnum_len1 = num_len1 + 1;\n\t\t\t\tend\n\t\t\tend\n\t\t\tchkarg(num_len1 >= 2, 'Points should be along Cartesian direction.');\n\t\t\t\n\t\t\tlall = this.lall;\n\t\t\tind = cell(1, Axis.count);\n\t\t\t\n\t\t\tfor w = Axis.elems\n\t\t\t\tloc_min = loc{w}(1);\n\t\t\t\tindw_min = ismembc2(loc_min, lall{w});\n\t\t\t\tif indw_min == 0\n\t\t\t\t\tindw_min = find(lall{w} < loc_min, 1, 'last');\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tloc_max = loc{w}(end);\n\t\t\t\tindw_max = ismembc2(loc_max, lall{w});\n\t\t\t\tif indw_max == 0\n\t\t\t\t\tindw_max = find(lall{w} > loc_max, 1, 'first');\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tind{w} = indw_min:indw_max;\n\t\t\tend\n\t\t\t\n\t\t\tisindlen1 = [length(ind{Axis.x}), length(ind{Axis.y}), length(ind{Axis.z})] == 1;\n\t\t\tif all(isindlen1)\n\t\t\t\tval = this.array(ind{:});\n\t\t\telse\n\t\t\t\tfor w = Axis.elems\n\t\t\t\t\tif isindlen1(w) % ndgrid() needs two data points to interpolate with\n\t\t\t\t\t\tindw = ind{w};\n\t\t\t\t\t\tif indw >= 2\n\t\t\t\t\t\t\tind{w} = [indw - 1, indw];\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tind{w} = [indw, indw + 1];\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tl = cell(1, Axis.count);\n\t\t\t\tfor w = Axis.elems\n\t\t\t\t\tl{w} = lall{w}(ind{w}(1):ind{w}(end));\n\t\t\t\tend\n\t\t\t\t[X, Y, Z] = ndgrid(l{:});\n\t\t\t\tV = this.array(ind{:});\n\t\t\t\t[Xi, Yi, Zi] = ndgrid(loc{:});\n\t\t\t\tval = interpn(X, Y, Z, V, Xi, Yi, Zi);\n\t\t\tend\n\t\tend\n\tend\t\t\nend\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/io/Scalar3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0367694622493283, "lm_q1q2_score": 0.01838473112466415}} {"text": "function test_example_nirs_fingertapping\n\n% MEM 4gb\n% WALLTIME 00:10:00\n\n%\n%% Analyzing NIRS data recorded during unilateral finger- and foot-tapping\n%\n% This example script demonstrates the analysis of data that is shared by Sujin Bak, Jinwoo Park, Jaeyoung Shin, and Jichai Jeong: _[Open Access fNIRS Dataset for Classification of Unilateral Finger- and Foot-Tapping](https://doi.org/10.6084/m9.figshare.9783755.v2)_.\n%\n% The following links point to the shared data, to the PDF manuscript that explains the shared data, and to a GitHub repository from one of the authors that contains some example analyses on the data.\n%\n%* \n%* \n%* \n%\n% The data includes the concentration changes of oxygenated/reduced hemoglobin ∆HbO/HbR, trigger information, and fNIRS channel information. The recordings were done for 30 subjects that were performing a finger- and foot-tapping task.\n%\n% The data were recorded by a three-wavelength continuous-time multi-channel fNIRS system (LIGHTNIRS, Shimadzu, Kyoto, Japan) consisting of eight light sources (Tx) and eight detectors (Rx). Four each of Tx and Rx were placed around C3 on the left hemisphere, and the rest were placed around C4 on the right hemisphere.\n%\n% The temporal structure of each trial is\n%\n%* instruction for 2s\n%* fixation cross, this indicates that the task has to be executed, for 10s\n%* \"stop\" for 2s\n%* fixation cross indicating rest period, for 15-17 seconds\n%\n% The total duration of a trial, including the instruction, ranges from 2+10+2+15=29 to 2+10+2+17=31 seconds.\n%\n%% # Building a MATLAB analysis script\n%\n\n% for now, getting the data from the below URL and unzipping it, works (JM added 20211201)\nt = tempdir;\nfilenames = unzip('https://figshare.com/ndownloader/files/18069143', t);\n\n% filenames = {\n% 'v2/fNIRS 01.mat'\n% 'v2/fNIRS 02.mat'\n% 'v2/fNIRS 03.mat'\n% 'v2/fNIRS 04.mat'\n% 'v2/fNIRS 05.mat'\n% 'v2/fNIRS 06.mat'\n% 'v2/fNIRS 07.mat'\n% 'v2/fNIRS 08.mat'\n% 'v2/fNIRS 09.mat'\n% 'v2/fNIRS 10.mat'\n% 'v2/fNIRS 11.mat'\n% 'v2/fNIRS 12.mat'\n% 'v2/fNIRS 13.mat'\n% 'v2/fNIRS 14.mat'\n% 'v2/fNIRS 15.mat'\n% 'v2/fNIRS 16.mat'\n% 'v2/fNIRS 17.mat'\n% 'v2/fNIRS 18.mat'\n% 'v2/fNIRS 19.mat'\n% 'v2/fNIRS 20.mat'\n% 'v2/fNIRS 21.mat'\n% 'v2/fNIRS 22.mat'\n% 'v2/fNIRS 23.mat'\n% 'v2/fNIRS 24.mat'\n% 'v2/fNIRS 25.mat'\n% 'v2/fNIRS 26.mat'\n% 'v2/fNIRS 27.mat'\n% 'v2/fNIRS 28.mat'\n% 'v2/fNIRS 29.mat'\n% 'v2/fNIRS 30.mat'\n% };\n\n% this allows switching easily between subjects, and eventually looping over all 30 subjects\nfilename = filenames{1};\n\n%% # Exploring the MATLAB files that hold the NIRS data\n%\n% The data is shared by the authors in the form of MATLAB files. Each file contains a bunch of separate variables, you can load it like this to represent it as a structure:\n%\nnirs = load(filename);\n\n% >> nirs\n% nirs =\n% struct with fields:\n% mrk: [1x1 struct]\n% mnt: [1x1 struct]\n% nfo: [1x1 struct]\n% ch1: [30003x1 double]\n% ch2: [30003x1 double]\n% ch3: [30003x1 double]\n% ch4: [30003x1 double]\n% ch5: [30003x1 double]\n% ch6: [30003x1 double]\n% ch7: [30003x1 double]\n% ch8: [30003x1 double]\n% ch9: [30003x1 double]\n% ch10: [30003x1 double]\n% ch11: [30003x1 double]\n% ch12: [30003x1 double]\n% ch13: [30003x1 double]\n% ch14: [30003x1 double]\n% ch15: [30003x1 double]\n% ch16: [30003x1 double]\n% ch17: [30003x1 double]\n% ch18: [30003x1 double]\n% ch19: [30003x1 double]\n% ch20: [30003x1 double]\n% ch21: [30003x1 double]\n% ch22: [30003x1 double]\n% ch23: [30003x1 double]\n% ch24: [30003x1 double]\n% ch25: [30003x1 double]\n% ch26: [30003x1 double]\n% ch27: [30003x1 double]\n% ch28: [30003x1 double]\n% ch29: [30003x1 double]\n% ch30: [30003x1 double]\n% ch31: [30003x1 double]\n% ch32: [30003x1 double]\n% ch33: [30003x1 double]\n% ch34: [30003x1 double]\n% ch35: [30003x1 double]\n% ch36: [30003x1 double]\n% ch37: [30003x1 double]\n% ch38: [30003x1 double]\n% ch39: [30003x1 double]\n% ch40: [30003x1 double]\n% dat: [1x1 struct]\n\n% Contrary to the description in the accompanying publication (see table 1 in the PDF manuscript) and in the GitHub repository, the MATLAB files do _not_ contain the variables |cntHb|, |clab|, etc. However, it is not so hard to make sense of the data: each channel is represented as a vector, there is header information, there is information about the optode montage, and there is information about the events.\n%\n% >> nirs.nfo\n% ans =\n% struct with fields:\n% fs: 13.3333\n% clab: {1x40 cell}\n% T: 30003\n% nEpochs: 1\n% length: 2.2502e+03\n% format: 'DOUBLE'\n% resolution: [1x40 double]\n% file: 'D:\\Experimental data\\NIRS motor imagery\\matdata\\fNIRS 01'\n% nEvents: 75\n% nClasses: 3\n% className: {'RIGHT' 'LEFT' 'FOOT'}\n\n%\n% >> nirs.mnt\n% ans =\n% struct with fields:\n% x: [40x1 double]\n% y: [40x1 double]\n% pos_3d: [3x40 double]\n% clab: {1x40 cell}\n% box: [2x41 double]\n% box_sz: [2x41 double]\n% scale_box: [2x1 double]\n% scale_box_sz: [2x1 double]\n\n%\n% >> nirs.mrk\n% ans =\n% struct with fields:\n% event: [1x1 struct]\n% time: [1x75 double]\n% y: [3x75 double]\n% className: {'RIGHT' 'LEFT' 'FOOT'}\n\n%% Convering the MATLAB structure to a FieldTrip raw data structure\n%\n% Since the data is not stored on disk in a [dataformat](/faq/dataformat/) that FieldTrip can directly read, we will circumvent the FieldTrip reading functions as outlined in [this frequenly asked question](/faq/how_can_i_import_my_own_dataformat/#circumvent-the-fieldtrip-reading-functions).\n%\n% We start with constructing a MATLAB data structure according to **[ft_datatype_raw](https://github.com/fieldtrip/fieldtrip/blob/release/utilities/ft_datatype_raw.m)**, as if it were produced by **[ft_preprocessing](https://github.com/fieldtrip/fieldtrip/blob/release/ft_preprocessing.m)**.\n%\ndata_raw = [];\ndata_raw.label = nirs.nfo.clab(:);\ndata_raw.trial{1} = [\n % transpose each channel, we want the data matrix to be Nchans * Nsamples\n nirs.ch1'\n nirs.ch2'\n nirs.ch3'\n nirs.ch4'\n nirs.ch5'\n nirs.ch6'\n nirs.ch7'\n nirs.ch8'\n nirs.ch9'\n nirs.ch10'\n nirs.ch11'\n nirs.ch12'\n nirs.ch13'\n nirs.ch14'\n nirs.ch15'\n nirs.ch16'\n nirs.ch17'\n nirs.ch18'\n nirs.ch19'\n nirs.ch20'\n nirs.ch21'\n nirs.ch22'\n nirs.ch23'\n nirs.ch24'\n nirs.ch25'\n nirs.ch26'\n nirs.ch27'\n nirs.ch28'\n nirs.ch29'\n nirs.ch30'\n nirs.ch31'\n nirs.ch32'\n nirs.ch33'\n nirs.ch34'\n nirs.ch35'\n nirs.ch36'\n nirs.ch37'\n nirs.ch38'\n nirs.ch39'\n nirs.ch40'\n ];\ndata_raw.fsample = nirs.nfo.fs;\ndata_raw.time{1} = ((1:nirs.nfo.T)-1)/nirs.nfo.fs;\n\n%% # Convert the optode montage to a layout for plotting\n%\n% In FieldTrip we can have a [detailled description](/faq/how_are_electrodes_magnetometers_or_gradiometers_described/#the-definition-of-nirs-sensors) of the NIRS optode placement and how optodes are combined to form channels. However, in this dataset this information is not complete and we cannot make a complete |opto| structure.\n%\n% This is how far we can get\n%\nopto = [];\nopto.label = nirs.mnt.clab(:);\nopto.chanpos = nirs.mnt.pos_3d'; % these are all nan\n\n% But this is not a complete description of the channel and sensor information according to **[ft_dataype_sens](https://github.com/fieldtrip/fieldtrip/blob/release/utilities/ft_datatype_sens.m)**. However, a full sensor definitioon is also not required: the opical densities have already been converted in HbO and HbR prior to sharing, so we only care about channel positions for plotting.\n%\n% For the plotting of channel level data (see also [this tutorial](/tutorial/plotting/)) we need a 2D layout. That is explained in detail in [this tutorial](/tutorial/layout/). If the |opto| definition had included 2D or 3D channel positions, then we could have used **[ft_prepare_layout](https://github.com/fieldtrip/fieldtrip/blob/release/ft_prepare_layout.m)** but now we will manually construct the layout structure.\n%\nlayout = [];\nlayout.label = nirs.mnt.clab(:);\nlayout.pos = [nirs.mnt.x(:) nirs.mnt.y(:)]; % these are all nan\nlayout.pos = nirs.mnt.box';\nlayout.width = nirs.mnt.box_sz(1,:)';\nlayout.height = nirs.mnt.box_sz(2,:)';\nlayout.outline = {};\nlayout.mask = {};\n\n% I don't think that the 41st position refers to an actual channel, so let's remove that.\n%\nlayout.pos(41, :) = [];\nlayout.width(41) = [];\nlayout.height(41) = [];\n\n% We can plot the layout using **[ft_plot_layout](https://github.com/fieldtrip/fieldtrip/blob/release/plotting/ft_plot_layout.m)** and inspect it in detail. That is something I have done multiple times, going back and forth in the script to ensure that my interpretation of the |mnt| field matches the data.\n%\nfigure\nft_plot_layout(layout, 'label', true)\n\n%\n% This shows four groups, with two groups of oxy channels on the left of the figure (for the left and right hemisphere), and the corresponding deoxy channels on the right of the figure. This matches with the schepatic display in figure 1 of the PDF manuscript, and with the displayed data in figure 3 of the PDF manuscript.\n%\n% To improve the plotting of topographies, we can also make an outline and mask. The outline comproses extra lines that are added to the figure, often we include a circle (representing the head) with a triangle at the top (representing the nose). The mask comprises a series of polygons that are used in topographic interpolation and masking the interpolated data that is outside the head, but also by masking the interpolated data that is in between the grid on the left and right hemisphere. This will become more clear at the end of this example script.\n%\npad = 0.2;\nsection = {1:10 11:20 21:30 31:40};\nfor i=1:4\n sel = section{i};\n % upper left\n corner1x = min(layout.pos(sel,1)-layout.width (sel)/2) - pad;\n corner1y = max(layout.pos(sel,2)+layout.height(sel)/2) + pad;\n\n % upper right\n corner2x = max(layout.pos(sel,1)+layout.width (sel)/2) + pad;\n corner2y = max(layout.pos(sel,2)+layout.height(sel)/2) + pad;\n\n % lower right\n corner3x = max(layout.pos(sel,1)+layout.width (sel)/2) + pad;\n corner3y = min(layout.pos(sel,2)-layout.height(sel)/2) - pad;\n\n % lower left\n corner4x = min(layout.pos(sel,1)-layout.width (sel)/2) - pad;\n corner4y = min(layout.pos(sel,2)-layout.height(sel)/2) - pad;\n\n layout.outline{i} = [\n corner1x corner1y\n corner2x corner2y\n corner3x corner3y\n corner4x corner4y\n corner1x corner1y % this closes the outline\n ];\n\n layout.mask{i} = [\n corner1x corner1y\n corner2x corner2y\n corner3x corner3y\n corner4x corner4y\n corner1x corner1y % this closes the outline\n ];\nend\n\nfigure\nft_plot_layout(layout, 'label', true, 'outline', true, 'mask', true)\n\n%\n% The layout now also shows the outline, as thick black lines. If you disable the outline, you can also see the mask as dotted lines.\n%\n%% # Parsing the events and segmenting the data in trials\n%\n% In general in FieldTrip events have to be aligned with samples. The first sample of a recording on disk is referred to as sample 1.\n%\n% The |mrk| field contains times\n%\n% >> nirs.mrk.time\n% ans =\n% Columns 1 through 9\n% 1950 30975 60975 91950 ...\n\n% These numbers are larger than the total number of samples, so they do not directly map onto samples. I started off assuming that the marker time is expressed in milliseconds, but that turned out not to be correct. Therefore I experimented with the following piece of code until I had something that made sense.\n%\n% This timestamp to sample ratio results in the events being nicely spaced over the whole experiment\n%\nratio = 75;\n\n% Note that `1/data.fsample = 0.075`, i.e., with the 13.333 Hz sampling rate each sample happens to be 75 ms. When working with unknown data it is not uncommon to have to deal with a puzzle like this, it reminds me of [Kabbalah](https://en.wikipedia.org/wiki/Kabbalah).\n%\nevent = [];\nfor i=1:nirs.nfo.nEvents\n event(i).type = 'marker';\n event(i).value = nirs.mrk.className{nirs.mrk.event.desc(i)};\n event(i).sample = round(nirs.mrk.time(i)/ratio) + 1;\n event(i).duration = nan;\n event(i).offset = nan;\nend\n\ncfg = [];\ncfg.event = event; % store the events in the configuration to have them displayed\ncfg.viewmode = 'vertical';\ncfg.preproc.demean = 'yes';\ncfg.blocksize = nirs.nfo.length; % show the data over the whole length\nft_databrowser(cfg, data_raw);\n\n%\n%% # Apply a band-pass filter on the continuous data\n%\ncfg = [];\ncfg.bpfilter = 'yes';\ncfg.bpfreq = [0.02 0.8];\ncfg.bpfilford = 2;\ndata_filt = ft_preprocessing(cfg, data_raw);\n\n%% # Segment the continuous data into trials\n%\n% To segment the data we have to create a so-called \"trial definition\". This would normally be done using **[ft_definetrial](https://github.com/fieldtrip/fieldtrip/blob/release/ft_definetrials.m)** and using the events that were read from the data on disk (had it been a supported file format). The trial definition specifies the begin and end sample of each trial, and the offset, i.e., how many samples the time defined as t=0 is shifted relative to the data segment. Furthermore, it can contain additional columns with trial specific information, such as condition codes.\n%\n% The temporal structure of each trial is\n%\n%* instruction for 2s\n%* fixation cross, this indicates that the task has to be executed, for 10s\n%* \"stop\" for 2s\n%* fixation cross indicating rest period, for 15-17 seconds\n%\n% The total duration of a trial, including the instruction, ranges from 2+10+2+15=29 to 2+10+2+17=31 seconds.\n%\n% We will use the standard FieldTrip |event| structure to make the trials, this is also what **[ft_read_event](https://github.com/fieldtrip/fieldtrip/blob/release/fileio/ft_read_event.m)** returns for supported data formats.\n%\ntaskonset = [event.sample]; % let's assume that the marker is at task onset\nbegsample = taskonset - 2*data_raw.fsample;\nendsample = taskonset + (10+2+15)*data_raw.fsample;\noffset = - 2*data_raw.fsample * ones(size(begsample)); % each trial has the same 2 seconds offset\n\n% The begin sample, end sample and offset should be integers:\n%\nbegsample = round(begsample);\nendsample = round(endsample);\noffset = round(offset);\n\n% and we map the right, left, and foot condition onto condition codes 1, 2, and 3.\n%\n[dummy, condition] = ismember({event.value}, {'RIGHT' 'LEFT' 'FOOT'});\n\ntrl = [begsample(:) endsample(:) offset(:) condition(:)];\n\ncfg = [];\ncfg.trl = trl;\ndata_segmented = ft_redefinetrial(cfg, data_filt);\n\n%% # Visualize the segmented data\n%\ncfg = [];\ncfg.event = event;\ncfg.viewmode = 'vertical';\ncfg.preproc.demean = 'no'; % it is filtered by now\nft_databrowser(cfg, data_segmented);\n\n%\n%% # Average the segmented data, conditional on each condition\n%\ncfg = [];\ncfg.trials = data_segmented.trialinfo==1;\ntimelockRight = ft_timelockanalysis(cfg, data_segmented);\ncfg.trials = data_segmented.trialinfo==2;\ntimelockLeft = ft_timelockanalysis(cfg, data_segmented);\ncfg.trials = data_segmented.trialinfo==3;\ntimelockFoot = ft_timelockanalysis(cfg, data_segmented);\n\n%% # Plot the averaged responses\n%\n%\ncfg = [];\ncfg.layout = layout;\ncfg.showoutline = 'yes';\ncfg.baseline = [-2 0];\ncfg.showlabels = 'yes';\ncfg.interactive = 'no'; % use MATLAB for zooming in\nft_multiplotER(cfg, timelockRight, timelockLeft, timelockFoot);\n\n%\n% Although some of the more noisy channels dominate the figure due to the automatic vertical scaling, if you zoom in and pay attention to |Ch4oxy|, |Ch5oxy|, and |Ch6oxy| over the left hemisphere, and |Ch14oxy| and |Ch16oxy| over the right hemisphere, you can see that the left hemisphere shows more activity during the right fingertapping task (blue) and the right hemisphere shows more activity following the left fingertapping task (red).\n%\n% This [example script](/example/nirs_layout/) explains in more detail how for a NIRS dataset the oxy and deoxy channels can either be plotted on top of each other (which is spatially consistent with how the data is recorded) or side-by-side. Plotting them side-by-side makes the results easier to interpret, especially if you have multiple responses (like we have here for left, right and foot conditions). For plotting topographic distributions you also have to ensure that your 2D channel layout does not have overlapping channels that have bvery different numbers.\n%\n%% # Plot the topography of the averaged responses\n%\n% This step benefits from the layout having an outline and especially a mask, otherwise the interpolation will cause the whole image to be color coded, including the pieces in between the hemispheres and in between the oxy (on the left) and deoxy channels (on the right).\n%\ncfg = [];\ncfg.layout = layout;\ncfg.interactive = 'yes';\ncfg.xlim = [7 15];\ncfg.ylim = [-0.004 0.004];\nfigure; ft_topoplotER(cfg, timelockRight);\nfigure; ft_topoplotER(cfg, timelockLeft);\nfigure; ft_topoplotER(cfg, timelockFoot);\n\n%\n%\n% From the topographic arrangements it is clear that the left hemisphere responds with an increase in HbO to the right fingertapping task and the right hemisphere to the left fingertapping task; the HbR (on the right side of the figure) shows the opposite pattern. Also interesting is that both left and right hemisphere show a decrease in HbO and an increase in HbR during the tapping of the foot.\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_example_nirs_fingertapping20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.03904829048965015, "lm_q1q2_score": 0.018153611608082897}} {"text": "function varargout = FUN_PLOTTER(varargin)\n% FUN_PLOTTER MATLAB code for FUN_PLOTTER.fig\n% FUN_PLOTTER, by itself, creates a new FUN_PLOTTER or raises the existing\n% singleton*.\n%\n% H = FUN_PLOTTER returns the handle to a new FUN_PLOTTER or the handle to\n% the existing singleton*.\n%\n% FUN_PLOTTER('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in FUN_PLOTTER.M with the given input arguments.\n%\n% FUN_PLOTTER('Property','Value',...) creates a new FUN_PLOTTER or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before FUN_PLOTTER_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to FUN_PLOTTER_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help FUN_PLOTTER\n\n% Last Modified by GUIDE v2.5 13-Feb-2013 04:22:47\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @FUN_PLOTTER_OpeningFcn, ...\n 'gui_OutputFcn', @FUN_PLOTTER_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before FUN_PLOTTER is made visible.\nfunction FUN_PLOTTER_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to FUN_PLOTTER (see VARARGIN)\n\n% Choose default command line output for FUN_PLOTTER\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes FUN_PLOTTER wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = FUN_PLOTTER_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclc\nwarning off\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'sin(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,sind(thta),'linewidth',3)\n set(handles.text1,'string','SINE PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'cos(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,cosd(thta),'linewidth',3)\n set(handles.text1,'string','COSINE PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton3.\nfunction pushbutton3_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'tan(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,tand(thta),'linewidth',3)\n set(handles.text1,'string','TANGENT PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton4.\nfunction pushbutton4_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'cot(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,cotd(thta),'linewidth',3)\n set(handles.text1,'string','COTANGENT PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton5.\nfunction pushbutton5_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'sec(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,secd(thta),'linewidth',3)\n set(handles.text1,'string','SECANT PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton6.\nfunction pushbutton6_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'csc(x)';\nv = get(handles.checkbox2,'value');\nif v == 1\n thta = 0:3*360;\n axes(handles.axes1)\n plot(thta,cscd(thta),'linewidth',3)\n set(handles.text1,'string','COSECANT PLOT FROM 0 TO 6*PI')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton7.\nfunction pushbutton7_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z x\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'log(t)';\nv = get(handles.checkbox2,'value');\nif v == 1\n x = 0:0.25:10;\n axes(handles.axes1)\n plot(x,log(x),'linewidth',3)\n set(handles.text1,'string','LOGRITHMIC PLOT FROM 0 TO 10')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in pushbutton8.\nfunction pushbutton8_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z x\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nz = 'exp(t)';\nv = get(handles.checkbox2,'value');\nif v == 1\n x = 0:0.25:10;\n axes(handles.axes1)\n plot(x,exp(x),'linewidth',3)\n set(handles.text1,'string','EXPONENTIAL PLOT FROM 0 TO 10')\n grid on\nelse\n msgbox('PLZ SET RANGE...TRY AGAIN','WARNING','warn','modal')\n set(handles.text1,'string','')\n cla(handles.axes1)\n reset(handles.axes1)\n set(handles.axes1,'box','on')\n set(handles.axes1,'xtick',[])\n set(handles.axes1,'ytick',[])\n return\nend\n\n% --- Executes on button press in checkbox2.\nfunction checkbox2_Callback(hObject, eventdata, handles)\n% hObject handle to checkbox2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of checkbox2\nset(handles.checkbox3,'value',0)\nset(handles.edit1,'enable','inactive')\nset(handles.edit2,'enable','inactive')\n% --- Executes on button press in checkbox3.\nfunction checkbox3_Callback(hObject, eventdata, handles)\n% hObject handle to checkbox3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of checkbox3\nset(handles.checkbox2,'value',0)\nset(handles.edit1,'enable','on')\nset(handles.edit2,'enable','on')\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in pushbutton10.\nfunction pushbutton10_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton10 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z p1\nv = get(handles.checkbox2,'value');\nif v == 1\n msgbox('CAN NOT WORK ON DEFAULT RANGE','WARNING','warn','modal')\n return\nend\nv1 = get(handles.checkbox3,'value');\nif v1 == 0\n msgbox('FIRST SET RANGE','WARNING','warn','modal')\n return\nend\na = str2double(get(handles.edit1,'string'));\nb = str2double(get(handles.edit2,'string'));\nif a > b\n msgbox('MIN IS GR8ER THAN MAX','WARNING','warn','modal')\n set(handles.edit1,'string','')\n set(handles.edit2,'string','')\n return\nend\nfx2 = get(handles.edit3,'string');\nz = fx2;\nif isempty(fx2) || isempty(a) || isempty(b)\n msgbox('EITHER MAX OR MIN OR FUNCTION FIELD IS EMPTY OR INVALID','WARNING...','modal')\n set(handles.edit1,'string','')\n set(handles.edit2,'string','')\n set(handles.edit3,'string','')\n return\nend\nfx3 = inline(fx2);\np1 = a:0.25:b;\np2 = p1;\nfor l = 1:length(p2)\n mag(l) = fx3(p2(l));\nend\naxes(handles.axes1)\nplot(p2,mag,'linewidth',3)\ngrid on\nset(handles.text1,'string',strcat('PLOT OF ',fx2,' FROM RANGE ',num2str(a),' TO ',num2str(b)))\n\n% --- Executes on button press in pushbutton11.\nfunction pushbutton11_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton11 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta x p1\nd = z;\nk = z;\nswitch k\n case 'sin(x)'\n fx = sym(k);\n n = str2double(inputdlg('INPUT ORDER OF DIFFRENTIATION','DY/DX'));\n if isnan(n)\n return\n end\n fx1 = diff(fx,n);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('sin\\theta','d(sin\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF SIN(X) AND SIN(X)')\n case 'cos(x)'\n fx = sym(k);\n n = str2double(inputdlg('INPUT ORDER OF DIFFRENTIATION','DY/DX'));\n if isnan(n)\n return\n end\n fx1 = diff(fx,n);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('cos\\theta','d(cos\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF COS(X) AND COS(X)')\n case 'tan(x)'\n fx = sym(k);\n fx1 = diff(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('tan\\theta','d(tan\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF TAN(X) AND TAN(X)')\n case 'cot(x)'\n fx = sym(k);\n fx1 = diff(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('cot\\theta','d(cot\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF COT(X) AND COT(X)')\n case 'sec(x)'\n fx = sym(k);\n fx1 = diff(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('sec\\theta','d(sec\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF SEC(X) AND SEC(X)')\n case 'csc(x)'\n fx = sym(k);\n fx1 = diff(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'r','linewidth',3)\n grid on\n %legend('csc\\theta','d(csc\\theta)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF CSC(X) AND CSC(X)')\n case 'log(t)'\n fx = sym(k);\n fx1 = diff(fx);\n r = x;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'r','linewidth',3)\n grid on\n %legend('log(x)','d(log(x))/dx')\n set(handles.text1,'string','DIFFRENTIATION OF LOG(X) AND LOG(X)')\n case 'exp(t)'\n fx = sym(k);\n fx1 = diff(fx);\n r = x;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'r','linewidth',1.5)\n grid on\n %legend('e^x','d(e^x)/dx')\n set(handles.text1,'string','DIFFRENTIATION OF EXP(X) AND EXP(X)')\n case d\n fx = sym(k);\n fx1 = diff(fx);\n r = p1;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'r','linewidth',1.8)\n grid on\n %legend(d,strcat('d(',d,')/dx'))\n set(handles.text1,'string',strcat('DIFFRENTIATION OF ',d,' AND ',d))\nend\n \n% --- Executes on button press in pushbutton12.\nfunction pushbutton12_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton12 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal z thta x p1\nd = z;\nk = z;\nswitch k\n case 'sin(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('sin\\theta','d(sin\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF SIN(X) AND SIN(X)')\n case 'cos(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('cos\\theta','d(cos\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF COS(X) AND COS(X)')\n case 'tan(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('tan\\theta','d(tan\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF TAN(X) AND TAN(X)')\n case 'cot(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('cot\\theta','d(cot\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF COT(X) AND COT(X)')\n case 'sec(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('sec\\theta','d(sec\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF SEC(X) AND SEC(X)')\n case 'csc(x)'\n fx = sym(k);\n fx1 = int(fx);\n for l = 1:length(thta)\n mag(l) = subs(fx1,deg2rad(thta(l)));\n end\n axes(handles.axes1)\n hold on\n plot(thta,mag,'g','linewidth',3)\n grid on\n %legend('csc\\theta','d(csc\\theta)/dx')\n set(handles.text1,'string','INTEGRATION OF CSC(X) AND CSC(X)')\n case 'log(t)'\n fx = sym(k);\n fx1 = int(fx);\n r = x;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'g','linewidth',3)\n grid on\n %legend('log(x)','d(log(x))/dx')\n set(handles.text1,'string','INTEGRATION OF LOG(X) AND LOG(X)')\n case 'exp(t)'\n fx = sym(k);\n fx1 = int(fx);\n r = x;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'g','linewidth',1.5)\n grid on\n %legend('e^x','d(e^x)/dx')\n set(handles.text1,'string','INTEGRATION OF EXP(X) AND EXP(X)')\n \n case d\n fx = sym(k);\n fx1 = int(fx);\n r = p1;\n for l = 1:length(r)\n mag(l) = subs(fx1,r(l));\n end\n axes(handles.axes1)\n hold on\n plot(r,mag,'g','linewidth',2.3)\n grid on\n %legend(d,strcat('d(',d,')/dx'))\n set(handles.text1,'string',strcat('INTEGRATION OF ',d,' AND ',d))\nend\n\n\n% --------------------------------------------------------------------\nfunction CL_EAR_Callback(hObject, eventdata, handles)\n% hObject handle to CL_EAR (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])\nset(handles.edit1,'string','')\nset(handles.edit2,'string','')\nset(handles.edit3,'string','')\nset(handles.checkbox2,'value',0)\nset(handles.checkbox3,'value',0)\n\n% --------------------------------------------------------------------\nfunction EXI_T_Callback(hObject, eventdata, handles)\n% hObject handle to EXI_T (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose\n\n\n% --------------------------------------------------------------------\nfunction CLEAR_AXES_Callback(hObject, eventdata, handles)\n% hObject handle to CLEAR_AXES (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncla(handles.axes1)\nreset(handles.axes1)\nset(handles.axes1,'box','on')\nset(handles.axes1,'xtick',[])\nset(handles.axes1,'ytick',[])", "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/41886-function-plotter-in-one-variable/function plotter/FUN_PLOTTER.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.05419873173281514, "lm_q1q2_score": 0.018134322647878395}} {"text": "function tapas_hgf_whichworld_plotTraj(r)\n% Plots trajectories estimated by fitModel for the hgf_whichworld perceptual model\n% Usage: est = tapas_fitModel(responses, inputs); tapas_hgf_plotTraj(est);\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Check whether we have a configuration structure\nif ~isfield(r,'c_prc')\n error('tapas:hgf:ConfigRequired', 'Configuration required: before calling tapas_hgf_whichworld_plotTraj, tapas_hgf_whichworld_config has to be called.');\nend\n\n% Number of worlds\nnw = r.c_prc.nw;\n\n% Define colors\ncolors = [1 0 0; 0.67 0 1; 0 0.67 1; 0.67 1 0];\n\n% Set up display\nscrsz = get(0,'screenSize');\nouterpos = [0.2*scrsz(3),0.2*scrsz(4),0.8*scrsz(3),0.8*scrsz(4)];\nfigure(...\n 'OuterPosition', outerpos,...\n 'Name','HGF trajectories');\n\n% Number of trials\nt = size(r.u,1);\n\n% Optional plotting of standard deviations (true or false)\nplotsd2 = true;\nplotsd3 = true;\n\n% Subplots\nsubplot(3,1,1);\n\nif plotsd3 == true\n upper3prior = r.p_prc.mu3_0 +sqrt(r.p_prc.sa3_0);\n lower3prior = r.p_prc.mu3_0 -sqrt(r.p_prc.sa3_0);\n upper3 = [upper3prior; r.traj.mu(:,3)+sqrt(r.traj.sa(:,3))];\n lower3 = [lower3prior; r.traj.mu(:,3)-sqrt(r.traj.sa(:,3))];\n \n plot(0, upper3prior, 'ob', 'LineWidth', 1);\n hold all;\n plot(0, lower3prior, 'ob', 'LineWidth', 1);\n fill([0:t, fliplr(0:t)], [(upper3)', fliplr((lower3)')], ...\n 'b', 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\nend\nplot(0:t, [r.p_prc.mu3_0; r.traj.mu(:,3)], 'b', 'LineWidth', 2);\nhold all;\nplot(0, r.p_prc.mu3_0, 'ob', 'LineWidth', 2); % prior\nxlim([0 t]);\ntitle('Posterior expectation \\mu_3 of log-volatility of tendency x_3', 'FontWeight', 'bold');\nxlabel('Trial number');\nylabel('\\mu_3');\n\nsubplot(3,1,2);\nif plotsd2 == true\n for j=1:nw\n upper2prior = r.p_prc.mu2_0(j) +sqrt(r.p_prc.sa2_0(j));\n lower2prior = r.p_prc.mu2_0(j) -sqrt(r.p_prc.sa2_0(j));\n upper2 = [upper2prior; r.traj.mu(:,2,j)+sqrt(r.traj.sa(:,2,j))];\n lower2 = [lower2prior; r.traj.mu(:,2,j)-sqrt(r.traj.sa(:,2,j))];\n \n plot(0, upper2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n hold all;\n plot(0, lower2prior, 'o', 'Color', colors(j,:), 'LineWidth', 1);\n fill([0:t, fliplr(0:t)], [(upper2)', fliplr((lower2)')], ...\n colors(j,:), 'EdgeAlpha', 0, 'FaceAlpha', 0.15);\n end\nend\nfor j=1:nw\n plot(0:t, [r.p_prc.mu2_0(j); r.traj.mu(:,2,j)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, r.p_prc.mu2_0(j), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nxlim([0 t]);\ntitle('Posterior expectations \\mu_2 of tendencies x_2', 'FontWeight', 'bold');\nxlabel({'Trial number', ' '}); % A hack to get the relative subplot sizes right\nylabel('\\mu_2');\nhold off;\n\nsubplot(3,1,3);\nfor j=1:nw\n plot(0:t, [tapas_sgm(r.p_prc.mu2_0(j), 1); tapas_sgm(r.traj.mu(:,2,j), 1)], 'Color', colors(j,:), 'LineWidth', 2);\n hold all;\n plot(0, tapas_sgm(r.p_prc.mu2_0(j), 1), 'o', 'Color', colors(j,:), 'LineWidth', 2); % prior\nend\nplot(1:t, r.u(:,1), '.', 'Color', [0 0 0]); % inputs\nif ~isempty(find(strcmp(fieldnames(r),'y'))) && ~isempty(r.y)\n y = r.y(:,1);\n if ~isempty(find(strcmp(fieldnames(r),'irr')))\n y(r.irr) = NaN; % weed out irregular responses\n plot(r.irr, 1.08.*ones([1 length(r.irr)]), 'x', 'Color', [1 0.7 0], 'Markersize', 11, 'LineWidth', 2); % irregular responses\n end\n if ~any(y>1) && ~any(y<0)\n plot(1:t, y, '.', 'Color', [1 0.7 0]); % responses\n else\n for j=1:nw\n plot(find(y==j), 1.08*ones([1 length(find(y==j))]), '.', 'Color', colors(j,:)); % responses\n end\n end\n title(['Response y, input u (black), and posterior probability of worlds s(\\mu_2) for \\kappa=', ...\n num2str(r.p_prc.ka), ', \\omega=', num2str(r.p_prc.om), ', \\vartheta=', num2str(r.p_prc.th)], ...\n 'FontWeight', 'bold');\n ylabel('y, u, s(\\mu_2)');\n axis([0 t -0.1 1.15]);\nelse\n title(['Input u (black) and posterior probability of worlds s(\\mu_2) for m_3=', ...\n num2str(r.p_prc.m), ', \\phi_3=', num2str(r.p_prc.phi), ', \\kappa=', ...\n num2str(r.p_prc.ka), ', \\omega=', num2str(r.p_prc.om), ', \\vartheta=', num2str(r.p_prc.th)], ...\n 'FontWeight', 'bold');\n ylabel('u, s(\\mu_2)');\n axis([0 t -0.1 1.1]);\nend\nplot(1:t, 0.5, 'k');\nxlabel('Trial number');\nhold off;\n", "meta": {"author": "translationalneuromodeling", "repo": "tapas", "sha": "604c56843c15411f5bd80190f81d845ac57d8592", "save_path": "github-repos/MATLAB/translationalneuromodeling-tapas", "path": "github-repos/MATLAB/translationalneuromodeling-tapas/tapas-604c56843c15411f5bd80190f81d845ac57d8592/HGF/tapas_hgf_whichworld_plotTraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03676946449231437, "lm_q1q2_score": 0.017953918965516895}} {"text": "function result = nsga2(opt, varargin)\n% Function: result = nsga2(opt, varargin)\n% Description: The main flowchart of of NSGA-II. Note:\n% All objectives must be minimization. If a objective is maximization, the\n% objective should be multipled by -1.\n%\n% Syntax:\n% result = nsga2(opt): 'opt' is generated by function nsgaopt().\n% result = nsga2(opt, param): 'param' can be any data type, it will be\n% pass to the objective function objfun().\n%\n% Then ,the result structure can be pass to plotnsga to display the\n% population: plotnsga(result);\n%\n% Parameters:\n% opt : A structure generated by funciton nsgaopt().\n% varargin : Additional parameter will be pass to the objective functions.\n% It can be any data type. For example, if you call: nsga2(opt, param),\n% then objfun would be called as objfun(x,param), in which, x is the\n% design variables vector.\n% Return:\n% result : A structure contains optimization result.\n%\n% LSSSSWC, NWPU\n% Revision: 1.2 Data: 2011-07-26\n%*************************************************************************\n\n\ntStart = tic();\n%*************************************************************************\n% Verify the optimization model\n%*************************************************************************\nopt = verifyOpt(opt);\n\n%*************************************************************************\n% variables initialization\n%*************************************************************************\nnVar = opt.numVar;\nnObj = opt.numObj;\nnCons = opt.numCons;\npopsize = opt.popsize;\n\n% pop : current population\n% newpop : new population created by genetic algorithm operators\n% combinepop = pop + newpop;\npop = repmat( struct(...\n 'var', zeros(1,nVar), ...\n 'obj', zeros(1,nObj), ...\n 'cons', zeros(1,nCons),...\n 'rank', 0,...\n 'distance', 0,...\n 'prefDistance', 0,... % preference distance used in R-NSGA-II\n 'nViol', 0,...\n 'violSum', 0),...\n [1,popsize]);\n\n% state: optimization state of one generation\nstate = struct(...\n'currentGen', 1,... % current generation number\n'evaluateCount', 0,... % number of objective function evaluation\n'totalTime', 0,... % total time from the beginning\n'firstFrontCount', 0,... % individual number of first front\n'frontCount', 0,... % number of front\n'avgEvalTime', 0 ... % average evaluation time of objective function (current generation)\n);\n\nresult.pops = repmat(pop, [opt.maxGen, 1]); % each row is the population of one generation\nresult.states = repmat(state, [opt.maxGen, 1]); % each row is the optimizaiton state of one generation\nresult.opt = opt; % use for output\n\n% global variables\nglobal STOP_NSGA; %STOP_NSGA : used in GUI , if STOP_NSGA~=0, then stop the optimizaiton\nSTOP_NSGA = 0;\n\n\n%*************************************************************************\n% initialize the P0 population\n%*************************************************************************\nngen = 1;\npop = opt.initfun{1}(opt, pop, opt.initfun{2:end});\n[pop, state] = evaluate(opt, pop, state, varargin{:});\n[opt, pop] = ndsort(opt, pop);\n\n% state\nstate.currentGen = ngen;\nstate.totalTime = toc(tStart);\nstate = statpop(pop, state);\n\nresult.pops(1, :) = pop;\nresult.states(1) = state;\n\n% output\n% plotnsga(result, ngen);\nopt = callOutputfuns(opt, state, pop);\n\n\n%*************************************************************************\n% NSGA2 iteration\n%*************************************************************************\nwhile( ngen < opt.maxGen && STOP_NSGA==0)\n % 0. Display some information\n\tngen = ngen+1;\n state.currentGen = ngen;\n% fprintf('\\n\\n************************************************************\\n');\n% fprintf('* Current generation %d / %d\\n', ngen, opt.maxGen);\n% fprintf('************************************************************\\n');\n \n % 1. Create new population\n newpop = selectOp(opt, pop);\n newpop = crossoverOp(opt, newpop, state);\n newpop = mutationOp(opt, newpop, state);\n [newpop, state] = evaluate(opt, newpop, state, varargin{:});\n\n % 2. Combine the new population and old population : combinepop = pop + newpop\n combinepop = [pop, newpop];\n \n % 3. Fast non dominated sort\n [opt, combinepop] = ndsort(opt, combinepop);\n \n % 4. Extract the next population\n pop = extractPop(opt, combinepop);\n\n % 5. Save current generation results\n state.totalTime = toc(tStart);\n state = statpop(pop, state);\n \n result.pops(ngen, :) = pop;\n result.states(ngen) = state;\n\n % 6. plot current population and output\n% if( mod(ngen, opt.plotInterval)==0 )\n% plotnsga(result, ngen);\n% end\n% if( mod(ngen, opt.outputInterval)==0 )\n% opt = callOutputfuns(opt, state, pop);\n% end\n \nend\n\n% call output function for closing file\nopt = callOutputfuns(opt, state, pop, -1);\n\n% close worker processes\nif( strcmpi(opt.useParallel, 'yes'))\n matlabpool close\nend\n\ntoc(tStart);\n\n\n", "meta": {"author": "Eric-Bradford", "repo": "TS-EMO", "sha": "9ec2aa2f54d1232f80d37494ac067f2ebc112688", "save_path": "github-repos/MATLAB/Eric-Bradford-TS-EMO", "path": "github-repos/MATLAB/Eric-Bradford-TS-EMO/TS-EMO-9ec2aa2f54d1232f80d37494ac067f2ebc112688/NGPM_v1.4/nsga2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.037326883863690125, "lm_q1q2_score": 0.017934771814473584}} {"text": "function HRVparams = InitializeHRVparams(project_name)\n%\n% settings = InitializeHRVparams('project_name')\n%\n% OVERVIEW: \n% This file stores settings and should be configured before\n% each use of the PhysioNet Cardiovascular Signal Toolbox:\n% 1. Project Specific Input/Output Data type and Folders\n% 2. How much does the user trust the data\n% 3. Global Settings (Window Size) for signal segmentation\n% 4. Quality Threshold Settings\n% 5. Debug Settings\n% 6. SQI Settings\n% 7. Preprocess Settings\n% 8. AF Detection Settings\n% 9. Time Domain Analysis Settings\n% 10. Frequency Domain Analysis Settings\n% 11. SDANN and SDNNI Analysis Settings\n% 12. PRSA Analysis Settings\n% 13. Peak Detection Settings\n% 14. Entropy and Multiscale Entropy - MSE - Settings\n% 15. Detrended Fluctuation Analysis - DFA - Settings\n% 16. Poincar� plot - Settings\n% 17. Heart Rate Turbulence (HRT) - Settings\n% 18. Output Settings \n% 19. Time of Process and Filename to Save Data\n%\n% INPUT: \n% project_name = a string with the name of the project - this\n% will determine the naming convention of file folders \n%\n% OUTPUT:\n% HRVparams - struct of various settings for the hrv_toolbox analysis\n%\n% DEPENDENCIES & LIBRARIES:\n% PhysioNet Cardiovascular Signal Toolbox\n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n%\n% REFERENCE: \n% Vest et al. \"An Open Source Benchmarked HRV Toolbox for Cardiovascular \n% Waveform and Interval Analysis\" Physiological Measurement (In Press), 2018. \n%\n%\tREPO: \n% https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox\n% ORIGINAL SOURCE AND AUTHORS: \n% Adriana N. Vest\n% Giulia Da Poian\n% Dependent scripts written by various authors \n% (see functions for details) \n%\tCOPYRIGHT (C) 2018 \n% LICENSE: \n% This software is offered freely and without warranty under \n% the GNU (v3 or later) public license. See license file for\n% more information\n%%\n\n\nif isempty(project_name)\n project_name = 'none';\nend\n\n% Set up input options for a specific project\nswitch project_name \n % Define new project name and parameters\n case 'MyProjectName' % Update with your project name\n HRVparams.Fs = NaN; % Spacify sampling frequency\n HRVparams.readdata = ''; % (Optional) Specify name for data input folder\n HRVparams.writedata = ''; % (Optional) Specify name for data output folder\n HRVparams.datatype = ''; % (Optional) Spacify Data type of input\n HRVparams.ext = ''; % (Optional) Spacify file extension of input (e.g., 'mat','qrs')\n \n % Existing demo projects\n case 'MVanalysis' % Morphological variability analysis ECG\n HRVparams.Fs = 1000; \n HRVparams.readdata = ''; \n HRVparams.writedata = ''; \n HRVparams.datatype = ''; \n HRVparams.ext = ''; \n case 'demo_NSR' % Parameters for demo using MIT nsr data\n HRVparams.readdata = strcat('TestData', filesep, 'Physionet_nsr2db');\n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsNSR');\n HRVparams.ext = 'ecg';\n HRVparams.Fs = 125;\n case 'demo_RRgen' \n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsRRgen');\n HRVparams.Fs = 125;\n HRVparams.demo.length = 5*60*60; % Length of demo RR intervals in seconds\n HRVparams.demo.pe = 0.0003; % Probability of ectopy ~ 1 per hr \n HRVparams.demo.pn = 0.0048; % Probability of noise ~ 16 per hr \n HRVparams.demo.seed = 1; % Seed for RRGEN\n case 'demoICU' % Parameters for ICU demo \n HRVparams.readdata = strcat('TestData');\n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsICU');\n HRVparams.ext = 'mat';\n HRVparams.Fs = 128;\n case 'demoAF' % Parameters for AF demo \n HRVparams.readdata = strcat('TestData');\n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsAFData');\n HRVparams.ext = 'mat';\n HRVparams.Fs = 128;\n case 'demoHRT' % Parameters for HRT demo \n HRVparams.readdata = strcat('TestData', filesep, 'Physionet_nsr2db');\n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsHRT');\n HRVparams.Fs = 128;\n case 'demoPVC' % Parameters for PVC demo \n HRVparams.readdata = strcat('TestData', filesep, 'mitdb-Arrhythmia');\n HRVparams.writedata = strcat('OutputData', filesep, 'ResultsPVC');\n HRVparams.Fs = 360;\n otherwise % Default\n HRVparams.Fs = NaN; % Spacify sampling frequency\n HRVparams.writedata = 'HRV_Output'; % (Optional) Specify name for data output folder\n \nend\n\nif isempty(HRVparams.writedata) \n % Default data OUTPUT folder name based on project name\n HRVparams.writedata = strcat(project_name,'_Results'); \n fprintf('New OUTPUT folder: \"%s\"\\n', HRVparams.writedata)\n mkdir(HRVparams.writedata); % Create output folder and \nelseif ~exist([pwd filesep HRVparams.writedata], 'dir')\n fprintf('New OUTPUT folder: \"%s\"\\n',HRVparams.writedata)\n mkdir(HRVparams.writedata); % Create output folder and \nend\naddpath(genpath(HRVparams.writedata)); % Add folder to search path\n\n%% 2. How much does the user trust the data:\n% This setting determines how stringently filtered the data is prior to\n% calculating HRV metrics. Raw ECG or Pulse data that has been labeled\n% using a peak detector (like jqrs) would require the most stringent\n% filtering, whereas RR interval data that has been reviewed by a human\n% technician would require the least amount of filtering. \n\n% - qrs detection no beats labeled - most stringent filters\n% - automatic beat detection beat typed - moderately stringent filtered\n% - hand corrected - least filtered, maybe no filter\n\n% EXPLAIN THE THRESHOLDS BETTER\n% ADD THIS TO A DEMO\n\nHRVparams.data_confidence_level = 1;\n% 1 - raw data with automatic beat detection\n% 2 - raw data with automatic beat detection, but beat typed (ie N, SV,etc)\n% 3 - technician reviewed data\n\n% * ^^^^ NOT YET IN USE ^^^^ *\n\n%% 3. Global Settings (Window Size)\n\nHRVparams.windowlength = 300;\t % Default: 300, seconds\nHRVparams.increment = 30; % Default: 30, seconds increment\nHRVparams.numsegs = 5; % Default: 5, number of segments to collect with lowest HR\nHRVparams.RejectionThreshold = .20; % Default: 0.2, amount (%) of data that can be rejected before a\n % window is considered too low quality for analysis\nHRVparams.MissingDataThreshold = .15; % Default: 0.15, maximum percentage of data allowable to be missing\n % from a window .15 = 15%\n%% 5. Debug Settings\n\nHRVparams.rawsig = 0; % Load raw signal if it is available for debugging\nHRVparams.debug = 0;\n\n%% 6. SQI Analysis Settings \nHRVparams.sqi.LowQualityThreshold = 0.9; % Default: 0.9, Threshold for which SQI represents good data\nHRVparams.sqi.windowlength = 10; % Default: 10, seconds, length of the comparison window\nHRVparams.sqi.increment = 1; % Default: 1, seconds\nHRVparams.sqi.TimeThreshold = 0.1; % Default: 0.1, seconds\nHRVparams.sqi.margin = 2; % Default: 2, seconds, Margin time not include in comparison \n\n\n%% 7. Preprocess Settings\n\nHRVparams.preprocess.figures = 0; % Figures on = 1, Figures off = 0\nHRVparams.preprocess.gaplimit = 2; % Default: 2, seconds; maximum believable gap in rr intervals\nHRVparams.preprocess.per_limit = 0.2; % Default: 0.2, Percent limit of change from one interval to the next\nHRVparams.preprocess.forward_gap = 3;\t % Default: 3, Maximum tolerable gap at beginning of timeseries in seconds\nHRVparams.preprocess.method_outliers = 'rem'; % Default: 'rem', Method of dealing with outliers\n % 'cub' = replace outlier points with cubic spline method\n % 'rem' = remove outlier points\n % 'pchip' = replace with pchip method\nHRVparams.preprocess.lowerphysiolim = 60/160; % Default: 60/160\nHRVparams.preprocess.upperphysiolim = 60/30; % Default: 60/30\nHRVparams.preprocess.method_unphysio = 'rem'; % Default: 'rem', Method of dealing with unphysiologically low beats\n % 'cub' = replace outlier points with cubic spline method\n % 'rem' = remove outlier points\n % 'pchip' = replace with pchip method\n\n% The following settings do not yet have any functional effect on \n% the output of preprocess.m: \nHRVparams.preprocess.threshold1 = 0.9 ;\t % Default: 0.9, Threshold for which SQI represents good data\nHRVparams.preprocess.minlength = 30; % Default: 30, The minimum length of a good data segment in seconds\n \n%% 8. AF Detection Settings and PVC detection\n\nHRVparams.af.on = 1; % Default: 1, AF Detection On or Off\nHRVparams.af.windowlength = 30; % Default: 30, Set to include ~30 beats in each window\nHRVparams.af.increment = 30; % Default: 30, No overlap necessary in AF feat calc\n\nHRVparams.PVC.qrsth = 0.1; % Default: 0.1, threshold for qrs detection\n\n%% 9. Time Domain Analysis Settings\n\nHRVparams.timedomain.on = 1; % Default: 1, Time Domain Analysis 1=On or 0=Off\nHRVparams.timedomain.dataoutput = 0; % 1 = Print results to .txt file\n % Anything else = utputs to return variables only\n % returned variables\nHRVparams.timedomain.alpha = 50 ; % Default: 50 ,In msec\nHRVparams.timedomain.win_tol = .15; % Default: .15, Maximum percentage of data allowable \n % to be missing from a window\n\n%% 10. Frequency Domain Analysis Settings\n\nHRVparams.freq.on = 1; % Default: 1, Frequency Domain Analysis 1=On or 0=Off\n\nULF = [0 .0033]; % Requires window > 300 s\nVLF = [0.0033 .04]; % Requires at least 300 s window\nLF = [.04 .15]; % Requires at least 25 s window\nHF = [0.15 0.4]; % Requires at least 7 s window\n\nHRVparams.freq.limits = [ULF; VLF; LF; HF];\nHRVparams.freq.zero_mean = 1; % Default: 1, Option for subtracting the mean from the input data\nHRVparams.freq.method = 'lomb'; % Default: 'lomb' \n % Options: 'lomb', 'burg', 'fft', 'welch' \nHRVparams.freq.plot_on = 0;\n\n% The following settings are for debugging spectral analysis methods\nHRVparams.freq.debug_sine = 0; % Default: 0, Adds sine wave to tachogram for debugging\nHRVparams.freq.debug_freq = 0.15; % Default: 0.15\nHRVparams.freq.debug_weight = .03; % Default: 0.03\n\n% Lomb:\nHRVparams.freq.normalize_lomb = 0;\t % Default: 0\n % 1 = Normalizes Lomb Periodogram, \n % 0 = Doesn't normalize \n\n% Burg: (not recommended)\nHRVparams.freq.burg_poles = 15; % Default: 15, Number of coefficients \n % for spectral estimation using the Burg\n % method (not recommended)\n\n% The following settings are only used when the user specifies spectral\n% estimation methods that use resampling : 'welch','fft', 'burg'\nHRVparams.freq.resampling_freq = 7; % Default: 7, Hz \nHRVparams.freq.resample_interp_method = 'cub'; % Default: 'cub'\n % 'cub' = cublic spline method\n % 'lin' = linear spline method\nHRVparams.freq.resampled_burg_poles = 100; % Default: 100\n\n%% 11. SDANN and SDNNI Analysis Settings\nHRVparams.sd.on = 1; % Default: 1, SD analysis 1=On or 0=Off\nHRVparams.sd.segmentlength = 300; % Default: 300, windows length in seconds\n\n%% 12. PRSA Analysis Settings\n\nHRVparams.prsa.on = 1; % Default: 1, PRSA Analysis 1=On or 0=Off\nHRVparams.prsa.win_length = 30; % Default: 30, The length of the PRSA signal \n % before and after the anchor points\n % (the resulting PRSA has length 2*L)\nHRVparams.prsa.thresh_per = 20; % Default: 20%, Percent difference that one beat can \n % differ from the next in the prsa code\nHRVparams.prsa.plot_results = 0; % Default: 0 \nHRVparams.prsa.scale = 2; % Default: 2, scale parameter for wavelet analysis (to compute AC and DC)\nHRVparams.prsa.min_anch = 20; % Default: 20, minimum number of anchors point required to create the \"average signal\"\n\n%% 13. Peak Detection Settings\n\n% The following settings are for jqrs.m\n\nHRVparams.PeakDetect.REF_PERIOD = 0.250; % Default: 0.25 (should be 0.15 for FECG), refractory period in sec between two R-peaks\nHRVparams.PeakDetect.THRES = .6; % Default: 0.6, Energy threshold of the detector \nHRVparams.PeakDetect.fid_vec = []; % Default: [], If some subsegments should not be used for finding the optimal \n % threshold of the P&T then input the indices of the corresponding points here\nHRVparams.PeakDetect.SIGN_FORCE = []; % Default: [], Force sign of peaks (positive value/negative value)\nHRVparams.PeakDetect.debug = 0; % Default: 0\nHRVparams.PeakDetect.ecgType = 'MECG'; % Default : MECG, options (adult MECG) or featl ECG (fECG) \nHRVparams.PeakDetect.windows = 15; % Befautl: 15,(in seconds) size of the window onto which to perform QRS detection\n\n\n%% 14. Entropy Settings\n% Multiscale Entropy\nHRVparams.MSE.on = 1; % Default: 1, MSE Analysis 1=On or 0=Off\nHRVparams.MSE.windowlength = []; % Default: [], windows size in hours, default perform MSE on the entire signal\nHRVparams.MSE.increment = []; % Default: [], window increment in hours\nHRVparams.MSE.RadiusOfSimilarity = 0.15; % Default: 0.15, Radius of similarity (% of std)\nHRVparams.MSE.patternLength = 2; % Default: 2, pattern length\nHRVparams.MSE.maxCoarseGrainings = 20; % Default: 20, Maximum number of coarse-grainings\nHRVparams.MSE.method = 'fir'; % Default 'fir', method use to generate the coarse-grain \n % time series options 'fir', 'butter' \nHRVparams.MSE.moment = 'mean'; % Default: 'mean', moment used to coarse-grain the time series\n % options 'mean', 'variance'\nHRVparams.MSE.constant_r = 1; % Default: 1, 1 use r as function of std of original time \n % series, 0 compute r as function of std at each scale \n \n \n% SampEn an ApEn \nHRVparams.Entropy.on = 1; % Default: 1, MSE Analysis 1=On or 0=Off\nHRVparams.Entropy.RadiusOfSimilarity = 0.15; % Default: 0.15, Radius of similarity (% of std)\nHRVparams.Entropy.patternLength = 2; % Default: 2, pattern length\n\n%% 15. DFA Settings\n\nHRVparams.DFA.on = 1; % Default: 1, DFA Analysis 1=On or 0=Off\nHRVparams.DFA.windowlength = []; % Default [], windows size in hours, default perform DFA on the entair signal\nHRVparams.DFA.increment = []; % Default: [], window increment in hours\nHRVparams.DFA.minBoxSize = 4 ; % Default: 4, Smallest box width\nHRVparams.DFA.maxBoxSize = []; % Largest box width (default in DFA code: signal length/4) \nHRVparams.DFA.midBoxSize = 16; % Medium time scale box width (default in DFA code: 16)\n\n%% 16. Poincar� plot\n\nHRVparams.poincare.on = 1; % Default: 1, Poincare Analysis 1=On or 0=Off\n\n%% 17. Heart Rate Turbulence (HRT) - Settings\n\nHRVparams.HRT.on = 1; % Default: 1, HRT Analysis 1=On or 0=Off\nHRVparams.HRT.BeatsBefore = 2; % Default: 2, # of beats before PVC \nHRVparams.HRT.BeatsAfter = 16; % Default: 16, # of beats after PVC and CP\nHRVparams.HRT.GraphOn = 0; % Default: 0, do not plot \nHRVparams.HRT.windowlength = 24; % Default 24h, windows size in hours\nHRVparams.HRT.increment = 24; % Default 24h, sliding window increment in hours\nHRVparams.HRT.filterMethod = 'mean5before'; % Default mean5before, HRT filtering option\n\n\n%% 18. Output Settings\n\nHRVparams.gen_figs = 0; % Generate figures\nHRVparams.save_figs = 0; % Save generated figures\nif HRVparams.save_figs == 1\n HRVparams.gen_figs = 1;\nend\n\n% Format settings for HRV Outputs\nHRVparams.output.format = 'csv'; % 'csv' - creates csv file for output\n % 'mat' - creates .mat file for output\nHRVparams.output.separate = 1; % Default : 1 = separate files for each subject\n % 0 = all results in one file\nHRVparams.output.num_win = []; % Specify number of lowest hr windows returned\n % leave blank if all windows should be returned\n % Format settings for annotations generated\nHRVparams.output.ann_format = 'binary'; % 'binary' = binary annotation file generated\n % 'csv' = ASCII CSV file generated\n \n%% 19. Filename to Save Data\nHRVparams.time = datestr(now, 'yyyymmdd'); % Setup time for filename of output\nHRVparams.filename = [HRVparams.time '_' project_name];\n\n\n%% Export Parameter as Latex Table\n% Note that if you change the order of the parameters or add parameters \n% this might not work\n\nExportHRVparams(HRVparams);\n\n\n\nend", "meta": {"author": "cliffordlab", "repo": "PhysioNet-Cardiovascular-Signal-Toolbox", "sha": "eec46e75e0b95c379ecb68cb0ebee0c4c9f54605", "save_path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox", "path": "github-repos/MATLAB/cliffordlab-PhysioNet-Cardiovascular-Signal-Toolbox/PhysioNet-Cardiovascular-Signal-Toolbox-eec46e75e0b95c379ecb68cb0ebee0c4c9f54605/InitializeHRVparams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.046724954145958314, "lm_q1q2_score": 0.017812467409823472}} {"text": "%DstarPO D*-PO navigation class\n%\n% A concrete subclass of the Navigation class that implements the D*\n% navigation algorithm; facilitates incremental replanning. This\n% implementation of D* is intended for multiobjective optimization (MOO)\n% problems - i.e. optimizes over several objectives/criteria - with the use\n% of Pareto fronts (see Lavin paper).\n%\n% Methods::\n% plan Compute the cost map given a goal and map\n% path Compute a path to the goal\n% visualize Display the obstacle map (deprecated)\n% plot Display the obstacle map\n% cost_get Return the specified cost layer\n% costmap_modify Modify the costmap\n% modify_cost Modify the costmap (deprecated, use costmap_modify)\n% costmap_get Return the current costmap\n% costmap_set Set the current costmap\n% distancemap_get Set the current distance map\n% display Print the parameters in human readable form\n% char Convert to string\n%\n% Properties::\n% TBD\n%\n% Example::\n% load map1 % load map\n% goal = [50,30];\n% start=[20,10];\n% ds = DstarPO(map); % create navigation object\n% ds.plan(goal,1) % create plan for specified goal\n% ds.path(start) % animate path from this start location\n% Example 2:\n% goal = [100;100];\n% start = [1;1];\n% ds = DstarPO(0); % create Navigation object with random occupancy grid\n% ds.addCost(1,L); % add 1st add'l cost layer L\n% ds.plan(goal,2); % setup costmap for specified goal\n% ds.path(start); % plan solution path start-goal, animate\n% P = as.path(start); % plan solution path start-goal, return path\n%\n% Notes::\n% - Obstacles are represented by Inf in the costmap.\n%\n% References::\n% - The D* algorithm for real-time planning of optimal traverses,\n% A. Stentz, Tech. Rep. CMU-RI-TR-94-37, The Robotics Institute,\n% Carnegie-Mellon University, 1994.\n% - A Pareto Optimal D* Search Algorithm for Multiobjective Path Planning,\n% A. Lavin.\n% - Robotics, Vision & Control, Sec 5.2.2,\n% Peter Corke, Springer, 2011.\n%\n% Author::\n% Alexander Lavin based on Dstar by Peter Corke\n%\n% See also Navigation, Dstar, DstarMOO, Astar, DXform.\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke, Alexander Lavin\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n%\n% This is an original algorithm written by Alexander Lavin.\n% http://alexanderlavin.com\n\n\n% Implementation notes:\n%\n% All the state is kept in the structure called d\n% X is an index into the array of states.\n% state pointers are kept as matlab array index rather than row,col format\n\nclassdef DstarPO < Navigation\n\n properties (SetAccess=private, GetAccess=private)\n\n costmap % world cost map: obstacle = Inf\n G % index of goal point\n N % number of objectives\n\n % info kept per cell (state)\n b % backpointer (0 means not set)\n t % tag: NEW OPEN CLOSED\n \n cost_g % path distance summation\n cost_h % path heuristic (state to goal) cost\n cost_01 % add'l cost layer 01 (unused)\n cost_02 % add'l cost layer 02 (unused)\n cost_03 % add'l cost layer 03 (unused)\n % add more cost layers if needed...\n\n priority\n tie\n \n % list of open states: 2xN matrix\n % each open point is a column, row 1 = index of cell, row 2 = k\n openlist\n niter\n\n changed\n\n openlist_maxlen % keep track of maximum length\n quiet\n\n % tag state values\n NEW = 0;\n OPEN = 1;\n CLOSED = 2;\n end\n\n methods\n\n % constructor\n function ds = DstarPO(world, varargin)\n %DstarPO.DstarPO D*-PO constructor\n %\n % DS = Dstar(MAP, OPTIONS) is a D* navigation object, and MAP is an\n % occupancy grid, a representation of a planar world as a\n % matrix whose elements are 0 (free space) or 1 (occupied).\n % The occupancy grid is coverted to a costmap with a unit cost\n % for traversing a cell.\n %\n % Options::\n % 'goal',G Specify the goal point (2x1)\n % 'metric',M Specify the distance metric as 'euclidean' (default)\n % or 'cityblock'.\n % 'inflate',K Inflate all obstacles by K cells.\n % 'quiet' Don't display the progress spinner\n %\n % Other options are supported by the Navigation superclass.\n %\n % Notes::\n % - If MAP == 0 a random map is created.\n %\n % See also Navigation.Navigation.\n\n % invoke the superclass constructor\n ds = ds@Navigation(world, varargin{:});\n\n opt.quiet = false;\n opt = tb_optparse(opt, varargin);\n ds.quiet = opt.quiet;\n\n ds.occgrid2costmap(ds.occgrid);\n\n\n % init the D* state variables\n ds.reset();\n if ~isempty(ds.goal)\n ds.goal_change();\n end\n ds.changed = false;\n end\n\n function reset(ds)\n %DstarPO.reset Reset the planner\n %\n % DS.reset() resets the D* planner. The next instantiation\n % of DS.plan() will perform a global replan.\n\n % build the matrices required to hold the state of each cell for D*\n ds.b = zeros(size(ds.costmap), 'uint32'); % backpointers\n ds.t = zeros(size(ds.costmap), 'uint8'); % tags\n ds.cost_g = Inf*ones(size(ds.costmap)); % path cost estimate\n ds.openlist = zeros(2,0); % the open list, one column per point\n \n ds.openlist_maxlen = -Inf;\n end\n\n function goal_change(ds)\n\n if isempty(ds.b)\n return;\n end\n goal = ds.goal;\n\n % keep goal in index rather than row,col format\n ds.G = sub2ind(size(ds.occgrid), goal(2), goal(1));\n ds.INSERT(ds.G, ds.projectCost(ds.G), 'goalset');\n ds.cost_g(ds.G) = 0;\n \n % new goal changes cost layers:\n ds.calcHeuristic(ds.occgrid, ds.goal);\n end\n\n function s = char(ds)\n %DstarPO.char Convert navigation object to string\n %\n % DS.char() is a string representing the state of the Dstar\n % object in human-readable form.\n %\n % See also Dstar.display, Navigation.char.\n \n % most of the work is done by the superclass\n s = char@Navigation(ds);\n\n % Dstar specific stuff\n if ~isempty(ds.costmap)\n s = char(s, sprintf(' costmap: %dx%d, open list %d', size(ds.costmap), numcols(ds.openlist)));\n else\n s = char(s, sprintf(' costmap: empty:'));\n end\n end\n\n function plot(ds, varargin)\n %DstarPO.plot Visualize navigation environment\n %\n % DS.plot() displays the occupancy grid and the goal distance\n % in a new figure. The goal distance is shown by intensity which\n % increases with distance from the goal. Obstacles are overlaid\n % and shown in red.\n %\n % DS.plot(P) as above but also overlays a path given by the set\n % of points P (Mx2).\n %\n % See also Navigation.plot.\n \n plot@Navigation(ds, 'distance', ds.cost_h, varargin{:});\n end\n\n % invoked by Navigation.step\n function n = next(ds, current)\n\n if ds.changed\n error('Cost map has changed, replan');\n end\n X = sub2ind(size(ds.costmap), current(2), current(1));\n X = ds.b(X);\n if X == 0\n n = [];\n else\n [r,c] = ind2sub(size(ds.costmap), X);\n n = [c;r];\n end\n end\n\n function plan(ds, goal, N)\n %DstarPO.plan Plan path to goal\n %\n % DS.plan() updates DS with a costmap of distance to the\n % goal from every non-obstacle point in the map. The goal is\n % as specified to the constructor.\n %\n % DS.plan(GOAL) as above but uses the specified goal.\n %\n % Note::\n % - If a path has already been planned, but the costmap was\n % modified, then reinvoking this method will replan,\n % incrementally updating the plan at lower cost than a full\n % replan.\n %\n % Inputs:\n % goal: goal state coordinates\n % N: number of optimization objectives; standard D* is 2\n % (i.e. distance and heuristic)\n \n ds.N = N; % number of optimization objectives\n ds.openlist = zeros(ds.N+1,0);\n \n % Setup cost layers. If a\n % cost layer is goal-dependent, it's setup function needs to\n % also be called in DS.goal_change(). If more cost layers are\n % needed, add similar to DS.cost_01.\n \n % initializations first:\n ds.cost_g = zeros(size(ds.occgrid));\n ds.cost_h = zeros(size(ds.occgrid)); % filled after setting goal below\n % if add'l costs haven't been added with addCost()\n if isempty(ds.cost_01)\n ds.cost_01 = zeros(size(ds.occgrid));\n end\n if isempty(ds.cost_02)\n ds.cost_02 = zeros(size(ds.occgrid));\n end\n if isempty(ds.cost_03)\n ds.cost_03 = zeros(size(ds.occgrid));\n end\n \n if nargin > 1\n ds.goal = goal; % invokes superclass method set.goal()\n end\n % for replanning no goal is needed, \n if isempty(ds.goal)\n error('must specify a goal point');\n end\n\n % Setup cost layers DS.cost_g and DS.cost_h.\n % assign values to the distance cost layer, set as DS.costmap\n ds.occgrid2costmap(ds.occgrid);\n % assign values to the heuristic cost layer, set as DS.cost_h\n ds.calcHeuristic(ds.occgrid, ds.goal);\n % Additional cost layers are added by the user with the\n % DS.addCost() method\n \n % Cost priority/tiebreaker: cost_g (distance to node)\n ds.priority = ds.cost_g;\n ds.tie = 1; % first cost: cost_g\n \n ds.niter = 0;\n while true\n if ~ds.quiet && mod(ds.niter, 20) == 0\n ds.spinner();\n end\n ds.niter = ds.niter + 1;\n\n if ds.PROCESS_STATE() < 0\n break;\n end\n if ds.verbose\n disp(' ')\n end\n end\n if ~ds.quiet\n fprintf('\\r');\n end\n ds.changed = false;\n end\n \n function layer = cost_get(ds)\n %DstarPO.cost_get Get the specified cost layer\n layer = ds.cost_02;\n end\n\n function c = distancemap_get(ds)\n %DstarPO.distancemap_get Get the current distance map\n %\n % C = DS.distancemap_get() is the current distance map. This map is the same size\n % as the occupancy grid and the value of each element is the shortest distance \n % from the corresponding point in the map to the current goal. It is computed\n % by Dstar.plan.\n %\n % See also Dstar.plan.\n c = ds.cost_h; % heuristic\n end\n\n function c = costmap_get(ds)\n %DstarPO.costmap_get Get the current costmap\n %\n % C = DS.costmap_get() is the current costmap. The cost map is the same size\n % as the occupancy grid and the value of each element represents the cost\n % of traversing the cell. It is autogenerated by the class constructor from\n % the occupancy grid such that:\n % - free cell (occupancy 0) has a cost of 1\n % - occupied cell (occupancy >0) has a cost of Inf\n %\n % See also Dstar.costmap_set, Dstar.costmap_modify.\n\n c = ds.costmap;\n end\n\n function costmap_set(ds, costmap)\n %DstarPO.costmap_set Set the current costmap\n %\n % DS.costmap_set(C) sets the current costmap. The cost map is the same size\n % as the occupancy grid and the value of each element represents the cost\n % of traversing the cell. A high value indicates that the cell is more costly\n % (difficult) to traverese. A value of Inf indicates an obstacle.\n %\n % Notes::\n % - After the cost map is changed the path should be replanned by \n % calling DS.plan(). \n %\n % See also Dstar.costmap_get, Dstar.costmap_modify.\n if ~all(size(costmap) == size(ds.occgrid))\n error('costmap must be same size as occupancy grid');\n end\n ds.costmap = costmap;\n ds.changed = true;\n end\n\n function costmap_modify(ds, point, newcost)\n %DstarPO.costmap_modify Modify cost map\n %\n % DS.costmap_modify(P, NEW) modifies the cost map at P=[X,Y] to\n % have the value NEW. If P (2xM) and NEW (1xM) then the cost of\n % the points defined by the columns of P are set to the corresponding\n % elements of NEW.\n %\n % Notes::\n % - After one or more point costs have been updated the path\n % should be replanned by calling DS.plan(). \n % - Replaces modify_cost, same syntax.\n %\n % See also Dstar.costmap_set, Dstar.costmap_get.\n\n if numel(point) == 2\n % for case of single point ensure it is a column vector\n point = point(:);\n end\n if numcols(point) ~= numcols(newcost)\n error('number of columns in point must match columns in newcost');\n end\n for i=1:numcols(point)\n X = sub2ind(size(ds.costmap), point(2,i), point(1,i));\n ds.costmap(X) = newcost(i);\n end\n if ds.t(X) == ds.CLOSED\n ds.INSERT(X, ds.h(X), 'modifycost');\n end\n ds.changed = true;\n end\n \n function addCost(ds, layer, values)\n %DstarPO.addCost Add an additional cost layer\n %\n % DS.addCost(layer,values) adds the matrix specified by values as a\n % cost layer.\n % Inputs\n % layer: 1, 2, or 3 to specify which cost layer to add\n % values: normalized matrix the size of the environment (100x100)\n if size(values)~=size(ds.occgrid)\n display('Layer size does not match the environment')\n return\n end\n if max(max(values))~=1 || min(min(values))~=0\n display('Layer values are not normalized [0:1]')\n return\n end\n \n if layer==1\n ds.cost_01 = values;\n elseif layer==2\n ds.cost_02 = values;\n elseif layer==3\n ds.cost_03 = values;\n else\n display('Layer index out of range')\n end\n end\n \n end % public methods\n\n methods (Access=protected)\n\n function occgrid2costmap(ds, og, cost)\n if nargin < 3\n cost = 1;\n end\n ds.costmap = og;\n ds.costmap(ds.costmap==1) = Inf; % occupied cells have Inf driving cost\n ds.costmap(ds.costmap==0) = cost; % unoccupied cells have driving cost\n end\n\n function calcHeuristic(ds, grid, goal)\n ds.cost_h=zeros(size(grid));\n for ii=1:size(grid,1)\n for jj=1:size(grid,2)\n ds.cost_h(ii,jj)=sqrt((ii-goal(1))^2+(jj-goal(2))^2);\n end\n end\n end\n \n % The main D* function as per the Stentz paper, comments Ln are the original\n % line numbers.\n function r = PROCESS_STATE(d)\n % States with the lowest cost value are removed from the\n % open list\n\n % Get Pareto optimal point off the open list\n [idx] = paretofront(normc(d.openlist(2:size(d.openlist,1),:)')); % w/ normalization\n front = d.openlist(:,idx);\n [k_old,col] = min(front(d.tie+1,:)); % d.tie specifies the row (cost_g) for tiebreaker\n X = front(1,col); % L1\n\n if isempty(X) % L2\n r = -1;\n return;\n end\n\n d.DELETE(X); % L3\n \n d.priority = d.cost_g; % updates priority cost layer\n\n if k_old < d.priority(X) % L4\n d.message('k_old < h(X): %f %f\\n', k_old, d.priority(X));\n for Y=d.neighbours(X) % L5\n if (d.priority(Y) <= k_old) && (d.priority(X) > d.updateCosts(Y,X,0)) % L6\n d.b(X) = Y;\n d.updateCosts(X,Y,d.N); %L7\n end\n end\n end\n\n % can we lower the path cost of any neighbours?\n if k_old == d.priority(X) % L8\n d.message('k_old == h(X): %f\\n', k_old);\n for Y=d.neighbours(X) % L9\n if (d.t(Y) == d.NEW) || ... % L10-12\n ( (d.b(Y) == X) && (d.priority(Y) ~= d.updateCosts(Y,X,0)) ) || ...\n ( (d.b(Y) ~= X) && (d.priority(Y) > d.updateCosts(Y,X,0)) )\n % Update and project the costs:\n d.updateCosts(Y,X,d.N);\n objspace = d.projectCost(Y,X);\n d.b(Y) = X;\n d.INSERT(Y, objspace, 'L13'); % L13\n end\n end\n else % L14\n d.message('k_old > h(X)');\n for Y=d.neighbours(X) % L15\n if (d.t(Y) == d.NEW) || ( (d.b(Y) == X) && (d.priority(Y) ~= d.updateCosts(Y,X,0)) )\n d.updateCosts(Y,X,d.N);\n objspace = d.projectCost(Y,X);\n d.b(Y) = X;\n d.INSERT(Y, objspace, 'L18'); % L18\n else\n if ( (d.b(Y) ~= X) && (d.priority(Y) > d.updateCosts(Y,X,0)) )\n d.INSERT(X, d.projectCost(X), 'L21'); % L21\n else\n if (d.b(Y) ~= X) && (d.priority(X) > d.updateCosts(Y,X,0)) && ...\n (d.t(Y) == d.CLOSED) && d.priority(Y) > k_old\n d.INSERT(Y, d.projectCost(Y), 'L25'); % L25\n end\n end\n end\n end\n end\n \n r = 0;\n return;\n end % process_state\n \n function k_new = updateCosts(ds, a, b, obj)\n % NOTE: Only for costs that accumulate (i.e. sum) over the\n % path, and for dynamic costs.\n % E.g. the heuristic parameter DS.cost_h only needs updating\n % when the goal state changes; it's values are stored for each\n % cell.\n %\n % Location moving from state b to a.\n if nargout > 0\n k_new = ds.cost_g(b) + ds.dc(b,a);\n return\n end\n if obj == 0 % just return what the new priority cost would be (k_new)\n return\n end\n if obj > 1 % base case\n ds.cost_g(a) = ds.cost_g(b) + ds.dc(b,a);\n % (no heuristic update needed)\n end\n if obj > 2 % w/ cost_01: elevation\n % (no elevation update needed)\n end\n if obj > 3 % w/ cost_02: solar\n sV = [cos(ds.niter/100);sin(ds.niter/100)]; % rotates 1rad per 100 steps\n ds.cost_02(a) = dot(sV,ds.vc(b,a));\n end\n if obj > 4 % w/ cost_03: risk\n % (no risk update needed)\n end\n end\n \n function pt = projectCost(ds, a, b)\n % Returns the projection of state a into objective space. If\n % specified, location is moving from b to a.\n switch nargin\n case 2\n pt = [ds.cost_g(a);\n ds.cost_h(a);\n ds.cost_01(a);\n ds.cost_02(a);\n ds.cost_03(a);\n ];\n case 3\n pt = [ds.cost_g(b) + ds.dc(a,b);\n ds.cost_h(a);\n ds.cost_01(a);\n ds.cost_02(a);\n ds.cost_03(a);\n ];\n otherwise\n return\n end\n end\n\n function kk = k(ds, X)\n i = ds.openlist(1,:) == X;\n kk = ds.openlist(2, i);\n end\n\n function INSERT(ds, X, pt, where)\n % Add state X to the openlist with objective space values\n % specified by pt.\n \n % where is for diagnostic purposes only\n ds.message('insert (%s) %d = %f\\n', where, X, pt);\n\n i = find(ds.openlist(1,:) == X);\n if length(i) > 1\n error('D*:INSERT: state in open list %d times', X);\n end\n\n if ds.t(X) == ds.NEW\n % add a new column to the open list\n ds.openlist = [ds.openlist [X; pt]];\n elseif ds.t(X) == ds.OPEN\n% k_new = min( ds.openlist(2,i), h_new );\n elseif ds.t(X) == ds.CLOSED\n if pt(ds.tie) < ds.priority(X) % break tie w/ ds.tie index\n % add a new column to the open list\n ds.openlist = [ds.openlist [X; pt]];\n end\n end\n\n % keep track of the max length of the openlist:\n if numcols(ds.openlist) > ds.openlist_maxlen\n ds.openlist_maxlen = numcols(ds.openlist);\n end\n\n ds.t(X) = ds.OPEN;\n end\n\n function DELETE(ds, X)\n ds.message('delete %d\\n', X);\n i = find(ds.openlist(1,:) == X);\n if length(i) ~= 1\n error('D*:DELETE: state %d doesnt exist', X);\n end\n ds.openlist(:,i) = []; % remove the column\n ds.t(X) = ds.CLOSED;\n end\n\n function kmin = GET_KMIN(ds)\n kmin = min(ds.openlist(2,:));\n end\n\n % return the distance of moving from state X to state Y\n function cost = dc(ds, X, Y)\n [r,c] = ind2sub(size(ds.costmap), [X; Y]);\n dist = sqrt(sum(diff([r c]).^2));\n dcost = (ds.costmap(X) + ds.costmap(Y))/2;\n\n cost = dist * dcost;\n end\n \n % return the robot unit vector; direction of moving from state X to state Y\n function vector = vc(ds, X, Y)\n [Xi,Xj] = ind2sub(size(ds.occgrid),X);\n [Yi,Yj] = ind2sub(size(ds.occgrid),Y);\n vector = [Yi-Xi;Yj-Xj];\n vector = vector/norm(vector);\n% slope = vector(2) / vector(1);\n% theta = dot([0,1],[vector])/(norm([0,1])*norm(vector)); \n end\n\n % return index of neighbour states as a row vector\n function Y = neighbours(ds, X)\n dims = size(ds.costmap);\n [r,c] = ind2sub(dims, X);\n\n % list of 8-way neighbours\n Y = [r-1 r-1 r-1 r r r+1 r+1 r+1; c-1 c c+1 c-1 c+1 c-1 c c+1];\n % only use neighbors w/in grid bounds...\n k = (min(Y)>0) & (Y(1,:)<=dims(1)) & (Y(2,:)<=dims(2));\n Y = Y(:,k);\n Y = sub2ind(dims, Y(1,:)', Y(2,:)')';\n end\n\n end % end of protected methods\nend % classdef\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/DstarPO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.037892428259344024, "lm_q1q2_score": 0.01776361518808787}} {"text": "function varargout = particleinB_E_gui(varargin)\n% PARTICLEINB_E_GUI M-file for particleinB_E_gui.fig\n% PARTICLEINB_E_GUI, by itself, creates a new PARTICLEINB_E_GUI or raises the existing\n% singleton*.\n%\n% H = PARTICLEINB_E_GUI returns the handle to a new PARTICLEINB_E_GUI or the handle to\n% the existing singleton*.\n%\n% PARTICLEINB_E_GUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in PARTICLEINB_E_GUI.M with the given input arguments.\n%\n% PARTICLEINB_E_GUI('Property','Value',...) creates a new PARTICLEINB_E_GUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before particleinB_E_gui_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to particleinB_E_gui_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help particleinB_E_gui\n\n% Last Modified by GUIDE v2.5 17-Jun-2011 05:04:25\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @particleinB_E_gui_OpeningFcn, ...\n 'gui_OutputFcn', @particleinB_E_gui_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before particleinB_E_gui is made visible.\nfunction particleinB_E_gui_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to particleinB_E_gui (see VARARGIN)\n\n% Choose default command line output for particleinB_E_gui\nhandles.output = hObject;\n\n%close all;\n%clear all;\nclc;\n\nset(handles.vx,'Value',0);\nset(handles.vy,'Value',0);\nset(handles.vz,'Value',0);\n\nset(handles.x,'Value',-10);\nset(handles.y,'Value',0);\nset(handles.z,'Value',0);\n\nset(handles.Bx,'Value',0);\nset(handles.By,'Value',-6);\nset(handles.Bz,'Value',0);\nset(handles.Ex,'Value',0)\nset(handles.Ey,'Value',0)\nset(handles.Ez,'Value',2)\n\nset(handles.q,'Value',1);\nset(handles.m,'Value',5);\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes particleinB_E_gui wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = particleinB_E_gui_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in start.\nfunction start_Callback(hObject, eventdata, handles)\n% hObject handle to start (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.stop,'String','Stop!!');\nguidata(hObject, handles);\n\nv0 = [get(handles.vx,'Value'), get(handles.vy,'Value'), get(handles.vz,'Value') ]'; %initial velocity\nB = [get(handles.Bx,'Value'), get(handles.By,'Value'), get(handles.Bz,'Value') ]'; %magnitude of B\nE = [get(handles.Ex,'Value'), get(handles.Ey,'Value'), get(handles.Ez,'Value') ]'; %magnitude of B\nm = get(handles.m,'Value'); % mass\nq = get(handles.q,'Value'); % charge on particle\nr0 = [get(handles.x,'Value'), get(handles.y,'Value'), get(handles.z,'Value') ]'; % initial position of particle\ntspan = [0 70];\n\n%to show B's direction\n[x_q,y_q] = meshgrid(-15:12:15,-15:12:15);\nz_q=10*ones(size(x_q));\n\nu_q=B(1)*ones(size(x_q));\nv_q=B(2)*ones(size(x_q));\nw_q=B(3)*ones(size(x_q));\nquiver3(x_q,y_q,z_q,u_q,v_q,w_q);\nhold all;\n\n% TO show electric field lines\nz_q=-10*ones(size(x_q));\n\nu_q=E(1)*ones(size(x_q));\nv_q=E(2)*ones(size(x_q));\nw_q=E(3)*ones(size(x_q));\nquiver3(x_q,y_q,z_q,u_q,v_q,w_q);\n\nlegend('B','E');\n\n% To draw axis and all\na_a = -15:0.1:15;\nz_a = zeros(size(a_a));\nplot3(a_a,z_a,z_a,'k','LineWidth',2);\nplot3(z_a,a_a,z_a,'k','LineWidth',2);\nplot3(z_a,z_a,a_a,'k','LineWidth',2);\n\n% To set axis limits\n%xlim([-15 15]);\n%ylim([-15 15]);\n%zlim([-15 15])\n\nxlabel ('x axis');\nylabel ('y axis');\nzlabel ('z axis');\ntitle ('Particle in a magnetic field');\n\nrotate3d(handles.axes,'on');\n\nplot3(r0(1),r0(2),r0(3),'*m','MarkerSize',9,'LineWidth',2);\n\ny0 = [r0; v0];\nf = @(t,y) [y(4:6); (q/m)*cross(y(4:6),B)+E];\n[t,y] = ode23t(f,tspan,y0);\n\n%To show animation\nfor n=1:length(y)\n plot3(y(n,1),y(n,2),y(n,3),'--.r');\n pause(0.00001);\n \n z_z = get(handles.stop,'String');\n if z_z == 'Stoped'\n break;\n end\n\nend\n\nguidata(hObject, handles);\n\n% --- Executes on slider movement.\nfunction B_Callback(hObject, eventdata, handles)\n% hObject handle to B (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\n\n\n% --- Executes during object creation, after setting all properties.\nfunction B_CreateFcn(hObject, eventdata, handles)\n% hObject handle to B (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction m_Callback(hObject, eventdata, handles)\n% hObject handle to m (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.m,'Value');\nset(handles.m_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction m_CreateFcn(hObject, eventdata, handles)\n% hObject handle to m (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction q_Callback(hObject, eventdata, handles)\n% hObject handle to q (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.q,'Value');\nset(handles.q_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction q_CreateFcn(hObject, eventdata, handles)\n% hObject handle to q (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on button press in clear.\nfunction clear_Callback(hObject, eventdata, handles)\n% hObject handle to clear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ncla(handles.axes);\n\n% --- Executes on button press in stop.\nfunction stop_Callback(hObject, eventdata, handles)\n% hObject handle to stop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.stop,'String','Stoped');\nguidata(hObject, handles);\n\n% --- Executes on slider movement.\nfunction x_Callback(hObject, eventdata, handles)\n% hObject handle to x (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.x,'Value');\nset(handles.x_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction x_CreateFcn(hObject, eventdata, handles)\n% hObject handle to x (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction y_Callback(hObject, eventdata, handles)\n% hObject handle to y (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.y,'Value');\nset(handles.y_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction y_CreateFcn(hObject, eventdata, handles)\n% hObject handle to y (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction z_Callback(hObject, eventdata, handles)\n% hObject handle to z (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.z,'Value');\nset(handles.z_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction z_CreateFcn(hObject, eventdata, handles)\n% hObject handle to z (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction vx_Callback(hObject, eventdata, handles)\n% hObject handle to vx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.vx,'Value');\nset(handles.vx_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction vx_CreateFcn(hObject, eventdata, handles)\n% hObject handle to vx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction vy_Callback(hObject, eventdata, handles)\n% hObject handle to vy (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.vy,'Value');\nset(handles.vy_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction vy_CreateFcn(hObject, eventdata, handles)\n% hObject handle to vy (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction vz_Callback(hObject, eventdata, handles)\n% hObject handle to vz (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.vz,'Value');\nset(handles.vz_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction vz_CreateFcn(hObject, eventdata, handles)\n% hObject handle to vz (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction E_Callback(hObject, eventdata, handles)\n% hObject handle to E (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\n\n\n% --- Executes during object creation, after setting all properties.\nfunction E_CreateFcn(hObject, eventdata, handles)\n% hObject handle to E (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction Ex_Callback(hObject, eventdata, handles)\n% hObject handle to Ex (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.Ex,'Value');\nset(handles.Ex_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Ex_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Ex (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction Ey_Callback(hObject, eventdata, handles)\n% hObject handle to Ey (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.Ey,'Value');\nset(handles.Ey_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Ey_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Ey (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction Ez_Callback(hObject, eventdata, handles)\n% hObject handle to Ez (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.Ez,'Value');\nset(handles.Ez_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Ez_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Ez (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction Bx_Callback(hObject, eventdata, handles)\n% hObject handle to Bx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.Bx,'Value');\nset(handles.Bx_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Bx_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Bx (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction By_Callback(hObject, eventdata, handles)\n% hObject handle to By (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.By,'Value');\nset(handles.By_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction By_CreateFcn(hObject, eventdata, handles)\n% hObject handle to By (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n% --- Executes on slider movement.\nfunction Bz_Callback(hObject, eventdata, handles)\n% hObject handle to Bz (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get (handles.Bz,'Value');\nset(handles.Bz_text,'String',num2str(a));\nguidata(hObject, handles);\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction Bz_CreateFcn(hObject, eventdata, handles)\n% hObject handle to Bz (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/33317-particle-in-electric-and-magnetic-field/particle_in_E_B/particleinB_E_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04272219815590353, "lm_q1q2_score": 0.01772539070478522}} {"text": "function [indBoundary]=tesBoundary(varargin)\n\n% function [indBoundary]=tesBoundary(F)\n% ------------------------------------------------------------------------\n%\n% Change log: \n% 2009\n% 2019/04/24 Added varargin support since V can be skipped\n% 2019/04/24 Started working on cell (e.g. mixed mesh) support, not\n% completed yet \n% 2020/07/09 Added mixed mesh support, works for pentahedra, needs work for\n% general case\n% 2021/10/08 Simplified\n% 2021/10/08 No longer needs vertices as input\n% ------------------------------------------------------------------------\n\n%% Parse input\n\nswitch nargin\n case 1\n F=varargin{1};\n case 2\n F=varargin{1};\n warning('Second input (vertices) no longer required. Update code to avoid future error.');\nend\n\n%%\n\nif isa(F,'cell')\n indBoundary=cell(size(F));\n for q=1:1:numel(F)\n indBoundary{q}=getBoundary(F{q});\n end\nelse\n [indBoundary]=getBoundary(F);\nend\n\nend\n\n%%\n\nfunction [indBoundary]=getBoundary(F)\n\nFs=sort(F,2); %Sort so faces with same nodes have the same rows\n[~,~,~,F_count]=cunique(Fs,'rows'); %get indices for unique faces\nindBoundary=find(F_count==1);\n\n% Old method\n% Fbs=sort(F,2);\n% sizVirt=numPoints*ones(1,size(Fbs,2));\n% ind_F = sub2indn(sizVirt,Fbs);\n% [~,indUni1,~]=unique(Fbs,'rows'); %Get indices for unique faces\n% ind_F_uni=ind_F(indUni1,:);\n% ind=1:1:size(Fbs,1);\n% ind=ind(~ismember(ind,indUni1));\n% ind_Fb_cut=ind_F(ind,:);\n% L_uni=~ismember(ind_F_uni,ind_Fb_cut);\n% indBoundary=indUni1(L_uni,:);\nend\n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/tesBoundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.04146227345168354, "lm_q1q2_score": 0.017676262448561256}} {"text": "function value = mm_header_check ( id, type, rep, field, symm )\n\n%*****************************************************************************80\n%\n%% MM_HEADER_CHECK checks the header strings for a Matrix Market file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character ( len = 14 ) ID, the Matrix Market identifier.\n% This value must be '%%MatrixMarket'.\n%\n% Input, character ( len = 6 ) TYPE, the Matrix Market type.\n% This value must be 'matrix'.\n%\n% Input, character ( len = 10 ) REP, the Matrix Market 'representation'\n% indicator. Possible values include:\n% 'coordinate' (for sparse data)\n% 'array' (for dense data)\n% 'elemental' (to be added)\n%\n% Input, character ( len = 7 ) FIELD, the Matrix Market 'field'.\n% Possible values include:\n% 'real'\n% 'double'\n% 'complex'\n% 'integer'\n% 'pattern' (for REP = 'coordinate' only)\n%\n% Input, character ( len = 19 ) SYMM, the Matrix Market symmetry.\n% Possible values include:\n% 'symmetric'\n% 'hermitian'\n% 'skew-symmetric'\n% 'general'\n%\n% Output, logical VALUE, is TRUE if the header checks out.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Test the input qualifiers.\n%\n if ( s_neqi ( id, '%%MatrixMarket' ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of ID was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', id );\n fprintf ( 1, ' Legal values are:\\n' );\n fprintf ( 1, ' \"%%MatrixMarket\"\\n' );\n value = FALSE;\n return;\n end\n\n if ( s_neqi ( type, 'matrix' ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of TYPE was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', type );\n fprintf ( 1, ' Legal values are:\\n' );\n fprintf ( 1, ' \"matrix\"\\n' );\n value = FALSE;\n return\n end\n\n if ( ...\n s_neqi ( rep, 'coordinate' ) & ...\n s_neqi ( rep, 'array' ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of REP was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', rep );\n fprintf ( 1, ' Legal values are:\\n' );\n fprintf ( 1, ' \"array\"\\n' );\n fprintf ( 1, ' \"coordinate\"\\n' );\n value = FALSE;\n return\n end\n\n if ( s_eqi ( rep, 'coordinate' ) )\n\n if ( ...\n s_neqi ( field, 'integer' ) & ...\n s_neqi ( field, 'real' ) & ...\n s_neqi ( field, 'double' ) & ...\n s_neqi ( field, 'complex' ) & ...\n s_neqi ( field, 'pattern' ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of FIELD was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', field );\n value = FALSE;\n return\n end\n\n elseif ( s_eqi ( rep, 'array' ) )\n\n if ( ...\n s_neqi ( field, 'integer' ) & ...\n s_neqi ( field, 'real' ) & ...\n s_neqi ( field, 'double' ) & ...\n s_neqi ( field, 'complex' ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of FIELD was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', field );\n value = FALSE;\n return\n end\n\n end\n\n if ( ...\n s_neqi ( symm, 'general' ) & ...\n s_neqi ( symm, 'symmetric' ) & ...\n s_neqi ( symm, 'hermitian' ) & ...\n s_neqi ( symm, 'skew-symmetric' ) ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MM_HEADER_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The value of SYMM was illegal:\\n' );\n fprintf ( 1, ' \"%s\".\\n', symm );\n value = FALSE;\n return\n end\n \n value = TRUE;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/mm_io/mm_header_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.0726367028476572, "lm_q1q2_score": 0.01759301828175392}} {"text": "function [funs, ends] = constructor(op, dom, data, pref)\n%CONSTRUCTOR CHEBFUN constructor.\n% FUNS = CONSTRUCTOR(OP, DOM) constructs the piecewise components (known as\n% \"FUNS\") used by a CHEBFUN object to represent the function OP on the\n% interval DOM. OP must be a function_handle, string, numerical vector, or a\n% cell array containing a combination of these first three data types. In the\n% later case, the number of elements in the array must be one less than the\n% length of the DOM vector.\n%\n% It is not expected that CHEBFUN.CONSTRUCTOR() be called directly, \n%\n% If OP is a function_handle or a string, it should be vectorised in that it\n% accepts a column vector of length N and return a matrix of size N x M. If M\n% ~= 1, we say the resulting CHEBFUN is \"array-valued\".\n%\n% CONSTRUCTOR(OP, DOM, DATA, PREF), where DATA is a MATLAB structure and PREF\n% is a CHEBFUNPREF object, allows construction data and alternative\n% construction preferences to be passed to the constructor. See CHEBFUNPREF\n% for more details on preferences.\n%\n% In particular, if PREF.SPLITTING = TRUE and OP is a function_handle or a\n% string, then the constructor adaptively introduces additional breakpoints\n% into the domain so as to better represent the function. These are returned\n% as the second output argument in [FUNS, END] = CONSTRUCTOR(OP, DOM).\n%\n% The DATA structure input contains information which needs to be passed to\n% the lower layers about parameters which may affect the construction process.\n% Presently, the only fields CONSTRUCTOR expects DATA to have on input are\n% DATA.EXPONENTS and DATA.SINGTYPE, which convey information about endpoint\n% singularities. These fields are populated by CHEBFUN.PARSEINPUTS as need be.\n% Before calling the FUN constructor, DATA will be augmented to include\n% information about the construction domain as well as the horizontal and\n% vertical scales involved in the construction procedure.\n%\n% See also CHEBFUN, CHEBFUNPREF.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Initial setup:\nnumIntervals = numel(dom) - 1;\n\n% Initialise hscale and vscale:\ndata.hscale = norm(dom, inf);\nif ( isinf(data.hscale) )\n data.hscale = 1;\nend\nif ( isempty(data.vscale) )\n data.vscale = 0;\nend\n\n% Sanity check:\nif ( iscell(op) && (numel(op) ~= numIntervals) )\n error('CHEBFUN:CHEBFUN:constructor:cellInput', ...\n ['Number of cell elements in OP must match the number of ', ...\n 'intervals in DOMAIN.'])\nend\n\n% Construct the FUNs.\nif ( pref.splitting )\n [funs, ends] = constructorSplit(op, dom, data, pref);\nelse\n [funs, ends] = constructorNoSplit(op, dom, data, pref);\nend\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% SPLITTING OFF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [funs, ends] = ...\n constructorNoSplit(op, domain, data, pref)\n% In 'OFF' mode, seek only one piece with length < maxLength.\n\n% Initial setup:\nnumIntervals = numel(domain) - 1;\nends = domain;\n\n% Initialise the FUN array:\nfuns = cell(1, numIntervals);\n\n% We only want to throw the warning 'CHEBFUN:constructor:notResolved'once:\nwarningThrown = false;\n\nsingDetect = pref.blowup;\nexps = data.exponents;\nsingTypes = data.singType;\n\n% Loop over the intervals:\nfor k = 1:numIntervals\n endsk = ends(k:k+1);\n % Unwrap if OP is a cell:\n if ( iscell(op) )\n opk = op{k};\n else\n opk = op;\n end\n\n if ( singDetect )\n % Extract the exponents for this interval:\n if ( ~isempty(exps) )\n data.exponents = exps(2*k-1:2*k);\n end\n % Replace the information for the singularity type in the preference:\n if ( ~isempty(singTypes) && ~ischar(singTypes) )\n data.singType = singTypes(2*k-1:2*k);\n end\n end\n\n % Call GETFUN() (which calls FUN.CONSTRUCTOR()):\n [funs{k}, ishappy, data.vscale] = getFun(opk, endsk, data, pref);\n\n % Warn if unhappy (as we're unable to split the domain to improve):\n if ( ~ishappy && ~warningThrown )\n if ( strcmpi(func2str(pref.tech), 'trigtech') )\n str = 'a non-trig representation';\n else\n str = '''splitting on''';\n end\n \n warning('CHEBFUN:CHEBFUN:constructor:notResolved', ...\n ['Function not resolved using %d pts.', ...\n ' Have you tried ' str, '?'], pref.techPrefs.maxLength);\n warningThrown = true;\n end\nend\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% SPLITTING ON %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [funs, ends] = constructorSplit(op, dom, data, pref)\n% In 'ON' mode, seek only many pieces with total length < maxlength.\n\n% Initial setup:\nnumIntervals = numel(dom) - 1;\nends = dom;\n\n% Set the maximum length (i.e., number of sample points for CHEBTECH):\npref.techPrefs.maxLength = pref.splitPrefs.splitLength;\n\n% We extrapolate when splitting so that we can construct functions like\n% chebfun(@sign,[-1 1]), which otherwise would not be happy at x = 0.\npref.techPrefs.extrapolate = true;\n\n% Initialise the FUN array:\nfuns = cell(1, numIntervals);\n% Initialise happiness:\nishappy = ones(1, numel(ends) - 1);\n\nsingDetect = pref.blowup;\nexps = data.exponents;\nsingTypes = data.singType;\n\n% Try to get one smooth piece for the entire domain before splitting:\nfor k = 1:numIntervals\n % Unwrap if OP is a cell:\n if ( iscell(op) )\n opk = op{k};\n else\n opk = op;\n end\n \n if ( singDetect )\n % Extract the singularity information for this interval:\n data = getSingInfo(exps, singTypes, 2*k-1:2*k, data);\n end\n\n [funs{k}, ishappy(k), data.vscale] = ...\n getFun(opk, ends(k:k+1), data, pref);\n \n % For the case where vscale is Inf due to blowup in the interior of the\n % domain:\n if ( isinf(data.vscale) )\n % An infinite vscale doesn't help us at all, but ruin the consequential\n % constructions at the lower levels:\n data.vscale = 0; \n end\n \nend\nsad = ~ishappy;\n \n% MAIN LOOP. If the above didn't work, enter main loop and start splitting.\n% (Note that at least one new breakpoint will be introduced).\nwhile ( any(sad) )\n % If a FUN is sad in a subinterval, split this subinterval.\n \n % Choose a subinterval to improve:\n \n% % Old choice = the first sad interval:\n% k = find(sad, 1, 'first');\n \n % New choice = the largest sad interval:\n diffEnds = diff(ends);\n diffEnds(~sad) = 0;\n [ignored, k] = max(diffEnds);\n \n % Ends of this subinterval:\n a = ends(k);\n b = ends(k+1);\n \n % Unwrap if OP is a cell:\n if ( iscell(op) )\n opk = op{k};\n else\n opk = op;\n end\n\n % Look for an edge:\n edge = fun.detectEdge(funs{k}, opk, data.hscale, data.vscale, pref);\n\n if ( singDetect )\n % Update singularity info:\n if ( ~isempty(exps) )\n exps = [exps(1:2*k-1), zeros(1,2), exps(2*k:end)];\n end\n if ( ~isempty(singTypes) )\n singTypes = [singTypes(1:2*k-1), singTypes(2*k-1), ...\n singTypes(2*k) singTypes(2*k:end)];\n end\n end\n \n if ( singDetect )\n % Extract the singularity information for this interval:\n data = getSingInfo(exps, singTypes, 2*k-1:2*k, data);\n end\n \n % Try to obtain happy child FUN objects on each new subinterval:\n [childLeft, happyLeft, data.vscale] = getFun(opk, [a, edge], data, pref);\n \n if ( singDetect )\n % Extract the singularity information for this interval:\n data = getSingInfo(exps, singTypes, 2*k+1:2*k+2, data);\n end\n \n [childRight, happyRight, data.vscale] = getFun(opk, [edge, b], data, pref);\n \n % Check for happiness/sadness:\n sad = [sad(1:k-1), ~happyLeft, ~happyRight, sad(k+1:end)];\n\n % Insert new pieces in to existing funs:\n funs = [funs(1:k-1), {childLeft, childRight}, funs(k+1:end)];\n ends = [ends(1:k), edge, ends(k+1:end)];\n \n % If a cell was given, we must store pieces on new intervals:\n if ( iscell(op) )\n op = [op(1:k), {opk}, op(k+1:end)];\n end\n\n % Fail if too many points are required:\n len = sum(cellfun(@length, funs));\n if ( len > pref.splitPrefs.splitMaxLength )\n warning('CHEBFUN:CHEBFUN:constructor:funNotResolved', ...\n 'Function not resolved using %d pts.', ...\n sum(cellfun(@length, funs)));\n return\n end\n\nend\n\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GETFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [g, ishappy, vscale] = getFun(op, dom, data, pref)\n%GETFUN Call the FUN constructor.\n\n% If the interval is very small then skip adaptation and treat OP as a constant:\nif ( diff(dom) < 4*1e-14*data.hscale && ~isnumeric(op) )\n op = op(mean(dom));\nend\n\n% Bolt domain information onto the data structure.\ndata.domain = dom;\n\n% Call the FUN constructor:\ng = fun.constructor(op, data, pref);\n\n% See if the construction was happy:\nishappy = get(g, 'ishappy');\n\n% Update the vertical scale:\nif ( ishappy )\n vscale = max([data.vscale, get(g, 'vscale')]);\nelse\n vscale = data.vscale;\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GETSINGINFO %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction data = getSingInfo(exps, singTypes, kk, data)\n% Place information about the singularity type in the data structure.\nif ( ~isempty(exps) )\n data.exponents = exps(kk);\nend\nif ( ~isempty(singTypes) )\n data.singType = singTypes(kk);\nend\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/constructor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.04603390141766851, "lm_q1q2_score": 0.017379670573425727}} {"text": "function varargout = GUI_2D_prestuptepla(varargin)\n\n% Last Modified by GUIDE v2.5 06-Mar-2011 12:28:11\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @GUI_2D_prestuptepla_OpeningFcn, ...\n 'gui_OutputFcn', @GUI_2D_prestuptepla_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before GUI_2D_prestuptepla is made visible.\nfunction GUI_2D_prestuptepla_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to GUI_2D_prestuptepla (see VARARGIN)\n\n% Choose default command line output for GUI_2D_prestuptepla\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes GUI_2D_prestuptepla wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = GUI_2D_prestuptepla_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in Run.\nfunction Run_Callback(hObject, eventdata, handles)\nclear global\nclc\n\nglobal tkon t\n\n% inputs\nro=str2double(get(handles.hustota,'String'));\nvod=str2double(get(handles.vodivost,'String'));\nCp=str2double(get(handles.kapacita,'String'));\nT0=str2double(get(handles.T0,'String'));\nTH=str2double(get(handles.TH,'String'));\nTD=str2double(get(handles.TD,'String'));\nTP=str2double(get(handles.TP,'String'));\nTL=str2double(get(handles.TL,'String'));\nL=str2double(get(handles.L,'String'));\nM=str2double(get(handles.M,'String'));\nN=str2double(get(handles.n,'String'));\ntkon=str2double(get(handles.tkon,'String'));\n\n% calculation ===================================================\na=vod/ro/Cp;\n% length step\ndx=L/(N-1);\n% time step\ndt=((dx)^2)/M/a;\nt=dt;\n\n% =======================================================\n% inicialy temperatures\nTpoc=zeros(N,N);\nfor i=1:1:N\n for j=1:1:N\n Tpoc(i,j)=T0;\n end\nend\n\nwhile t=' 21 '<=' 252 'scalar'}));\n ip.addOptional('sel','F',@(x)any(validatestring(x,{'F' 'G'})));\n ip.addOptional('rr',0.4,@(x)validateattributes(x,{'double'},{'real' 'finite' '>=' 0 '<=' 1 'scalar'}));\n ip.addOptional('pw','W',@(x)any(validatestring(x,{'A' 'W'})));\n ip.addOptional('md','N',@(x)any(validatestring(x,{'N' 'T'})));\n ip.addOptional('analyze',false,@(x)validateattributes(x,{'logical'},{'scalar'}));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n ds = validate_dataset(ipr.ds,'CrossEntropy');\n sn = ipr.sn;\n temp = validate_template(ipr.temp);\n out = validate_output(ipr.out);\n bw = ipr.bw;\n sel = validate_selection(ipr.sel,ds.Groups);\n rr = ipr.rr;\n pw = ipr.pw;\n md = ipr.md;\n analyze = ipr.analyze;\n\n nargoutchk(1,2);\n\n [result,stopped] = run_cross_entropy_internal(ds,sn,temp,out,bw,sel,rr,pw,md,analyze);\n\nend\n\nfunction [result,stopped] = run_cross_entropy_internal(ds,sn,temp,out,bw,sel,rr,pw,md,analyze)\n\n result = [];\n stopped = false;\n e = [];\n\n ds = initialize(ds,sn,bw,sel,rr,pw,md);\n t = ds.T;\n\n bar = waitbar(0,'Initializing cross-entropy measures...','CreateCancelBtn',@(src,event)setappdata(gcbf(),'Stop',true));\n setappdata(bar,'Stop',false);\n cleanup = onCleanup(@()delete(bar));\n\n pause(1);\n waitbar(0,bar,'Calculating cross-entropy measures...');\n pause(1);\n\n try\n\n k = size(ds.Portfolios,1);\n tk = t * k;\n\n futures(1:t,1:k) = parallel.FevalFuture;\n futures_max = 0;\n futures_results = cell(t,k);\n\n for j = 1:k\n windows_r = extract_rolling_windows(ds.Portfolios{j,2},ds.BW);\n windows_pods = extract_rolling_windows(ds.Portfolios{j,3},ds.BW);\n\n for i = 1:t\n futures(i,j) = parfeval(@main_loop,1,windows_r{i},windows_pods{i},ds.PW,ds.MD);\n end\n end\n\n for i = 1:tk\n if (getappdata(bar,'Stop'))\n stopped = true;\n break;\n end\n\n [future_index,value] = fetchNext(futures);\n [future_i,future_j] = ind2sub([t k],future_index);\n futures_results{future_i,future_j} = value;\n\n futures_max = max([future_index futures_max]);\n waitbar((futures_max - 1) / tk,bar);\n\n if (getappdata(bar,'Stop'))\n stopped = true;\n break;\n end\n end\n\n catch e\n end\n\n try\n cancel(futures);\n catch\n end\n\n if (~isempty(e))\n delete(bar);\n rethrow(e);\n end\n\n if (stopped)\n delete(bar);\n return;\n end\n\n pause(1);\n waitbar(1,bar,'Finalizing cross-entropy measures...');\n pause(1);\n\n try\n ds = finalize(ds,futures_results);\n catch e\n delete(bar);\n rethrow(e);\n end\n\n pause(1);\n waitbar(1,bar,'Writing cross-entropy measures...');\n pause(1);\n\n try\n write_results(ds,temp,out);\n delete(bar);\n catch e\n delete(bar);\n rethrow(e);\n end\n\n if (analyze)\n analyze_result(ds)\n end\n\n result = ds;\n\nend\n\n%% PROCESS\n\nfunction ds = initialize(ds,sn,bw,sel,rr,pw,md)\n\n n = ds.N;\n t = ds.T;\n\n if (strcmp(sel,'G'))\n g = ds.Groups;\n gd = ds.GroupDelimiters;\n gs = cell(g,1);\n\n for i = 1:g\n if (i == 1)\n gs{i} = 1:gd(1);\n elseif (i == g)\n gs{i} = (gd(i - 1) + 1):n;\n else\n gs{i} = (gd(i - 1) + 1):gd(i);\n end\n end\n\n cds_ref = ds.CDS;\n cds = zeros(t,g);\n\n r_ref = ds.Returns;\n r = zeros(t,g);\n\n for i = 1:g\n gs_i = gs{i};\n gs_i_len = numel(gs_i);\n\n r_i = r_ref(:,gs_i);\n w_i = 1 ./ (repmat(gs_i_len,t,1) - sum(isnan(r_i),2));\n r(:,i) = sum(r_i .* repmat(w_i,1,gs_i_len),2,'omitnan');\n\n cds_i = cds_ref(:,gs_i);\n w_i = 1 ./ (repmat(gs_i_len,t,1) - sum(isnan(cds_i),2));\n cds(:,i) = sum(cds_i .* repmat(w_i,1,gs_i_len),2,'omitnan');\n end\n\n cp_ref = ds.Capitalizations;\n\n if (isempty(cp_ref))\n cp = [];\n else\n cp = zeros(t,g);\n\n for i = 1:g\n cp(:,i) = sum(cp_ref(:,gs{i}),2,'omitnan');\n end\n end\n\n lb_ref = ds.Liabilities;\n\n if (isempty(lb_ref))\n lb = [];\n else\n lb = zeros(t,g);\n\n for i = 1:g\n lb(:,i) = sum(lb_ref(:,gs{i}),2,'omitnan');\n end\n end\n\n n = g;\n else\n cds = ds.CDS;\n cp = ds.Capitalizations;\n lb = ds.Liabilities;\n r = ds.Returns;\n end\n\n pods = cds ./ rr;\n\n if (n <= 10)\n nc = n;\n\n if (strcmp(sel,'G'))\n pfc = ds.GroupShortNames.';\n else\n pfc = ds.FirmNames;\n end\n\n pf = {'Unique' r pods []};\n else\n nc = 6;\n nch = nc / 2;\n\n pfc = arrayfun(@(x)sprintf('C%d',x),1:nc,'UniformOutput',false);\n pf = [repmat({''},4,1) cell(4,3)];\n\n rw = extract_rolling_windows(ds.Returns,bw);\n\n pf_indices = zeros(t,nc);\n pf_pods = zeros(t,nc);\n pf_r = zeros(t,nc);\n\n for i = 1:t\n [cds_i,indices] = sort(cds(i,:),'ascend');\n\n indices(isnan(cds_i)) = [];\n indices = [fliplr(indices(end-nch+1:end)) fliplr(indices(1:nch))];\n\n pf_r(i,:) = r(i,indices);\n pf_pods(i,:) = pods(i,indices);\n pf_indices(i,:) = indices;\n end\n\n pf(1,1:4) = {'CDS Spreads' pf_r pf_pods pf_indices};\n\n pf_indices = zeros(t,nc);\n pf_pods = zeros(t,nc);\n pf_r = zeros(t,nc);\n\n for i = 1:t\n [v_i,indices] = sort(var(rw{i}),'ascend');\n\n indices(isnan(v_i)) = [];\n indices = [fliplr(indices(end-nch+1:end)) fliplr(indices(1:nch))];\n\n pf_r(i,:) = r(i,indices);\n pf_pods(i,:) = pods(i,indices);\n pf_indices(i,:) = indices;\n end\n\n pf(2,1:4) = {'Returns Variance' pf_r pf_pods pf_indices};\n\n if (isempty(cp))\n offset = 3;\n else\n pf_indices = zeros(t,nc);\n pf_pods = zeros(t,nc);\n pf_r = zeros(t,nc);\n\n for i = 1:t\n [cp_i,indices] = sort(cp(i,:),'ascend');\n\n indices(isnan(cp_i)) = [];\n indices = [fliplr(indices(end-nch+1:end)) fliplr(indices(1:nch))];\n\n pf_r(i,:) = r(i,indices);\n pf_pods(i,:) = pods(i,indices);\n pf_indices(i,:) = indices;\n end\n\n pf(3,:) = {'Capitalization' pf_r pf_pods pf_indices};\n offset = 4;\n end\n\n if (~isempty(lb))\n pf_indices = zeros(t,nc);\n pf_pods = zeros(t,nc);\n pf_r = zeros(t,nc);\n\n for i = 1:t\n [lb_i,indices] = sort(lb(i,:),'ascend');\n\n indices(isnan(lb_i)) = [];\n indices = [fliplr(indices(end-nch+1:end)) fliplr(indices(1:nch))];\n\n pf_r(i,:) = r(i,indices);\n pf_pods(i,:) = pods(i,indices);\n pf_indices(i,:) = indices;\n end\n\n pf(offset,:) = {'Liabilities' pf_r pf_pods pf_indices};\n offset = offset + 1;\n end\n\n pf(:,offset:end) = [];\n end\n\n ds.Result = 'CrossEntropy';\n ds.ResultDate = now(); %#ok \n ds.ResultAnalysis = @(ds)analyze_result(ds);\n ds.ResultSerial = sn;\n\n ds.BW = bw;\n ds.LGD = 1 - rr;\n ds.MD = md;\n ds.PW = pw;\n ds.RR = rr;\n ds.SEL = sel;\n\n ds.PortfolioComponents = pfc;\n ds.Portfolios = pf;\n\n all_label = [' (RR=' num2str(ds.RR * 100) '%, ' ds.PW ', ' ds.MD ')'];\n\n ds.LabelsMeasuresSimple = {'SI' 'SV' 'CoJPoDs'};\n ds.LabelsMeasures = {['SI' all_label] ['SV' all_label] ['CoJPoDs' all_label]};\n\n ds.LabelsIndicatorsSimple = {'JPoD' 'FSI' 'PCE'};\n ds.LabelsIndicators = {['JPoD' all_label] ['FSI' all_label] ['PCE' all_label]};\n\n ds.LabelsSheetsSimple = [{'Indicators' 'Average DiDe'} ds.LabelsMeasuresSimple];\n ds.LabelsSheets = [{'Indicators' 'Average DiDe'} ds.LabelsMeasures];\n\n ds.Indicators = NaN(t,numel(ds.LabelsIndicators));\n\n ds.AverageDiDe = NaN(nc);\n ds.DiDe = cell(t,1);\n ds.SI = NaN(t,nc);\n ds.SV = NaN(t,nc);\n\n ds.CoJPoDs = NaN(t,nc);\n\n ds.ComparisonReferences = {'Indicators' [] strcat({'CE-'},ds.LabelsIndicatorsSimple)};\n\nend\n\nfunction window_results = main_loop(r,pods,pw,md)\n\n window_results = struct();\n\n nan_indices = any(isnan(r),1);\n n = numel(nan_indices);\n\n r(:,nan_indices) = [];\n pods(:,nan_indices) = [];\n\n if (strcmp(pw,'A'))\n pods = mean(pods,1).';\n else\n [t,n] = size(pods);\n w = repmat(fliplr(((1 - 0.98) / (1 - 0.98^t)) .* (0.98 .^ (0:1:t-1))).',1,n);\n pods = sum(pods .* w,1).';\n end\n\n [g,p] = cimdo(r,pods,md);\n\n if (any(isnan(p)))\n window_results.JPoD = NaN;\n window_results.FSI = NaN;\n window_results.PCE = NaN;\n window_results.DiDe = NaN(n);\n window_results.SI = NaN(1,n);\n window_results.SV = NaN(1,n);\n window_results.CoJPoDs = NaN(1,n);\n else\n opods = pods;\n pods = NaN(n,1);\n pods(~nan_indices) = opods;\n\n [jpod,fsi,pce,dide,si,sv,cojpods] = cross_entropy_metrics(pods,g,p);\n window_results.JPoD = jpod;\n window_results.FSI = fsi;\n window_results.PCE = pce;\n window_results.DiDe = dide;\n window_results.SI = si;\n window_results.SV = sv;\n window_results.CoJPoDs = cojpods;\n end\n\nend\n\nfunction ds = finalize(ds,results)\n\n t = ds.T;\n k = size(results,2);\n\n if (k == 1)\n for i = 1:t\n result = results{i};\n\n ds.Indicators(i,:) = [result.JPoD result.FSI result.PCE];\n\n ds.DiDe{i} = result.DiDe;\n ds.SI(i,:) = result.SI;\n ds.SV(i,:) = result.SV;\n\n ds.CoJPoDs(i,:) = result.CoJPoDs;\n end\n else\n jpod_avg = mean(cellfun(@(x)x.JPoD,results,'UniformOutput',true),2,'omitnan');\n fsi_avg = mean(cellfun(@(x)x.FSI,results,'UniformOutput',true),2,'omitnan');\n pce_avg = mean(cellfun(@(x)x.PCE,results,'UniformOutput',true),2,'omitnan');\n ds.Indicators = [jpod_avg fsi_avg pce_avg];\n\n dide = cellfun(@(x)x.DiDe,results,'UniformOutput',false);\n si = cellfun(@(x)x.SI,results,'UniformOutput',false);\n sv = cellfun(@(x)x.SI,results,'UniformOutput',false);\n\n cojpods = cellfun(@(x)x.CoJPoDs,results,'UniformOutput',false);\n\n for i = 1:t\n ds.DiDe{i} = mean(cat(3,dide{i,:}),3);\n ds.SI(i,:) = mean(cat(3,si{i,:}),3);\n ds.SV(i,:) = mean(cat(3,sv{i,:}),3);\n\n ds.CoJPoDs(i,:) = mean(cat(3,cojpods{i,:}),3);\n end\n end\n\n ds.AverageDiDe = sum(cat(3,ds.DiDe{:}),3) ./ numel(ds.DiDe);\n\n si_vec = ds.SI(:);\n si_max = max(si_vec,[],'omitnan');\n si_min = min(si_vec,[],'omitnan');\n ds.SI = (ds.SI - si_min) ./ (si_max - si_min);\n\n sv_vec = ds.SV(:);\n sv_max = max(sv_vec,[],'omitnan');\n sv_min = min(sv_vec,[],'omitnan');\n ds.SV = (ds.SV - sv_min) ./ (sv_max - sv_min);\n\nend\n\nfunction write_results(ds,temp,out)\n\n [out_path,~,~] = fileparts(out);\n\n try\n if (exist(out_path,'dir') ~= 7)\n mkdir(out_path);\n end\n\n if (exist(out,'file') == 2)\n delete(out);\n end\n catch\n error('A system I/O error occurred while writing the results.');\n end\n\n copy_result = copyfile(temp,out,'f');\n\n if (copy_result == 0)\n error('The results file could not be created from the template file.');\n end\n\n dates_str = cell2table(ds.DatesStr,'VariableNames',{'Date'});\n\n labels_all = ds.PortfolioComponents;\n\n if (size(ds.Portfolios,1) == 1)\n if (strcmp(ds.SEL,'G'))\n header = {'Groups'};\n else\n header = {'Firms'};\n end\n else\n header = {'Components'};\n end\n\n labels = ds.LabelsIndicatorsSimple;\n tab = [dates_str array2table(ds.Indicators,'VariableNames',labels)];\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{1},'WriteRowNames',true);\n\n vars = [labels_all.' num2cell(ds.AverageDiDe)];\n tab = cell2table(vars,'VariableNames',[header labels_all]);\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{2},'WriteRowNames',true);\n\n tab = [dates_str array2table(ds.SI,'VariableNames',labels_all)];\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{3},'WriteRowNames',true);\n\n tab = [dates_str array2table(ds.SV,'VariableNames',labels_all)];\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{4},'WriteRowNames',true);\n\n tab = [dates_str array2table(ds.CoJPoDs,'VariableNames',labels_all)];\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{5},'WriteRowNames',true);\n\n worksheets_batch(out,ds.LabelsSheetsSimple,ds.LabelsSheets);\n\nend\n\n%% PLOTTING\n\nfunction analyze_result(ds)\n\n if (size(ds.Portfolios,1) > 1)\n safe_plot(@(id)plot_portfolios_coverage(ds,id));\n end\n\n safe_plot(@(id)plot_indicators(ds,id));\n safe_plot(@(id)plot_dide(ds,id));\n safe_plot(@(id)plot_sequence_dide(ds,id));\n safe_plot(@(id)plot_sequence_cojpods(ds,id));\n\nend\n\nfunction plot_portfolios_coverage(ds,id)\n\n if (strcmp(ds.SEL,'G'))\n n = ds.Groups;\n labels = ds.GroupShortNames.';\n else\n n = ds.N;\n labels = ds.FirmNames;\n end\n\n nc = numel(ds.PortfolioComponents);\n\n k = size(ds.Portfolios,1);\n\n seq = 1:n;\n\n counts = cell(k + 1,2);\n count_total = zeros(n,1);\n\n for i = 1:k\n pf_indices = ds.Portfolios{i,4};\n pf_indices = pf_indices(:);\n\n [values_unique,~,indices_unique] = unique(pf_indices);\n\n count = zeros(n,1);\n count(values_unique) = accumarray(indices_unique,1);\n\n count_total = count_total + count;\n\n [count,order] = sort(count);\n counts(i + 1,:) = {(count ./ (sum(count) / nc)) labels(order)};\n end\n\n [count_total,order] = sort(count_total);\n counts(1,:) = {(count_total ./ (sum(count_total) / nc)) labels(order)};\n\n if (k == 4)\n spp = [2 3];\n spo = {[1 4] 2 3 5 6};\n elseif (k == 3)\n spp = [3 2];\n spo = {[1 5] 2 4 6};\n else\n spp = [2 2];\n spo = {[1 3] 2 4};\n end\n\n f = figure('Name','Cross-Entropy Measures > Reduced Portfolios Coverage','Units','normalized','Position',[100 100 0.85 0.85],'Tag',id);\n\n subs = gobjects(k + 1,1);\n\n sub_1 = subplot(spp(1),spp(2),spo{1});\n bar(sub_1,seq,counts{1,1},'FaceColor',[0.749 0.862 0.933]);\n set(sub_1,'XLim',[0 (ds.N + 1)],'XTick',seq,'XTickLabel',counts{1,2},'XTickLabelRotation',90);\n set(sub_1,'YLim',[0 1],'YTick',0:0.1:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(0:0.1:1) .* 100,'UniformOutput',false));\n title('Overall');\n\n subs(1) = sub_1;\n\n for i = 1:k\n sub = subplot(spp(1),spp(2),spo{i + 1});\n bar(sub,seq,counts{i + 1,1},'FaceColor',[0.749 0.862 0.933]);\n set(sub,'XLim',[0 (ds.N + 1)],'XTick',seq,'XTickLabel',counts{i + 1,2},'XTickLabelRotation',90);\n set(sub,'YLim',[0 1],'YTick',0:0.1:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(0:0.1:1) .* 100,'UniformOutput',false));\n title(ds.Portfolios{i,1});\n\n subs(i + 1) = sub;\n end\n\n set(subs,'YGrid','on');\n\n figure_title(f,'Reduced Portfolios Coverage');\n\n maximize_figure(f);\n\nend\n\nfunction plot_indicators(ds,id)\n\n nc = numel(ds.PortfolioComponents);\n\n jpod = smooth_data(ds.Indicators(:,1));\n fsi = smooth_data(ds.Indicators(:,2));\n pce = smooth_data(ds.Indicators(:,3));\n\n f = figure('Name','Cross-Entropy Measures > Indicators','Units','normalized','Position',[100 100 0.85 0.85],'Tag',id);\n\n sub_1 = subplot(2,2,1:2);\n plot(sub_1,ds.DatesNum,jpod);\n set(sub_1,'YLim',plot_limits(jpod,0.1,0));\n t1 = title(sub_1,ds.LabelsIndicatorsSimple{1});\n set(t1,'Units','normalized');\n t1_position = get(t1,'Position');\n set(t1,'Position',[0.4783 t1_position(2) t1_position(3)]);\n\n sub_2 = subplot(2,2,3);\n plot(sub_2,ds.DatesNum,fsi);\n set(sub_2,'YLim',[1 nc],'YTick',1:nc);\n title(sub_2,ds.LabelsIndicatorsSimple{2});\n\n sub_3 = subplot(2,2,4);\n plot(sub_3,ds.DatesNum,pce);\n set(sub_3,'YLim',[0 1],'YTick',0:0.1:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(0:0.1:1) .* 100,'UniformOutput',false));\n title(sub_3,ds.LabelsIndicatorsSimple{3});\n\n set([sub_1 sub_2 sub_3],'XLim',[ds.DatesNum(1) ds.DatesNum(end)],'XTickLabelRotation',45);\n set([sub_1 sub_2 sub_3],'XGrid','on','YGrid','on');\n\n if (ds.MonthlyTicks)\n date_ticks([sub_1 sub_2 sub_3],'x','mm/yyyy','KeepLimits','KeepTicks');\n else\n date_ticks([sub_1 sub_2 sub_3],'x','yyyy','KeepLimits');\n end\n\n figure_title(f,['Indicators (RR=' num2str(ds.RR * 100) '%, ' ds.PW ', ' ds.MD ')']);\n\n maximize_figure(f);\n\nend\n\nfunction plot_dide(ds,id)\n\n nc = numel(ds.PortfolioComponents);\n\n dide = ds.AverageDiDe;\n didev = dide(:);\n\n [dide_x,dide_y] = meshgrid(1:nc,1:nc);\n dide_x = dide_x(:) + 0.5;\n dide_y = dide_y(:) + 0.5;\n\n dide_txt = cellstr(num2str(didev,'~%.4f'));\n\n for i = 1:nc^2\n didev_i = didev(i);\n\n if (didev_i == 0)\n dide_txt{i} = '0';\n elseif (didev_i == 1)\n dide_txt{i} = '';\n end\n end\n\n lt_indices = (dide < 0.2) & (dide ~= 1);\n ge_indices = (dide >= 0.2) & (dide ~= 1);\n\n dide(lt_indices) = 0;\n dide(ge_indices) = 1;\n dide = dide - (eye(nc) .* 0.5);\n dide = padarray(dide,[1 1],'post');\n\n didev = dide(:);\n didev_ones = any(didev == 1);\n didev_zeros = any(didev == 0);\n\n f = figure('Name','Cross-Entropy Measures > Average Distress Dependency','Units','normalized','Position',[100 100 0.85 0.85],'Tag',id);\n\n pcolor(dide);\n\n if (didev_ones && didev_zeros)\n colormap([1 1 1; 0.65 0.65 0.65; 0.749 0.862 0.933]);\n else\n if (didev_ones)\n colormap([0.65 0.65 0.65; 0.749 0.862 0.933]);\n else\n colormap([1 1 1; 0.65 0.65 0.65]);\n end\n end\n\n text(dide_x,dide_y,dide_txt,'HorizontalAlignment','center');\n axis image;\n\n ax = gca();\n set(ax,'TickLength',[0 0]);\n set(ax,'XAxisLocation','top','XTick',1.5:(nc + 0.5),'XTickLabels',ds.PortfolioComponents,'XTickLabelRotation',45);\n set(ax,'YDir','reverse','YTick',1.5:(nc + 0.5),'YTickLabels',ds.PortfolioComponents,'YTickLabelRotation',45);\n\n figure_title(f,'Average Distress Dependency');\n\n maximize_figure(f);\n\nend\n\nfunction plot_sequence_dide(ds,id)\n\n nc = numel(ds.PortfolioComponents);\n\tnc_ones = ones(1,nc);\n\n t = ds.T;\n dn = ds.DatesNum;\n mt = ds.MonthlyTicks;\n\n ts_si = ds.SI;\n ts_sv = ds.SV;\n\n data = [repmat({dn},1,nc); mat2cell(ts_si,t,nc_ones); mat2cell(ts_sv,t,nc_ones)];\n\n sequence_titles = ds.PortfolioComponents;\n\n plots_title = [repmat(ds.LabelsMeasures(1),1,nc); repmat(ds.LabelsMeasures(2),1,nc)];\n\n x_limits = [dn(1) dn(end)];\n\n y_limits = [0 1];\n y_ticks = 0:0.1:1;\n\n core = struct();\n\n core.N = nc;\n core.Data = data;\n core.Function = @(subs,data)plot_function(subs,data);\n\n core.OuterTitle = 'Cross-Entropy Measures > Distress Dependency Time Series';\n core.InnerTitle = 'Distress Dependency Time Series';\n core.SequenceTitles = sequence_titles;\n\n core.PlotsAllocation = [2 1];\n core.PlotsSpan = {1 2};\n core.PlotsTitle = plots_title;\n\n core.XDates = {mt mt};\n core.XGrid = {true true};\n core.XLabel = {[] []};\n core.XLimits = {x_limits x_limits};\n core.XRotation = {[] []};\n core.XTick = {[] []};\n core.XTickLabels = {[] []};\n\n core.YGrid = {true true};\n core.YLabel = {[] []};\n core.YLimits = {y_limits y_limits};\n core.YRotation = {[] []};\n core.YTick = {y_ticks y_ticks};\n core.YTickLabels = {[] []};\n\n sequential_plot(core,id);\n\n function plot_function(subs,data)\n\n x = data{1};\n si = data{2};\n sv = data{3};\n\n d = min(find(isnan(si),1,'first'),find(isnan(sv),1,'first'));\n\n if (isempty(d))\n xd = [];\n else\n xd = x(d) - 1;\n end\n\n\t\tsub_1 = subs(1);\n plot(sub_1,x,si,'Color',[0.000 0.447 0.741]);\n\n if (~isempty(xd))\n hold(sub_1,'on');\n plot(sub_1,[xd xd],get(sub_1,'YLim'),'Color',[1.000 0.400 0.400]);\n hold(sub_1,'off');\n end\n\n\t\tsub_2 = subs(2);\n plot(sub_2,x,sv,'Color',[0.000 0.447 0.741]);\n\n if (~isempty(xd))\n hold(sub_2,'on');\n plot(sub_2,[xd xd],get(sub_2,'YLim'),'Color',[1.000 0.400 0.400]);\n hold(sub_2,'off');\n end\n\n end\n\nend\n\nfunction plot_sequence_cojpods(ds,id)\n\n nc = numel(ds.PortfolioComponents);\n\n t = ds.T;\n dn = ds.DatesNum;\n mt = ds.MonthlyTicks;\n\n ts = smooth_data(ds.CoJPoDs);\n\n data = [repmat({dn},1,nc); mat2cell(ts,t,ones(1,nc))];\n\n sequence_titles = ds.PortfolioComponents;\n\n plots_title = repmat(ds.LabelsMeasures(3),1,nc);\n\n x_limits = [dn(1) dn(end)];\n y_limits = plot_limits(ts,0.1,0);\n\n y_tick_labels = @(x)sprintf('%.2f%%',x .* 100);\n\n core = struct();\n\n core.N = nc;\n core.Data = data;\n core.Function = @(subs,data)plot_function(subs,data);\n\n core.OuterTitle = 'Cross-Entropy Measures > CoJPoDs Time Series';\n core.InnerTitle = 'CoJPoDs Time Series';\n core.SequenceTitles = sequence_titles;\n\n core.PlotsAllocation = [1 1];\n core.PlotsSpan = {1};\n core.PlotsTitle = plots_title;\n\n core.XDates = {mt};\n core.XGrid = {true};\n core.XLabel = {[]};\n core.XLimits = {x_limits};\n core.XRotation = {45};\n core.XTick = {[]};\n core.XTickLabels = {[]};\n\n core.YGrid = {true};\n core.YLabel = {[]};\n core.YLimits = {y_limits};\n core.YRotation = {[]};\n core.YTick = {[]};\n core.YTickLabels = {y_tick_labels};\n\n sequential_plot(core,id);\n\n function plot_function(subs,data)\n\n x = data{1};\n y = data{2};\n\n d = find(isnan(y),1,'first');\n\n if (isempty(d))\n xd = [];\n else\n xd = x(d) - 1;\n end\n\n\t\tsub_1 = subs(1);\n plot(sub_1,x,y,'Color',[0.000 0.447 0.741]);\n\n if (~isempty(xd))\n hold(sub_1,'on');\n plot(sub_1,[xd xd],get(sub_1,'YLim'),'Color',[1.000 0.400 0.400]);\n hold(sub_1,'off');\n end\n\n end\n\nend\n\n%% VALIDATION\n\nfunction out = validate_output(out)\n\n [path,name,extension] = fileparts(out);\n\n if (~strcmpi(extension,'.xlsx'))\n out = fullfile(path,[name extension '.xlsx']);\n end\n\nend\n\nfunction sel = validate_selection(sel,groups)\n\n if (strcmp(sel,'G') && (groups == 0))\n error('The selection cannot be set to groups because their are not defined in the dataset.');\n end\n\nend\n\nfunction temp = validate_template(temp)\n\n sheets = {'Indicators' 'Average DiDe' 'SI' 'SV' 'CoJPoDs'};\n file_sheets = validate_xls(temp,'T');\n\n if (~all(ismember(sheets,file_sheets)))\n error(['The template must contain the following sheets: ' sheets{1} sprintf(', %s',sheets{2:end}) '.']);\n end\n\n worksheets_batch(temp,sheets);\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsMeasures/run_cross_entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.036769467922763914, "lm_q1q2_score": 0.017094183415856345}} {"text": "function [rollback, ev, nefv] = pne_detect_events(reg_ev, nefv, cefv, step)\n%PNE_DETECT_EVENTS Detect events from event function values\n% [ROLLBACK, CRITICAL_EVENTS, NEFV] = ...\n% PNE_DETECT_EVENTS(REG_EV, NEFV, CEFV, STEP)\n%\n% Determines whether any events have been detected based on the\n% corresponding \"current\" and \"next\" event function values. If any events\n% are detected, the relevant information is returned in CRITICAL_EVENTS,\n% along with a ROLLBACK flag indicating whether to roll back the proposed\n% next step.\n%\n% Inputs:\n% REG_EV : struct containing info about registered event fcns\n% NEFV : cell array of Next Event Function Values\n% CEFV : cell array of Current Event Function Values\n% STEP : current step size\n%\n% Outputs:\n% ROLLBACK : flag indicating whether any event has requested a\n% rollback step, if ROLLBACK is true, then CRITICAL_EVENTS will\n% have length 1\n% CRITICAL_EVENTS : struct array containing information about any\n% detected events, with fields:\n% eidx : event index, index in REG_EV, 0 if no event detected\n% name : name of event function, empty if none detected\n% zero : 1 if zero has been detected, 0 otherwise\n% (i.e. interval detected or no event detected)\n% idx : index(es) of critical elements in event function\n% step_scale : linearly interpolated estimate of scaling factor\n% for current step size required to reach event zero\n% log : 1 log the event in the results, 0 don't log the event\n% (set to 1 for zero events, 0 otherwise, can be\n% modified by callbacks)\n% msg : event message, set to something generic like\n% 'ZERO detected for TARGET_LAM event' or\n% 'INTERVAL detected for QLIM(3) event', but intended\n% to be changed/updated by callbacks\n% NEFV : cell array of Next Event Function Values\n% (possibly updated to be exactly zero to avoid re-detection of\n% an interval following a zero detection)\n\n% MP-Opt-Model\n% Copyright (c) 2016-2021, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% and Shrirang Abhyankar, Argonne National Laboratory\n%\n% This file is part of MP-Opt-Model.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://github.com/MATPOWER/mp-opt-model for more info.\n\n%% initialize result variables\nrollback = 0;\nev = struct( ... %% initialize struct for storing critical events\n 'eidx', 0, ...\n 'zero', 0, ...\n 'step_scale', 1, ...\n 'log', 0, ...\n 'name', '', ...\n 'idx', 0, ...\n 'msg', '' ...\n);\n\n%% other initialization\ni = 1; %% index into ev struct\nnef = length(nefv); %% number of event functions\n\n%% detect events, first look for event intervals for events requesting rollback\nfor eidx = 1:nef\n if ~reg_ev(eidx).locate %% if event doesn't request rollback to locate zero\n continue; %% skip to next event\n end\n\n %% current and previous event function signs\n c_sign = sign(nefv{eidx});\n p_sign = sign(cefv{eidx});\n\n %% if there's been a sign change and we aren't within event tolerance ...\n idx = find( abs(c_sign) == 1 & c_sign == -p_sign & ...\n abs(nefv{eidx}) > reg_ev(eidx).tol );\n if ~isempty(idx)\n if step == 0 %% if it's a \"repeat\" step\n %% (e.g. after warmstart with possible fcn change)\n %% ... make this one the critical one and call it a ZERO event\n ev.eidx = eidx;\n ev.zero = 1;\n ev.step_scale = 1;\n ev.log = 1;\n ev.name = reg_ev(eidx).name;\n ev.idx = idx;\n ev.msg = 'ZERO (BIFURCATION)';\n i = i + 1;\n break;\n else\n %% ... compute step size scaling factors and find index of smallest one\n [step_scale, j] = ...\n min(cefv{eidx}(idx) ./ (cefv{eidx}(idx) - nefv{eidx}(idx)) );\n\n %% if it's smaller than the current critical one ...\n if step_scale < ev.step_scale\n %% ... make this one the critical one\n ev.eidx = eidx;\n ev.zero = 0;\n ev.step_scale = step_scale;\n ev.log = 0;\n ev.name = reg_ev(eidx).name;\n ev.idx = idx(j);\n ev.msg = 'INTERVAL';\n rollback = 1; %% signal that a rollback event has been detected\n end\n end\n end\nend\n\n%% if no rollback events were detected\nif rollback == 0\n %% search for event zeros\n for eidx = 1:nef\n %% if there's an event zero ...\n idx = find( abs(nefv{eidx}) <= reg_ev(eidx).tol );\n if ~isempty(idx)\n %% set event function to exactly zero\n %% (to prevent possible INTERVAL detection again on next step)\n nefv{eidx}(idx) = 0;\n\n %% ... make this one the critical one\n ev(i).eidx = eidx;\n ev(i).zero = 1;\n ev(i).step_scale = 1;\n ev(i).log = 1;\n ev(i).name = reg_ev(eidx).name;\n ev(i).idx = idx;\n ev(i).msg = 'ZERO';\n i = i + 1;\n end\n end\n \n %% and if no zeros were detected\n if i == 1\n %% search for intervals for non-rollback events\n for eidx = 1:nef\n %% current and previous event function signs\n c_sign = sign(nefv{eidx});\n p_sign = sign(cefv{eidx});\n\n %% if there's been a sign change ...\n idx = find( abs(c_sign) == 1 & c_sign == -p_sign );\n if ~isempty(idx)\n %% ... compute step size scaling factors ...\n step_scale = cefv{eidx}(idx) ./ (cefv{eidx}(idx) - nefv{eidx}(idx));\n\n %% ... and save the info as an interval detection\n ev(i).eidx = eidx;\n ev(i).zero = 0;\n ev(i).step_scale = step_scale;\n ev(i).log = 0;\n ev(i).name = reg_ev(eidx).name;\n ev(i).idx = idx;\n ev(i).msg = 'INTERVAL';\n i = i + 1;\n end\n end\n end\nend\n\n%% update msgs\nif ev(1).eidx\n for i = 1:length(ev)\n if length(nefv{ev(i).eidx}) > 1\n s1 = sprintf('(%d)', ev(i).idx);\n else\n s1 = '';\n end\n if rollback\n s2 = sprintf(' : ROLLBACK by %g', ev(i).step_scale);\n else\n s2 = '';\n end\n ev(i).msg = sprintf('%s detected for %s%s event%s', ...\n ev(i).msg, ev(i).name, s1, s2);\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/mp-opt-model/lib/pne_detect_events.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.03963883569746136, "lm_q1q2_score": 0.017050540076292864}} {"text": "%ETS Elementary Transform Sequence class\n%\n% Manipulate a sequence (vector) of elementary transformations\n% - ETS.TX\n% - ETS.TY\n% - ETS.TZ\n% - ETS.RX\n% - ETS.RY\n% - ETS.RZ\n%\n% Methods::\n% ETS Construct a sequence from string\n% isrot True if rotational transform\n% istrans True if translational transform\n% isjoint Is ETS a function of qj\n% njoints Maximum joint variable index\n% axis Axis of translation or rotation\n% find Find ETS that is a function of qj\n% subs Substitute element of sequence\n%-\n% eval Evaluate ETS\n% jacobian Compute Jacobian of ETS\n%-\n% display Display a sequence in human readable form\n% char Convert sequence to a string\n%\n% Example::\n% ets = ETS('Rx(q1)Tx(a1)Ry(q2)Ty(a3)Rz(q3)Rx(pi/2)')\n% ets.eval([1 2 3]);\n%\n% Notes::\n% - Still experimental\n%\n% See also trchain, trchain2.\n\n% TODO:\n% - handle 2D case\n% - do DHFactor\n% - accept parameters from a passed struct rather as well as workspace\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n%\n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nclassdef ETS < handle\n \n properties\n type % ETS.TX, ETS.TY, ETS.TZ, ETS.RX, ETS.RY, ETS.RZ\n \n val\n joint % joint number, if a joint, else 0\n constant % eg. 90, for angles\n sign\n symconstant % eg. L1, for lengths\n \n % DH parameters\n theta\n D\n A\n alpha\n offset\n prismatic\n end\n \n properties (Constant)\n TX = 0;\n TY = 1;\n TZ = 2;\n RX = 3;\n RY = 4;\n RZ = 5;\n DH = 6;\n DHM = 7;\n \n names = {'Tx', 'Ty', 'Tz', 'Rx', 'Ry', 'Rz', 'DH', 'DHm' };\n end\n % Element.java\n % // one of ETS.TX, ETS.TY ... ETS.RZ, DH_STANDARD/MODIFIED\n % \tint\t\ttype;\n %\n % \t// transform parameters, only one of these is set\n % \tString\tvar; // eg. q1, for joint var ETS.TYpes\n % \tString\tsymconst; // eg. L1, for lengths\n % \tint\t\tconstant; // eg. 90, for angles\n %\n % \t// DH parameters, only set if ETS.TYpe is DH_STANDARD/MODIFIED\n % \tint \ttheta,\n % alpha;\n % String A,\n % D;\n % int prismatic;\n % int offset;\n \n methods\n function ets = ETS(s, varargin)\n %ETS.ETS Construct elementary transform element or sequence\n %\n % e = ETS() is a new ETS object.\n %\n % e = ETS(t) is a clone of the ETS object t and all properties are copied.\n %\n % e = ETS(op, v) is a new ETS object of type op and value v. OP can be any\n % of\n % 'Rx' rotation about the x-axis\n % 'Ry' rotation about the y-axis\n % 'Rz' rotation about the z-axis\n % 'Tx' translation along the x-axis\n % 'Ty' translation along the y-axis\n % 'Tz' translation along the z-axis\n % 'transl' sequence of finite translations along the x-, y- and z-directions.\n % 'rpy' sequence of finite rotations about the x-, y- and z-directions.\n %\n % e = ETS(str) is a sequence of ETS objects, each described by a\n % subexpression in the string STR. Each subexpression comprises an\n % operation as per the table above followed by parentheses and a value.\n % For example:\n %\n % ets = ETS('Rx(q1)Tx(a1)Ry(q2)Ty(a3)Rz(q3)Rx(pi/2)')\n \n if nargin == 0\n ets.joint = false;\n ets.constant = [];\n return;\n end\n \n if ischar(s) || isstring(s)\n s = string(s);\n if strfind(s, '(')\n % string of tokens\n tokens = regexp(s, '\\s*(?R.?|T.)\\(\\s*(?[^)]*)\\s*\\)\\s*', 'names');\n \n joint = 1;\n \n ets = [];\n for token = tokens\n \n % get the argument for this transform element\n \n % deal with case of symbolic arg or workspace expression\n if token.arg.startsWith(\"q\") || token.arg.startsWith(\"*\")\n x = ETS(token.op, \"\");\n x.joint = joint;\n joint = joint+1;\n else\n x = ETS(token.op, string(token.arg));\n x.joint = 0;\n end\n \n ets = [ets x]; % append to the list\n end\n else\n % ETS('transl', [v])\n % ETS('rpy', [v]);\n switch s\n case 'transl'\n v = varargin{1};\n \n ets = [];\n if v(1) ~= 0\n ets = [ets ETS('Tx', v(1))];\n end\n if v(2) ~= 0\n ets = [ets ETS('Ty', v(2))];\n end\n if v(3) ~= 0\n ets = [ets ETS('Tz', v(3))];\n end\n case 'rpy'\n v = varargin{1};\n \n ets = [];\n if v(1) ~= 0\n ets = [ets ETS('Rx', v(1))];\n end\n if v(2) ~= 0\n ets = [ets ETS('Ry', v(2))];\n end\n if v(3) ~= 0\n ets = [ets ETS('Rz', v(3))];\n end\n \n case 'Rx'\n ets = ETS(ETS.RX, varargin{1});\n case 'Ry'\n ets = ETS(ETS.RY, varargin{1});\n case 'Rz'\n ets = ETS(ETS.RZ, varargin{1});\n case 'Tx'\n ets = ETS(ETS.TX, varargin{1});\n case 'Ty'\n ets = ETS(ETS.TY, varargin{1});\n case 'Tz'\n ets = ETS(ETS.TZ, varargin{1});\n \n otherwise\n error('RTB:trchain:badarg', 'unknown operator/option %s', s);\n end\n end\n \n elseif isnumeric(s)\n ets = ETS();\n ets.type = s;\n ets.val = varargin{1};\n \n elseif isa(s, 'ETS')\n % clone the object\n ets.type = s.type;\n ets.joint = s.joint;\n ets.val = s.val;\n ets.symconstant = s.symconstant;\n \n if nargin > 1\n ets.type = varargin{1};\n end\n \n if nargin > 2\n if varargin{2} < 0\n ets = ets.negate();\n end\n end\n end\n end\n \n function s = op(ets)\n s = ets.names{ets.type+1};\n end\n \n function s = char(ets)\n s = '';\n for x=ets\n e = x.op;\n \n if isjoint(x)\n e = \" \" + e + \"(*q\" + x.joint + x.val + \")\";\n else\n e = e + \"(\" + x.val + \")\";\n end\n s = strcat(s, e);\n end\n end\n \n function display(ets)\n %ETS.display Display parameters\n %\n % ETS.display() displays the transform parameters in compact single line format.\n %\n % Notes::\n % - This method is invoked implicitly at the command line when the result\n % of an expression is a Link object and the command has no trailing\n % semicolon.\n %\n % See also Link.char, Link.dyn, SerialLink.showlink.\n loose = strcmp( get(0, 'FormatSpacing'), 'loose');\n if loose\n disp(' ');\n end\n disp([inputname(1), ' = '])\n disp( char(ets) );\n end % display()\n \n% function disp(ets)\n% disp( show(ets) );\n% end\n \n\n %-------------------------------------------------------------\n \n function T = eval(ets, q)\n \n T = eye(4,4);\n \n for x = ets\n % get the argument for this transform element\n if x.isjoint()\n % from the passed in vector q\n \n arg = q(x.joint);\n else % or the workspace\n \n try\n arg = evalin('base', x.val);\n catch\n error('RTB:ETS:badarg', 'variable %s does not exist', x.val);\n end\n end\n \n % now evaluate the element and update the transform chain\n switch x.type\n case ETS.RX\n T = T * trotx(arg, 'deg');\n case ETS.RY\n T = T * troty(arg, 'deg');\n case ETS.RZ\n T = T * trotz(arg, 'deg');\n case ETS.TX\n T = T * transl(arg, 0, 0);\n case ETS.TY\n T = T * transl(0, arg, 0);\n case ETS.TZ\n T = T * transl(0, 0, arg);\n otherwise\n error('RTB:ETS:badarg', 'unknown operator %s', x.op);\n end\n end\n \n T = trnorm(T);\n \n % if isa(q, 'symfun')\n % T = formula(T);\n % end\n end\n \n\n \n function J = jacobian(ets, q)\n n = ets.njoints();\n J = zeros(6, n);\n for j=1:n\n % find derivative with respect to q_j\n k = ets.find(j);\n deriv = ets(k).deriv(q(j));\n pre = eval( ets(1:k-1), q );\n post = eval( ets(k+1:end), q );\n Td = trnorm(pre)*deriv*trnorm(post);\n J(:,j) = [ Td(1:3,4); vex(t2r(Td)) ];\n end\n end\n \n \n \n function T = deriv(ets, q)\n switch ets.type\n case ETS.RX\n T = r2t( skew([1 0 0])*rotx(q) );\n case ETS.RY\n T = r2t( skew([0 1 0])*roty(q) );\n case ETS.RZ\n T = r2t( skew([0 0 1])*rotz(q) );\n case ETS.TX\n T = transl(1, 0, 0);\n case ETS.TY\n T = transl(0, 1, 0);\n case ETS.TZ\n T = transl(0, 0, 1);\n end\n T(4,4) = 0;\n end\n \n \n%********************************************************************\n% D H F A C T O R\n%********************************************************************\n \n function xo = subs(ets, k, x)\n fprintf(' Subs: %s := %s\\n', char(ets(k)), char(x));\n xo = [ets(1:k-1) x ets(k+1:end)];\n end\n \n function k = find(ets, j)\n [~,k] = find([ets.joint] == j);\n end\n \n \n function n = njoints(ets)\n n = max([ets.joint]');\n end\n \n function b = isjoint(ets, j)\n b = [ets.joint] ~= 0;\n end\n \n function b = istrans(ets)\n b = ismember(ets.type, [ETS.TX ETS.TY ETS.TZ]);\n \n end\n \n function b = isrot(ets)\n b = ismember(ets.type, [ETS.RX ETS.RY ETS.RZ]);\n end\n \n function b = axis(ets)\n b = char( mod([ets.type],3) + 'x' );\n \n end\n \n function v = sametype(ets, next)\n v = ets.type == next.type;\n end\n \n \n function s = show(ets)\n for i=1:numel(ets)\n e = ets(i);\n s = sprintf('%s: type=%d, joint %d, val=%g. const=%s. sign=%d, sym=%s\\n', ...\n char(e), e.type, e.joint, e.val, e.constant, e.sign, e.symconstant);\n if nargout == 0\n disp(s);\n end\n end\n end\n \n function negate(ets)\n ets.constant = -ets.constant;\n \n s = ets.symconst;\n \n % add initial sign char if none\n if s(1) ~= '+' && s(1) ~= '-'\n s = ['+' s];\n end\n \n % go through the string and flip all sign chars\n kp = strfind(s, '+');\n kn = strfind(s, '-');\n s(kp) = '-';\n s(kn) = '+';\n \n % if inital sign is + remove it\n if s(1) == '+';\n s = s(2:end);\n end\n \n ets.symconst = s;\n end\n \n % methods from Element.java\n % *\tpublic boolean istrans()\n % *\tpublic boolean isrot()\n % *\tpublic int axis()\n % *\tpublic boolean isjoint() {\n % *\tpublic boolean factorMatch(int dhWhich, int i, int verbose) {\n % *\tpublic void add(Element e) {\n % *\tpublic Element(int ETS.TYpe, int constant) {\n % *\tpublic Element(int ETS.TYpe)\t// new of specified ETS.TYpe\n % *\n % *\tpublic static String toString(Element [] e) {\n % *\tpublic String argString() {\n % *\tpublic String toString() {\n % *\n % * Constructors:\n % *\tElement(Element e) \t// clone of argument\n % *\tElement(Element e, int ETS.TYpe, int sign) // clone of argument with new ETS.TYpe\n % *\tElement(Element e, int ETS.TYpe) // clone of argument with new ETS.TYpe\n % *\tElement(String s)\n \n \n \n function v = plus(ets, e)\n if isstring(ets) && isa(e, 'ETS')\n % string concatenate\n v = ets + char(e);\n end\n end\n \n function symPlus(ets, e)\n end\n \n function new = merge(a, b)\n if isjoint(a)\n new = ETS(a);\n new.val = num2str(eval(new.val + \"+\" + b.val));\n elseif isjoint(b)\n new = ETS(b);\n new.val = num2str(eval(new.val + \"+\" + a.val));\n else\n % two constants\n new = ETS(a);\n new.val = num2str(eval(new.val + \"+\" + b.val));\n new.symconstant = new.symconstant + \"+\" + b.symconstant;\n if eval(new.val) == 0\n new = [];\n end\n end\n if isempty(new)\n fprintf(' Merging: %s %s -> (nil)\\n', char(a), char(b));\n else\n fprintf(' Merging: %s %s -> %s\\n', char(a), char(b), char(new));\n end\n end\n \n\n function b = swap(ets, next, dhWhich)\n \n b = false\n \n % don't swap if both are joint variables\n \n if ets.isjoint() && next.isjoint()\n return\n end\n \n switch (dhWhich)\n case 'standard'\n % we want to sort terms into the order:\tRZ\tTX\tTZ\tRX\n \n if ((ets.type == ETS.TZ) && (next.type == ETS.TX)) || ...\n ((ets.type == ETS.TX) && (next.type == ETS.RX) && next.isjoint()) || ... % push constant translations through rotational joints of the same ETS.TYpe\n ((ets.type == ETS.TY) && (next.type == ETS.RY)) && next.isjoint() || ...\n ((ets.type == ETS.TZ) && (next.type == ETS.RZ)) && next.isjoint() || ...\n (~ets.isjoint() && (this.type == ETS.RX) && (next.type == ETS.TX)) || ...\n (~ets.isjoint() && (this.type == ETS.RY) && (next.type == ETS.TY)) ||....\n (~ets.isjoint() && ~next.isjoint() && (this.type == ETS.TZ) && (next.type == ETS.RZ)) || ...\n ((ets.type == ETS.TY) && (next.type == ETS.TZ)) || ... % move ETS.TY terms to the right\n ((ets.type == ETS.TY) && (next.type == ETS.TX))\n \n fprintf(['Swap: ' char(ets) ' <-> ' char(next)] );\n b = true;\n end\n case 'modified'\n if ((ets.type == ETS.RX) && (next.type == ETS.TX)) || ...\n ((ets.type == ETS.RY) && (next.type == ETS.TY)) || ...\n ((ets.type == ETS.RZ) && (next.type == ETS.TZ)) || ...\n ((ets.type == ETS.TZ) && (next.type == ETS.TX))\n \n fprintf(['Swap: ' char(ets) ' <-> ' char(next)] );\n b = true;\n end\n otherwise\n error('bad DH ETS.TYpe');\n end\n b = false;\n end\n \n \n % \t/**\n % \t * Substitute this transform for a triple of transforms\n % * that includes an ETS.RZ or ETS.TZ.\n % *\n % \t * @return\t- null if no substituion required\n % \t *\t\t\t- array of Elements to substitute\n % \t */\n function s = substituteToZ(ets, prev)\n \n switch ets.type\n \n \n case ETS.TX\n s(1) = ETS(ETS.RY, 90);\n s(2) = ETS(ets, ETS.TZ);\n s(3) = ETS(ETS.RY, -90);\n \n \n case ETS.TY\n % there are two options here\n if prev.type == ETS.RZ\n s(1) = ETS(ETS.RZ, 90);\n s(2) = ETS(ets, ETS.TX);\n s(3) = ETS(ETS.RZ, -90);\n else\n s(1) = ETS(ETS.RX, -90);\n s(2) = ETS(ets, ETS.TZ);\n s(3) = ETS(ETS.RX, 90);\n end\n \n case ETS.RX\n s(1) = ETS(ETS.RY, 90);\n s(2) = ETS(ets, ETS.RZ);\n s(3) = ETS(ETS.RY, -90);\n case ETS.RY\n s(1) = ETS(ETS.RX, -90);\n s(2) = ETS(ets, ETS.RZ);\n s(3) = ETS(ETS.RX, 90);\n \n case ETS.RY\n s(1) = ETS(ETS.RZ, 90);\n s(2) = ETS(ets, ETS.RX);\n s(3) = ETS(ETS.RZ, -90);\n otherwise\n s = [];\n end\n end\n \n function s = substituteTY(ets, k)\n \n pref = -1;\n \n try\n if ets(k+1).axis == 'x'\n pref = ETS.RX;\n end\n end\n \n \n try\n if ets(k+1).axis == 'z'\n pref = ETS.RZ;\n end\n end\n \n assert(pref >= 0, 'substituteTY, can''t decide');\n \n if pref == ETS.RX\n s(1) = ETS(ETS.RX, -90);\n s(2) = ETS(ets(k), ETS.TZ);\n s(3) = ETS(ETS.RX, 90);\n else\n s(1) = ETS(ETS.RZ, 90);\n s(2) = ETS(ets(k), ETS.TX);\n s(3) = ETS(ETS.RZ, -90);\n end\n \n end\n \n function s = substituteRY(ets)\n \n s(1) = ETS(ETS.RZ, 90);\n s(2) = ETS(ets, ETS.RX);\n s(3) = ETS(ETS.RZ, -90);\n end\n \n \n % \t/**\n % \t * Simple rewriting rule for adjacent transform pairs. Attempt to\n % \t * eliminate ETS.TY and ETS.RY.\n % \t * @param\tprevious element in list\n % \t * @return\t- null if no substituion required\n % \t *\t\t\t- array of Elements to subsitute\n % \t */\n function s = substituteY(this, prev, next)\n \n s = [];\n \n if (prev.isjoint() || e.isjoint())\n return\n end\n \n % note that if rotation is -90 we must make the displacement -ve */\n if ((prev.type == ETS.RX) && (this.type == ETS.TY))\n % RX.TY -> TZ.RX\n s(1) = ETS(this, ETS.TZ, prev.constant);\n s(2) = ETS(prev);\n elseif ((prev.type == ETS.RX) && (this.type == ETS.TZ))\n % RX.TZ -> TY.RX\n s(1) = ETS(this, ETS.TY, -prev.constant);\n s(2) = ETS(prev);\n elseif ((prev.type == ETS.RY) && (this.type == ETS.TX))\n % RY.TX-> TZ.RY\n s(1) = ETS(this, ETS.TZ, -prev.constant);\n s(2) = ETS(prev);\n elseif ((prev.type == ETS.RY) && (this.type == ETS.TZ))\n % RY.TZ-> TX.RY\n s(1) = ETS(this, ETS.TX, prev.constant);\n s(2) = ETS(prev);\n elseif ((prev.type == ETS.TY) && (this.type == ETS.RX))\n % TY.RX -> RX.TZ\n s(1) = ETS(this);\n s(2) = ETS(prev, ETS.TZ, -this.constant);\n %%return s;\n s = [];\n elseif ((prev.type == ETS.RY) && (this.type == ETS.RX))\n % RY(Q).RX -> RX.RZ(-Q)\n s(1) = ETS(this);\n s(2) = ETS(prev, ETS.RZ, -1);\n elseif ((prev.type == ETS.RX) && (this.type == ETS.RY))\n % RX.RY -> RZ.RX\n s(1) = ETS(this, ETS.RZ);\n s(2) = ETS(prev);\n elseif ((prev.type == ETS.RZ) && (this.type == ETS.RX))\n % RZ.RX -> RX.RY\n s(1) = ETS(this);\n s(2) = ETS(prev, ETS.RY);\n s = [];\n end\n end\n \n\n function out = mergeterms(ets)\n i = 1;\n while i < numel(ets)-1\n cur = ets(i);\n next = ets(i+1);\n if cur.sametype(next)\n new = merge(cur, next);\n if isempty(new)\n % cancelation\n ets(i:i+1) = [];\n else\n ets(i) = new;\n ets(i+1) = [];\n end\n else\n i = i+ 1;\n end\n\n end\n out = ets;\n end\n \n function out = ordering(ets)\n for i=1:numel(ets)-1\n cur = ets(i);\n next = ets(i+1);\n \n % TZ RZ -> RZ TZ\n if cur.type == ETS.TZ && next.type == ETS.RZ && next.isjoint()\n ets(i) = next;\n ets(i+1) = cur;\n fprintf(' Swap: %s <--> %s\\n', char(cur), char(next));\n end\n \n % RX TX -> TX RX\n if cur.type == ETS.RX && next.type == ETS.TX && ~next.isjoint()\n ets(i) = next;\n ets(i+1) = cur;\n fprintf(' Swap: %s <--> %s\\n', char(cur), char(next));\n end\n end\n out = ets;\n end\n \n function out = simplify(ets)\n fprintf('--------- simplify\\n');\n ets = mergeterms(ets);\n while 1\n len = numel(ets);\n \n ets = ordering(ets);\n ets = mergeterms(ets);\n \n if numel(ets) == len\n break;\n end\n end\n \n out = ets;\n end\n \n\n function v = contains(ets, which)\n w = ETS.name2type(which);\n for e = ets\n v = e.type == w;\n if v\n return\n end\n end\n end\n \n function dhfactor(ets)\n disp(char(ets))\n \n % find which joint to substitute\n fprintf('--------- align joints with z-axis\\n');\n fixup = find( ets.isjoint & ([ets.type] ~= ETS.RZ) );\n \n for k=fliplr(fixup) % work right to left so indices are not broken\n new = substituteToZ(ets(k));\n ets = subs(ets, k, new);\n end\n disp(char(ets))\n \n %\n ets = simplify(ets);\n disp(char(ets)) \n \n % now eliminate all Ry\n if ets.contains('Ry')\n fprintf('--------- eliminate RY\\n');\n \n fixup = find( [ets.type] == ETS.RY );\n \n for k=fliplr(fixup) % work right to left so indices are not broken\n new = substituteRY(ets(k));\n ets = subs(ets, k, new);\n end\n \n disp(char(ets))\n \n ets = simplify(ets);\n end\n \n % now eliminate all Ty\n if ets.contains('Ty')\n fprintf('--------- eliminate TY\\n');\n fixup = find( [ets.type] == ETS.TY );\n \n for k=fliplr(fixup) % work right to left so indices are not broken\n new = substituteTY(ets, k);\n ets = subs(ets, k, new);\n end\n \n disp(char(ets))\n \n ets = simplify(ets);\n end\n \n ets = ordering(ets);\n \n disp(char(ets))\n \n factorize(ets)\n end\n \n function nfactors = factorize(ets, mdh)\n if nargin < 2\n mdh = false;\n end\n verbose = true;\n nfactors = 0;\n \n out = [];\n \n for i=1:length(ets)\n j = i;\n jvars = 0; match = 0;\n \n % scan next 4 terms\n if verbose\n fprintf(\"start at \" + ets(i));\n end\n \n match = 0; jvars = 0; j = i;\n for f=1:4\n if j > length(ets)\n break;\n else\n e = ets(j);\n end\n \n if e.factormatch(f, mdh)\n j = j + 1;\n match = match + 1;\n if (e.isjoint())\n jvars = jvars + 1;\n end\n if jvars > 1\t% can only have 1 joint var per DH\n break;\n end\n end\n end\n \n if match == 0 || jvars == 0\n continue;\t\t% no DH subexpression found, keep looking\n end\n \n \n if verbose\n fprintf(\" found subexpression \" + match + \" \" + jvars + \"\\n\");\n end\n \n if jvars == 0\n continue;\n end\n \n first = i;\n last = j;\n if jvars > 1\n last = last - 1;\n end\n \n [first last]\n \n% dh = ETS();\n% dh.type = ETS.DH;\n% \n% for j=first:last\n% dh.add( this.get(i) );\n% this.remove(i);\n% end\n% \n% this.add(i, dh);\n% nfactors = nfactors + 1;\n% if verbose\n% fprintf(\" result: \" + dh);\n% end\n \n end\n end\n \n function match = factormatch(ets, i, mdh)\n \n if nargin < 2\n mdh = false;\n end\n \n if mdh\n dhFactors = [\n ETS.RX 0\n ETS.TX 0\n ETS.RZ 1\n ETS.RZ 1 ];\n else\n dhFactors = [\n ETS.RZ 1\n ETS.TX 0\n ETS.TZ 1\n ETS.RX 0 ];\n end\n \n match =\t(ets.type == dhFactors(i,1)) && ...\n ~((dhFactors(i,2) == 0) && ets.isjoint());\n \n fprintf(\" matching \" + ets + \" (i=\" + i + \") \" + \" to \" + ...\n op(dhFactors(i,1)) + \"<\" + dhFactors(i,2) + \">\" + ...\n \" -> \" + match + \"\\n\");\n end\n \n function new = \tadd(e1, e2)\n assert(e1.type == DH || e1.type == DHM, 'wrong element type');\n \n \n fprintf(\" adding: \" + e1 + \" += \" + e2);\n switch e2.type\n case RZ\n if e2.isjoint()\n e1.prismatic = 0;\n e1.var = e1.var;\n e1.offset = e1.constant;\n e1.theta = 0.0;\n else\n e1.theta = e1.constant;\n end\n case TX\n e1.A = e2.symconst;\n case TZ\n if e1.isjoint()\n e1.prismatic = 1;\n e1.var = e2.var;\n e1.D = null;\n else\n e1.D = e2.symconst;\n end\n case RX\n e1.alpha = e2.constant;\n otherwise\n \n error(\"cant factorize \" + e);\n end\n end\n end\n\n methods (Static)\n function t = name2type(name)\n switch lower(name)\n case 'rx', t = ETS.RX;\n case 'ry', t = ETS.RY;\n case 'rz', t = ETS.RZ;\n case 'tx', t = ETS.TX;\n case 'ty', t = ETS.TY;\n case 'tz', t = ETS.TZ;\n end\n end\n end\nend\n\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/ETS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.034100424362588755, "lm_q1q2_score": 0.017050212181294377}} {"text": "\nfunction r = foldl(list, identity, func)\n% VAL = FOLDL(ARRAY, ID, FUNC)\n% Perform a left fold over ARRAY with FUNC using ID as the identity.\n% FOLDL applies FUNC to the current identity (initially ID) and each item\n% of ARRAY successively. Thus, FOLDL iterates over ARRAY with FUNC. ID\n% is updated to be the result of this function. The final result of ID\n% is returned from the function.\n%\n% FOLDL is most simply viewed as the haskell code\n% foldl [] id f = id\n% foldl x:xs id f = foldl xs (f id x) f\n%\n% FOLDL and FOLDR are implemented as a loop for optimization purposes in\n% these libraries. FOLDL is tail recursive and thus more efficient on\n% most platforms that use the above functional definition.\n%\n% Examples of Common FOLDL uses:\n% sum(array) == foldl(array, 0, @(a,b) a + b)\n% all(array) == foldl(array, true, @(a,b) a && b)\n% any(array) == foldl(array, false, @(a,b) a || b)\n%\n\n if isempty(list)\n r = identity;\n return;\n end\n\n if iscell(list)\n for i = 1:numel(list)\n identity = func(identity, list{i});\n end\n else\n for i = 1:numel(list)\n identity = func(identity, list(i));\n end\n end\n\n r = identity;\nend\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/18835-functional-library/foldl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.046033904362384165, "lm_q1q2_score": 0.016542934689570073}} {"text": "%qrscorrect() - Correct for false positive and negative QRS peaks\n% and align peaks for maximum correlation.\n%\n% Usage:\n% >>Peaks=qrscorrect(Peaks,Ecg,fs)\n%\n% Inputs:\n% Peaks: Indeces of located QRS peaks\n% Ecg: vector of ecg data\n% sampling frequency.\n%\n% Ouput:\n% Peaks: Corrected peaks\n%\n% Note: progress bar designed to work as part of fmrib_qrsdetect.\n%\n% Author: Rami Niazy, FMRIB Centre, University of Oxford.\n%\n% \n%\n% Copyright (c) 2004 Rami Niazy, FMRIB Centre, University of Oxford.\n%\n\n\n% Copyright (C) 2004 Rami K. Niazy, FMRIB Centre, University of Oxford\n% rami@fmrib.ox.ac.uk\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%\n\n% Dec 23, 2004\n% use binary prcorr2\n% instead of corrcoef\n\n% Dec 17, 2004\n% use corrcoef instead of\n% corr2\n\n% Dec 15, 2004\n% Median of all peaks used\n% for correction instead of\n% section median.\n\n% Nov 4, 2004\n% Changed order of correction\n% Added additional alignment\n\n% Nov 3, 2004\n% Added check and \n% adjustment of edge peaks clearance\n\n% Oct 26, 2004\n% Fixed bug for non-int fs case\n\nfunction Peaks=qrscorrect(Peaks,Ecg,fs)\n\n% init\n%------\nP=zeros(1,length(Ecg));\nP(Peaks)=1;\ndP_std=std(diff(Peaks));\ndP_med=median(diff(Peaks));\npad=round(5*fs);\nsecL=round(10*fs);\nsections=floor(length(P)/secL)+1;\n\nif length(P((sections-1)*secL+1:end))=barth\n if percentdone>=25 & Flag25==0\n fprintf('25%% ')\n Flag25=1;\n elseif percentdone>=50 & Flag50==0\n fprintf('50%% ')\n Flag50=1;\n elseif percentdone>=75 & Flag75==0\n fprintf('75%% ')\n Flag75=1;\n elseif percentdone==100\n fprintf('100%%\\n')\n else\n fprintf('.')\n end\n\n while barth<=percentdone\n barth=barth+barth_step;\n end\n if barth>100\n barth=100;\n end\n end \nend\n\n\n%Check Edge Peaks\n%----------------\nPeaks=find(P==1);\npc1=2;\npc2=1;\n\nwhile (pc1>1 | pc2>0)\n\tdP=diff(Peaks);\n\thwinl=round(mean(dP)/2);\n\tsearchw=round(0.33*mean(dP));\n \n\tpc1=1;\n\tif length(Peaks)>5\n for p=1:5\n try \n tmp=Ecg(Peaks(p)-hwinl-searchw:Peaks(p)+hwinl);\n break;\n catch\n pc1=pc1+1;\n end\n end\n\tend\n\t\n\tif pc1>1\n Peaks(1:pc1-1)=[];\n\tend\n\t\n\tpc2=0;\n\tif length(Peaks)>5\n for p=length(Peaks):-1:length(Peaks-4)\n try \n tmp=Ecg(Peaks(p)-hwinl:Peaks(p)+hwinl+searchw);\n break;\n catch\n pc2=pc2+1;\n end\n end\n\tend\n\t\n\tif pc2>0\n Peaks(end-pc2:end)=[];\n\tend\nend\n\n%Finding corrected peaks\n%-----------------------\nsearchwL=length(searchw);\npeaksL=length(Peaks);\nqrs=zeros(hwinl*2+1,peaksL);\nqrs2=zeros(hwinl*2+1,peaksL);\nbarth=2;\n\n% Find average Heart Beat for use in alignment\n%---------------------------------------------\nfor p=1:peaksL\n qrs(:,p)=Ecg(Peaks(p)-hwinl:Peaks(p)+hwinl);\nend\n\nm_qrs=mean(qrs,2);\n% figure;plot(qrs)\n\n% Align Peaks (1)\n%----------------\nfor p=1:peaksL\n \n %wait bar\n if p==1\n barth=5;\n barth_step=barth;\n Flag25=0;\n Flag50=0;\n Flag75=0;\n fprintf('\\nStage 3 of 5: Aligning QRS Peaks (1)\\n');\n end\n \n %-----------------calc------------------------------------------\n \n ppn=1;\n for B=Peaks(p)-searchw:Peaks(p)+searchw\n C(ppn)=prcorr2(Ecg(B-hwinl:B+hwinl),m_qrs);;\n ppn=ppn+1;\n\tend\n\t[CV,CP]=max(C);\n\tBeta=CP-(searchw+1);\n\tPeaks(p)=Peaks(p)+Beta;\n \n %---------------------------------------------------------------\n %update wait bar\n percentdone=floor(p*100/(peaksL));\n if floor(percentdone)>=barth\n if percentdone>=25 & Flag25==0\n fprintf('25%% ')\n Flag25=1;\n elseif percentdone>=50 & Flag50==0\n fprintf('50%% ')\n Flag50=1;\n elseif percentdone>=75 & Flag75==0\n fprintf('75%% ')\n Flag75=1;\n elseif percentdone==100\n fprintf('100%%\\n')\n else\n fprintf('.')\n end\n\n while barth<=percentdone\n barth=barth+barth_step;\n end\n if barth>100\n barth=100;\n end\n end \nend\nbarth=2;\nP=zeros(1,length(Ecg));\nP(Peaks)=1;\n\n% Correct for FN\n%---------------\nfor s=1:sections\n \n %wait bar\n if s==1\n barth=5;\n barth_step=barth;\n Flag25=0;\n Flag50=0;\n Flag75=0;\n fprintf('\\nStage 4 of 5: Correcting for False Negative detection.\\n');\n end\n \n %-----------------calc------------------------------------------\n \n \n \n f_flag=0;\n if s==1\n sec=P(1:secL+pad);\n elseif s==sections\n sec=P((s-1)*secL+1-pad:end);\n else\n sec=P((s-1)*secL+1-pad:s*secL+pad);\n end\n \n sec_P=find(sec==1);\n sec_dP=diff(sec_P);\n dP_med=median(sec_dP);\n \n false_n=1;\n while ~isempty(false_n)\n false_n=find(sec_dP>(1.5*dP_med));\n if ~isempty(false_n)\n f_flag=1;\n sec(sec_P(false_n(1))+round(dP_med))=1;%sec_dP(false_n(1)-1)\n sec_P=find(sec==1);\n sec_dP=diff(sec_P);\n false_n=find(sec_dP>(1.5*dP_med));\n end\n end\n \n \n if f_flag==1\n if s==1\n P(1:secL+pad)=sec;\n elseif s==sections\n P((s-1)*secL+1-pad:end)=sec;\n else\n P((s-1)*secL+1-pad:s*secL+pad)=sec;\n end\n end\n \n %---------------------------------------------------------------\n %update wait bar\n percentdone=floor(s*100/sections);\n if floor(percentdone)>=barth\n if percentdone>=25 & Flag25==0\n fprintf('25%% ')\n Flag25=1;\n elseif percentdone>=50 & Flag50==0\n fprintf('50%% ')\n Flag50=1;\n elseif percentdone>=75 & Flag75==0\n fprintf('75%% ')\n Flag75=1;\n elseif percentdone==100\n fprintf('100%%\\n')\n else\n fprintf('.')\n end\n\n while barth<=percentdone\n barth=barth+barth_step;\n end\n if barth>100\n barth=100;\n end\n end\nend\n\nbarth=2;\nPeaks=find(P==1);\npeaksL=length(Peaks);\nbarth=2;\n% Align Peaks (2)\n%----------------\nfor p=2:peaksL-1\n \n %wait bar\n if p==2\n barth=5;\n barth_step=barth;\n Flag25=0;\n Flag50=0;\n Flag75=0;\n fprintf('\\nStage 5 of 5: Aligning QRS Peaks (2)\\n');\n end\n \n %-----------------calc------------------------------------------\n \n ppn=1;\n for B=Peaks(p)-searchw:Peaks(p)+searchw\n C(ppn)=prcorr2(Ecg(B-hwinl:B+hwinl),m_qrs);\n ppn=ppn+1;\n\tend\n\t[CV,CP]=max(C);\n\tBeta=CP-(searchw+1);\n\tPeaks(p)=Peaks(p)+Beta;\n \n %---------------------------------------------------------------\n %update wait bar\n percentdone=floor((p-1)*100/(peaksL-2));\n if floor(percentdone)>=barth\n if percentdone>=25 & Flag25==0\n fprintf('25%% ')\n Flag25=1;\n elseif percentdone>=50 & Flag50==0\n fprintf('50%% ')\n Flag50=1;\n elseif percentdone>=75 & Flag75==0\n fprintf('75%% ')\n Flag75=1;\n elseif percentdone==100\n fprintf('100%%\\n')\n else\n fprintf('.')\n end\n\n while barth<=percentdone\n barth=barth+barth_step;\n end\n if barth>100\n barth=100;\n end\n end \nend\n\n% for p=2:peaksL-1\n% qrs2(:,p-1)=Ecg(Peaks(p)-hwinl:Peaks(p)+hwinl);\n% end\n% figure;plot(qrs2);\nreturn;\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/fmrib1.21/qrscorrect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.04272219556589849, "lm_q1q2_score": 0.016444291912331984}} {"text": "function hcell_node_display ( node_xy_file_name )\n\n%*****************************************************************************80\n%\n%% HCELL_NODE_DISPLAY displays the nodes in the H-Cell.\n%\n% Usage:\n%\n% hcell_node_display ( node_xy_file_name )\n%\n% A typical invocation might be\n%\n% hcell_node_display ( 'xy3.txt' )\n%\n% or\n%\n% hcell_node_display ( 'xy6.txt' )\n%\n% But if you simply say \n%\n% hcell_node_display\n%\n% the program will give you a chance to enter the file names\n% interactively.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, filename NODE_XY_FILE_NAME, the name of a file \n% containing the XY coordinates of nodes.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HCELL_NODE_DISPLAY:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Display the nodes in the HCELL problem.\\n' );\n%\n% Do we have the XY file?\n%\n if ( nargin < 1 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HCELL_NODE_DISPLAY:\\n' );\n node_xy_file_name = input ( 'Enter the name of the XY coordinate file:' );\n\n end\n\n [ m1, n1 ] = r8mat_header_read ( node_xy_file_name );\n\n node_xy = r8mat_data_read ( node_xy_file_name, m1, n1 );\n%\n% Plot the nodes.\n% \n plot ( node_xy(1,:), node_xy(2,:), 'bo' )\n%\n% Add the boundary of the region to the plot.\n%\n hcell_boundary_add ( 'r' );\n%\n% Add the invisible bounding box.\n%\n hcell_box_add ( 'w' )\n\n axis equal\n \n title ( 'Node coordinates' )\n\n text ( 45.0, 20.0, node_xy_file_name )\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HCELL_NODE_DISPLAY:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction column_num = file_column_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_COLUMN_COUNT counts the columns in the first line of a file.\n%\n% Discussion:\n%\n% The file is assumed to be a simple text file.\n%\n% Most lines of the file are presumed to consist of COLUMN_NUM words,\n% separated by spaces. There may also be some blank lines, and some \n% comment lines, which have a \"#\" in column 1.\n%\n% The routine tries to find the first non-comment non-blank line and\n% counts the number of words in that line.\n%\n% If all lines are blanks or comments, it goes back and tries to analyze\n% a comment line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the file.\n%\n% Output, integer COLUMN_NUM, the number of columns in the file.\n%\n FALSE = 0;\n TRUE = 1;\n%\n% Open the file.\n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_COLUMN_COUNT - Error!' );\n column_num = -1;\n return;\n end\n%\n% Read one line, but skip blank lines and comment lines.\n% Use FGETL so we drop the newline character!\n%\n got_one = FALSE;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( s_len_trim ( line ) == 0 )\n\n elseif ( line(1) == '#' )\n\n else\n got_one = TRUE;\n break;\n end\n\n end\n\n fclose ( input_unit );\n\n if ( got_one == FALSE ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\\n' );\n fprintf ( 1, ' The file does not seem to contain any data.\\n' );\n column_num = -1;\n return;\n end\n\n column_num = s_word_count ( line );\n\n return\nend\nfunction row_num = file_row_count ( input_file_name )\n\n%*****************************************************************************80\n%\n%% FILE_ROW_COUNT counts the number of row records in a file.\n%\n% Discussion:\n%\n% Each input line is a \"RECORD\".\n%\n% The records are divided into three groups:\n% \n% * BLANK LINES (nothing but blanks)\n% * COMMENT LINES (begin with a '#')\n% * DATA RECORDS (anything else)\n%\n% The value returned by the function is the number of data records.\n%\n% By the way, if the MATLAB routine FGETS is used, instead of\n% FGETL, then the variable LINE will include line termination \n% characters, which means that a blank line would not actually\n% have zero characters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILE_NAME, the name of the input file.\n%\n% Output, integer ROW_NUM, the number of rows found. \n%\n input_unit = fopen ( input_file_name );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FILE_ROW_COUNT - Error!\\n' );\n fprintf ( 1, ' Could not open the file \"%s\".\\n', input_file_name );\n error ( 'FILE_ROW_COUNT - Error!' );\n row_num = -1;\n return;\n end\n\n blank_num = 0;\n comment_num = 0;\n row_num = 0;\n \n record_num = 0;\n\n while ( 1 )\n\n line = fgetl ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n record_num = record_num + 1;\n record_length = s_len_trim ( line );\n \n if ( record_length <= 0 )\n blank_num = blank_num + 1;\n elseif ( line(1) == '#' )\n comment_num = comment_num + 1;\n else\n row_num = row_num + 1;\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction hcell_box_add ( box_color )\n\n%*****************************************************************************80\n%\n%% HCELL_BOX_ADD adds a box around the HCELL region.\n%\n% Discussion:\n%\n% This routine can only ADD graphics to an already existing plot.\n% So call PLOT first and then this routine.\n%\n% The box is normally drawn with the color white ('w').\n% In this case, it doesn't actually appear on the screen.\n% However, it does force MATLAB to make the picture bigger,\n% giving us space to write some titles.\n%\n% Usage:\n%\n% hcell_box_add ( box_color )\n%\n% A typical invocation might be\n%\n% hcell_box_add ( 'w' )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, character BOX_COLOR, the color to be used to draw the box.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HCELL_BOX_ADD:\\n' );\n fprintf ( 1, ' Add a bounding box to a plot of the HCELL problem.\\n' );\n%\n% Do we have a color?\n%\n if ( nargin < 1 )\n box_color = 'w'\n end\n%\n% Set the coordinates of the invisible bounding box that\n% allows us to display the file name within the plot area.\n%\n box_x = [ -5.00, 110.00, 110.00, -5.00, -5.00 ];\n box_y = [ -5.00, -5.00, 21.00, 21.00, -5.00 ];\n\n line ( box_x, box_y, 'color', box_color )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HCELL_BOX_ADD:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\nfunction table = r8mat_data_read ( input_filename, m, n )\n\n%*****************************************************************************80\n%\n%% R8MAT_DATA_READ reads data from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Input, integer M, N, the number of rows and columns of data.\n%\n% Output, real TABLE(M,N), the point coordinates.\n%\n table = [];\n%\n% Build up the format string for reading M real numbers.\n%\n string = ' ';\n\n for i = 0 : m\n string = strcat ( string, ' %f' );\n end\n\n input_unit = fopen ( input_filename );\n\n if ( input_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_DATA_READ - Error!\\n' );\n fprintf ( 1, ' Could not open the file.\\n' );\n error ( 'R8MAT_DATA_READ - Error!' );\n return;\n end\n\n i = 0;\n\n while ( i < n )\n\n line = fgets ( input_unit );\n\n if ( line == -1 )\n break;\n end\n\n if ( line(1) == '#' )\n\n elseif ( s_len_trim ( line ) == 0 )\n \n else\n\n [ x, count ] = sscanf ( line, string );\n\n if ( count == m )\n i = i + 1;\n table(1:m,i) = x(1:m);\n end\n\n end\n\n end\n\n fclose ( input_unit );\n\n return\nend\nfunction [ m, n ] = r8mat_header_read ( input_filename )\n\n%*****************************************************************************80\n%\n%% R8MAT_HEADER_READ reads the header from an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string INPUT_FILENAME, the name of the input file.\n%\n% Output, integer M, the spatial dimension.\n%\n% Output, integer N, the number of points.\n%\n m = file_column_count ( input_filename );\n\n if ( m <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data columns in\\n' );\n fprintf ( 1, ' the file %s.\\n', input_filename );\n end\n\n n = file_row_count ( input_filename );\n\n if ( n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\\n' );\n fprintf ( 1, ' There was some kind of I/O problem while trying\\n' );\n fprintf ( 1, ' to count the number of data rows in\\n' );\n fprintf ( 1, ' the file %s\\n', input_filename );\n end\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/hcell_flow_display/hcell_node_display.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.05834584593319027, "lm_q1q2_score": 0.016418847512551717}} {"text": "function varargout = subsref(F, index)\n%SUBSREF BALLFUNV subsref.\n%\n% ( )\n% F(X,Y,Z) returns the values of the BALLFUNV F evaluated on the array \n% (X,Y,Z) in cartesian coordinates. \n%\n% F(R, L, TH, 'spherical') returns the values of the BALLFUNV F evaluated\n% on the array (R,TH,LAM) in spherical coordinates. \n%\n% F(K) returns the first component of F if K = 1, the second if K = 2, and\n% the third if K = 3.\n%\n% F(R, :, :, 'spherical') returns a SPHEREFUNV representing the BALLFUNV \n% F along a radial shell. \n%\n% F(:, :, :) returns F.\n%\n% .\n% F.PROP returns the property PROP of F as defined by GET(F,'PROP').\n%\n% { }\n% Throws an error.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% check for empty CHEBFUN2V object.\nif ( isempty(F) )\n varargout = {[]};\n return\nend\n\n% Recursive going through the ref structure:\nidx = index(1).subs;\nswitch index(1).type\n \n case '.'\n % Call GET() for .PROP access.\n out = get(F, idx);\n if ( numel(index) > 1 )\n % Recurse on SUBSREF():\n index(1) = [];\n out = subsref(out, index);\n end\n varargout = {out};\n \n case '()'\n if ( isa(idx{1}, 'double') && numel(idx)==1 )\n Fc = F.comp;\n if all( idx{1} == 1 )\n varargout = {Fc{1}};\n elseif ( all( idx{1} == 2 ) )\n varargout = {Fc{2}};\n elseif ( ( all(idx{1} == 3) ) )\n varargout = {Fc{3}};\n else\n error('CHEBFUN:BALLFUNV:subsref:index', ...\n 'BALLFUNV only contains three components');\n end\n else\n % F(X,Y,Z), F(X,Y,Z,str), etc. \n Fc = F.comp; \n v1 = subsref(Fc{1}, index); \n v2 = subsref(Fc{2}, index);\n v3 = subsref(Fc{3}, index);\n varargout = {[v1 ; v2 ; v3]};\n end\n \n otherwise\n error('CHEBFUN:BALLFUNV:subsref:unexpectedType', ...\n ['??? Unexpected index.type of ' index(1).type]);\n \nend\n\n% Recurse down:\nif ( numel(index) > 1 )\n index(1) = [];\n varargout = { subsref( varargout{ : }, index ) };\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfunv/subsref.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.03622005495467345, "lm_q1q2_score": 0.016417169043974132}} {"text": "function mpc = toggle_dcline(mpc, on_off)\n%TOGGLE_DCLINE Enable, disable or check status of DC line modeling.\n% MPC = TOGGLE_DCLINE(MPC, 'on')\n% MPC = TOGGLE_DCLINE(MPC, 'off')\n% T_F = TOGGLE_DCLINE(MPC, 'status')\n%\n% Enables, disables or checks the status of a set of OPF userfcn\n% callbacks to implement DC lines as a pair of linked generators.\n% While it uses the OPF extension mechanism, this implementation\n% works for simple power flow as well as OPF problems.\n%\n% These callbacks expect to find a 'dcline' field in the input MPC,\n% where MPC.dcline is an ndc x 17 matrix with columns as defined\n% in IDX_DCLINE, where ndc is the number of DC lines.\n%\n% The 'int2ext' callback also packages up flow results and stores them\n% in appropriate columns of MPC.dcline.\n%\n% NOTE: Because of the way this extension modifies the number of\n% rows in the gen and gencost matrices, caution must be taken\n% when using it with other extensions that deal with generators.\n%\n% Examples:\n% mpc = loadcase('t_case9_dcline');\n% mpc = toggle_dcline(mpc, 'on');\n% results1 = runpf(mpc);\n% results2 = runopf(mpc);\n%\n% See also IDX_DCLINE, ADD_USERFCN, REMOVE_USERFCN, RUN_USERFCN.\n\n% MATPOWER\n% Copyright (c) 2011-2016, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\nif strcmp(upper(on_off), 'ON')\n %% define named indices into data matrices\n c = idx_dcline;\n\n %% check for proper input data\n if ~isfield(mpc, 'dcline') || size(mpc.dcline, 2) < c.LOSS1\n error('toggle_dcline: case must contain a ''dcline'' field, an ndc x %d matrix.', c.LOSS1);\n end\n if isfield(mpc, 'dclinecost') && size(mpc.dcline, 1) ~= size(mpc.dclinecost, 1)\n error('toggle_dcline: number of rows in ''dcline'' field (%d) and ''dclinecost'' field (%d) do not match.', ...\n size(mpc.dcline, 1), size(mpc.dclinecost, 1));\n end\n l0 = mpc.dcline(:, c.LOSS0);\n l1 = mpc.dcline(:, c.LOSS1);\n k = find( (l0 + l1 .* mpc.dcline(:, c.PMIN) < 0) | ...\n (l0 + l1 .* mpc.dcline(:, c.PMAX) < 0) );\n if ~isempty(k)\n warning('toggle_dcline: loss can be negative for DC line from bus %d to %d\\n', ...\n [mpc.dcline(k, c.F_BUS:c.T_BUS)]');\n end\n\n %% add callback functions\n %% note: assumes all necessary data included in 1st arg (mpc, om, results)\n %% so, no additional explicit args are needed\n mpc = add_userfcn(mpc, 'ext2int', @userfcn_dcline_ext2int);\n mpc = add_userfcn(mpc, 'formulation', @userfcn_dcline_formulation);\n mpc = add_userfcn(mpc, 'int2ext', @userfcn_dcline_int2ext);\n mpc = add_userfcn(mpc, 'printpf', @userfcn_dcline_printpf);\n mpc = add_userfcn(mpc, 'savecase', @userfcn_dcline_savecase);\n mpc.userfcn.status.dcline = 1;\nelseif strcmp(upper(on_off), 'OFF')\n mpc = remove_userfcn(mpc, 'savecase', @userfcn_dcline_savecase);\n mpc = remove_userfcn(mpc, 'printpf', @userfcn_dcline_printpf);\n mpc = remove_userfcn(mpc, 'int2ext', @userfcn_dcline_int2ext);\n mpc = remove_userfcn(mpc, 'formulation', @userfcn_dcline_formulation);\n mpc = remove_userfcn(mpc, 'ext2int', @userfcn_dcline_ext2int);\n mpc.userfcn.status.dcline = 0;\nelseif strcmp(upper(on_off), 'STATUS')\n if isfield(mpc, 'userfcn') && isfield(mpc.userfcn, 'status') && ...\n isfield(mpc.userfcn.status, 'dcline')\n mpc = mpc.userfcn.status.dcline;\n else\n mpc = 0;\n end\nelse\n error('toggle_dcline: 2nd argument must be ''on'', ''off'' or ''status''');\nend\n\n\n%%----- ext2int ------------------------------------------------------\nfunction mpc = userfcn_dcline_ext2int(mpc, mpopt, args)\n%\n% mpc = userfcn_dcline_ext2int(mpc, mpopt, args)\n%\n% This is the 'ext2int' stage userfcn callback that prepares the input\n% data for the formulation stage. It expects to find a 'dcline' field\n% in mpc as described above. The optional args are not currently used.\n% It adds two dummy generators for each in-service DC line, with the\n% appropriate upper and lower generation bounds and corresponding\n% entries in gencost. It also expands columns of any A and N matrices\n% accordingly, if present.\n\n%% define named indices into data matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\nc = idx_dcline;\n\n%% initialize some things\nif isfield(mpc, 'dclinecost')\n havecost = 1;\nelse\n havecost = 0;\nend\n\n%% save version with external indexing\nmpc.order.ext.dcline = mpc.dcline; %% external indexing\nif havecost\n mpc.order.ext.dclinecost = mpc.dclinecost; %% external indexing\nend\n\n%% work with only in-service DC lines\nmpc.order.dcline.status.on = find(mpc.dcline(:, c.BR_STATUS) > 0);\nmpc.order.dcline.status.off = find(mpc.dcline(:, c.BR_STATUS) <= 0);\n\n%% remove out-of-service DC lines\ndc = mpc.dcline(mpc.order.dcline.status.on, :); %% only in-service DC lines\nif havecost\n dcc = mpc.dclinecost(mpc.order.dcline.status.on, :); %% only in-service DC lines\n mpc.dclinecost = dcc;\nend\nndc = size(dc, 1); %% number of in-service DC lines\no = mpc.order;\n\n%%----- convert stuff to internal indexing -----\ndc(:, c.F_BUS) = o.bus.e2i(dc(:, c.F_BUS));\ndc(:, c.T_BUS) = o.bus.e2i(dc(:, c.T_BUS));\nmpc.dcline = dc;\n\n%%----- create gens to represent DC line terminals -----\n%% ensure consistency of initial values of PF, PT and losses\n%% (for simple power flow cases)\ndc(:, c.PT) = dc(:, c.PF) - (dc(:, c.LOSS0) + dc(:, c.LOSS1) .* dc(:, c.PF));\n\n%% create gens\nfg = zeros(ndc, size(mpc.gen, 2));\nfg(:, MBASE) = 100;\nfg(:, GEN_STATUS) = dc(:, c.BR_STATUS); %% status (should be all 1's)\nfg(:, PMIN) = -Inf;\nfg(:, PMAX) = Inf;\ntg = fg;\nfg(:, GEN_BUS) = dc(:, c.F_BUS); %% from bus\ntg(:, GEN_BUS) = dc(:, c.T_BUS); %% to bus\nfg(:, PG) = -dc(:, c.PF); %% flow (extracted at \"from\")\ntg(:, PG) = dc(:, c.PT); %% flow (injected at \"to\")\nfg(:, QG) = dc(:, c.QF); %% VAr injection at \"from\"\ntg(:, QG) = dc(:, c.QT); %% VAr injection at \"to\"\nfg(:, VG) = dc(:, c.VF); %% voltage set-point at \"from\"\ntg(:, VG) = dc(:, c.VT); %% voltage set-point at \"to\"\nk = find(dc(:, c.PMIN) >= 0); %% min positive direction flow\nif ~isempty(k) %% contrain at \"from\" end\n fg(k, PMAX) = -dc(k, c.PMIN); %% \"from\" extraction lower lim\nend\nk = find(dc(:, c.PMAX) >= 0); %% max positive direction flow\nif ~isempty(k) %% contrain at \"from\" end\n fg(k, PMIN) = -dc(k, c.PMAX); %% \"from\" extraction upper lim\nend\nk = find(dc(:, c.PMIN) < 0); %% max negative direction flow\nif ~isempty(k) %% contrain at \"to\" end\n tg(k, PMIN) = dc(k, c.PMIN); %% \"to\" injection lower lim\nend\nk = find(dc(:, c.PMAX) < 0); %% min negative direction flow\nif ~isempty(k) %% contrain at \"to\" end\n tg(k, PMAX) = dc(k, c.PMAX); %% \"to\" injection upper lim\nend\nfg(:, QMIN) = dc(:, c.QMINF); %% \"from\" VAr injection lower lim\nfg(:, QMAX) = dc(:, c.QMAXF); %% \"from\" VAr injection upper lim\ntg(:, QMIN) = dc(:, c.QMINT); %% \"to\" VAr injection lower lim\ntg(:, QMAX) = dc(:, c.QMAXT); %% \"to\" VAr injection upper lim\n\n%% fudge PMAX a bit if necessary to avoid triggering\n%% dispatchable load constant power factor constraints\nfg(isload(fg), PMAX) = -1e-6;\ntg(isload(tg), PMAX) = -1e-6;\n\n%% set all terminal buses to PV (except ref bus)\nrefbus = find(mpc.bus(:, BUS_TYPE) == REF);\nmpc.bus(dc(:, c.F_BUS), BUS_TYPE) = PV;\nmpc.bus(dc(:, c.T_BUS), BUS_TYPE) = PV;\nmpc.bus(refbus, BUS_TYPE) = REF;\n\n%% expand A and N, if present\nnb = size(mpc.bus, 1);\nng = size(mpc.gen, 1);\nif isfield(mpc, 'A') && ~isempty(mpc.A)\n [mA, nA] = size(mpc.A);\n if nA >= 2*nb + 2*ng %% assume AC dimensions\n mpc.A = [ mpc.A(:, 1:2*nb+ng) sparse(mA, 2*ndc) ...\n mpc.A(:, 2*nb+ng+(1:ng)) sparse(mA, 2*ndc) ...\n mpc.A(:, (2*nb+2*ng+1:nA)) ];\n else %% assume DC dimensions\n mpc.A = [ mpc.A(:, 1:nb+ng) sparse(mA, 2*ndc) ...\n mpc.A(:, (nb+ng+1:nA)) ];\n end\nend\nif isfield(mpc, 'N') && ~isempty(mpc.N)\n [mN, nN] = size(mpc.N);\n if nN >= 2*nb + 2*ng %% assume AC dimensions\n mpc.N = [ mpc.N(:, 1:2*nb+ng) sparse(mN, 2*ndc) ...\n mpc.N(:, 2*nb+ng+(1:ng)) sparse(mN, 2*ndc) ...\n mpc.N(:, (2*nb+2*ng+1:nN)) ];\n else %% assume DC dimensions\n mpc.N = [ mpc.N(:, 1:nb+ng) sparse(mN, 2*ndc) ...\n mpc.N(:, (nb+ng+1:nN)) ];\n end\nend\n\n%% append dummy gens\nmpc.gen = [mpc.gen; fg; tg];\n\n%% gencost\nif isfield(mpc, 'gencost') && ~isempty(mpc.gencost)\n ngcc = size(mpc.gencost, 2); %% dimensions of gencost\n [pc, qc] = pqcost(mpc.gencost, ng); %% split out re/active costs\n if havecost %% user has provided costs\n ndccc = size(dcc, 2); %% number of dclinecost columns\n ccc = max([ngcc; ndccc]); %% number of columns in new gencost\n if ccc > ngcc %% right zero-pad gencost\n pc = [pc zeros(ng, ccc-ngcc)];\n if ~isempty(qc) %% pad Qg costs, too\n qc = [qc zeros(ng, ccc-ngcc)];\n end\n ngcc = ccc;\n end\n\n %% flip function across vertical axis and append to gencost\n %% (PF for DC line = -PG for dummy gen at \"from\" bus)\n for k = 1:ndc\n if dcc(k, MODEL) == POLYNOMIAL\n nc = dcc(k, NCOST);\n temp = dcc(k, NCOST+(1:nc));\n %% flip sign on coefficients of odd terms\n %% (every other starting with linear term,\n %% that is, the next to last one)\n temp((nc-1):-2:1) = -temp((nc-1):-2:1);\n else %% dcc(k, MODEL) == PW_LINEAR\n nc = dcc(k, NCOST);\n temp = dcc(k, NCOST+(1:2*nc));\n %% switch sign on horizontal coordinate\n xx = -temp(1:2:2*nc);\n yy = temp(2:2:2*nc);\n temp(1:2:2*nc) = xx(end:-1:1);\n temp(2:2:2*nc) = yy(end:-1:1);\n end\n padding = zeros(1, ngcc-NCOST-length(temp));\n gck = [dcc(k, 1:NCOST) temp padding];\n \n %% append to gencost\n pc = [pc; gck];\n end\n %% define zero cost for \"to\" end gen\n dcgc = ones(ndc, 1) * [2 0 0 2 zeros(1, ngcc-4)];\n else\n %% use zero cost as default on \"from\" end gen\n dcgc = ones(ndc, 1) * [2 0 0 2 zeros(1, ngcc-4)];\n pc = [pc; dcgc];\n end\n %% always use zero cost on \"to\" end gen\n pc = [pc; dcgc];\n\n %% reassemble gencost\n if ~isempty(qc)\n qc = [qc; dcgc; dcgc]; %% always use zero cost Qg, both ends\n mpc.gencost = [pc; qc];\n else\n mpc.gencost = pc;\n end\nend\n\n\n%%----- formulation --------------------------------------------------\nfunction om = userfcn_dcline_formulation(om, mpopt, args)\n%\n% om = userfcn_dcline_formulation(om, mpopt, args)\n%\n% This is the 'formulation' stage userfcn callback that defines the\n% user constraints for the dummy generators representing DC lines.\n% It expects to find a 'dcline' field in the mpc stored in om, as\n% described above. By the time it is passed to this callback,\n% MPC.dcline should contain only in-service lines and the from and\n% two bus columns should be converted to internal indexing. The\n% optional args are not currently used.\n%\n% If Pf, Pt and Ploss are the flow at the \"from\" end, flow at the\n% \"to\" end and loss respectively, and L0 and L1 are the linear loss\n% coefficients, the the relationships between them is given by:\n% Pf - Ploss = Pt\n% Ploss = L0 + L1 * Pf\n% If Pgf and Pgt represent the injections of the dummy generators\n% representing the DC line injections into the network, then\n% Pgf = -Pf and Pgt = Pt, and we can combine all of the above to\n% get the following constraint on Pgf ang Pgt:\n% -Pgf - (L0 - L1 * Pgf) = Pgt\n% which can be written:\n% -L0 <= (1 - L1) * Pgf + Pgt <= -L0\n\n%% define named indices into data matrices\nc = idx_dcline;\n\n%% initialize some things\nmpc = om.get_mpc();\ndc = mpc.dcline;\nndc = size(dc, 1); %% number of in-service DC lines\nng = size(mpc.gen, 1) - 2*ndc; %% number of original gens/disp loads\n\n%% constraints\nnL0 = -dc(:, c.LOSS0) / mpc.baseMVA;\nL1 = dc(:, c.LOSS1);\nAdc = [sparse(ndc, ng) spdiags(1-L1, 0, ndc, ndc) speye(ndc, ndc)];\n\n%% add them to the model\nom.add_lin_constraint('dcline', Adc, nL0, nL0, {'Pg'});\n\n\n%%----- int2ext ------------------------------------------------------\nfunction results = userfcn_dcline_int2ext(results, mpopt, args)\n%\n% results = userfcn_dcline_int2ext(results, mpopt, args)\n%\n% This is the 'int2ext' stage userfcn callback that converts everything\n% back to external indexing and packages up the results. It expects to\n% find a 'dcline' field in the results struct as described for mpc\n% above. It also expects that the last 2*ndc entries in the gen and\n% gencost matrices correspond to the in-service DC lines (where ndc is\n% the number of rows in MPC.dcline. These extra rows are removed from\n% gen and gencost and the flow is taken from the PG of these gens and\n% placed in the flow column of the appropiate dcline row. Corresponding\n% columns are also removed from any A and N matrices, if present. The\n% optional args are not currently used.\n\n%% define named indices into data matrices\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\nc = idx_dcline;\n\n%% initialize some things\no = results.order;\nk = find(o.ext.dcline(:, c.BR_STATUS));\nndc = length(k); %% number of in-service DC lines\nng = size(results.gen, 1) - 2*ndc; %% number of original gens/disp loads\nnb = size(results.bus, 1);\n\n%% extract dummy gens\nfg = results.gen(ng +(1:ndc), :);\ntg = results.gen(ng+ndc+(1:ndc), :);\n\n%% remove dummy gens\nresults.gen = results.gen(1:ng, :);\nif isfield(results, 'gencost') && ~isempty(results.gencost)\n results.gencost = results.gencost(1:ng, :);\nend\n\n%% delete corresponding columns from A and N, if present\nif isfield(results, 'A') && ~isempty(results.A)\n [mA, nA] = size(results.A);\n if nA >= 2*nb + 2*ng + 4*ndc %% assume AC dimensions\n results.A = results.A(:, [1:2*nb+ng 2*nb+ng+2*ndc+(1:ng) 2*nb+2*ng+4*ndc+1:nA]);\n else %% assume DC dimensions\n results.A = results.A(:, [1:nb+ng nb+ng+2*ndc+1:nA]);\n end\nend\nif isfield(results, 'N') && ~isempty(results.N)\n [mN, nN] = size(results.N);\n if nN >= 2*nb + 2*ng + 4*ndc %% assume AC dimensions\n results.N = results.N(:, [1:2*nb+ng 2*nb+ng+2*ndc+(1:ng) 2*nb+2*ng+4*ndc+1:nN]);\n else %% assume DC dimensions\n results.N = results.N(:, [1:nb+ng nb+ng+2*ndc+1:nN]);\n end\nend\n\n%% get the solved flows\nresults.dcline(:, c.PF) = -fg(:, PG);\nresults.dcline(:, c.PT) = tg(:, PG);\nresults.dcline(:, c.QF) = fg(:, QG);\nresults.dcline(:, c.QT) = tg(:, QG);\nresults.dcline(:, c.VF) = fg(:, VG);\nresults.dcline(:, c.VT) = tg(:, VG);\nif size(fg, 2) >= MU_QMIN\n results.dcline(:, c.MU_PMIN ) = fg(:, MU_PMAX) + tg(:, MU_PMIN);\n results.dcline(:, c.MU_PMAX ) = fg(:, MU_PMIN) + tg(:, MU_PMAX);\n results.dcline(:, c.MU_QMINF) = fg(:, MU_QMIN);\n results.dcline(:, c.MU_QMAXF) = fg(:, MU_QMAX);\n results.dcline(:, c.MU_QMINT) = tg(:, MU_QMIN);\n results.dcline(:, c.MU_QMAXT) = tg(:, MU_QMAX);\nend\n\n%%----- convert stuff back to external indexing -----\nresults.order.int.dcline = results.dcline; %% save internal version\n%% copy results to external version\no.ext.dcline(k, c.PF:c.VT) = results.dcline(:, c.PF:c.VT);\nif size(results.dcline, 2) == c.MU_QMAXT\n o.ext.dcline(k, c.MU_PMIN:c.MU_QMAXT) = results.dcline(:, c.MU_PMIN:c.MU_QMAXT);\nend\nresults.dcline = o.ext.dcline; %% use external version\n\n\n%%----- printpf ------------------------------------------------------\nfunction results = userfcn_dcline_printpf(results, fd, mpopt, args)\n%\n% results = userfcn_dcline_printpf(results, fd, mpopt, args)\n%\n% This is the 'printpf' stage userfcn callback that pretty-prints the\n% results. It expects a results struct, a file descriptor and a MATPOWER\n% options struct. The optional args are not currently used.\n\n%% define named indices into data matrices\nc = idx_dcline;\n\n%% options\nSUPPRESS = mpopt.out.suppress_detail;\nif SUPPRESS == -1\n if size(results.bus, 1) > 500\n SUPPRESS = 1;\n else\n SUPPRESS = 0;\n end\nend\nOUT_ALL = mpopt.out.all;\nOUT_BRANCH = OUT_ALL == 1 || (OUT_ALL == -1 && ~SUPPRESS && mpopt.out.branch);\nif OUT_ALL == -1\n OUT_ALL_LIM = ~SUPPRESS * mpopt.out.lim.all;\nelseif OUT_ALL == 1\n OUT_ALL_LIM = 2;\nelse\n OUT_ALL_LIM = 0;\nend\nif OUT_ALL_LIM == -1\n OUT_LINE_LIM = ~SUPPRESS * mpopt.out.lim.line;\nelse\n OUT_LINE_LIM = OUT_ALL_LIM;\nend\nctol = mpopt.opf.violation; %% constraint violation tolerance\nptol = 1e-4; %% tolerance for displaying shadow prices\n\n%%----- print results -----\ndc = results.dcline;\nndc = size(dc, 1);\nkk = find(dc(:, c.BR_STATUS) ~= 0);\nif OUT_BRANCH\n fprintf(fd, '\\n================================================================================');\n fprintf(fd, '\\n| DC Line Data |');\n fprintf(fd, '\\n================================================================================');\n fprintf(fd, '\\n Line From To Power Flow Loss Reactive Inj (MVAr)');\n fprintf(fd, '\\n # Bus Bus From (MW) To (MW) (MW) From To ');\n fprintf(fd, '\\n------ ------ ------ --------- --------- --------- --------- ---------');\n loss = 0;\n for k = 1:ndc\n if dc(k, c.BR_STATUS) %% status on\n fprintf(fd, '\\n%5d%8d%8d%11.2f%11.2f%11.2f%11.2f%11.2f', ...\n k, dc(k, c.F_BUS:c.T_BUS), dc(k, c.PF:c.PT), ...\n dc(k, c.PF) - dc(k, c.PT), dc(k, c.QF:c.QT) );\n loss = loss + dc(k, c.PF) - dc(k, c.PT);\n else\n fprintf(fd, '\\n%5d%8d%8d%11s%11s%11s%11s%11s', ...\n k, dc(k, c.F_BUS:c.T_BUS), '- ', '- ', '- ', '- ', '- ');\n end\n end\n fprintf(fd, '\\n ---------');\n fprintf(fd, '\\n Total:%11.2f\\n', loss);\nend\n\nif OUT_LINE_LIM == 2 || (OUT_LINE_LIM == 1 && ...\n (any(dc(kk, c.PF) > dc(kk, c.PMAX) - ctol) || ...\n any(dc(kk, c.MU_PMIN) > ptol) || ...\n any(dc(kk, c.MU_PMAX) > ptol)))\n fprintf(fd, '\\n================================================================================');\n fprintf(fd, '\\n| DC Line Constraints |');\n fprintf(fd, '\\n================================================================================');\n fprintf(fd, '\\n Line From To Minimum Actual Flow Maximum');\n fprintf(fd, '\\n # Bus Bus Pmin mu Pmin (MW) Pmax Pmax mu ');\n fprintf(fd, '\\n------ ------ ------ --------- --------- --------- --------- ---------');\n for k = 1:ndc\n if OUT_LINE_LIM == 2 || (OUT_LINE_LIM == 1 && ...\n (dc(k, c.PF) > dc(k, c.PMAX) - ctol || ...\n dc(k, c.MU_PMIN) > ptol || ...\n dc(k, c.MU_PMAX) > ptol))\n if dc(k, c.BR_STATUS) %% status on\n fprintf(fd, '\\n%5d%8d%8d', k, dc(k, c.F_BUS:c.T_BUS) );\n if dc(k, c.MU_PMIN) > ptol\n fprintf(fd, '%11.3f', dc(k, c.MU_PMIN) );\n else\n fprintf(fd, '%11s', '- ' );\n end\n fprintf(fd, '%11.2f%11.2f%11.2f', ...\n dc(k, c.PMIN), dc(k, c.PF), dc(k, c.PMAX) );\n if dc(k, c.MU_PMAX) > ptol\n fprintf(fd, '%11.3f', dc(k, c.MU_PMAX) );\n else\n fprintf(fd, '%11s', '- ' );\n end\n else\n fprintf(fd, '\\n%5d%8d%8d%11s%11s%11s%11s%11s', ...\n k, dc(k, c.F_BUS:c.T_BUS), '- ', '- ', '- ', '- ', '- ');\n end\n end\n end\n fprintf(fd, '\\n');\nend\n\n\n%%----- savecase -----------------------------------------------------\nfunction mpc = userfcn_dcline_savecase(mpc, fd, prefix, args)\n%\n% mpc = userfcn_dcline_savecase(mpc, fd, prefix, args)\n%\n% This is the 'savecase' stage userfcn callback that prints the M-file\n% code to save the 'dcline' field in the case file. It expects a\n% MATPOWER case struct (mpc), a file descriptor and variable prefix\n% (usually 'mpc.'). The optional args are not currently used.\n\n%% define named indices into data matrices\nc = idx_dcline;\n\n%% save it\nncols = size(mpc.dcline, 2);\nfprintf(fd, '\\n%%%%----- DC Line Data -----%%%%\\n');\nif ncols < c.MU_QMAXT\n fprintf(fd, '%%\\tfbus\\ttbus\\tstatus\\tPf\\tPt\\tQf\\tQt\\tVf\\tVt\\tPmin\\tPmax\\tQminF\\tQmaxF\\tQminT\\tQmaxT\\tloss0\\tloss1\\n');\nelse\n fprintf(fd, '%%\\tfbus\\ttbus\\tstatus\\tPf\\tPt\\tQf\\tQt\\tVf\\tVt\\tPmin\\tPmax\\tQminF\\tQmaxF\\tQminT\\tQmaxT\\tloss0\\tloss1\\tmuPmin\\tmuPmax\\tmuQminF\\tmuQmaxF\\tmuQminT\\tmuQmaxT\\n');\nend\ntemplate = '\\t%d\\t%d\\t%d\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g\\t%.9g';\nif ncols == c.MU_QMAXT\n template = [template, '\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f'];\nend\ntemplate = [template, ';\\n'];\nfprintf(fd, '%sdcline = [\\n', prefix);\nfprintf(fd, template, mpc.dcline.');\nfprintf(fd, '];\\n');\n\n%% to do, make it save mpc.dclinecost too (somehow I forgot this)\n%% have a look at the saving of gencost in savecase for template\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/toggle_dcline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.04742587805815601, "lm_q1q2_score": 0.016366920497674946}} {"text": "function [C_smooth]=patchSmoothFaceMeasure(varargin)\n\n% function [C_smooth]=patchSmoothFaceMeasure(F,V,C,smoothPar)\n\n%% Parse input\nswitch nargin \n case 3\n F=varargin{1};\n V=varargin{2};\n C=varargin{3};\n smoothPar=[];\n case 4\n F=varargin{1};\n V=varargin{2};\n C=varargin{3};\n smoothPar=varargin{4};\nend\n\nsmoothParDefault.lambda=0.5;\nsmoothParDefault.n=1;\nsmoothParDefault.faceFaceConnectivity=[];\nsmoothPar=structComplete(smoothPar,smoothParDefault,1);\n\n%% Get connectivity array\nif isempty(smoothPar.faceFaceConnectivity)\n [connectivityStruct]=patchConnectivity(F,V);\n faceFaceConnectivity=connectivityStruct.face.face;\nend\n\n%%\n\nnumSmoothIterations=smoothPar.n; \nlambdaSmooth=smoothPar.lambda;\n\n%%\n\nnDims=size(C,2); %Number of dimensions\nlogicValid=faceFaceConnectivity>0;\nC_smooth=C;\nC_smooth_step=C; \nfor qIter=1:numSmoothIterations\n %Loop for all dimensions\n for qDim=1:1:nDims\n Xp=NaN(size(C,1),size(faceFaceConnectivity,2));\n Xp(logicValid)=C_smooth(faceFaceConnectivity(logicValid),qDim);\n Xp=gnanmean(Xp,2); \n C_smooth_step(:,qDim)=Xp;\n end\n C_smooth=((1-lambdaSmooth).*C_smooth)+(lambdaSmooth.*C_smooth_step);\nend\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/patchSmoothFaceMeasure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.03308597683940491, "lm_q1q2_score": 0.016284525259088124}} {"text": "% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED \"AS IS.\" THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.\n%\n% file: poisspdf_of_lambda.m\n% Used when you want to integrate a poisson pdf with \n% respect to lambda.\n%\n% 022300 tdr created\n% 030400 tdr replaced global variable approach to getting x and n to binopdf.\n% 031600 tdr converted from binopdf_of_p.m to poisson dist.\n% 032200 tdr replaced for loop with vector argument.\n\nfunction y = poisspdf_of_lambda(lambda, x)\n\nif nargin ~= 2, \n error('Requires two input arguments (lambda,x)');\nend\n\ny = poisspdf_0ok(x,lambda);\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3031-accurate-confidence-intervals/ci_tool/poisspdf_of_lambda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.03732689055684297, "lm_q1q2_score": 0.01619917918695062}} {"text": "function [y,newp,retcode]=ssfile(obj,y,p,d,id) %#ok\n\n% risessfile -- computes the steady state of ... analytically\n%\n% ::\n%\n%\n% [y,newp,retcode]=risessfile(obj,y,p,d,id)\n%\n% Args:\n%\n% - **obj** [rise|dsge]: model object (not always needed)\n%\n% - **y** [vector]: endo_nbr x 1 vector of initial steady state\n%\n% - **p** [struct]: parameter structure\n%\n% - **d** [struct]: definitions\n%\n% - **id** [vector]: location of the variables to calculate\n%\n% Returns:\n% :\n%\n% - **y** []: endo_nbr x 1 vector of updated steady state\n%\n% - **newp** [struct]: structure containing updated parameters if any\n%\n% - **retcode** [0|number]: return 0 if there are no problems, else return\n% any number different from 0\n%\n% Note:\n%\n% - this is new approach has three main advantages relative to the previous\n% one:\n% - The file is valid whether we have many regimes or not\n% - The user does not need to know what regime is being computed\n% - It is in sync with the steady state model\n%\n% Example:\n%\n% See also:\n\n% Conversion of Dynare file [Dynare_edo_steadystate.m] into RISE file [risessfile.m]\n%\n% Done 23-Jul-2017 00:31:15.\n\nretcode=0;\n\nif nargin==1\n % list of endogenous variables to be calculated\n %----------------------------------------------\n % y=get(obj,'endo_list');\n y={'RC','RK','WC','WK','YC','YK','MCC','MCK','KC','KK','PKB','R','L','QK',...\n 'HC','HSC','HK','HSK','UHC','UHSC','UHK','UHSK','empC','HrC',...\n 'empK','HrK','empSC','HrSC','empSK','HrSK','unemp','EIK','EC','INFWC',...\n 'INFWK','INFC','INFK','DIFFNORMGDP','NORMINFGDP','DIFFREALGDP',...\n 'DIFFREALEC','DIFFREALEIK','DIFFREALW','AH','INFGDP','INFCNA','INFCOR',...\n 'GAP','PFGAP','INFC10','ECD','KD','RCD','QCD','KCH','RCH','ECH','QCH',...\n 'LAGKD','LAGKCH','UK','UC','DIFFREALECH','DIFFREALECD','betas','XiL',...\n 'Lpref','EFFK','MUZK','MUZM','HG','MUC','MUK','EFFECD','EFFECH','STAR',...\n 'RL1','RL2','RL3','RL4','RL5','RL6','RL7','RT2','DIFFREALGDP_obs',...\n 'DIFFREALEC_obs','DIFFREALEIK_obs','DIFFREALECD_obs','DIFFREALECH_obs',...\n 'DIFFREALW_obs','AH_obs','INFCNA_obs','INFCOR_obs','INFK_obs','R_obs',...\n 'RT2_obs','unemp_obs'};\n % list of parameters to be computed during steady state calculation\n %-------------------------------------------------------------------\n newp={'AA','AHSS','A_HC','A_HK','DD','DIFFREALECDSS','DIFFREALECDSS_obs',...\n 'DIFFREALECHSS','DIFFREALECHSS_obs','DIFFREALECSS','DIFFREALECSS_obs',...\n 'DIFFREALEIKSS','DIFFREALEIKSS_obs','DIFFREALGDPSS','DIFFREALGDPSS_obs',...\n 'DIFFREALWSS','DIFFREALWSS_obs','ECDSS','ECHSS','ECSS','EIKSS','HCSS',...\n 'HKSS','HSCSS','HSKSS','HSS','HrCSS','HrKSS','HrSCSS','HrSKSS',...\n 'IMPHSSS','INFC10SS','INFCNASS','INFCNASS_obs','INFCORSS','INFCORSS_obs',...\n 'INFCSS','INFGDPSS','INFKSS','INFKSS_obs','INFWCSS','INFWKSS','KCDSS',...\n 'KCHSS','KCSS','KKSS','LSS','MCCSS','MCKSS','MUCSS','MUCSShabit','MUKSS',...\n 'MUKSShabit','MUZCSS','ONE','PKBSS','PYSS','QCDSS','QCHSS','QKSS',...\n 'RCDSS','RCHSS','RCSS','RKSS','RL1SS','RL2SS','RL3SS','RL4SS','RL5SS',...\n 'RL6SS','RL7SS','RR','RSS','RSS_obs','RT2SS','RT2SS_obs','Rnr','UCSS',...\n 'UHCSS','UHKSS','UHSCSS','UHSKSS','UKSS','USS','WCSS','WKSS','YCSS',...\n 'YKSS','YYSS','beta_','beta_0','beta_2','empCSS','empKSS','empSCSS',...\n 'empSKSS','eta_cd','eta_cd_eta_cnn','eta_ch','eta_ch_eta_cnn','eta_cnn',...\n 'hc_hk','mu_','s_c_ech','s_ecdc','s_k','s_k_ecd','s_k_eik','s_yc',...\n 'theta_wc','theta_wk','unempSS','unempSS_obs','xsi_HrC','xsi_HrK',...\n 'xsi_NC','xsi_NK','ycbi','ycbi_ykb','ykb'};\nelse\n \n newp=struct();\n \n %start_steady_state;\n \n newp.beta_0 = p.pbeta;\n newp.beta_2 = p.pbeta*p.rpr; % s.s. funds rate premium\n newp.beta_ = newp.beta_2;\n newp.MUZCSS=1;\n newp.ONE=1;\n newp.USS=1;\n newp.MUKSS=p.MUZKSS*p.MUZMSS;\n newp.MUCSS=p.MUZKSS^p.alpha_*p.MUZMSS;\n newp.MUKSShabit=newp.MUKSS;\n newp.MUCSShabit=newp.MUCSS;\n newp.PKBSS=p.theta_k/(p.theta_k-1)*(p.theta_c-1)/p.theta_c;\n newp.PYSS=1;\n newp.MCCSS=(p.theta_c-1)/p.theta_c;\n newp.MCKSS=(p.theta_k-1)/p.theta_k;\n newp.RKSS=newp.MUKSS/newp.beta_2-(1-p.delta_);\n newp.RCSS=newp.MUKSS/newp.beta_2-(1-p.delta_);\n newp.RCHSS=newp.MUCSS/newp.beta_2-(1-p.delta_ch); % Housing sector\n newp.RCDSS=newp.MUKSS/newp.beta_2-(1-p.delta_cd); % Durable sector\n newp.USS=1;\n newp.mu_=newp.RCSS;\n newp.AA=p.alpha_/newp.RKSS*newp.MCKSS;\n newp.DD = 0.135;\n newp.RR = 0.075;\n newp.eta_cnn=1;\n newp.eta_cd_eta_cnn=newp.DD/((newp.MUKSShabit-newp.beta_2*p.h_cd)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_cd/newp.MUKSShabit)*(1-(1-p.delta_cd)/newp.MUKSS)/newp.RCDSS);\n newp.eta_ch_eta_cnn=newp.RR/((newp.MUCSShabit-newp.beta_2*p.h_ch)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_ch/newp.MUCSShabit)*(1-(1-p.delta_ch)/newp.MUCSS)/newp.RCHSS);\n newp.eta_ch=newp.eta_ch_eta_cnn;\n newp.eta_cd=newp.eta_cd_eta_cnn;\n newp.DD=newp.eta_cd_eta_cnn*(newp.MUKSShabit-newp.beta_2*p.h_cd)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_cd/newp.MUKSShabit)*(1-(1-p.delta_cd)/newp.MUKSS)/newp.RCDSS;\n newp.RR=newp.eta_ch_eta_cnn*(newp.MUCSShabit-newp.beta_2*p.h_ch)/(1-newp.beta_2*p.h/newp.MUCSShabit)*(1-p.h/newp.MUCSShabit)/(1-p.h_ch/newp.MUCSShabit)*(1-(1-p.delta_ch)/newp.MUCSS)/newp.RCHSS;\n newp.Rnr=(1-(1-p.delta_)/newp.MUKSS)*newp.AA*newp.MUKSS;\n newp.ycbi_ykb=((1-p.s_AS)-newp.Rnr)/((newp.DD*(1-p.s_AS)/(1+newp.RR))+newp.Rnr);\n newp.hc_hk=newp.ycbi_ykb*(newp.RCSS*newp.MCKSS/(newp.RKSS*newp.MCCSS))^(p.alpha_/(1-p.alpha_));\n newp.HSS=0.25;\n newp.AHSS=newp.HSS;\n newp.HKSS=newp.HSS/(1+newp.hc_hk);\n newp.HCSS=newp.HSS-newp.HKSS;\n newp.HrCSS=1/3;\n newp.HrKSS=1/3;\n newp.empCSS=newp.HCSS/newp.HrCSS;\n newp.empKSS=newp.HKSS/newp.HrKSS;\n newp.ycbi=newp.HCSS*(newp.AA)^(p.alpha_/(1-p.alpha_));\n newp.ykb=newp.HKSS*(newp.AA)^(p.alpha_/(1-p.alpha_));\n newp.YCSS=newp.ycbi;\n newp.YKSS=newp.ykb;\n newp.KCSS=newp.AA*newp.ycbi*newp.MUKSS;\n newp.KKSS=newp.AA*newp.ykb*newp.MUKSS;\n newp.ECHSS=newp.RR/(1+newp.RR)*newp.ycbi*(1-p.s_AS);\n newp.ECSS=1/(1+newp.RR)*newp.ycbi*(1-p.s_AS);\n newp.ECDSS=newp.DD*newp.PKBSS*newp.ECSS;\n newp.EIKSS=(1-(1-p.delta_)/newp.MUKSS)*(newp.KCSS+newp.KKSS);\n newp.KCDSS=newp.ECDSS/(1-(1-p.delta_cd)/newp.MUKSS);\n newp.KCHSS=newp.ECHSS/(1-(1-p.delta_ch)/newp.MUCSS);\n newp.YYSS=(newp.YCSS+newp.YKSS*newp.PKBSS)/newp.PYSS;\n newp.s_k_ecd=newp.ECDSS/newp.YKSS;\n newp.s_c_ech=newp.ECHSS/newp.YCSS;\n newp.s_k_eik=newp.EIKSS/newp.YKSS;\n newp.s_yc = (newp.YCSS/newp.YYSS);\n newp.s_ecdc=newp.PKBSS*newp.ECDSS/(newp.ECSS+newp.PKBSS*newp.ECDSS+(newp.MUCSS/newp.beta_2-1+p.delta_ch)*newp.KCHSS);\n newp.INFCNASS=exp(.02/4);\n newp.INFCSS = newp.INFCNASS*((newp.MUZCSS/p.MUZKSS)^(1-p.alpha_))^(-newp.s_ecdc);\n newp.INFCORSS=newp.INFCNASS;\n newp.INFKSS=newp.INFCSS*(newp.MUZCSS/p.MUZKSS)^(1-p.alpha_);\n newp.INFWCSS=newp.INFCSS*p.MUZKSS^p.alpha_*p.MUZMSS;\n newp.INFWKSS=newp.INFWCSS;\n newp.RSS=newp.INFCSS/newp.beta_0*newp.MUCSS;\n newp.RT2SS=exp(p.tp2)*newp.RSS;\n newp.INFC10SS = newp.INFCNASS;\n newp.IMPHSSS = newp.RCHSS*newp.KCHSS;\n newp.s_k=newp.PKBSS*newp.YKSS/newp.YYSS;\n newp.INFGDPSS=newp.INFCSS^(newp.YCSS/newp.YYSS)*newp.INFKSS^(newp.YKSS*newp.PKBSS/(newp.YYSS));\n newp.LSS=newp.eta_cnn/(newp.ECSS*(1-p.h/newp.MUCSShabit))-newp.eta_cnn*newp.beta_2*p.h/(newp.ECSS*(newp.MUCSShabit-p.h));\n newp.WCSS=newp.MCCSS*(1-p.alpha_)*newp.YCSS/newp.HCSS;\n newp.WKSS=newp.MCKSS*(1-p.alpha_)*newp.YKSS/newp.HKSS;\n % xsiN_xsiH_C = ((newp.HrCSS/newp.empCSS)^(1+p.sigmah))/(1+1/p.sigmah);\n % xsiN_xsiH_K = ((newp.HrKSS/newp.empKSS)^(1+p.sigmah))/(1+1/p.sigmah);\n % gC = (1/(1+p.sigman) + 1/p.sigmah)*(xsiN_xsiH_C*(1+p.sigmah)/p.sigmah)^(-(1+p.sigman)/(1+p.sigman+p.sigmah));\n % markup_xsiN_C = (newp.HCSS^((1+p.sigmah)*(1+p.sigman)/(1+p.sigmah+p.sigman)-1))*gC/(newp.LSS*newp.WCSS);\n % gK = (1/(1+p.sigman) + 1/p.sigmah)*(xsiN_xsiH_K*(1+p.sigmah)/p.sigmah)^(-(1+p.sigman)/(1+p.sigman+p.sigmah));\n % markup_xsiN_K = (newp.HKSS^((1+p.sigmah)*(1+p.sigman)/(1+p.sigmah+p.sigman)-1))*gK/(newp.LSS*newp.WKSS);\n % markup_w = (1-newp.unempSS)^((1+p.sigmah+p.sigman)/(1+p.sigmah) - 1 - p.sigman);\n markup_w = (1-p.unempSS)^((1+p.sigmah+p.sigman)/(1+p.sigmah) - 1 - p.sigman);\n newp.theta_wc = markup_w/(markup_w -1); newp.theta_wk = newp.theta_wc;\n newp.A_HC=newp.LSS*(newp.theta_wc-1)/newp.theta_wc*newp.WCSS/(((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));\n newp.A_HK=newp.LSS*(newp.theta_wk-1)/newp.theta_wk*newp.WKSS/(((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));\n newp.xsi_NC=newp.A_HC/((1/(1+p.sigman)+1/p.sigmah)*(newp.HCSS^p.sigman/newp.HrCSS^(1+p.sigman+p.sigmah))^((1+p.sigman)/(1+p.sigman+p.sigmah)));\n newp.xsi_NK=newp.A_HK/((1/(1+p.sigman)+1/p.sigmah)*(newp.HKSS^p.sigman/newp.HrKSS^(1+p.sigman+p.sigmah))^((1+p.sigman)/(1+p.sigman+p.sigmah)));\n newp.xsi_HrC=newp.xsi_NC*(1+p.sigmah)/p.sigmah*(newp.HCSS^p.sigman/newp.HrCSS^(1+p.sigman+p.sigmah));\n newp.xsi_HrK=newp.xsi_NK*(1+p.sigmah)/p.sigmah*(newp.HKSS^p.sigman/newp.HrKSS^(1+p.sigman+p.sigmah));\n newp.UHCSS=newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;\n newp.UHKSS=newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;\n newp.HSCSS=(newp.WCSS*newp.LSS/(newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))))^(1/(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));\n newp.HSKSS=(newp.WKSS*newp.LSS/(newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))))^(1/(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah))));\n newp.empSCSS=((1+p.sigmah)/p.sigmah*newp.xsi_NC/newp.xsi_HrC)^(-1/(1+p.sigmah+p.sigman))*newp.HSCSS^(1/(1+p.sigman/(1+p.sigmah)));\n newp.empSKSS=((1+p.sigmah)/p.sigmah*newp.xsi_NK/newp.xsi_HrK)^(-1/(1+p.sigmah+p.sigman))*newp.HSKSS^(1/(1+p.sigman/(1+p.sigmah)));\n newp.HrSCSS=newp.HSCSS/newp.empSCSS;\n newp.HrSKSS=newp.HSKSS/newp.empSKSS;\n newp.UHSCSS=newp.A_HC*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HSCSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;\n newp.UHSKSS=newp.A_HK*((1+p.sigman)/(1+p.sigman/(1+p.sigmah)))*newp.HSKSS^(-1+(1+p.sigman)/(1+p.sigman/(1+p.sigmah)))/newp.LSS;\n newp.unempSS=(newp.empSCSS+newp.empSKSS-(newp.empCSS+newp.empKSS))/(newp.empSCSS+newp.empSKSS);\n newp.QKSS=1;\n newp.QCDSS=1;\n newp.QCHSS=1;\n newp.UCSS=1;\n newp.UKSS=1;\n % XiBSS=1;\n % XiDSS=1;\n % XiHSS=1;\n newp.RL1SS=newp.RSS;\n newp.RL2SS=newp.RSS;\n newp.RL3SS=newp.RSS;\n newp.RL4SS=newp.RSS;\n newp.RL5SS=newp.RSS;\n newp.RL6SS=newp.RSS;\n newp.RL7SS=newp.RSS;\n newp.DIFFREALECSS =exp( log(newp.MUCSS));\n newp.DIFFREALEIKSS =exp( log(newp.MUKSS));\n newp.DIFFREALECDSS =exp( log(newp.MUKSS));\n newp.DIFFREALECHSS =exp( log(newp.MUCSS));\n newp.DIFFREALWSS =exp( log(newp.MUCSS) );\n newp.DIFFREALGDPSS =exp( (1-newp.s_k)*log(newp.MUCSS)+(newp.s_k)*log(newp.MUKSS));\n \n %end_steady_state;\n \n %trends;\n \n newp.DIFFREALGDPSS_obs=(1-newp.s_k)*log(newp.MUCSS)*100+(newp.s_k)*log(newp.MUKSS)*100;\n newp.DIFFREALECSS_obs=log(newp.MUCSS)*100;\n newp.DIFFREALEIKSS_obs=log(newp.MUKSS)*100;\n newp.DIFFREALECDSS_obs=log(newp.MUKSS)*100;\n newp.DIFFREALECHSS_obs=log(newp.MUCSS)*100;\n newp.DIFFREALWSS_obs=log(newp.MUCSS)*100;\n newp.INFCNASS_obs=(1-newp.s_ecdc)*log(newp.INFCSS)*100+newp.s_ecdc*log(newp.INFKSS)*100;\n newp.INFCORSS_obs=(1-newp.s_ecdc)*log(newp.INFCSS)*100+newp.s_ecdc*log(newp.INFKSS)*100;\n newp.INFKSS_obs=log(newp.INFCSS)*100-log(newp.MUKSS)*100+log(newp.MUCSS)*100;\n newp.RSS_obs=log(newp.RSS)*100;\n newp.RT2SS_obs=log(newp.RT2SS)*100;\n newp.unempSS_obs=100*log(newp.unempSS);\n \n %end_trends;\n \n ys = [\n newp.RCSS\n newp.RKSS\n newp.WCSS\n newp.WKSS\n newp.YCSS\n newp.YKSS\n newp.MCCSS\n newp.MCKSS\n newp.KCSS\n newp.KKSS\n newp.PKBSS\n newp.RSS\n newp.LSS\n newp.QKSS\n newp.HCSS\n newp.HSCSS\n newp.HKSS\n newp.HSKSS\n newp.UHCSS\n newp.UHSCSS\n newp.UHKSS\n newp.UHSKSS\n newp.empCSS\n newp.HrCSS\n newp.empKSS\n newp.HrKSS\n newp.empSCSS\n newp.HrSCSS\n newp.empSKSS\n newp.HrSKSS\n newp.unempSS\n newp.EIKSS\n newp.ECSS\n newp.INFWCSS\n newp.INFWKSS\n newp.INFCSS\n newp.INFKSS\n newp.ONE\n newp.ONE\n newp.DIFFREALGDPSS\n newp.DIFFREALECSS\n newp.DIFFREALEIKSS\n newp.DIFFREALWSS\n newp.AHSS\n newp.INFGDPSS\n newp.INFCNASS\n newp.INFCORSS\n newp.ONE\n newp.ONE\n newp.INFC10SS\n newp.ECDSS\n newp.KCDSS\n newp.RCDSS\n newp.QCDSS\n newp.KCHSS\n newp.RCHSS\n newp.ECHSS\n newp.QCHSS\n newp.KCDSS\n newp.KCHSS\n newp.USS\n newp.USS\n newp.DIFFREALECHSS\n newp.DIFFREALECDSS\n newp.beta_\n newp.ONE\n newp.ONE\n newp.ONE\n p.MUZKSS\n p.MUZMSS\n newp.ONE\n newp.MUCSS\n newp.MUKSS\n newp.ONE\n newp.ONE\n newp.ONE\n newp.RL1SS\n newp.RL2SS\n newp.RL3SS\n newp.RL4SS\n newp.RL5SS\n newp.RL6SS\n newp.RL7SS\n newp.RT2SS\n newp.DIFFREALGDPSS_obs\n newp.DIFFREALECSS_obs\n newp.DIFFREALEIKSS_obs\n newp.DIFFREALECDSS_obs\n newp.DIFFREALECHSS_obs\n newp.DIFFREALWSS_obs\n newp.ONE\n newp.INFCNASS_obs\n newp.INFCORSS_obs\n newp.INFKSS_obs\n newp.RSS_obs\n newp.RT2SS_obs\n newp.unempSS_obs\n ];\n \n \n y(id)=ys;\n \nend\n\nend", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/VariousModels/frb/EDO/ssfile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.03161876795303394, "lm_q1q2_score": 0.01580938397651697}} {"text": "function [vert, face] = read_ply(fn)\n\n% READ_PLY reads triangles, tetraheders or hexaheders from a Stanford *.ply file\n%\n% Use as\n% [vert, face, prop, face_prop] = read_ply(filename)\n%\n% Documentation is provided on\n% http://paulbourke.net/dataformats/ply/\n% http://en.wikipedia.org/wiki/PLY_(file_format)\n%\n% See also WRITE_PLY, WRITE_VTK, READ_VTK\n\n% Copyright (C) 2013-2018, Robert Oostenveld\n%\n% $Id$\n\nfid = fopen_or_error(fn, 'r');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the file starts with an ascii header\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nline = readline(fid);\nif ~strcmp(line, 'ply')\n fclose(fid);\n ft_error('unexpected header line');\nend\nline = readline(fid);\n\nif ~strncmp(line, 'format', 6)\n fclose(fid);\n ft_error('unexpected header line');\nelse\n format = line(8:end);\nend\nline = readline(fid);\n\nif ~strncmp(line, 'element vertex', 14)\n fclose(fid);\n ft_error('unexpected header line');\nelse\n nvert = str2double(line(16:end));\nend\nline = readline(fid);\n\nprop = [];\nwhile strncmp(line, 'property', 8)\n tok = tokenize(line);\n prop(end+1).format = tok{2};\n prop(end ).name = tok{3};\n line = readline(fid);\nend\n\nif ~strncmp(line, 'element face', 12)\n fclose(fid);\n ft_error('unexpected header line');\nelse\n nface = str2double(line(14:end));\nend\nline = readline(fid);\n\nif ~strcmp(line, 'property list uchar int vertex_index') && ...\n ~strcmp(line, 'property list uchar int vertex_indices') && ...\n ~strcmp(line, 'property list uchar uint vertex_index') && ...\n ~strcmp(line, 'property list uchar uint vertex_indices')\n % the wikipedia documentation specifies vertex_index, but the OPTOCAT files have vertex_indices\n\n % it would not be very difficult to enhance the reader here with another\n % representation of the faces, i.e. something else than \"uchar int\"\n fclose(fid);\n ft_error('unexpected header line');\nend\nline = readline(fid);\n\nwhile ~strcmp(line, 'end_header')\n line = readline(fid);\nend\n\noffset = ftell(fid);\nfclose(fid);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% the file continues with a section of data, which can be ascii or binary\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nswitch format\n\n case 'ascii 1.0'\n\n fid = fopen_or_error(fn, 'rt');\n fseek(fid, offset, 'cof');\n dat = fscanf(fid,'%f',[numel(prop), nvert])';\n for j=1:length(prop)\n vert.(prop(j).name) = dat(:,j);\n end\n face = zeros(nface,0);\n num = zeros(nface,1);\n for i=1:nface\n % each polygon can have a different number of elements\n num(i) = fscanf(fid,'%f',1);\n face(i,1:num(i)) = fscanf(fid,'%f',num(i));\n end\n fclose(fid);\n\n case 'binary_little_endian 1.0'\n\n fid = fopen_or_error(fn, 'rb', 'l');\n fseek(fid, offset, 'cof');\n\n dat = zeros(nvert,length(prop));\n for i=1:nvert\n for j=1:length(prop)\n dat(i,j) = fread(fid, 1, prop(j).format);\n end % for each property\n end % for each vertex\n for j=1:length(prop)\n switch prop(j).format\n % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64\n case 'char'\n vert.(prop(j).name) = uint8(dat(:,j));\n case 'uchar'\n vert.(prop(j).name) = uint8(dat(:,j));\n case 'short'\n vert.(prop(j).name) = int16(dat(:,j));\n case 'ushort'\n vert.(prop(j).name) = uint16(dat(:,j));\n otherwise\n vert.(prop(j).name) = dat(:,j);\n end\n end\n clear dat;\n\n face = zeros(nface,0);\n num = zeros(nface,1);\n for i=1:nface\n % each polygon can have a different number of elements\n num(i) = fread(fid, 1, 'uint8');\n face(i,1:num(i)) = fread(fid, num(i), 'int32');\n end\n fclose(fid);\n\n case 'binary_big_endian 1.0'\n % this is exactly the same as the code above, except that the file is opened as big endian\n\n fid = fopen_or_error(fn, 'rb', 'b');\n fseek(fid, offset, 'cof');\n\n dat = zeros(nvert,length(prop));\n for i=1:nvert\n for j=1:length(prop)\n dat(i,j) = fread(fid, 1, prop(j).format);\n end % for each property\n end % for each vertex\n for j=1:length(prop)\n switch prop(j).format\n % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64\n case 'char'\n vert.(prop(j).name) = uint8(dat(:,j));\n case 'uchar'\n vert.(prop(j).name) = uint8(dat(:,j));\n case 'short'\n vert.(prop(j).name) = int16(dat(:,j));\n case 'ushort'\n vert.(prop(j).name) = uint16(dat(:,j));\n otherwise\n vert.(prop(j).name) = dat(:,j);\n end\n end\n clear dat;\n\n face = zeros(nface,0);\n num = zeros(nface,1);\n for i=1:nface\n % each polygon can have a different number of elements\n num(i) = fread(fid, 1, 'uint8');\n face(i,1:num(i)) = fread(fid, num(i), 'int32');\n end\n fclose(fid);\n\n otherwise\n ft_error('unsupported format');\nend % switch\n \n\n% each polygon can have a different number of elements\n% mark all invalid entries with nan\nif any(num0\n % MATLAB indexes start at 1, inside the file they start at 0\n face = face+1;\nend\n\nend % function read_ply\n\n\nfunction line = readline(fid)\n% read the next line from the ascii header, skip all comment lines\nline = fgetl(fid);\nwhile strncmp(line, 'comment', 7)\n line = fgetl(fid);\nend\nend % function readline\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/fileio/private/read_ply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.03514484652711669, "lm_q1q2_score": 0.015793835168680628}} {"text": "% [INPUT]\n% ds = A structure representing the dataset.\n% sn = A string representing the serial number of the result file.\n% temp = A string representing the full path to the Excel spreadsheet used as template for the result file.\n% out = A string representing the full path to the Excel spreadsheet to which the results are written, eventually replacing the previous ones.\n% bw = An integer [21,252] representing the dimension of each rolling window (optional, default=252).\n% bws = An integer [1,10] representing the number of steps between each rolling window (optional, default=10).\n% fevd = A string representing the FEVD type used by the variance decomposition (optional, default='G'):\n% - 'G' for generalized FEVD;\n% - 'O' for orthogonal FEVD.\n% lags = An integer [1,3] representing the number of lags of the VAR model used by the variance decomposition (optional, default=2).\n% h = An integer [1,10] representing the prediction horizon used by the variance decomposition (optional, default=4).\n% analyze = A boolean that indicates whether to analyse the results and display plots (optional, default=false).\n%\n% [OUTPUT]\n% result = A structure representing the original dataset inclusive of intermediate and final calculations.\n% stopped = A boolean that indicates whether the process has been stopped through user input.\n\nfunction [result,stopped] = run_spillover(varargin)\n\n persistent ip;\n\n if (isempty(ip))\n ip = inputParser();\n ip.addRequired('ds',@(x)validateattributes(x,{'struct'},{'nonempty'}));\n ip.addRequired('sn',@(x)validateattributes(x,{'char'},{'nonempty' 'size' [1 NaN]}));\n ip.addRequired('temp',@(x)validateattributes(x,{'char'},{'nonempty' 'size' [1 NaN]}));\n ip.addRequired('out',@(x)validateattributes(x,{'char'},{'nonempty' 'size' [1 NaN]}));\n ip.addOptional('bw',252,@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 21 '<=' 252 'scalar'}));\n ip.addOptional('bws',10,@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 1 '<=' 10 'scalar'}));\n ip.addOptional('fevd','G',@(x)any(validatestring(x,{'G' 'O'})));\n ip.addOptional('lags',2,@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 1 '<=' 3 'scalar'}));\n ip.addOptional('h',4,@(x)validateattributes(x,{'double'},{'real' 'finite' 'integer' '>=' 1 '<=' 10 'scalar'}));\n ip.addOptional('analyze',false,@(x)validateattributes(x,{'logical'},{'scalar'}));\n end\n\n ip.parse(varargin{:});\n\n ipr = ip.Results;\n ds = validate_dataset(ipr.ds,'Spillover');\n sn = ipr.sn;\n temp = validate_template(ipr.temp);\n out = validate_output(ipr.out);\n bw = ipr.bw;\n bws = ipr.bws;\n fevd = ipr.fevd;\n lags = ipr.lags;\n h = ipr.h;\n analyze = ipr.analyze;\n\n nargoutchk(1,2);\n\n [result,stopped] = run_spillover_internal(ds,sn,temp,out,bw,bws,fevd,lags,h,analyze);\n\nend\n\nfunction [result,stopped] = run_spillover_internal(ds,sn,temp,out,bw,bws,fevd,lags,h,analyze)\n\n result = [];\n stopped = false;\n e = [];\n\n indices = unique([1:bws:ds.T ds.T]);\n ds = initialize(ds,sn,bw,bws,indices,fevd,lags,h);\n\n rng(double(bitxor(uint16('T'),uint16('B'))));\n cleanup_1 = onCleanup(@()rng('default'));\n\n bar = waitbar(0,'Initializing spillover measures...','CreateCancelBtn',@(src,event)setappdata(gcbf(),'Stop',true));\n setappdata(bar,'Stop',false);\n cleanup_2 = onCleanup(@()delete(bar));\n\n pause(1);\n waitbar(0,bar,'Calculating spillover measures...');\n pause(1);\n\n try\n\n windows = extract_rolling_windows(ds.Returns,ds.BW);\n windows = windows(indices);\n windows_len = numel(windows);\n\n futures(1:windows_len) = parallel.FevalFuture;\n futures_max = 0;\n futures_results = cell(windows_len,1);\n\n for i = 1:windows_len\n futures(i) = parfeval(@main_loop,1,windows{i},ds.FEVD,ds.Lags,ds.H);\n end\n\n for i = 1:windows_len\n if (getappdata(bar,'Stop'))\n stopped = true;\n break;\n end\n\n [future_index,value] = fetchNext(futures);\n futures_results{future_index} = value;\n\n futures_max = max([future_index futures_max]);\n waitbar((futures_max - 1) / windows_len,bar);\n\n if (getappdata(bar,'Stop'))\n stopped = true;\n break;\n end\n end\n\n catch e \n end\n\n try\n cancel(futures);\n catch\n end\n\n if (~isempty(e))\n delete(bar);\n rethrow(e);\n end\n\n if (stopped)\n delete(bar);\n return;\n end\n\n pause(1);\n waitbar(1,bar,'Finalizing spillover measures...');\n pause(1);\n\n try\n ds = finalize(ds,futures_results);\n catch e\n delete(bar);\n rethrow(e);\n end\n\n pause(1);\n waitbar(1,bar,'Writing spillover measures...');\n pause(1);\n\n try\n write_results(ds,temp,out);\n delete(bar);\n catch e\n delete(bar);\n rethrow(e);\n end\n\n if (analyze)\n analyze_result(ds);\n end\n\n result = ds;\n\nend\n\n%% PROCESS\n\nfunction ds = initialize(ds,sn,bw,bws,indices,fevd,lags,h)\n\n n = ds.N;\n t = ds.T;\n\n ds.Result = 'Spillover';\n ds.ResultDate = now(); %#ok \n ds.ResultAnalysis = @(ds)analyze_result(ds);\n ds.ResultSerial = sn;\n\n ds.BW = bw;\n ds.BWS = bws;\n ds.FEVD = fevd;\n ds.H = h;\n ds.Lags = lags;\n ds.Windows = numel(indices);\n ds.WindowsIndices = indices;\n\n all_label = [' (' fevd ', H=' num2str(ds.H) ', LAGS=' num2str(ds.Lags) ')'];\n\n ds.LabelsIndicatorsSimple = {'SI'};\n ds.LabelsIndicators = {['SI' all_label]};\n\n ds.LabelsSheetsSimple = {'From' 'To' 'Net' 'Indicators'};\n ds.LabelsSheets = {['From' all_label] ['To' all_label] ['Net' all_label] 'Indicators'};\n\n ds.VarianceDecompositions = cell(t,1);\n\n ds.SpilloversFrom = NaN(t,n);\n ds.SpilloversTo = NaN(t,n);\n ds.SpilloversNet = NaN(t,n);\n\n ds.Indicators = NaN(t,numel(ds.LabelsIndicators));\n\n ds.ComparisonReferences = {'Indicators' [] strcat({'SP-'},ds.LabelsIndicatorsSimple)};\n\nend\n\nfunction window_results = main_loop(r,fevd,lags,h)\n\n window_results = struct();\n\n vd = variance_decomposition(r,fevd,lags,h);\n window_results.VarianceDecomposition = vd;\n\n [sf,st,sn,si] = spillover_metrics(vd);\n window_results.SpilloversFrom = sf;\n window_results.SpilloversTo = st;\n window_results.SpilloversNet = sn;\n window_results.SI = si;\n\nend\n\nfunction ds = finalize(ds,results)\n\n window_indices = ds.WindowsIndices;\n\n for i = 1:numel(results)\n result = results{i};\n index = window_indices(i);\n\n ds.VarianceDecompositions{index} = result.VarianceDecomposition;\n\n ds.SpilloversFrom(index,:) = result.SpilloversFrom;\n ds.SpilloversTo(index,:) = result.SpilloversTo;\n ds.SpilloversNet(index,:) = result.SpilloversNet;\n\n ds.Indicators(index) = result.SI;\n end\n\n if (ds.BWS > 1)\n n = ds.N;\n t = ds.T;\n x = ds.DatesNum;\n\n nan_indices = ~ismember((1:t).',window_indices);\n step_indices = find(nan_indices);\n step_indices_len = numel(step_indices);\n\n vd = ds.VarianceDecompositions;\n vd(cellfun(@isempty,vd)) = {NaN(n,n)};\n\n for i = 1:n\n for j = 1:n\n vd_ij = cellfun(@(vdf)vdf(i,j),vd);\n vd_ij(nan_indices) = spline(x(~nan_indices),vd_ij(~nan_indices),x(nan_indices));\n\n for k = 1:step_indices_len\n step_index = step_indices(k);\n\n vd_k = vd{step_index};\n vd_k(i,j) = vd_ij(step_index);\n vd{step_index} = vd_k;\n end\n end \n end\n\n for i = 1:step_indices_len\n step_index = step_indices(i);\n\n vd_i = vd{step_index};\n vd_i = bsxfun(@rdivide,vd_i,sum(vd_i,2));\n ds.VarianceDecompositions{step_index} = vd_i;\n\n [sf,st,sn,si] = spillover_metrics(vd_i);\n ds.SpilloversFrom(step_index,:) = sf;\n ds.SpilloversTo(step_index,:) = st;\n ds.SpilloversNet(step_index,:) = sn;\n ds.Indicators(step_index,1) = si;\n end\n end\n\n ds.SpilloversFrom = distress_data(ds.SpilloversFrom,ds.Defaults);\n ds.SpilloversTo = distress_data(ds.SpilloversTo,ds.Defaults);\n ds.SpilloversNet = distress_data(ds.SpilloversNet,ds.Defaults);\n\nend\n\nfunction write_results(ds,temp,out)\n\n [out_path,~,~] = fileparts(out);\n\n try\n if (exist(out_path,'dir') ~= 7)\n mkdir(out_path);\n end\n\n if (exist(out,'file') == 2)\n delete(out);\n end\n catch\n error('A system I/O error occurred while writing the results.');\n end\n\n copy_result = copyfile(temp,out,'f');\n\n if (copy_result == 0)\n error('The output file could not be created from the template file.');\n end\n\n dates_str = cell2table(ds.DatesStr,'VariableNames',{'Date'});\n\n for i = 1:(numel(ds.LabelsSheetsSimple) - 1)\n sheet = ds.LabelsSheetsSimple{i};\n measure = ['Spillovers' strrep(sheet,' ','')];\n\n tab = [dates_str array2table(ds.(measure),'VariableNames',ds.FirmNames)];\n writetable(tab,out,'FileType','spreadsheet','Sheet',sheet,'WriteRowNames',true);\n end\n\n tab = [dates_str array2table(ds.Indicators,'VariableNames',strrep(ds.LabelsIndicatorsSimple,' ','_'))];\n writetable(tab,out,'FileType','spreadsheet','Sheet',ds.LabelsSheetsSimple{end},'WriteRowNames',true);\n\n worksheets_batch(out,ds.LabelsSheetsSimple,ds.LabelsSheets);\n\nend\n\n%% PLOTTING\n\nfunction analyze_result(ds)\n\n safe_plot(@(id)plot_index(ds,id));\n safe_plot(@(id)plot_spillovers(ds,id));\n safe_plot(@(id)plot_sequence(ds,id));\n\nend\n\nfunction plot_index(ds,id)\n\n si = smooth_data(ds.Indicators(:,1));\n\n f = figure('Name','Spillover Measures > Spillover Index','Units','normalized','Position',[100 100 0.85 0.85],'Tag',id);\n\n sub_1 = subplot(1,6,1:5);\n plot(sub_1,ds.DatesNum,si,'Color',[0.000 0.447 0.741]);\n set(sub_1,'XLim',[ds.DatesNum(1) ds.DatesNum(end)],'XTickLabelRotation',45);\n set(sub_1,'XGrid','on','YGrid','on');\n title(sub_1,ds.LabelsIndicators{1});\n\n if (ds.MonthlyTicks)\n date_ticks(sub_1,'x','mm/yyyy','KeepLimits','KeepTicks');\n else\n date_ticks(sub_1,'x','yyyy','KeepLimits');\n end\n\n sub_2 = subplot(1,6,6);\n boxplot(sub_2,si,'Notch','on','Symbol','k.');\n set(findobj(f,'type','line','Tag','Median'),'Color','g');\n set(findobj(f,'-regexp','Tag','\\w*Whisker'),'LineStyle','-');\n set(sub_2,'TickLength',[0 0],'XTick',[],'XTickLabels',[]);\n\n figure_title(f,'Spillover Index');\n\n maximize_figure(f);\n\nend\n\nfunction plot_spillovers(ds,id)\n\n from = smooth_data(ds.SpilloversFrom);\n from = bsxfun(@rdivide,from,sum(from,2,'omitnan'));\n from(isnan(from)) = 0;\n\n to = smooth_data(ds.SpilloversTo);\n to = bsxfun(@rdivide,to,sum(to,2,'omitnan'));\n to(isnan(to)) = 0;\n\n net = smooth_data(ds.SpilloversNet);\n net = [min(net,[],2,'omitnan') max(net,[],2,'omitnan')];\n\n f = figure('Name','Spillover Measures > Spillovers','Units','normalized','Position',[100 100 0.85 0.85],'Tag',id);\n\n sub_1 = subplot(2,2,1);\n area(sub_1,ds.DatesNum,from,'EdgeColor',[0.000 0.447 0.741],'FaceColor','none');\n set(sub_1,'XLim',[ds.DatesNum(1) ds.DatesNum(end)],'XTickLabelRotation',45);\n set(sub_1,'YLim',[0 1],'YTick',0:0.2:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(0:0.2:1) .* 100,'UniformOutput',false));\n title(sub_1,'Spillovers From Others');\n\n sub_2 = subplot(2,2,3);\n area(sub_2,ds.DatesNum,to,'EdgeColor',[0.000 0.447 0.741],'FaceColor','none');\n set(sub_2,'XLim',[ds.DatesNum(1) ds.DatesNum(end)],'XTickLabelRotation',45);\n set(sub_2,'YLim',[0 1],'YTick',0:0.2:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(0:0.2:1) .* 100,'UniformOutput',false));\n title(sub_2,'Spillovers To Others');\n\n sub_3 = subplot(2,2,[2 4]);\n fill(sub_3,[ds.DatesNum; flipud(ds.DatesNum)],[net(:,1); fliplr(net(:,2))],[0.65 0.65 0.65],'EdgeColor','none','FaceAlpha',0.35);\n hold on;\n plot(sub_3,ds.DatesNum,mean(net,2),'Color',[0.000 0.447 0.741]);\n plot(sub_3,ds.DatesNum,zeros(ds.T,1),'Color',[1.000 0.400 0.400]);\n hold off;\n set(sub_3,'XLim',[ds.DatesNum(1) ds.DatesNum(end)],'XTickLabelRotation',45);\n set(sub_3,'YLim',[-1 1],'YTick',-1:0.2:1,'YTickLabels',arrayfun(@(x)sprintf('%.f%%',x),(-1:0.2:1) .* 100,'UniformOutput',false));\n set(sub_3,'XGrid','on','YGrid','on');\n title(sub_3,'Net Spillovers');\n\n if (ds.MonthlyTicks)\n date_ticks([sub_1 sub_2 sub_3],'x','mm/yyyy','KeepLimits','KeepTicks');\n else\n date_ticks([sub_1 sub_2 sub_3],'x','yyyy','KeepLimits');\n end\n\n figure_title(f,['Spillovers (' ds.FEVD ', H=' num2str(ds.H) ', LAGS=' num2str(ds.Lags) ')']);\n\n maximize_figure(f);\n\nend\n\nfunction plot_sequence(ds,id)\n\n n = ds.N;\n t = ds.T;\n dn = ds.DatesNum;\n mt = ds.MonthlyTicks;\n\n from_all = smooth_data(ds.SpilloversFrom);\n to_all = smooth_data(ds.SpilloversTo);\n net_all = smooth_data(ds.SpilloversNet);\n\n data = [repmat({dn},1,n); mat2cell(from_all,t,ones(1,n)); mat2cell(to_all,t,ones(1,n)); mat2cell(net_all,t,ones(1,n))];\n\n plots_title = [repmat({'From'},1,n); repmat({'To'},1,n); repmat({'Net'},1,n)];\n\n x_limits = [dn(1) dn(end)];\n\n ft = [from_all to_all];\n y_limits_from = [0 1];\n y_limits_to = plot_limits(max(max(ft)),0.1,0);\n y_limits_to(2) = ceil(y_limits_to(2) * 10) / 10;\n y_limits_net = [-1 1];\n\n y_ticks_from = 0:0.2:1;\n y_ticks_to = 0:0.2:y_limits_to(2);\n y_ticks_net = -1:0.2:1;\n y_tick_labels = @(x)sprintf('%.f%%',x * 100);\n\n core = struct();\n\n core.N = n;\n core.Data = data;\n core.Function = @(subs,data)plot_function(subs,data);\n\n core.OuterTitle = 'Spillover Measures > Spillovers Time Series';\n core.InnerTitle = 'Spillovers Time Series';\n core.SequenceTitles = ds.FirmNames;\n\n core.PlotsAllocation = [3 1];\n core.PlotsSpan = {1 2 3};\n core.PlotsTitle = plots_title;\n\n core.XDates = {mt mt mt};\n core.XGrid = {true true true};\n core.XLabel = {[] [] []};\n core.XLimits = {x_limits x_limits x_limits};\n core.XRotation = {45 45 45};\n core.XTick = {[] [] []};\n core.XTickLabels = {[] [] []};\n\n core.YGrid = {true true true};\n core.YLabel = {[] [] []};\n core.YLimits = {y_limits_from y_limits_to y_limits_net};\n core.YRotation = {[] [] []};\n core.YTick = {y_ticks_from y_ticks_to y_ticks_net};\n core.YTickLabels = {y_tick_labels y_tick_labels y_tick_labels};\n\n sequential_plot(core,id);\n\n function plot_function(subs,data)\n\n x = data{1};\n from = data{2};\n to = data{3};\n net = data{4};\n\n d = find(isnan(net),1,'first');\n\n if (isempty(d))\n xd = [];\n else\n xd = x(d) - 1;\n end\n\n\t\tsub_1 = subs(1);\n plot(sub_1,x,from,'Color',[0.000 0.447 0.741]);\n if (~isempty(xd))\n hold(sub_1,'on');\n plot(sub_1,[xd xd],get(sub_1,'YLim'),'Color',[1.000 0.400 0.400]);\n hold(sub_1,'off');\n end\n\n\t\tsub_2 = subs(2);\n plot(sub_2,x,to,'Color',[0.000 0.447 0.741]);\n hold(sub_2,'on');\n plot(sub_2,x,ones(numel(x),1),'Color',[1.000 0.400 0.400]);\n if (~isempty(xd))\n plot(sub_2,[xd xd],get(sub_2,'YLim'),'Color',[1.000 0.400 0.400]);\n end\n hold(sub_2,'off');\n\n\t\tsub_3 = subs(3);\n plot(sub_3,x,net,'Color',[0.000 0.447 0.741]);\n hold(sub_3,'on');\n plot(sub_3,x,zeros(numel(x),1),'Color',[1.000 0.400 0.400]);\n if (~isempty(xd))\n plot(sub_3,[xd xd],get(sub_3,'YLim'),'Color',[1.000 0.400 0.400]);\n end\n hold(sub_3,'off');\n\n end\n\nend\n\n%% VALIDATION\n\nfunction out = validate_output(out)\n\n [path,name,extension] = fileparts(out);\n\n if (~strcmpi(extension,'.xlsx'))\n out = fullfile(path,[name extension '.xlsx']);\n end\n\nend\n\nfunction temp = validate_template(temp)\n\n sheets = {'From' 'To' 'Net' 'Indicators'};\n file_sheets = validate_xls(temp,'T');\n\n if (~all(ismember(sheets,file_sheets)))\n error(['The template must contain the following sheets: ' sheets{1} sprintf(', %s',sheets{2:end}) '.']);\n end\n\n worksheets_batch(temp,sheets);\n\nend\n", "meta": {"author": "TommasoBelluzzo", "repo": "SystemicRisk", "sha": "f5e9b4823eabab2130974e535d13762c0cb3e4bf", "save_path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk", "path": "github-repos/MATLAB/TommasoBelluzzo-SystemicRisk/SystemicRisk-f5e9b4823eabab2130974e535d13762c0cb3e4bf/ScriptsMeasures/run_spillover.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.03358950927793164, "lm_q1q2_score": 0.015746446603896996}} {"text": "function gpcf = gpcf_mask(varargin)\n%GPCF_MASK Create a mask covariance function\n%\n% Description\n% GPCF = GPCF_MASK('PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% creates a mask covariance function structure in\n% which the named parameters have the specified values. Any\n% unspecified parameters are set to default values.\n%\n% GPCF = GPCF_MASK(GPCF,'PARAM1',VALUE1,'PARAM2,VALUE2,...) \n% modify a covariance function structure with the named\n% parameters altered with the specified values.\n% \n% Mask covariance function returns correlation 1 if input\n% values X_i and X_j are both non zero and 0 otherwise.\n%\n% Parameters for mask covariance function\n% selectedVariables - vector defining which inputs are used\n%\n% See also\n% GP_SET, GPCF_*, PRIOR_*, MEAN_*\n\n% Copyright (c) 2007-2010 Jarno Vanhatalo\n% Copyright (c) 2008-2010 Jaakko Riihim�ki\n% Copyright (c) 2010 Aki Vehtari\n\n% This software is distributed under the GNU General Public\n% License (version 3 or later); please refer to the file\n% License.txt, included with the software, for details.\n\n ip=inputParser;\n ip.FunctionName = 'GPCF_MASK';\n ip.addOptional('gpcf', [], @isstruct);\n ip.addParamValue('selectedVariables',[], ...\n @(x) isempty(x) || (isvector(x) && all(x>0)));\n ip.parse(varargin{:});\n gpcf=ip.Results.gpcf;\n\n if isempty(gpcf)\n % Initialize a covariance function structure\n init=true;\n gpcf.type = 'gpcf_mask';\n else\n % Modify a covariance function structure\n if ~isfield(gpcf,'type') && ~isequal(gpcf.type,'gpcf_mask')\n error('First argument does not seem to be a valid covariance function structure')\n end\n init=false;\n end\n \n if ~ismember('selectedVariables',ip.UsingDefaults)\n if ~isempty(ip.Results.selectedVariables)\n gpcf.selectedVariables = ip.Results.selectedVariables;\n elseif isfield(gpcf,'selectedVariables')\n gpcf=rmfield(gpcf,'selectedVariables');\n end\n end\n if init\n gpcf.fh.pak = @gpcf_mask_pak;\n gpcf.fh.unpak = @gpcf_mask_unpak;\n gpcf.fh.lp = @gpcf_mask_lp;\n gpcf.fh.lpg = @gpcf_mask_lpg;\n gpcf.fh.cfg = @gpcf_mask_cfg;\n gpcf.fh.ginput = @gpcf_mask_ginput;\n gpcf.fh.cov = @gpcf_mask_cov;\n gpcf.fh.trcov = @gpcf_mask_trcov;\n gpcf.fh.trvar = @gpcf_mask_trvar;\n gpcf.fh.recappend = @gpcf_mask_recappend;\n end\n \nend\n\nfunction [w,s] = gpcf_mask_pak(gpcf, w)\n%GPCF_MASK_PAK Combine GP covariance function parameters into\n% one vector.\n%\n% Description\n% W = GPCF_MASK_PAK(GPCF) takes a covariance function\n% structure GPCF and combines the covariance function\n% parameters and their hyperparameters into a single row\n% vector W. This is a mandatory subfunction used for \n% example in energy and gradient computations.\n%\n% w = []\n%\n% See also\n% GPCF_MASK_UNPAK\n \n w = []; s = {};\nend\n\nfunction [gpcf, w] = gpcf_mask_unpak(gpcf, w)\n%GPCF_MASK_UNPAK Sets the covariance function parameters into\n% the structure\n%\n% Description\n% [GPCF, W] = GPCF_MASK_UNPAK(GPCF, W) takes a covariance\n% function structure GPCF and a parameter vector W, and\n% returns a covariance function structure identical to the\n% input, except that the covariance parameters have been set\n% to the values in W. Deletes the values set to GPCF from W\n% and returns the modified W. This is a mandatory subfunction \n% used for example in energy and gradient computations.\n%\n% Assignment is inverse of \n% w = []\n%\n% See also\n% GPCF_MASK_PAK\n \nend\n\nfunction lp = gpcf_mask_lp(gpcf)\n%GPCF_MASK_LP Evaluate the energy of prior of covariance function parameters\n%\n% Description\n% LP = GPCF_MASK_LP(GPCF) takes a covariance function\n% structure GPCF and returns log(p(th)), where th collects the\n% parameters. This is a mandatory subfunction used for example \n% in energy computations.\n%\n% See also\n% GPCF_MASK_PAK, GPCF_MASK_UNPAK, GPCF_MASK_LPG, GP_E\n\n lp = 0;\n \nend\n\nfunction lpg = gpcf_mask_lpg(gpcf)\n%GPCF_MASK_LPG Evaluate gradient of the log prior with respect\n% to the parameters.\n%\n% Description\n% LPG = GPCF_MASK_LPG(GPCF) takes a covariance function\n% structure GPCF and returns LPG = d log (p(th))/dth, where th\n% is the vector of parameters. This is a mandatory subfunction \n% used for example in gradient computations.\n%\n% See also\n% GPCF_MASK_PAK, GPCF_MASK_UNPAK, GPCF_MASK_LP, GP_G\n \n lpg = [];\n\nend\n\nfunction DKff = gpcf_mask_cfg(gpcf, x, x2, mask,i1)\n%GPCF_MASK_CFG Evaluate gradient of covariance function\n% with respect to the parameters.\n%\n% Description\n% DKff = GPCF_MASK_CFG(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to th (cell array with matrix elements). This is a \n% mandatory subfunction used in gradient computations.\n%\n% DKff = GPCF_MASK_CFG(GPCF, X, X2) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X2) with\n% respect to th (cell array with matrix elements). This subfunction \n% is needed when using sparse approximations (e.g. FIC).\n%\n% DKff = GPCF_MASK_CFG(GPCF, X, [], MASK) takes a covariance\n% function structure GPCF, a matrix X of input vectors and\n% returns DKff, the diagonal of gradients of covariance matrix\n% Kff = k(X,X2) with respect to th (cell array with matrix\n% elements). This subfunction is needed when using sparse \n% approximations (e.g. FIC).\n%\n% DKff = GPCF_MASK_CFG(GPCF, X, X2, [], i) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X2), or k(X,X)\n% if X2 is empty, with respect to ith hyperparameter. This subfunction\n% is needed when using memory save option in gp_set.\n%\n% See also\n% GPCF_MASK_PAK, GPCF_MASK_UNPAK, GPCF_MASK_LP, GP_G\n\n DKff = {};\n \nend\n\nfunction [DKff, lpg] = gpcf_mask_ginput(gpcf, x, x2, i1)\n%GPCF_MASK_GINPUT Evaluate gradient of covariance function with \n% respect to x.\n%\n% Description\n% DKff = GPCF_MASK_GINPUT(GPCF, X) takes a covariance function\n% structure GPCF, a matrix X of input vectors and returns\n% DKff, the gradients of covariance matrix Kff = k(X,X) with\n% respect to X (cell array with matrix elements). This subfunction\n% is needed when computing gradients with respect to inducing\n% inputs in sparse approximations.\n%\n% DKff = GPCF_MASK_GINPUT(GPCF, X, X2) takes a covariance\n% function structure GPCF, a matrix X of input vectors\n% and returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2) with respect to X (cell array with matrix elements).\n% This subfunction is needed when computing gradients with \n% respect to inducing inputs in sparse approximations.\n%\n% DKff = GPCF_MASK_GINPUT(GPCF, X, X2, i) takes a covariance\n% function structure GPCF, a matrix X of input vectors\n% and returns DKff, the gradients of covariance matrix Kff =\n% k(X,X2), or k(X,X) if X2 is empty, with respect to ith covariate\n% in X. This subfunction is needed when using memory saving option\n% in gp_set.\n%\n% See also\n% GPCF_MASK_PAK, GPCF_MASK_UNPAK, GPCF_MASK_LP, GP_G\n \n [n, m] =size(x);\n \n if nargin == 2 || isempty(x2)\n ii1 = 0;\n for i=1:m\n for j = 1:n\n ii1 = ii1 + 1;\n DKff{ii1} = zeros(n);\n lpg(ii1) = 0;\n end\n end\n elseif nargin == 3 || nargin == 4\n ii1 = 0;\n for i=1:m\n for j = 1:n\n ii1 = ii1 + 1;\n DKff{ii1} = zeros(n, size(x2,1));\n lpg(ii1) = 0; \n end\n end\n end\n if nargin==4\n DKff=DKff{1};\n end\nend\n\nfunction C = gpcf_mask_cov(gpcf, x1, x2, varargin)\n%GP_MASK_COV Evaluate covariance matrix between two input vectors\n%\n% Description \n% C = GP_MASK_COV(GP, TX, X) takes in covariance function of a\n% Gaussian process GP and two matrixes TX and X that contain\n% input vectors to GP. Returns covariance matrix C. Every\n% element ij of C contains covariance between inputs i in TX\n% and j in X. This is a mandatory subfunction used for example in\n% prediction and energy computations.\n%\n% See also\n% GPCF_MASK_TRCOV, GPCF_MASK_TRVAR, GP_COV, GP_TRCOV\n \n if isempty(x2)\n x2=x1;\n end\n [n1,m1]=size(x1);\n [n2,m2]=size(x2);\n \n if m1~=m2\n error('the number of columns of X1 and X2 has to be same')\n end\n\n C=repmat(true,n1,n2);\n if isfield(gpcf, 'selectedVariables')\n for j = 1:length(gpcf.selectedVariables)\n jj=gpcf.selectedVariables(j);\n C = C & bsxfun(@and,x1(:,jj)~=0,x2(:,jj)'~=0);\n end\n else\n for j = 1:m1\n C = C & bsxfun(@and,x1(:,j)~=0,x2(:,j)'~=0);\n end\n end\n C=double(C);\n \nend\n\nfunction C = gpcf_mask_trcov(gpcf, x)\n%GP_MASK_TRCOV Evaluate training covariance matrix of inputs\n%\n% Description\n% C = GP_MASK_TRCOV(GP, TX) takes in covariance function of a\n% Gaussian process GP and matrix TX that contains training\n% input vectors. Returns covariance matrix C. Every element ij\n% of C contains covariance between inputs i and j in TX. This \n% is a mandatory subfunction used for example in prediction \n% and energy computations.\n%\n% See also\n% GPCF_MASK_COV, GPCF_MASK_TRVAR, GP_COV, GP_TRCOV\n\n [n,m]=size(x);\n\n C=repmat(true,n,n);\n if isfield(gpcf, 'selectedVariables')\n for j = 1:length(gpcf.selectedVariables)\n jj=gpcf.selectedVariables(j);\n C = C & bsxfun(@and,x(:,jj)~=0,x(:,jj)'~=0);\n end\n else\n for j = 1:m\n C = C & bsxfun(@and,x(:,j)~=0,x(:,j)'~=0);\n end\n end\n C=double(C);\n \nend\n\nfunction C = gpcf_mask_trvar(gpcf, x)\n%GP_MASK_TRVAR Evaluate training variance vector\n%\n% Description\n% C = GP_MASK_TRVAR(GPCF, TX) takes in covariance function of a\n% Gaussian process GPCF and matrix TX that contains training\n% inputs. Returns variance vector C. Every element i of C\n% contains variance of input i in TX. This is a mandatory \n% subfunction used for example in prediction and energy \n% computations.\n%\n% See also\n% GPCF_MASK_COV, GP_COV, GP_TRCOV\n\n [n,m]=size(x);\n C=true(n,1);\n if isfield(gpcf, 'selectedVariables')\n for j = 1:length(gpcf.selectedVariables)\n jj=gpcf.selectedVariables(j);\n C = C & x(:,jj)~=0;\n end\n else\n for j = 1:m\n C = C & x(:,j)~=0;\n end\n end\n C=double(C);\n \nend\n\nfunction reccf = gpcf_mask_recappend(reccf, ri, gpcf)\n%RECAPPEND Record append\n%\n% Description\n% RECCF = GPCF_MASK_RECAPPEND(RECCF, RI, GPCF) takes a\n% covariance function record structure RECCF, record index RI\n% and covariance function structure GPCF with the current MCMC\n% samples of the parameters. Returns RECCF which contains\n% all the old samples and the current samples from GPCF.\n% This subfunction is needed when using MCMC sampling (gp_mc).\n%\n% See also\n% GP_MC and GP_MC -> RECAPPEND\n\n if nargin == 2\n % Initialize the record\n reccf.type = 'gpcf_mask';\n\n % Initialize parameters\n reccf.coeffSigma2= [];\n\n % Set the function handles\n reccf.fh.pak = @gpcf_mask_pak;\n reccf.fh.unpak = @gpcf_mask_unpak;\n reccf.fh.lp = @gpcf_mask_lp;\n reccf.fh.lpg = @gpcf_mask_lpg;\n reccf.fh.cfg = @gpcf_mask_cfg;\n reccf.fh.cov = @gpcf_mask_cov;\n reccf.fh.trcov = @gpcf_mask_trcov;\n reccf.fh.trvar = @gpcf_mask_trvar;\n reccf.fh.recappend = @gpcf_mask_recappend;\n else\n % Append to the record\n if isfield(gpcf, 'selectedVariables')\n reccf.selectedVariables = gpcf.selectedVariables;\n end\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/external/dmlt/external/gpstuff/gp/gpcf_mask.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702847, "lm_q2_score": 0.04468086868252905, "lm_q1q2_score": 0.01573668218105581}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% To run: Edit user options in npscalc.m and execute the code.\n%\n% This code is intended to accompany the manuscript entitled:\n% \n% A simple approach to measure computed tomography (CT) modulation transfer \n% function (MTF) and noise-power spectrum (NPS) using the American College \n% of Radiology (ACR) accreditation phantom\n%\n% Please do not distribute.\n%\n% This program requires the following 4 files:\n% npscalc.m\n% SliceBrowser.m\n% SliceBrowser.fig\n% license.txt\n%\n% Purpose: To calculate the 3D NPS using CT data of the American College\n% of Radiology (ACR) accreditation phantom.\n%\n% Input: Two consecutive scans of the phantom are needed. The program \n% requires a data directory to be selected in which there are \n% only two subdirectories containing only CT slices corresponding \n% to the third module of the phantom. Be careful of partial\n% volume effects with surrounding modules.\n%\n% i.e., datadir\n% |-> scan 1 dir\n% | | -> only module 3 slices\n% | \n% |-> scan 2 dir\n% |-> only module 3 slices\n%\n% Copyright 2012 Saul N. Friedman\n% Distributed under the terms of the \"New BSD License.\" Please see\n% license.txt.\n%\n% N.B.: SliceBrowser.m is an altered version of code by Marian Uhercik.\n% Please see license.txt.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% ======================================================================\n%> SLICEBROWSER M-file for SliceBrowser.fig\n%> SliceBrowser is an interactive viewer of 3D volumes, \n%> it shows 3 perpendicular slices (XY, YZ, ZX) with 3D pointer.\n%> Input: a) VOLUME - a 3D matrix with volume data\n%> b) VOLUME - a 4D matrix with volume data over time\n%> Control:\n%> - Clicking into the window changes the location of 3D pointer.\n%> - 3D pointer can be moved also by keyboard arrows.\n%> - Pressing +/- will switch to next/previous volume.\n%> - Pressing 1,2,3 will change the focus of current axis.\n%> - Pressing 'e' will print the location of 3D pointer.\n%> - Pressing 'c' switches between color-mode and grayscale.\n%> - Pressing 'q' switches scaling of axis (equal/normal).\n%> Example of usage:\n%> load mri.dat\n%> volume = squeeze(D);\n%> SliceBrowser(volume);\n%>\n%> Last modified by Saul N. Friedman\n% ======================================================================\nfunction varargout = SliceBrowser(varargin)\n\n% Documentation generated GUIDE:\n%\n%SLICEBROWSER M-file for SliceBrowser.fig\n% SLICEBROWSER, by itself, creates a new SLICEBROWSER or raises the existing\n% singleton*.\n%\n% H = SLICEBROWSER returns the handle to a new SLICEBROWSER or the handle to\n% the existing singleton*.\n%\n% SLICEBROWSER('Property','Value',...) creates a new SLICEBROWSER using the\n% given property value pairs. Unrecognized properties are passed via\n% varargin to SliceBrowser_OpeningFcn. This calling syntax produces a\n% warning when there is an existing singleton*.\n%\n% SLICEBROWSER('CALLBACK') and SLICEBROWSER('CALLBACK',hObject,...) call the\n% local function named CALLBACK in SLICEBROWSER.M with the given input\n% arguments.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help SliceBrowser\n\n% Last Modified by GUIDE v2.5 01-Sep-2008 13:14:20\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 0;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @SliceBrowser_OpeningFcn, ...\n 'gui_OutputFcn', @SliceBrowser_OutputFcn, ...\n 'gui_LayoutFcn', [], ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before SliceBrowser is made visible.\nfunction SliceBrowser_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin unrecognized PropertyName/PropertyValue pairs from the\n% command line (see VARARGIN)\n\n% Choose default command line output for SliceBrowser\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes SliceBrowser wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\nif (length(varargin) <=0)\n error('Input volume has not been specified.');\nend;\nvolume = varargin{1};\nif (ndims(volume) ~= 3 && ndims(volume) ~= 4)\n error('Input volume must have 3 or 4 dimensions.');\nend;\nhandles.volume = volume;\n\nhandles.axis_equal = 0;\nhandles.color_mode = 1;\nif (size(volume,4) ~= 3)\n handles.color_mode = 0;\nend;\n\n% set main wnd title\nset(gcf, 'Name', 'Slice Viewer')\n\n% init 3D pointer\nvol_sz = size(volume); \nif (ndims(volume) == 3)\n vol_sz(4) = 1;\nend;\npointer3dt = floor(vol_sz/2)+1;\nhandles.pointer3dt = pointer3dt;\nhandles.vol_sz = vol_sz;\n\nplot3slices(hObject, handles);\n\n% stores ID of last axis window \n% (0 means that no axis was clicked yet)\nhandles.last_axis_id = 0;\n\n% Update handles structure\nguidata(hObject, handles);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = SliceBrowser_OutputFcn(hObject, eventdata, handles)\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on mouse press over axes background.\nfunction Subplot1_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to Subplot1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% This object contains the XY slice\n\nxaxis = getappdata(0,'uaxis');\nyaxis = getappdata(0,'vaxis');\nzaxis = getappdata(0,'waxis');\naxlabel = getappdata(0,'axlabel');\ndeltayaxis = yaxis(2) - yaxis(1);\ndeltaxaxis = xaxis(2) - xaxis(1);\ndeltazaxis = zaxis(2) - zaxis(1);\n\n%disp('Subplot1:BtnDown');\npt=get(gca,'currentpoint');\nif length(xaxis) > 0 && length(yaxis) \n xpos=round((pt(1,2)+xaxis(end))/deltaxaxis); ypos=round((pt(1,1)+yaxis(end))/deltayaxis);\nelse\nxpos=round(pt(1,2)); ypos=round(pt(1,1));\nend\nzpos = handles.pointer3dt(3);\ntpos = handles.pointer3dt(4);\nhandles.pointer3dt = [xpos ypos zpos tpos];\nhandles.pointer3dt = clipointer3d(handles.pointer3dt,handles.vol_sz);\nplot3slices(hObject, handles);\n% store this axis as last clicked region\nhandles.last_axis_id = 1;\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on mouse press over axes background.\nfunction Subplot2_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to Subplot2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% This object contains the YZ slice\n\nxaxis = getappdata(0,'uaxis');\nyaxis = getappdata(0,'vaxis');\nzaxis = getappdata(0,'waxis');\naxlabel = getappdata(0,'axlabel');\ndeltayaxis = yaxis(2) - yaxis(1);\ndeltaxaxis = xaxis(2) - xaxis(1);\ndeltazaxis = zaxis(2) - zaxis(1);\n\n%disp('Subplot2:BtnDown');\npt=get(gca,'currentpoint');\nif length(xaxis) > 0 && length(zaxis) \n xpos=round((pt(1,2)+xaxis(end))/deltaxaxis); zpos=round((pt(1,1)+zaxis(end))/deltazaxis);\nelse\nxpos=round(pt(1,2)); zpos=round(pt(1,1));\nend\nypos = handles.pointer3dt(2);\ntpos = handles.pointer3dt(4);\nhandles.pointer3dt = [xpos ypos zpos tpos];\nhandles.pointer3dt = clipointer3d(handles.pointer3dt,handles.vol_sz);\nplot3slices(hObject, handles);\n% store this axis as last clicked region\nhandles.last_axis_id = 2;\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on mouse press over axes background.\nfunction Subplot3_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to Subplot3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% This object contains the XZ slice\n\nxaxis = getappdata(0,'uaxis');\nyaxis = getappdata(0,'vaxis');\nzaxis = getappdata(0,'waxis');\naxlabel = getappdata(0,'axlabel');\ndeltayaxis = yaxis(2) - yaxis(1);\ndeltaxaxis = xaxis(2) - xaxis(1);\ndeltazaxis = zaxis(2) - zaxis(1);\n\n%disp('Subplot3:BtnDown');\npt=get(gca,'currentpoint');\nif length(xaxis) > 0 && length(zaxis) \n ypos=round((pt(1,1)+yaxis(end))/deltayaxis); zpos=round((pt(1,2)+zaxis(end))/deltazaxis);\nelse\nzpos=round(pt(1,2)); ypos=round(pt(1,1));\nend\nxpos = handles.pointer3dt(1);\ntpos = handles.pointer3dt(4);\nhandles.pointer3dt = [xpos ypos zpos tpos];\nhandles.pointer3dt = clipointer3d(handles.pointer3dt,handles.vol_sz);\nplot3slices(hObject, handles);\n% store this axis as last clicked region\nhandles.last_axis_id = 3;\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Executes on key press with focus on SliceBrowserFigure and no controls selected.\nfunction SliceBrowserFigure_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to SliceBrowserFigure (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n%disp('SliceBrowserFigure_KeyPressFcn');\ncurr_char = int8(get(gcf,'CurrentCharacter'));\nif isempty(curr_char)\n return;\nend;\n\nxpos = handles.pointer3dt(1);\nypos = handles.pointer3dt(2);\nzpos = handles.pointer3dt(3); \ntpos = handles.pointer3dt(4); \n% Keys:\n% - up: 30\n% - down: 31\n% - left: 28\n% - right: 29\n% - '1': 49\n% - '2': 50\n% - '3': 51\n% - 'e': 101\n% - plus: 43\n% - minus: 45\nswitch curr_char\n case 99 % 'c'\n handles.color_mode = 1 - handles.color_mode;\n if (handles.color_mode ==1 && size(handles.volume,4) ~= 3)\n handles.color_mode = 0;\n end;\n \n case 113 % 'q'\n handles.axis_equal = 1 - handles.axis_equal;\n \n case 30\n switch handles.last_axis_id\n case 1\n xpos = xpos -1;\n case 2\n xpos = xpos -1;\n case 3\n zpos = zpos -1;\n case 0\n end;\n case 31\n switch handles.last_axis_id\n case 1\n xpos = xpos +1;\n case 2\n xpos = xpos +1;\n case 3\n zpos = zpos +1;\n case 0\n end;\n case 28\n switch handles.last_axis_id\n case 1\n ypos = ypos -1;\n case 2\n zpos = zpos -1;\n case 3\n ypos = ypos -1;\n case 0\n end;\n case 29\n switch handles.last_axis_id\n case 1\n ypos = ypos +1;\n case 2\n zpos = zpos +1;\n case 3\n ypos = ypos +1;\n case 0\n end;\n case 43\n % plus key\n tpos = tpos+1;\n case 45\n % minus key\n tpos = tpos-1;\n case 49\n % key 1\n handles.last_axis_id = 1;\n case 50\n % key 2\n handles.last_axis_id = 2;\n case 51\n % key 3\n handles.last_axis_id = 3;\n case 101\n disp(['[' num2str(xpos) ' ' num2str(ypos) ' ' num2str(zpos) ' ' num2str(tpos) ']']);\n otherwise\n return\nend;\nhandles.pointer3dt = [xpos ypos zpos tpos];\nhandles.pointer3dt = clipointer3d(handles.pointer3dt,handles.vol_sz);\nplot3slices(hObject, handles);\n% Update handles structure\nguidata(hObject, handles);\n\n% --- Plots all 3 slices XY, YZ, XZ into 3 subplots\nfunction [sp1,sp2,sp3] = plot3slices(hObject, handles)\n% pointer3d 3D coordinates in volume matrix (integers)\n\nhandles.pointer3dt;\nsize(handles.volume);\nvalue3dt = handles.volume(handles.pointer3dt(1), handles.pointer3dt(2), handles.pointer3dt(3), handles.pointer3dt(4));\n\ntext_str = ['[X:' int2str(handles.pointer3dt(1)) ...\n ', Y:' int2str(handles.pointer3dt(2)) ...\n ', Z:' int2str(handles.pointer3dt(3)) ...\n ', Time:' int2str(handles.pointer3dt(4)) '/' int2str(handles.vol_sz(4)) ...\n '], value:' num2str(value3dt)];\nset(handles.pointer3d_info, 'String', text_str);\nguidata(hObject, handles);\n\nif (handles.color_mode ==1)\n sliceXY = squeeze(handles.volume(:,:,handles.pointer3dt(3),:));\n sliceYZ = squeeze(handles.volume(handles.pointer3dt(1),:,:,:));\n sliceXZ = squeeze(handles.volume(:,handles.pointer3dt(2),:,:));\n\n max_xyz = max([ max(sliceXY(:)) max(sliceYZ(:)) max(sliceXZ(:)) ]);\n min_xyz = min([ min(sliceXY(:)) min(sliceYZ(:)) min(sliceXZ(:)) ]);\n clims = [ min_xyz max_xyz ];\nelse\n sliceXY = squeeze(handles.volume(:,:,handles.pointer3dt(3),handles.pointer3dt(4)));\n sliceYZ = squeeze(handles.volume(handles.pointer3dt(1),:,:,handles.pointer3dt(4)));\n sliceXZ = squeeze(handles.volume(:,handles.pointer3dt(2),:,handles.pointer3dt(4)));\n\n max_xyz = max([ max(sliceXY(:)) max(sliceYZ(:)) max(sliceXZ(:)) ]);\n min_xyz = min([ min(sliceXY(:)) min(sliceYZ(:)) min(sliceXZ(:)) ]);\n clims = [ min_xyz max_xyz ];\nend;\nsliceZY = squeeze(permute(sliceYZ, [2 1 3]));\n\nxaxis = getappdata(0,'uaxis');\nyaxis = getappdata(0,'vaxis');\nzaxis = getappdata(0,'waxis');\naxlabel = getappdata(0,'axlabel');\nif length(xaxis) > 0 && length(yaxis) && length(zaxis)\ndeltayaxis = yaxis(2) - yaxis(1);\ndeltaxaxis = xaxis(2) - xaxis(1);\ndeltazaxis = zaxis(2) - zaxis(1);\nend\n \n\nsp1 = subplot(2,2,1);\n%colorbar;\nif length(xaxis) > 0 && length(yaxis) \n imagesc([yaxis(1) yaxis(end)],[xaxis(1) xaxis(end)],sliceXY,clims)\nelse\nimagesc(sliceXY, clims);\nend\nif (handles.axis_equal == 1)\n axis image;\nelse\n axis normal;\nend;\ntitle('Slice XY');\nif exist('axlabel')\n xlabel(['Y',axlabel]);ylabel(['X',axlabel])\nelse\nylabel('X');xlabel('Y');\nend\nif length(xaxis) > 0 && length(yaxis) \n line([handles.pointer3dt(2).*deltayaxis - yaxis(end) handles.pointer3dt(2).*deltayaxis - yaxis(end)], [-size(handles.volume,1) size(handles.volume,1)]);\n line([-size(handles.volume,2) size(handles.volume,2)], [handles.pointer3dt(1).*deltaxaxis - xaxis(end) handles.pointer3dt(1).*deltaxaxis - xaxis(end)]);\nelse\nline([handles.pointer3dt(2) handles.pointer3dt(2)], [0 size(handles.volume,1)]);\nline([0 size(handles.volume,2)], [handles.pointer3dt(1) handles.pointer3dt(1)]);\nend\n%set(allchild(gca),'ButtonDownFcn',@Subplot1_ButtonDownFcn);\nset(allchild(gca),'ButtonDownFcn','SliceBrowser(''Subplot1_ButtonDownFcn'',gca,[],guidata(gcbo))');\n\n\nsp2 = subplot(2,2,2);\nif length(xaxis) > 0 &&length(zaxis) > 0 \n imagesc([zaxis(1) zaxis(end)],[xaxis(1) xaxis(end)],sliceXZ,clims)\nelse\nimagesc(sliceXZ, clims);\nend\nif (handles.axis_equal == 1)\n axis image;\nelse\n axis normal;\nend;\ntitle('Slice XZ');\nif exist('axlabel')\n ylabel(['X',axlabel]);xlabel(['Z',axlabel])\nelse\nylabel('X');xlabel('Z');\nend\nif length(xaxis) > 0 && length(zaxis) \n line([handles.pointer3dt(3).*deltazaxis - zaxis(end) handles.pointer3dt(3).*deltazaxis - zaxis(end)], [-size(handles.volume,1).*deltaxaxis size(handles.volume,1).*deltaxaxis]);\nline([-size(handles.volume,3).*deltazaxis size(handles.volume,3).*deltazaxis], [handles.pointer3dt(1).*deltaxaxis - xaxis(end) handles.pointer3dt(1).*deltaxaxis - xaxis(end)]);\nelse\nline([handles.pointer3dt(3) handles.pointer3dt(3)], [0 size(handles.volume,1)]);\nline([0 size(handles.volume,3)], [handles.pointer3dt(1) handles.pointer3dt(1)]);\nend\n%set(allchild(gca),'ButtonDownFcn',@Subplot2_ButtonDownFcn);\nset(allchild(gca),'ButtonDownFcn','SliceBrowser(''Subplot2_ButtonDownFcn'',gca,[],guidata(gcbo))');\n\n\n\nsp3 = subplot(2,2,3);\nif length(yaxis) > 0 && length(zaxis) > 0 \n imagesc([yaxis(1) yaxis(end)],[zaxis(1) zaxis(end)],sliceZY,clims)\nelse\nimagesc(sliceZY, clims);\nend\nif (handles.axis_equal == 1)\n axis image;\nelse\n axis normal;\nend;\ntitle('Slice ZY');\nif exist('axlabel')\n ylabel(['Z',axlabel]);xlabel(['Y',axlabel])\nelse\nylabel('Z');xlabel('Y');\nend\n\nif length(yaxis) > 0 && length(zaxis) \n line([-size(handles.volume,2) size(handles.volume,2)], [handles.pointer3dt(3).*deltazaxis - zaxis(end) handles.pointer3dt(3).*deltazaxis - zaxis(end)]);\n line([handles.pointer3dt(2).*deltayaxis - yaxis(end) handles.pointer3dt(2).*deltayaxis - yaxis(end)], [-size(handles.volume,3).*deltazaxis size(handles.volume,3).*deltazaxis]);\nelse\nline([0 size(handles.volume,2)], [handles.pointer3dt(3) handles.pointer3dt(3)]);\nline([handles.pointer3dt(2) handles.pointer3dt(2)], [0 size(handles.volume,3)]);\nend\n%set(allchild(gca),'ButtonDownFcn',@Subplot3_ButtonDownFcn);\nset(allchild(gca),'ButtonDownFcn','SliceBrowser(''Subplot3_ButtonDownFcn'',gca,[],guidata(gcbo))');\n\n\nfunction pointer3d_out = clipointer3d(pointer3d_in,vol_size)\npointer3d_out = pointer3d_in;\nfor p_id=1:4\n if (pointer3d_in(p_id) > vol_size(p_id))\n pointer3d_out(p_id) = vol_size(p_id);\n end;\n if (pointer3d_in(p_id) < 1)\n pointer3d_out(p_id) = 1;\n end;\nend;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41401-calculation-of-ct-mtf-and-nps-using-the-acr-accreditation-phantom/SliceBrowser.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.034100429025267616, "lm_q1q2_score": 0.015720869962397094}} {"text": "classdef unbndfun < classicfun\n%UNBNDFUN Represent global functions on an unbounded interval [-inf inf] or\n% a semi-infinite interval [-inf b] or [a inf].\n%\n% Constructor inputs:\n% UNBNDFUN(OP) constructs a UNBNDFUN object from the function handle OP on the\n% domain determined by the default in CHEBFUNPREF by mapping the domain to\n% [-1, 1] and constructing a ONEFUN object to represent the function\n% prescribed by OP. OP should be vectorised (i.e., accept a vector input)\n% and output a vector of the same length as its input.\n%\n% UNBNDFUN(OP, DATA) constructs an UNBNDFUN object using the data supplied in\n% the DATA structure. DATA fields used by UNBNDFUN are:\n% DATA.DOMAIN (Default: Determined by CHEBFUNPREF)\n% A row vector with two elements in increasing order defining the\n% construction domain. At least one element must be infinite.\n% In addition, UNBNDFUN may modify the following DATA fields before passing\n% them on to the ONEFUN constructor:\n% DATA.HSCALE (Default: Determined by DATA.DOMAIN)\n% Horizontal construction scale.\n% DATA.EXPONENTS (Default: Empty)\n% Exponents describing the behavior of the function at the endpoints of\n% the construction domain. (See SINGFUN.)\n% DATA.SINGTYPE (Default: Empty)\n% Types of endpoint singularities to search for. (See SINGFUN.)\n% If any fields in DATA are empty or not supplied, or if DATA itself is empty\n% or not supplied, appropriate default values are set. Any fields in DATA\n% which are not recognized will be passed as-is to the ONEFUN constructor.\n%\n% UNBNDFUN(OP, DATA, PREF) overrides the default behavior with that given by\n% the preferences in the structure or CHEBFUNPREF object PREF. See\n% CHEBFUNPREF for details.\n%\n% See also CLASSICFUN, CHEBFUNPREF, ONEFUN.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% UNBNDFUN Class Description:\n%\n% The UNBNDFUN class represents global functions on the infinite or\n% semi-infinite interval [-inf, b], [a, inf], or [-inf, inf]. It achieves this\n% by taking a onefun on [-1, 1] and applying a nonlinear mapping.\n%\n% Note that all binary UNBNDFUN operators (methods which can take two UNBNDFUN\n% arguments) assume that the domains of the UNBNDFUN objects agree. The methods\n% will not throw warnings if assumption is violated, but the results will not be\n% meaningful under that circumstance.\n%\n% Class diagram: [<>] <>-- [<>]\n% ^\n% |\n% [unbndfun]\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% CLASS CONSTRUCTOR:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = false )\n \n function obj = unbndfun(op, data, pref)\n \n % Parse inputs.\n if ( (nargin < 1) || isempty(op) )\n obj.domain = [];\n obj.mapping = [];\n obj.onefun = [];\n return\n end\n\n if ( (nargin < 2) || isempty(data) )\n data = struct();\n end\n\n if ( (nargin < 3) || isempty(pref) )\n pref = chebfunpref();\n else\n pref = chebfunpref(pref);\n end\n\n data = parseDataInputs(data, pref);\n\n % Check domain\n if ( ~all(size(data.domain) == [1, 2]) || (diff(data.domain) <= 0) )\n error('CHEBFUN:UNBNDFUN:unbndfun:domain',...\n ['Domain argument should be a row vector with two ', ...\n 'entries in increasing order.']);\n elseif ( ~any(isinf(data.domain)) )\n error('CHEBFUN:UNBNDFUN:unbndfun:boundedDomain',...\n 'Domain argument should be unbounded.');\n end\n\n % Remap the OP to be a function on [-1, 1].\n unbndmap = unbndfun.createMap(data.domain);\n if ( isa(op, 'function_handle') )\n op = @(x) op(unbndmap.For(x));\n elseif ( isnumeric(op) )\n if ( ~any(op(:)) )\n op = @(x) zeros(length(x), size(op, 2));\n else\n %[TODO]: Implement this.\n error('CHEBFUN:UNBNDFUN:unbndfun:inputValues',...\n ['UNBNDFUN does not support non-zero construction ' ...\n 'from values.']);\n end\n end\n\n % Deal with exponents for singular functions.\n if ( isempty(data.exponents) )\n % The user hasn't supplied exponents, but functions on\n % unbounded domains are often singular once remapped to [-1,\n % 1]. Try to detect this by seeing if the function is infinite\n % at either endpoint and, if so, enable singularity detection.\n lVal = feval(op, -1);\n rVal = feval(op, 1);\n if ( any(isinf([lVal rVal])) )\n pref.blowup = true;\n singType = pref.blowupPrefs.defaultSingType;\n data.singType = {singType, singType};\n end\n else\n % Remapping to [-1, 1] negates exponents, which are given with\n % respect to the function on the infinite domain.\n ind = isinf(data.domain);\n pref.blowup = true;\n data.exponents(ind) = -data.exponents(ind);\n end\n\n % Call the ONEFUN constructor:\n obj.onefun = onefun.constructor(op, data, pref);\n\n % Add the domain and mapping:\n obj.domain = data.domain;\n obj.mapping = unbndmap;\n end\n \n end\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %% STATIC METHODS:\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n methods ( Access = public, Static = true ) \n \n % Retrieve and modify preferences for this class.\n prefs = pref(varargin);\n \n % Noninear map from [-1, 1] to the domain of the UNBNDFUN.\n m = createMap(domain);\n \n % Make a UNBNDFUN (constructor shortcut):\n f = make(varargin); \n \n end\n \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% PRIVATE METHODS IMPLEMENTED IN THIE FILE:\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction data = parseDataInputs(data, pref)\n%PARSEDATAINPUTS Parse inputs from the DATA structure and assign defaults.\n\nif ( ~isfield(data, 'domain') || isempty(data.domain) )\n data.domain = pref.domain;\nend\n\nif ( ~isfield(data, 'hscale') || isempty(data.hscale) )\n % TODO: Why is the hscale of an unbounded domain always 1?\n data.hscale = 1;\nend\n\nif ( ~isfield(data, 'exponents') || isempty(data.exponents) )\n data.exponents = [];\nend\n\nif ( ~isfield(data, 'singType') || isempty(data.singType) )\n data.singType = [];\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@unbndfun/unbndfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.031618765101415466, "lm_q1q2_score": 0.01556238104905943}} {"text": "function cvt_write ( ndim, n, batch, seed_init, seed, init_string, it_max, ...\n it_fixed, it_num, it_diff, energy, sample_string, sample_num, r, ...\n file_out_name )\n\n%*****************************************************************************80\n%\n%% CVT_WRITE writes a CVT dataset to a file.\n%\n% Discussion:\n%\n% The initial lines of the file are comments, which begin with a\n% '#' character.\n%\n% Thereafter, each line of the file contains the NDIM-dimensional\n% components of the next entry in the set.\n%\n% Modified:\n%\n% 17 November 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NDIM, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, integer BATCH, sets the maximum number of sample points\n% generated at one time. It is inefficient to generate the sample\n% points 1 at a time, but memory intensive to generate them all\n% at once. You might set BATCH to min ( SAMPLE_NUM, 10000 ), for instance.\n%\n% Input, integer SEED_INIT, the initial random number seed.\n%\n% Input, integer SEED, the current random number seed.\n%\n% Input, character INIT_STRING(*), specifies how the initial\n% generators are chosen:\n% filename, by reading data from a file;\n% 'GRID', picking points from a grid;\n% 'HALTON', from a Halton sequence;\n% 'RAND', using MATLAB RAND function;\n% 'UNIFORM', using a simple uniform RNG;\n%\n% Input, integer IT_MAX, the maximum number of iterations allowed.\n%\n% Input, integer IT_FIXED, the maximum number of iterations to take\n% with a fixed set of sample points.\n%\n% Input, integer IT_NUM, the actual number of iterations taken.\n%\n% Input, real IT_DIFF, the L2 norm of the change\n% in the CVT coordinates on the last iteration.\n%\n% Input, real ENERGY, the discrete \"energy\", divided\n% by the number of sample points.\n%\n% Input, string SAMPLE_STRING, specifies how the region is sampled:\n% 'GRID', picking points from a grid;\n% 'HALTON', from a Halton sequence;\n% 'RAND', using MATLAB RAND function;\n% 'UNIFORM', using a simple uniform RNG;\n%\n% Input, integer SAMPLE_NUM, the number of sampling points used on\n% each iteration.\n%\n% Input, real R(NDIM,N), the points.\n%\n% Input, string FILE_OUT_NAME, the name of\n% the output file.\n%\n file_out_unit = fopen ( file_out_name, 'w' );\n\n if ( file_out_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CVT_WRITE - Fatal error!\\n' );\n fprintf ( 1, ' Could not open the output file:\\n' );\n fprintf ( 1, ' \"%s\".\\n', file_out_name );\n error ( 'CVT_WRITE - Fatal error!' );\n end\n\n fprintf ( file_out_unit, '# %s\\n', file_out_name );\n fprintf ( file_out_unit, '# created by CVT_WRITE.M\\n' );\n fprintf ( file_out_unit, '#\\n' );\n fprintf ( file_out_unit, '# Spatial dimension NDIM = %12d\\n', ndim );\n fprintf ( file_out_unit, '# Number of points N = %12d\\n', n );\n fprintf ( file_out_unit, '# Initial SEED_INIT = %12d\\n', seed_init );\n fprintf ( file_out_unit, '# Current SEED = %12d\\n', seed );\n fprintf ( file_out_unit, '# INIT = \"%s\"\\n', init_string );\n fprintf ( file_out_unit, '# Max iterations IT_MAX = %12d\\n', it_max );\n fprintf ( file_out_unit, '# IT_FIXED (fixed samples) = %12d\\n', it_fixed );\n fprintf ( file_out_unit, '# Iterations IT_NUM = %12d\\n', it_num );\n fprintf ( file_out_unit, '# Difference IT_DIFF = %12f\\n', it_diff );\n fprintf ( file_out_unit, '# CVT ENERGY = %12f\\n', energy );\n fprintf ( file_out_unit, '# SAMPLE = \"%s\"\\n', sample_string );\n fprintf ( file_out_unit, '# SAMPLE_NUM = %12d\\n', sample_num );\n fprintf ( file_out_unit, '# Sample BATCH size = %12d\\n', batch );\n fprintf ( file_out_unit, '# EPSILON (unit roundoff ) = %e\\n', eps );\n fprintf ( file_out_unit, '#\\n' );\n\n for j = 1 : n\n for i = 1 : ndim\n fprintf ( file_out_unit, ' %10f', r(i,j) );\n end\n fprintf ( file_out_unit, '\\n' );\n end\n\n fclose ( file_out_unit );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cvt_movie/cvt_write.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.04958901824356766, "lm_q1q2_score": 0.015077128166720988}} {"text": "function [concentrationMatrix, excRxnNames, timeVec, biomassVec] = dynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)\n% Performs dynamic FBA simulation using the static optimization approach\n%\n% USAGE:\n%\n% [concentrationMatrix, excRxnNames, timeVec, biomassVec] = dynamicFBA(model, substrateRxns, initConcentrations, initBiomass, timeStep, nSteps, plotRxns, exclUptakeRxns)\n%\n% INPUTS:\n% model: COBRA model structure\n% substrateRxns: List of exchange reaction names for substrates\n% initially in the media that may change (e.g. not\n% h2o or co2)\n% initConcentrations: Initial concentrations of substrates (in the same\n% structure as `substrateRxns`)\n% initBiomass: Initial biomass (must be non zero)\n% timeStep: Time step size\n% nSteps: Maximum number of time steps\n%\n% OPTIONAL INPUTS:\n% plotRxns: Reactions to be plotted (Default = {'EX_glc(e)', 'EX_ac(e)', 'EX_for(e)'})\n% exclUptakeRxns: List of uptake reactions whose substrate concentrations do not change\n% (Default = {'EX_co2(e)', 'EX_o2(e)', 'EX_h2o(e)', 'EX_h(e)'})\n%\n% OUTPUTS:\n% concentrationMatrix: Matrix of extracellular metabolite concentrations\n% excRxnNames: Names of exchange reactions for the EC metabolites\n% timeVec: Vector of time points\n% biomassVec: Vector of biomass values\n%\n% If no initial concentration is given for a substrate that has an open\n% uptake in the model (i.e. `model.lb < 0`) the concentration is assumed to\n% be high enough to not be limiting. If the uptake rate for a nutrient is\n% calculated to exceed the maximum uptake rate for that nutrient specified\n% in the model and the max uptake rate specified is > 0, the maximum uptake\n% rate specified in the model is used instead of the calculated uptake\n% rate.\n%\n% NOTE:\n%\n% The dynamic FBA method implemented in this function is essentially\n% the same as the method described in\n% [`Varma, A., and B. O. Palsson. Appl. Environ. Microbiol. 60:3724 (1994)`].\n% This function does not implement the dynamic FBA using dynamic optimization approach\n% described in [`Mahadevan, R. et al. Biophys J, 83:1331-1340 (2003)`].\n%\n% .. Author: - Markus Herrgard 8/22/06\n\nglobal WAITBAR_TYPE\n\nif (nargin < 7)\n plotRxns = {'EX_glc(e)','EX_ac(e)','EX_for(e)'};\nend\n\n% Uptake reactions whose substrate concentrations do not change\nif (nargin < 8)\n exclUptakeRxns = {'EX_co2(e)','EX_o2(e)','EX_h2o(e)','EX_h(e)'};\nend\n\n% Find exchange rxns\nexcInd = findExcRxns(model,false);\nexcInd = excInd & ~ismember(model.rxns,exclUptakeRxns);\nexcRxnNames = model.rxns(excInd);\nlength(excRxnNames)\n% Figure out if substrate reactions are correct\nmissingInd = find(~ismember(substrateRxns,excRxnNames));\nif (~isempty(missingInd))\n for i = 1:length(missingInd)\n fprintf('%s\\n',substrateRxns{missingInd(i)});\n end\n error('Invalid substrate uptake reaction!');\nend\n\n% Initialize concentrations\n[~, substrateMatchInd] = ismember(substrateRxns,excRxnNames);\nconcentrations = zeros(length(excRxnNames),1);\nconcentrations(substrateMatchInd) = initConcentrations;\n\n% Deal with reactions for which there are no initial concentrations\noriginalBound = -model.lb(excInd);\nnoInitConcentration = (concentrations == 0 & originalBound > 0);\nconcentrations(noInitConcentration) = 1000;\n\nbiomass = initBiomass;\n\n% Initialize bounds\nuptakeBound = concentrations/(biomass*timeStep);\n\n% Make sure bounds are not higher than what are specified in the model\naboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);\nuptakeBound(aboveOriginal) = originalBound(aboveOriginal);\nmodel.lb(excInd) = -uptakeBound;\n\nconcentrationMatrix = sparse(concentrations);\nbiomassVec = biomass;\ntimeVec(1) = 0;\n\nfprintf('Step number\\tBiomass\\n');\nshowprogress(0,'Dynamic FBA analysis in progress ...');\nfor stepNo = 1:nSteps\n % Run FBA\n sol = optimizeCbModel(model,'max','one');\n mu = sol.f;\n if (sol.stat ~= 1 || mu == 0)\n fprintf('\\nNo feasible solution - nutrients exhausted. Biomass:\\t %f\\n', biomass);\n break;\n end\n uptakeFlux = sol.x(excInd);\n biomass = biomass*exp(mu*timeStep);\n %biomass = biomass*(1+mu*timeStep);\n biomassVec(end+1) = biomass;\n\n % Update concentrations\n concentrations = concentrations - uptakeFlux/mu*biomass*(1-exp(mu*timeStep));\n %concentrations = concentrations + uptakeFlux*biomass*timeStep;\n concentrations(concentrations <= 0) = 0;\n concentrationMatrix(:,end+1) = sparse(concentrations);\n\n % Update bounds for uptake reactions\n uptakeBound = concentrations/(biomass*timeStep);\n % This is to avoid any numerical issues\n uptakeBound(uptakeBound > 1000) = 1000;\n % Figure out if the computed bounds were above the original bounds\n aboveOriginal = (uptakeBound > originalBound) & (originalBound > 0);\n % Revert to original bounds if the rate was too high\n uptakeBound(aboveOriginal) = originalBound(aboveOriginal);\n uptakeBound(abs(uptakeBound) < 1e-9) = 0;\n\n model.lb(excInd) = -uptakeBound;\n\n if WAITBAR_TYPE ~= 1\n fprintf('%d\\t%f\\n',stepNo,biomass);\n end\n showprogress(stepNo/nSteps);\n timeVec(stepNo+1) = stepNo*timeStep;\nend\n\nselNonZero = any(concentrationMatrix>0,2);\nconcentrationMatrix = concentrationMatrix(selNonZero,:);\nexcRxnNames = excRxnNames(selNonZero);\nselPlot = ismember(excRxnNames,plotRxns);\n\n% Plot concentrations as a function of time\nclf\nsubplot(1,2,1);\nplot(timeVec,biomassVec);\naxis tight\ntitle('Biomass');\nsubplot(1,2,2);\nplot(timeVec,concentrationMatrix(selPlot,:));\naxis tight\nlegend(strrep(excRxnNames(selPlot),'EX_',''));\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/dynamicFBA/dynamicFBA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.03567854844248507, "lm_q1q2_score": 0.015074352080392478}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright 2014 National Renewable Energy Laboratory and National \n% Technology & Engineering Solutions of Sandia, LLC (NTESS). \n% Under the terms of Contract DE-NA0003525 with NTESS, \n% the U.S. Government retains certain rights in this software.\n% \n% Licensed under the Apache License, Version 2.0 (the \"License\");\n% you may not use this file except in compliance with the License.\n% You may obtain a copy of the License at\n% \n% http://www.apache.org/licenses/LICENSE-2.0\n% \n% Unless required by applicable law or agreed to in writing, software\n% distributed under the License is distributed on an \"AS IS\" BASIS,\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n% See the License for the specific language governing permissions and\n% limitations under the License.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclassdef responseClass maxHeight\n maxHeight = max(bodyMesh(ibod).Points(:,3))+max(bodyMesh(ibod).deltaPos(:,3));\n end\n end \n if options.axisLimits(6) == -999\n options.axisLimits(6) = maxHeight;\n end \n if options.saveSetting == 0\n % Create video file and open it for writing\n video = VideoWriter('waveViz.avi'); \n video.FrameRate = 1/(simu.dtOut*options.timesPerFrame); \n open(video); \n elseif options.saveSetting == 1\n % Create the gif file\n gifFilename = 'waveViz.gif';\n end \n % Initialize figure and image counter\n figure();\n imageCount = 0; \n for i=1:length(t)\n if t(i) >= options.startEndTime(1) && t(i) <= options.startEndTime(2)\n imageCount = imageCount + 1;\n for ibod = 1:length(obj.bodies)\n % Apply rotation to each point\n rotMat = eulXYZ2RotMat(obj.bodies(ibod).position(1+options.timesPerFrame*(i-1),4), ...\n obj.bodies(ibod).position(1+options.timesPerFrame*(i-1),5), ...\n obj.bodies(ibod).position(1+options.timesPerFrame*(i-1),6));\n for ipts=1:length(bodyMesh(ibod).Points(:,1))\n bodyMesh(ibod).rotation(ipts,:) = (rotMat*bodyMesh(ibod).Points(ipts,:).').';\n end\n\n % Calculate full position changes due to rotation,\n % translation, and center of gravity\n bodyMesh(ibod).pointsNew = bodyMesh(ibod).rotation + bodyMesh(ibod).deltaPos(i,:) + body(ibod).centerGravity.';\n\n % Create and plot final triangulation of geometry with applied changes\n bodFinal = triangulation(bodyMesh(ibod).Conns,bodyMesh(ibod).pointsNew);\n trisurf(bodFinal,'FaceColor',[1 1 0],'EdgeColor','k','EdgeAlpha',.2)\n hold on\n end\n % Create and wave elevation grid\n Z = waveElevationGrid(waves, t(i), X, Y, simu.dtOut, simu.gravity);\n surf(X,Y,Z,'FaceAlpha',.85,'EdgeColor','none')\n hold on\n % Display seafloor\n seaFloor = -waves.waterDepth*ones(size(X, 1));\n surf(X,Y,seaFloor,'FaceColor',[.4 .4 0],'EdgeColor','none');\n hold on\n % Time visual\n nDecimals = max(0,ceil(-log10(simu.dtOut*options.timesPerFrame)));\n nLeading = ceil(log10(max(t)));\n tAnnot = sprintf(['time = %' num2str(nDecimals+nLeading+1) '.' num2str(nDecimals) 'f s'],t(i));\n % Settings and labels\n caxis([min(waves.waveAmpTime(:,2)) max(waves.waveAmpTime(:,2))])\n colormap winter\n c = colorbar;\n ylabel(c, 'Wave Elevation (m)')\n title({'Wave Elevation and Geometry Visualization',tAnnot})\n xlabel('x(m)')\n ylabel('y(m)')\n zlabel('z(m)')\n daspect([1 1 1])\n axis(options.axisLimits)\n % Create figure while iterating through time loop\n drawnow;\n % Capture figure for saving\n frame = getframe(gcf);\n if options.saveSetting == 0\n % Save to video\n writeVideo(video,frame); \n elseif options.saveSetting == 1\n % Save to gif\n im = frame2im(frame); \n [imind,cm] = rgb2ind(im,256); \n if imageCount == 1 \n imwrite(imind,cm,gifFilename,'gif', 'Loopcount',inf); \n else \n imwrite(imind,cm,gifFilename,'gif','WriteMode','append','DelayTime',simu.dtOut); \n end \n end\n hold off\n end\n end \n % Close video file\n if options.saveSetting == 0\n close(video); \n end \n end\n \n function writeText(obj)\n % This method writes WEC-Sim outputs to a (ASCII) text file.\n % This method is executed by specifying ``simu.outputtxt=1``\n % in the ``wecSimInputFile.m``.\n filename = ['output/wave.txt'];\n fid = fopen(filename,'w+');\n header = {'time','elevation'};\n for ii=1:length(header)\n tmp(ii) = length(header{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n header_fmt = ['%' num2str(numChar) 's '];\n ncols = length(header);\n tmp = size(obj.wave.time);\n nrows = tmp(1); clear tmp;\n data_fmt = [repmat('%10.5f ',1,ncols) '\\n'];\n data = zeros(nrows,ncols);\n data(:,1) = obj.wave.time;\n data(:,2) = obj.wave.elevation;\n if ncols > 2\n for ii = 3:length(header)\n eval(['data(:,' num2str(ii) ') = obj.wave.' header{ii} ';']);\n end\n end\n for ii = 1:length(header)\n fprintf(fid,header_fmt,header{ii});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n % bodies\n signals = {'position','velocity','acceleration','forceTotal','forceExcitation','forceRadiationDamping','forceAddedMass','forceRestoring','forceMorisonAndViscous','forceLinearDamping'};\n header = {'time', ...\n 'position_1' ,'position_2' ,'position_3' ,'position_4' ,'position_5' ,'position_6' , ...\n 'velocity_1' ,'velocity_2' ,'velocity_3' ,'velocity_4' ,'velocity_5' ,'velocity_6' , ...\n 'acceleration_1' ,'acceleration_2' ,'acceleration_3' ,'acceleration_4' ,'acceleration_5' ,'acceleration_6' , ...\n 'forceTotal_1' ,'forceTotal_2' ,'forceTotal_3' ,'forceTotal_4' ,'forceTotal_5' ,'forceTotal_6' , ...\n 'forceExcitation_1' ,'forceExcitation_2' ,'forceExcitation_3' ,'forceExcitation_4' ,'forceExcitation_5' ,'forceExcitation_6' , ...\n 'forceRadiationDamping_1' ,'forceRadiationDamping_2' ,'forceRadiationDamping_3' ,'forceRadiationDamping_4' ,'forceRadiationDamping_5' ,'forceRadiationDamping_6' , ...\n 'forceAddedMass_1' ,'forceAddedMass_2' ,'forceAddedMass_3' ,'forceAddedMass_4' ,'forceAddedMass_5' ,'forceAddedMass_6' , ...\n 'forceRestoring_1' ,'forceRestoring_2' ,'forceRestoring_3' ,'forceRestoring_4' ,'forceRestoring_5' ,'forceRestoring_6' , ...\n 'forceMorisonAndViscous_1' ,'forceMorisonAndViscous_2' ,'forceMorisonAndViscous_3' ,'forceMorisonAndViscous_4' ,'forceMorisonAndViscous_5' ,'forceMorisonAndViscous_6' , ...\n 'forceLinearDamping_1' ,'forceLinearDamping_2' ,'forceLinearDamping_3' ,'forceLinearDamping_4' ,'forceLinearDamping_5' ,'forceLinearDamping_6' };\n for ii=1:length(signals)\n tmp(ii) = length(signals{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n ncols = 1 + length(signals)*6;\n tmp = size(obj.bodies(1).time);\n nrows = tmp(1); clear tmp;\n header_fmt = ['%' num2str(numChar) 's ']; \n data_fmt = [repmat('%10.5f ',1,ncols) '\\n'];\n for ibod = 1:length(obj.bodies)\n filename = ['output/body' num2str(ibod) '_' obj.bodies(ibod).name '.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows,ncols);\n data(:,1) = obj.bodies(ibod).time;\n fprintf(fid,header_fmt,header{1});\n for isignal=1:length(signals)\n for idof = 1:6\n fprintf(fid,header_fmt,header{1 + (isignal-1)*6+idof});\n end\n data(:, 1+(isignal-1)*6+1:1+(isignal-1)*6+6) = obj.bodies(ibod).(signals{isignal});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n if isfield(obj.bodies(ibod),'cellPressures_hydrostatic')\n filename = ['output/body' num2str(ibod) '_' obj.bodies(ibod).name '_cellPressure_hydrostatic.txt'];\n fid = fopen(filename,'w+');\n header_2 = {'time'};\n tmp = size(obj.bodies(ibod).cellPressures_hydrostatic);\n nrows2 = tmp(1);\n ncols2 = tmp(2)+1;\n for icell=1:ncols2-1\n header_2{icell+1} = ['cell_' num2str(icell)];\n end\n tmp = length(header_2{end});\n numChar = max(tmp)+2; clear tmp;\n header_fmt_2 = ['%' num2str(numChar) 's '];\n data_fmt_2 = [repmat('%10.5f ',1,ncols2) '\\n'];\n data = zeros(nrows2,ncols2);\n data(:,1) = obj.bodies(ibod).cellPressures_time;\n data(:,2:end) = obj.bodies(ibod).cellPressures_hydrostatic;\n for jj = 1:length(header_2)\n fprintf(fid,header_fmt_2,header_2{jj});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt_2,data');\n fclose(fid);\n % wave linear\n filename = ['output/body' num2str(ibod) '_' obj.bodies(ibod).name '_cellPressure_waveLinear.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows2,ncols2);\n data(:,1) = obj.bodies(ibod).cellPressures_time;\n data(:,2:end) = obj.bodies(ibod).cellPressures_waveLinear;\n for jj = 1:length(header_2)\n fprintf(fid,header_fmt_2,header_2{jj});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt_2,data');\n fclose(fid);\n % wave nonlinear\n filename = ['output/body' num2str(ibod) '_' obj.bodies(ibod).name '_cellPressure_waveNonLinear.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows2,ncols2);\n data(:,1) = obj.bodies(ibod).cellPressures_time;\n data(:,2:end) = obj.bodies(ibod).cellPressures_waveNonLinear;\n for jj = 1:length(header_2)\n fprintf(fid,header_fmt_2,header_2{jj});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt_2,data');\n fclose(fid);\n end\n end\n % ptos\n if isfield(obj.ptos,'name')\n signals = {'position','velocity','acceleration','forceTotal','forceActuation','forceConstraint','forceInternalMechanics','powerInternalMechanics'};\n header = {'time', ...\n 'position_1' ,'position_2' ,'position_3' ,'position_4' ,'position_5' ,'position_6' , ...\n 'velocity_1' ,'velocity_2' ,'velocity_3' ,'velocity_4' ,'velocity_5' ,'velocity_6' , ...\n 'acceleration_1' ,'acceleration_2' ,'acceleration_3' ,'acceleration_4' ,'acceleration_5' ,'acceleration_6' , ...\n 'forceTotal_1' ,'forceTotal_2' ,'forceTotal_3' ,'forceTotal_4' ,'forceTotal_5' ,'forceTotal_6' , ...\n 'forceActuation_1' ,'forceActuation_2' ,'forceActuation_3' ,'forceActuation_4' ,'forceActuation_5' ,'forceActuation_6' , ...\n 'forceConstraint_1' ,'forceConstraint_2' ,'forceConstraint_3' ,'forceConstraint_4' ,'forceConstraint_5' ,'forceConstraint_6' , ...\n 'forceInternalMechanics_1','forceInternalMechanics_2','forceInternalMechanics_3','forceInternalMechanics_4','forceInternalMechanics_5','forceInternalMechanics_6', ...\n 'powerInternalMechanics_1','powerInternalMechanics_2','powerInternalMechanics_3','powerInternalMechanics_4','powerInternalMechanics_5','powerInternalMechanics_6', };\n for ii=1:length(signals)\n tmp(ii) = length(signals{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n ncols = 1 + length(signals)*6;\n tmp = size(obj.ptos(1).time);\n nrows = tmp(1); clear tmp;\n header_fmt = ['%' num2str(numChar) 's ']; \n data_fmt = [repmat('%10.5f ',1,ncols) '\\n'];\n for ipto = 1:length(obj.ptos)\n filename = ['output/pto' num2str(ipto) '_' obj.ptos(ipto).name '.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows,ncols);\n data(:,1) = obj.ptos(ipto).time;\n fprintf(fid,header_fmt,header{1});\n for isignal=1:length(signals)\n for idof = 1:6\n fprintf(fid,header_fmt,header{1 + (isignal-1)*6+idof});\n end\n data(:, 1+(isignal-1)*6+1:1+(isignal-1)*6+6) = obj.ptos(ipto).(signals{isignal});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n end\n end\n % constraints\n if isfield(obj.constraints,'name')\n signals = {'position','velocity','acceleration','forceConstraint'};\n header = {'time', ...\n 'position_1' ,'position_2' ,'position_3' ,'position_4' ,'position_5' ,'position_6' , ...\n 'velocity_1' ,'velocity_2' ,'velocity_3' ,'velocity_4' ,'velocity_5' ,'velocity_6' , ...\n 'acceleration_1' ,'acceleration_2' ,'acceleration_3' ,'acceleration_4' ,'acceleration_5' ,'acceleration_6' , ...\n 'forceConstraint_1','forceConstraint_2','forceConstraint_3','forceConstraint_4','forceConstraint_5','forceConstraint_6' };\n for ii=1:length(signals)\n tmp(ii) = length(signals{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n ncols = 1 + length(signals)*6;\n tmp = size(obj.constraints(1).time);\n nrows = tmp(1); clear tmp;\n header_fmt = ['%' num2str(numChar) 's ']; \n data_fmt = [repmat('%10.5f ',1,ncols) '\\n'];\n for icon = 1:length(obj.constraints)\n filename = ['output/constraint' num2str(icon) '_' obj.constraints(icon).name '.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows,ncols);\n data(:,1) = obj.constraints(icon).time;\n fprintf(fid,header_fmt,header{1});\n for isignal=1:length(signals)\n for idof = 1:6\n fprintf(fid,header_fmt,header{1 + (isignal-1)*6+idof});\n end\n data(:, 1+(isignal-1)*6+1:1+(isignal-1)*6+6) = obj.constraints(icon).(signals{isignal});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n end\n end\n %ptoSim\n if isfield(obj.ptosim,'time')\n f1 = fields(obj.ptosim);\n count = 1;\n header = {'time'};\n data = obj.ptosim.time;\n for ifld1=1:(length(f1)-1)\n f2 = fields(obj.ptosim.(f1{ifld1}));\n for iins = 1:length(obj.ptosim.(f1{ifld1}))\n for ifld2 = 1:length(f2)\n count = count+1;\n header{count} = [f1{ifld1} num2str(iins) '_' f2{ifld2}];\n data(:,count) = obj.ptosim.(f1{ifld1}).(f2{ifld2});\n end\n end\n end\n for ii=1:length(header)\n tmp(ii) = length(header{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n header_fmt = ['%' num2str(numChar) 's ']; \n data_fmt = [repmat('%10.5f ',1,length(header)) '\\n'];\n filename = ['output/ptosim.txt'];\n fid = fopen(filename,'w+');\n for ii=1:length(header)\n fprintf(fid,header_fmt,header{ii});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n end\n % mooring\n if isfield(obj.mooring,'name')\n signals = {'position','velocity','forceMooring'};\n header = {'time', ...\n 'position_1' ,'position_2' ,'position_3' ,'position_4' ,'position_5' ,'position_6' , ...\n 'velocity_1' ,'velocity_2' ,'velocity_3' ,'velocity_4' ,'velocity_5' ,'velocity_6' , ...\n 'forceMooring_1','forceMooring_2','forceMooring_3','forceMooring_4','forceMooring_5','forceMooring_6' };\n for ii=1:length(signals)\n tmp(ii) = length(signals{ii});\n end\n numChar = max(tmp)+2; clear tmp;\n ncols = 1 + length(signals)*6;\n tmp = size(obj.mooring(1).time);\n nrows = tmp(1); clear tmp;\n header_fmt = ['%' num2str(numChar) 's ']; \n data_fmt = [repmat('%10.5f ',1,ncols) '\\n'];\n for imoor = 1:length(obj.mooring)\n filename = ['output/mooring' num2str(imoor) '_' obj.mooring(imoor).name '.txt'];\n fid = fopen(filename,'w+');\n data = zeros(nrows,ncols);\n data(:,1) = obj.mooring(imoor).time;\n fprintf(fid,header_fmt,header{1});\n for isignal=1:length(signals)\n for idof = 1:6\n fprintf(fid,header_fmt,header{1 + (isignal-1)*6+idof});\n end\n data(:, 1+(isignal-1)*6+1:1+(isignal-1)*6+6) = obj.mooring(imoor).(signals{isignal});\n end\n fprintf(fid,'\\n');\n fprintf(fid,data_fmt,data');\n fclose(fid);\n end\n end \n end\n end\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/objects/responseClass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879061178313897, "lm_q2_score": 0.03210070845319382, "lm_q1q2_score": 0.015048510754444912}} {"text": "function [meanDoseV, stdDoseV, DVHm, volsV, shiftXv, shiftYv, shiftZv] = simulate_organ_motion(planC,structNumV,doseNum, igrtFlag)\n%function [DVH_out, DVHm, volsV] = simulate_organ_motion(planC,structNumV,doseNum)\n%\n%APA, 09/21/2012\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nindexS = planC{end};\n\n%Number of Fractions and Trials\nnumFractions = 1; % 48\nnumTrials = 1; % 200\nnumStructs = length(structNumV);\n\nshiftXv = zeros(1,numTrials);\nshiftYv = shiftXv;\nshiftZv = shiftXv;\n\nstructurenamesC = {planC{indexS.structures}.structureName};\nrectumIndex = getMatchingIndex('rectum_o',lower(structurenamesC),'exact');\nrectalCS = calculate_structure_cross_sectional_area(rectumIndex,planC);\nbladderVol = getMatchingIndex('bladder_o',lower(structurenamesC),'exact');\n\n% % Systematic Shifts in cm (Inter-treatment)\n% XdispSys_Std = 0; % L-R\n% YdispSys_Std = 0; % A-P\n% ZdispSys_Std = 0; % S-I\n \n% % Random Shifts in cm (inter-fraction)\n% XdispRnd_Std = 1; % L-P\n% YdispRnd_Std = 1; % A-P\n% ZdispRnd_Std = 1; % S-I\n\n%Distances are in cm\nXpdfMean = 0; % L-P\nYpdfMean = 0; % A-P\nZpdfMean = 0; % S-I\n\n%Get scan associated with doseNum\nscanNum = getAssociatedScan(planC{indexS.dose}(doseNum).assocScanUID, planC);\n\nif isempty(scanNum) %Assume dose is associated with this scan\n scanNum = getStructureAssociatedScan(structNumV(1),planC);\nend\n\n%Get reference transformation matrix for doseNum\nif ~isempty(scanNum) && isempty(planC{indexS.dose}(doseNum).transM)\n referenceTransM = planC{indexS.scan}(scanNum).transM;\nelse\n referenceTransM = planC{indexS.dose}(doseNum).transM;\nend\n\n%Store the reference doseArray\nreferenceDoseArray = planC{indexS.dose}(doseNum).doseArray;\n\n%Try and get a binWidth from stateS. If it doesnt exist, get it from\n%the CERROptions file (allows this function to be called outside CERR)\nglobal stateS;\nif ~isempty(stateS) && isfield(stateS, 'optS') && isfield(stateS.optS, 'DVHBinWidth') && ~isempty(stateS.optS.DVHBinWidth)\n binWidth = stateS.optS.DVHBinWidth;\nelse\n optS = CERROptions;\n binWidth = optS.DVHBinWidth;\nend\n\n%Compute DVH at given dose\nstructCount = 0;\nfor structNum = structNumV\n structCount = structCount + 1;\n [dosesCurrentV{structCount}, volsV{structCount}] = getDVH(structNum, doseNum, planC);\nend\n\n%Divide doseArray into fractions\nplanC{indexS.dose}(doseNum).doseArray = planC{indexS.dose}(doseNum).doseArray / numFractions;\n\n%Get systematic errors\n% deltaX_systematic = randn(1, numTrials) * XdispSys_Std + XpdfMean;\n% deltaY_systematic = randn(1, numTrials) * YdispSys_Std + YpdfMean;\n% deltaZ_systematic = randn(1, numTrials) * ZdispSys_Std + ZpdfMean;\n\nhWait = waitbar(0,'Computing plan robustness...');\n\nif isempty(referenceTransM)\n referenceTransM_matrix = eye(4);\nelse\n referenceTransM_matrix = referenceTransM;\nend\n\n\n%Obtain DVH calculation points in blocks\noptS = planC{indexS.CERROptions};\n\nROIImageSize = [planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension1 planC{indexS.scan}(scanNum).scanInfo(1).sizeOfDimension2];\n\ndeltaY = planC{indexS.scan}(scanNum).scanInfo(1).grid1Units;\n\n%Get raster segments for structure.\nstructCount = 0;\nfor structNum = structNumV\n \n structCount = structCount + 1;\n \n [segmentsM, planC, isError] = getRasterSegments(structNum, planC);\n \n if isempty(segmentsM)\n isError = 1;\n end\n numSegs = size(segmentsM,1);\n \n %Relative sampling of ROI voxels in this place, compared to CT spacing.\n %Set when rasterSegments are generated (usually on import).\n sampleRate = optS.ROISampleRate;\n \n %Sample the rows\n indFullV = 1 : numSegs;\n if sampleRate ~= 1\n rV = 1 : length(indFullV);\n rV([rem(rV+sampleRate-1,sampleRate)~=0]) = [];\n indFullV = rV;\n end\n \n %Block process to avoid swamping on large structures\n if isfield(optS, 'DVHBlockSize') & ~isempty(optS.DVHBlockSize)\n DVHBlockSize = optS.DVHBlockSize;\n else\n DVHBlockSize = 5000;\n end\n \n blocks{structCount} = ceil(length(indFullV)/DVHBlockSize);\n \n start = 1;\n \n for b = 1 : blocks{structCount}\n \n %Build the interpolation points matrix\n \n dummy = zeros(1,DVHBlockSize * ROIImageSize(1));\n x1V = dummy;\n y1V = dummy;\n z1V = dummy;\n volsSectionV{structCount} = dummy;\n \n if start+DVHBlockSize > length(indFullV)\n stop = length(indFullV);\n else\n stop = start + DVHBlockSize - 1;\n end\n \n indV = indFullV(start:stop);\n \n mark = 1;\n for i = indV\n \n tmpV = segmentsM(i,1:10);\n delta = tmpV(5) * sampleRate;\n xV = tmpV(3): delta : tmpV(4);\n len = length(xV);\n rangeV = ones(1,len);\n yV = tmpV(2) * rangeV;\n zV = tmpV(1) * rangeV;\n sliceThickness = tmpV(10);\n %v = delta^2 * sliceThickness;\n v = delta * (deltaY*sampleRate) * sliceThickness;\n x1V(mark : mark + len - 1) = xV;\n y1V(mark : mark + len - 1) = yV;\n z1V(mark : mark + len - 1) = zV;\n volsSectionV{structCount}(mark : mark + len - 1) = v;\n mark = mark + len;\n \n end\n \n %cut unused matrix elements\n x1V = x1V(1:mark-1);\n y1V = y1V(1:mark-1);\n z1V = z1V(1:mark-1);\n volsSectionV{structCount} = volsSectionV{structCount}(1:mark-1);\n \n %Get transformation matrices for both dose and structure.\n transMDose = getTransM('dose', doseNum, planC);\n transMStruct = getTransM('struct', structNum, planC);\n \n %Forward transform the structure's coordinates.\n if ~isempty(transMStruct)\n [x1V, y1V, z1V] = applyTransM(transMStruct, x1V, y1V, z1V);\n end\n \n dvhCalcPtsC{structCount}{b} = [x1V', y1V', z1V'];\n \n %Interpolate.\n % [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);\n \n % dosesV = [dosesV, dosesSectionV];\n % volsV = [volsV, volsSectionV{structCount}];\n \n start = stop + 1;\n \n end\n \nend\n\n%Loop over to generate DVH\nfor iTrial = 1:numTrials\n\n [deltaX_systematic, deltaY_systematic, deltaZ_systematic, XdispRnd_Std, YdispRnd_Std, ZdispRnd_Std] = getShiftParameters(rectalCS,bladderVol,igrtFlag);\n deltaX_systematic = min(max(deltaX_systematic,-1.0),1.0);\n deltaY_systematic = min(max(deltaY_systematic,-1.5),1.5);\n deltaZ_systematic = min(max(deltaZ_systematic,-1.0),1.0);\n deltaX = deltaX_systematic + randn(1, numFractions) * XdispRnd_Std + XpdfMean;\n deltaY = deltaY_systematic + randn(1, numFractions) * YdispRnd_Std + YpdfMean;\n deltaZ = deltaZ_systematic + randn(1, numFractions) * ZdispRnd_Std + ZpdfMean;\n \n % To get planned DVH - comment it otherwise\n deltaX = 0;\n deltaY = 0;\n deltaZ = 0; \n \n shiftXv(1,iTrial) = mean(deltaX);\n shiftYv(1,iTrial) = mean(deltaY);\n shiftZv(1,iTrial) = mean(deltaZ); \n \n structCount = 0;\n for structNum = structNumV\n \n structCount = structCount + 1;\n \n tmpDoseV = zeros(1,length(dosesCurrentV{structCount}));\n \n for iFraction = 1:numFractions\n \n waitbar(((iTrial-1)*numStructs + structCount)/(numTrials*numStructs),hWait)\n \n transM = referenceTransM_matrix;\n transM(1:3,4) = transM(1:3,4) + [deltaX(iFraction); deltaY(iFraction); deltaZ(iFraction)];\n \n %Apply the new transM to dose\n planC{indexS.dose}(doseNum).transM = transM;\n \n % Convert Dose to Gy\n if max(planC{indexS.dose}(doseNum).doseArray(:)) > 150\n planC{indexS.dose}(doseNum).doseArray = planC{indexS.dose}(doseNum).doseArray/100;\n end\n \n %Get doses and volumes of points in structure.\n %[dosesV, volsV] = getDVH(structNum, doseNum, planC);\n \n \n volsV{structCount} = [];\n dosesV{structCount} = [];\n \n for b = 1 : blocks{structCount}\n x1V = dvhCalcPtsC{structCount}{b}(:,1);\n y1V = dvhCalcPtsC{structCount}{b}(:,2);\n z1V = dvhCalcPtsC{structCount}{b}(:,3);\n \n %Back transform the coordinates into the doses' coordinate system.\n [x1V, y1V, z1V] = applyTransM(inv(transM), x1V, y1V, z1V);\n \n %Interpolate.\n [dosesSectionV] = getDoseAt(doseNum, x1V, y1V, z1V, planC);\n \n dosesV{structCount} = [dosesV{structCount}, dosesSectionV];\n volsV{structCount} = [volsV{structCount}, volsSectionV{structCount}];\n end\n \n tmpDoseV = tmpDoseV + dosesV{structCount};\n \n end\n \n DVHm{structCount}(:,iTrial) = single(tmpDoseV(:));\n \n end\n \n\nend\n\nclose(hWait)\n\n%Reassign reference transM and doseArray to doseNum\nplanC{indexS.dose}(doseNum).transM = referenceTransM;\nplanC{indexS.dose}(doseNum).doseArray = referenceDoseArray;\n\n\n%Compute Mean and Std Dev in blocks\nstructCount = 0;\nfor structNum = structNumV\n \n structCount = structCount + 1;\n \n numVoxels = length(volsV{structCount});\n DVHBlockSize = 5000;\n blocks = ceil(numVoxels/DVHBlockSize);\n start = 1;\n \n for b = 1 : blocks\n \n if start+DVHBlockSize > numVoxels\n stop = numVoxels;\n else\n stop = start + DVHBlockSize - 1;\n end\n \n DVH_block = DVHm{structCount}(start:stop,:);\n \n meanDoseV{structCount}(start:stop) = mean(DVH_block,2);\n stdDoseV{structCount}(start:stop) = std(DVH_block,0,2);\n \n start = stop + 1;\n \n end\nend\n\n% %Histogram for the expectation of dose over all trials\n% [doseBinsV, volsHistV] = doseHist(meanDoseV, volsV, binWidth);\n% DVH_out = [doseBinsV(:)'; volsHistV(:)'];\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_Data_Extraction/simulate_organ_motion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142018, "lm_q2_score": 0.034100421908547486, "lm_q1q2_score": 0.014929966041270849}} {"text": "function [x,y,K]=postprocessSDP(newx,newy,prepinfo,newK)\n% [x,y,K]=postprocessSDP(newx,newy,prepinfo,newK)\n% postprocessSDP: Postprocesses an SDP solution using the info from\n% preprocessing (preprocessSDP)\n%\n% ********** INTERNAL FUNCTION OF SEDUMI **********\n%\n% See also sedumi, preprocessSDP\n\n% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko\n% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)\n%\n% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)\n% Dept. Econometrics & O.R., Tilburg University, the Netherlands.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% Affiliation SeDuMi 1.03 and 1.04Beta (2000):\n% Dept. Quantitative Economics, Maastricht University, the Netherlands.\n%\n% Affiliations up to SeDuMi 1.02 (AUG1998):\n% CRL, McMaster University, Canada.\n% Supported by the Netherlands Organization for Scientific Research (NWO).\n%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n% 02110-1301, USA\n\nif issparse(newx)\n x=sparse([]);\nelse\n x=[];\nend\ny=newy;\nK=newK;\n\nfor j=length(prepinfo):-1:1\n op=prepinfo{j};\n switch op(1)\n case 0\n %Do nothing\n x=[newx(end-op(2)+1:end);x];\n newx=newx(1:end-op(2));\n case 1\n %Diagonal matrix\n x=[reshape(diag(newx(1:op(2))),op(2)^2,1);x];\n newx=newx(op(2)+1:end);\n K.l=K.l-op(2);\n K.s(end+1)=op(2);\n K.rsdpN=K.rsdpN+1;\n end\nend", "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/postprocessSDP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03067580403685995, "lm_q1q2_score": 0.01473906977168712}} {"text": "%%*****************************************************************\n%% sqlp: main solver \n%%*****************************************************************\n%% SDPT3: version 4.0\n%% Copyright (c) 1997 by\n%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************\n\n function [obj,X,y,Z,info,runhist] = sqlpmain(blk,At,C,b,par,parbarrier,X0,y0,Z0);\n\n global spdensity smallblkdim printlevel msg\n global solve_ok use_LU exist_analytic_term numpertdiagschur \n global schurfun schurfun_par \n%%\n matlabversion = par.matlabversion;\n vers = par.vers;\n predcorr = par.predcorr;\n gam = par.gam; \n expon = par.expon;\n gaptol = par.gaptol;\n inftol = par.inftol;\n steptol = par.steptol;\n maxit = par.maxit;\n printlevel = par.printlevel;\n stoplevel = par.stoplevel;\n scale_data = par.scale_data;\n spdensity = par.spdensity;\n rmdepconstr = par.rmdepconstr;\n smallblkdim = par.smallblkdim;\n schurfun = par.schurfun;\n schurfun_par = par.schurfun_par;\n ublksize = par.ublksize; \n%%\n tstart = clock; \n X = X0; y = y0; Z = Z0; \n for p = 1:size(blk,1)\n if strcmp(blk{p,1},'u'); Z{p} = zeros(blk{p,2},1); end\n end\n%%\n%%-----------------------------------------\n%% convert unrestricted blk to linear blk. \n%%-----------------------------------------\n%%\n convertlen = 0; \n [blk,At,C,X,Z,u2lblk,ublkidx] = sqlpu2lblk(blk,At,C,X,Z,par,convertlen);\n for p = 1:size(blk,1) \n pblk = blk(p,:); \n if (u2lblk(p) == 1) \n n = 2*blk{p,2}; \n blk{p,1} = 'l'; blk{p,2} = n;\n parbarrier{p} = zeros(1,n);\n At{p} = [At{p}; -At{p}]; \n tau = max(1,norm(C{p})); \n C{p} = [C{p}; -C{p}]; \n msg = 'convert ublk to lblk'; \n if (printlevel); fprintf(' *** %s',msg); end\n b2 = 1 + abs(b'); \n normCtmp = 1+norm(C{p});\n normAtmp = 1+sqrt(sum(At{p}.*At{p}));\n if (n > 1000)\n const = sqrt(n); \n else\n\t const = n; \n end\n if (par.startpoint == 1)\n X{p} = const* max([1,b2./normAtmp]) *ones(n,1); \n Z{p} = const* max([1,normAtmp/sqrt(n),normCtmp/sqrt(n)]) *ones(n,1);\n X{p} = X{p}.*(1+1e-10*randmat(n,1,0,'u')); \n Z{p} = Z{p}.*(1+1e-10*randmat(n,1,0,'u')); \n\t else\n const = max(abs(X{p})) + 100; \n X{p} = [X{p}+const; const*ones(n/2,1)]; \n %%old: const = 100; Z{p} = [const*ones(n/2,1); const*ones(n/2,1)];\n Z{p} = [abs(Z0{p}); abs(Z0{p})] + 1e-4; \n end\n end\n end\n%%-----------------------------------------\n%% check whether {A1,...,Am} is \n%% linearly independent. \n%%-----------------------------------------\n%%\n m0 = length(b); \n [At,b,y,indeprows,par.depconstr,feasible,par.AAt] = ...\n checkdepconstr(blk,At,b,y,rmdepconstr);\n if (~feasible)\n obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1); \n runhist = []; \n msg = 'SQLP is not feasible'; \n if (printlevel); fprintf('\\n %s \\n',msg); end\n return;\n end\n par.normAAt = norm(par.AAt,'fro'); \n%%\n%%-----------------------------------------\n%% scale SQLP data. Note: must be done only \n%% after checkdepconstr\n%%-----------------------------------------\n%%\n normA2 = 1+ops(At,'norm'); \n normb2 = 1+norm(b); \n normC2 = 1+ops(C,'norm'); \n normX0 = 1+ops(X0,'norm'); \n normZ0 = 1+ops(Z0,'norm'); \n if (scale_data)\n [At,C,b,normA,normC,normb,X,y,Z] = scaling(blk,At,C,b,X,y,Z);\n else\n normA = 1; normC = 1; normb = 1; \n end \n%%\n%%-----------------------------------------\n%% find the combined list of non-zero \n%% elements of Aj, j = 1:k, for each k. \n%% IMPORTANT NOTE: Ak, C are permuted.\n%%-----------------------------------------\n%% \n par.numcolAt = length(b); \n [At,C,X,Z,par.permA,par.permZ] = sortA(blk,At,C,b,X,Z);\n [par.isspA,par.nzlistA,par.nzlistAsum,par.isspAy,par.nzlistAy] = nzlist(blk,At,par);\n%%\n%%-----------------------------------------\n%% create an artifical non-negative block \n%% for a purely log-barrier problem\n%%-----------------------------------------\n%%\n numblkold = size(blk,1); \n nn = 0; \n for p = 1:size(blk,1);\n pblk = blk(p,:); \n idx = find(parbarrier{p}==0); \n if ~isempty(idx); \n if strcmp(pblk{1},'l') \n nn = nn + length(idx); \n elseif strcmp(pblk{1},'q') \n nn = nn + sum(pblk{2}(idx)); \n elseif strcmp(pblk{1},'s') \n nn = nn + sum(pblk{2}(idx)); \n end\n end\n end\n if (nn==0)\n analytic_prob = 1; \n numblk = size(blk,1)+1; \n blk{numblk,1} = 'l'; blk{numblk,2} = 1; \n At{numblk,1} = sparse(1,length(b)); \n C{numblk,1} = 1; \n X{numblk,1} = 1e3; \n Z{numblk,1} = 1e3;\n parbarrier{numblk,1} = 0; \n u2lblk(numblk,1) = 0;\n nn = nn + 1; \n else\n analytic_prob = 0; \n end\n%%\n exist_analytic_term = 0; \n for p = 1:size(blk,1);\n idx = find(parbarrier{p} > 0); \n if ~isempty(idx); \n exist_analytic_term = 1; \n end\n end\n%%-----------------------------------------\n%% initialization\n%%-----------------------------------------\n%%\n EE = ops(blk,'identity');\n normE2 = ops(EE,'norm'); Zpertold = 1; \n for p = 1:size(blk,1) \n normCC(p) = 1+ops(C(p),'norm');\n normEE(p) = 1+ops(EE(p),'norm'); \n end\n [Xchol,indef(1)] = blkcholfun(blk,X); \n [Zchol,indef(2)] = blkcholfun(blk,Z); \n if any(indef)\n msg = 'stop: X or Z not positive definite'; \n if (printlevel); fprintf('\\n %s\\n',msg); end\n info.termcode = -3;\n info.msg1 = msg;\n obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1); \n runhist = []; \n return;\n end \n AX = AXfun(blk,At,par.permA,X); \n rp = b-AX;\n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n ZpATynorm = ops(ZpATy,'norm');\n Rd = ops(C,'-',ZpATy);\n objadd0 = 0; \n if (scale_data)\n for p = 1:size(blk,1)\n pblk = blk(p,:); \n objadd0 = objadd0 + sum(parbarrier{p}.*pblk{2})*log(normA{p}); \n end\n end\n objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0;\n obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd; \n gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd); \n relgap = gap/(1+sum(abs(obj)));\n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n infeas = max(prim_infeas,dual_infeas); \n if (scale_data)\n infeas_org(1) = prim_infeas*normb;\n infeas_org(2) = dual_infeas*normC;\n else\n infeas_org = [0,0]; \n end\n trXZ = blktrace(blk,X,Z,parbarrier); \n if (nn > 0); mu = trXZ/nn; else; mu = gap/ops(X,'getM'); end\n normX = ops(X,'norm'); \n%% \n termcode = 0; restart = 0; \n pstep = 1; dstep = 1; pred_convg_rate = 1; corr_convg_rate = 1;\n prim_infeas_min = prim_infeas; \n dual_infeas_min = dual_infeas; \n prim_infeas_best = prim_infeas; \n dual_infeas_best = dual_infeas; \n infeas_best = infeas; \n relgap_best = relgap; \n homRd = inf; homrp = inf; dy = zeros(length(b),1); \n msg = []; msg2 = []; msg3 = [];\n runhist.pobj = obj(1);\n runhist.dobj = obj(2); \n runhist.gap = gap;\n runhist.relgap = relgap;\n runhist.pinfeas = prim_infeas;\n runhist.dinfeas = dual_infeas;\n runhist.infeas = infeas; \n runhist.pstep = 0; \n runhist.dstep = 0; \n runhist.step = 0; \n runhist.normX = normX; \n runhist.cputime = etime(clock,tstart); \n ttime.preproc = runhist.cputime; \n ttime.pred = 0; ttime.pred_pstep = 0; ttime.pred_dstep = 0; \n ttime.corr = 0; ttime.corr_pstep = 0; ttime.corr_dstep = 0; \n ttime.pchol = 0; ttime.dchol = 0; ttime.misc = 0; \n%%\n%%-----------------------------------------\n%% display parameters and initial info\n%%-----------------------------------------\n%%\n if (printlevel >= 2)\n fprintf('\\n********************************************');\n fprintf('***********************\\n');\n fprintf(' SDPT3: Infeasible path-following algorithms'); \n fprintf('\\n********************************************');\n fprintf('***********************\\n');\n [hh,mm,ss] = mytime(ttime.preproc); \n if (printlevel>=3) \n fprintf(' version predcorr gam expon scale_data\\n');\n if (vers == 1); fprintf(' HKM '); elseif (vers == 2); fprintf(' NT '); end\n fprintf(' %1.0f %4.3f',predcorr,gam);\n fprintf(' %1.0f %1.0f %1.0f\\n',expon,scale_data); \n fprintf('\\nit pstep dstep pinfeas dinfeas gap')\n fprintf(' prim-obj dual-obj cputime\\n');\n fprintf('------------------------------------------------');\n fprintf('-------------------\\n');\n fprintf('%2.0f|%4.3f|%4.3f|%2.1e|%2.1e|',0,0,0,prim_infeas,dual_infeas);\n fprintf('%2.1e|%- 7.6e %- 7.6e| %s:%s:%s|',gap,obj(1),obj(2),hh,mm,ss);\n end\n end\n%%\n%%---------------------------------------------------------------\n%% start main loop\n%%---------------------------------------------------------------\n%%\n param.termcode = termcode; \n param.iter = 0; \n param.obj = obj;\n param.relgap = relgap; \n param.prim_infeas = prim_infeas; param.dual_infeas = dual_infeas; \n param.homRd = homRd; param.homrp = homrp; \n param.AX = AX; param.ZpATynorm = ZpATynorm;\n param.normA = normA; \n param.normb = normb; param.normC = normC;\n param.normX0 = normX0; param.normZ0 = normZ0; \n param.m0 = m0; param.indeprows = indeprows;\n param.prim_infeas_bad = 0; \n param.dual_infeas_bad = 0; \n param.prim_infeas_min = prim_infeas; \n param.dual_infeas_min = dual_infeas; \n param.gaptol = gaptol;\n param.inftol = inftol; \n param.maxit = maxit;\n param.scale_data = scale_data;\n param.printlevel = printlevel; \n param.ublksize = ublksize; \n Xbest = X; ybest = y; Zbest = Z; \n%%\n for iter = 1:maxit;\n tstart = clock; \n timeold = tstart;\n update_iter = 0; breakyes = 0; \n pred_slow = 0; corr_slow = 0; step_short = 0; \n par.parbarrier = parbarrier; \n par.iter = iter; \n par.obj = obj; \n par.relgap = relgap; \n par.pinfeas = prim_infeas; \n par.dinfeas = dual_infeas;\n par.rp = rp; \n par.y = y; \n par.dy = dy; \n par.normX = normX; \n par.ZpATynorm = ZpATynorm; \n %%if (printlevel > 2); fprintf(' %2.1e',par.normX); end\n if (iter == 1 | restart); Cpert = min(1,normC2/ops(EE,'norm')); end\n if (runhist.dinfeas(1) > 1e-3) & (~exist_analytic_term) ...\n & (relgap > 1e-4) \n if (par.normX > 5e3 & iter < 20)\n Cpert = Cpert*0.5; \n elseif (par.normX > 5e2 & iter < 20); \n Cpert = Cpert*0.3; \n else; \n Cpert = Cpert*0.1; \n end\n Rd = ops(Rd,'+',EE,Cpert); \n %%if (printlevel > 2); fprintf('|%2.1e',Cpert); end\n end\n%%---------------------------------------------------------------\n%% predictor step.\n%%---------------------------------------------------------------\n%%\n if (predcorr)\n sigma = 0; \n else \n sigma = 1-0.9*min(pstep,dstep); \n if (iter == 1); sigma = 0.5; end; \n end\n sigmu = cell(size(blk,1),1);\n for p = 1:size(blk,1)\n sigmu{p} = max(sigma*mu, parbarrier{p}'); \n end\n invXchol = cell(size(blk,1),1); \n invZchol = ops(Zchol,'inv'); \n if (vers == 1);\n [par,dX,dy,dZ,coeff,L,hRd] = ...\n HKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol);\n elseif (vers == 2);\n [par,dX,dy,dZ,coeff,L,hRd] = ...\n NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);\n end\n if (solve_ok <= 0)\n msg = 'stop: difficulty in computing predictor directions'; \n if (printlevel); fprintf('\\n %s',msg); end\n runhist.pinfeas(iter+1) = runhist.pinfeas(iter); \n runhist.dinfeas(iter+1) = runhist.dinfeas(iter); \n runhist.relgap(iter+1) = runhist.relgap(iter); \n runhist.cputime(iter+1) = etime(clock,tstart); \n termcode = -4;\n break; %% do not ues breakyes = 1\n end\n timenew = clock;\n ttime.pred = ttime.pred + etime(timenew,timeold); timeold = timenew; \n%%\n%%-----------------------------------------\n%% step-lengths for predictor step\n%%-----------------------------------------\n%%\n if (gam == 0) \n gamused = 0.9 + 0.09*min(pstep,dstep); \n else\n gamused = gam;\n end \n [Xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol); \n pstep = min(1,gamused*full(Xstep));\n timenew = clock; \n ttime.pred_pstep = ttime.pred_pstep + etime(timenew,timeold); timeold = timenew;\n Zstep = steplength(blk,Z,dZ,Zchol,invZchol); \n dstep = min(1,gamused*full(Zstep));\n trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...\n + dstep*blktrace(blk,X,dZ,parbarrier) ...\n + pstep*dstep*blktrace(blk,dX,dZ,parbarrier);\n if (nn > 0); mupred = trXZnew/nn; else; mupred = 1e-16; end\n mupredhist(iter) = mupred;\n timenew = clock; \n ttime.pred_dstep = ttime.pred_dstep + etime(timenew,timeold); timeold = timenew;\n%%\n%%-----------------------------------------\n%% stopping criteria for predictor step.\n%%-----------------------------------------\n%%\n if (min(pstep,dstep) < steptol) & (stoplevel) & (iter > 10)\n msg = 'stop: steps in predictor too short';\n if (printlevel) \n fprintf('\\n %s',msg);\n fprintf(': pstep = %3.2e, dstep = %3.2e\\n',pstep,dstep);\n end\n runhist.cputime(iter+1) = etime(clock,tstart); \n termcode = -2; \n breakyes = 1; \n end\n if (~predcorr)\n if (iter >= 2) \n idx = [max(2,iter-2) : iter];\n pred_slow = all(mupredhist(idx)./mupredhist(idx-1) > 0.4);\n idx = [max(2,iter-5) : iter];\n pred_convg_rate = mean(mupredhist(idx)./mupredhist(idx-1));\n pred_slow = pred_slow + (mupred/mu > 5*pred_convg_rate);\n end \n if (max(mu,infeas) < 1e-6) & (pred_slow) & (stoplevel)\n msg = 'stop: lack of progress in predictor'; \n if (printlevel) \n fprintf('\\n %s',msg);\n fprintf(': mupred/mu = %3.2f, pred_convg_rate = %3.2f.',...\n mupred/mu,pred_convg_rate);\n end\n runhist.cputime(iter+1) = etime(clock,tstart); \n termcode = -2; \n breakyes = 1;\n else \n update_iter = 1; \n end\n end\n%%---------------------------------------------------------------\n%% corrector step.\n%%---------------------------------------------------------------\n%%\n if (predcorr) & (~breakyes)\n step_pred = min(pstep,dstep);\n if (mu > 1e-6)\n if (step_pred < 1/sqrt(3)); \n expon_used = 1; \n else\n expon_used = max(expon,3*step_pred^2); \n end\n else \n expon_used = max(1,min(expon,3*step_pred^2)); \n end \n if (nn==0)\n sigma = 0.2; \n elseif (mupred < 0) \n sigma = 0.8; \n else\n sigma = min(1, (mupred/mu)^expon_used);\n end\n sigmu = cell(size(blk,1),1); \n for p = 1:size(blk,1)\n sigmu{p} = max(sigma*mu, parbarrier{p}'); \n end\t \n if (vers == 1)\n [dX,dy,dZ] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n dX,dZ,coeff,L,X,Z);\n elseif (vers == 2)\n [dX,dy,dZ] = NTcorr(blk,At,par,rp,Rd,sigmu,hRd,...\n dX,dZ,coeff,L,X,Z); \n end\n if (solve_ok <= 0)\n msg = 'stop: difficulty in computing corrector directions'; \n if (printlevel); fprintf('\\n %s',msg); end\n runhist.pinfeas(iter+1) = runhist.pinfeas(iter); \n runhist.dinfeas(iter+1) = runhist.dinfeas(iter); \n runhist.relgap(iter+1) = runhist.relgap(iter); \n runhist.cputime(iter+1) = etime(clock,tstart); \n termcode = -4;\n break; %% do not ues breakyes = 1\n end\n timenew = clock;\n ttime.corr = ttime.corr + etime(timenew,timeold); timeold = timenew; \n%%\n%%-----------------------------------\n%% step-lengths for corrector step\n%%-----------------------------------\n%%\n if (gam == 0) \n gamused = 0.9 + 0.09*min(pstep,dstep); \n else\n gamused = gam;\n end \n Xstep = steplength(blk,X,dX,Xchol,invXchol);\n pstep = min(1,gamused*full(Xstep));\n timenew = clock;\n ttime.corr_pstep = ttime.corr_pstep+etime(timenew,timeold); timeold = timenew;\n Zstep = steplength(blk,Z,dZ,Zchol,invZchol);\n dstep = min(1,gamused*full(Zstep));\n trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...\n + dstep*blktrace(blk,X,dZ,parbarrier)...\n + pstep*dstep*blktrace(blk,dX,dZ,parbarrier); \n if (nn > 0); mucorr = trXZnew/nn; else; mucorr = 1e-16; end\n timenew = clock;\n ttime.corr_dstep = ttime.corr_dstep+etime(timenew,timeold); timeold = timenew;\n%%\n%%-----------------------------------------\n%% stopping criteria for corrector step\n%%-----------------------------------------\n if (iter >= 2) \n idx = [max(2,iter-2) : iter];\n corr_slow = all(runhist.gap(idx)./runhist.gap(idx-1) > 0.8); \n idx = [max(2,iter-5) : iter];\n corr_convg_rate = mean(runhist.gap(idx)./runhist.gap(idx-1));\n corr_slow = corr_slow + (mucorr/mu > max(min(1,5*corr_convg_rate),0.8));\n end \n\t if (max(relgap,infeas) < 1e-6) & (iter > 20) ...\n & (corr_slow > 1) & (stoplevel)\n msg = 'stop: lack of progress in corrector'; \n \t if (printlevel) \n fprintf('\\n %s',msg);\n fprintf(': mucorr/mu = %3.2f, corr_convg_rate = %3.2f',...\n mucorr/mu,corr_convg_rate); \n end\n runhist.cputime(iter+1) = etime(clock,tstart); \n termcode = -2; \n breakyes = 1;\n else\n update_iter = 1;\n end\n end \n%%---------------------------------------------------------------\n%% udpate iterate\n%%---------------------------------------------------------------\n indef = [1,1]; \n if (update_iter)\n for t = 1:5\n [Xchol,indef(1)] = blkcholfun(blk,ops(X,'+',dX,pstep)); \n timenew = clock;\n ttime.pchol = ttime.pchol + etime(timenew,timeold); timeold = timenew;\n if (indef(1)); pstep = 0.8*pstep; else; break; end \n end\n\t if (t > 1); pstep = gamused*pstep; end\n\t for t = 1:5\n [Zchol,indef(2)] = blkcholfun(blk,ops(Z,'+',dZ,dstep)); \n timenew = clock;\n ttime.dchol = ttime.dchol + etime(timenew,timeold); timeold = timenew; \n if (indef(2)); dstep = 0.8*dstep; else; break; end \n end\n\t if (t > 1); dstep = gamused*dstep; end\n %%-------------------------------------------\n AXtmp = AX + pstep*AXfun(blk,At,par.permA,dX);\n prim_infeasnew = norm(b-AXtmp)/normb2;\n if (relgap < 5*infeas); alpha = 1e2; else; alpha = 1e3; end\n if any(indef)\n if indef(1); msg = 'stop: X not positive definite'; end\n if indef(2); msg = 'stop: Z not positive definite'; end\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -3;\n breakyes = 1; \n elseif (prim_infeasnew > max([1e-8,relgap,20*prim_infeas]) & iter > 10) ...\n | (prim_infeasnew > max([1e-7,1e3*prim_infeas,0.1*relgap]) & relgap < 1e-2) ...\n | (prim_infeasnew > alpha*max([1e-9,param.prim_infeas_min]) ...\n & (prim_infeasnew > max([3*prim_infeas,0.1*relgap])) ...\n & (iter > 25) & (dual_infeas < 1e-6) & (relgap < 0.1)) ...\n | ((prim_infeasnew > 1e3*prim_infeas & prim_infeasnew > 1e-12) ...\n & (max(relgap,dual_infeas) < 1e-8))\n if (stoplevel) \n msg = 'stop: primal infeas has deteriorated too much'; \n if (printlevel); fprintf('\\n %s, %2.1e',msg,prim_infeasnew); end\n termcode = -7; \n breakyes = 1; \n end\n elseif (trXZnew > 1.05*runhist.gap(iter)) & (~exist_analytic_term) ...\n\t & ((infeas < 1e-5) & (relgap < 1e-4) & (iter > 20) ...\n\t | (max(infeas,relgap) < 1e-7) & (iter > 10)) \n if (stoplevel) \n msg = 'stop: progress in duality gap has deteriorated'; \n if (printlevel); fprintf('\\n %s, %2.1e',msg,trXZnew); end\n termcode = -8; \n breakyes = 1; \n end\n else\n X = ops(X,'+',dX,pstep); \n y = y + dstep*dy; \n Z = ops(Z,'+',dZ,dstep);\n end\n end\n%%---------------------------------------------------------------\n%% adjust linear blk arising from unrestricted blk\n%%---------------------------------------------------------------\n if (~breakyes)\n for p = 1:size(blk,1)\n if (u2lblk(p) == 1)\n len = blk{p,2}/2; \n xtmp = min(X{p}([1:len]),X{p}(len+[1:len])); \n alpha = 0.8; \n X{p}([1:len]) = X{p}([1:len]) - alpha*xtmp;\n X{p}(len+[1:len]) = X{p}(len+[1:len]) - alpha*xtmp;\n if (mu < 1e-4) %% old: (mu < 1e-7)\n Z{p} = 0.5*mu./max(1,X{p}); %% good to keep this step\n else\n ztmp = min(1,max(Z{p}([1:len]),Z{p}(len+[1:len])));\n if (dual_infeas > 1e-4 & dstep < 0.2)\n beta = 0.3; \n else \n beta = 0.0; \n end\n %% important to set beta = 0 at later stage. \n Z{p}([1:len]) = Z{p}([1:len]) + beta*ztmp;\n Z{p}(len+[1:len]) = Z{p}(len+[1:len]) + beta*ztmp;\n end\n end\n end\n end\n%%--------------------------------------------------\n%% perturb Z: do this step before checking for break\n%%--------------------------------------------------\n if (~breakyes) & (~exist_analytic_term)\n trXZtmp = blktrace(blk,X,Z);\n trXE = blktrace(blk,X,EE);\n Zpert = max(1e-12,0.2*min(relgap,prim_infeas)).*normC2./normE2;\n Zpert = min(Zpert,0.1*trXZtmp./trXE);\n Zpert = min([1,Zpert,1.5*Zpertold]); \n if (infeas < 0.1) \n Z = ops(Z,'+',EE,Zpert); \n [Zchol,indef(2)] = blkcholfun(blk,Z);\n if any(indef(2))\n msg = 'stop: Z not positive definite'; \n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -3;\n breakyes = 1; \n end\n %%if (printlevel > 2); fprintf(' %2.1e',Zpert); end\n end\n Zpertold = Zpert; \n end\n%%---------------------------------------------------------------\n%% compute rp, Rd, infeasibities, etc\n%%---------------------------------------------------------------\n%%\n AX = AXfun(blk,At,par.permA,X); \n rp = b-AX;\n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n ZpATynorm = ops(ZpATy,'norm');\n Rd = ops(C,'-',ZpATy);\n objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0; \n obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd; \n gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n relgap = gap/(1+sum(abs(obj))); \n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n infeas = max(prim_infeas,dual_infeas); \n if (scale_data)\n infeas_org(1) = prim_infeas*normb;\n infeas_org(2) = dual_infeas*normC;\n end\n homRd = inf; homrp = inf; \n if (ops(parbarrier,'norm') == 0)\n if (obj(2) > 0); homRd = ZpATynorm/(obj(2)); end\n if (obj(1) < 0); homrp = norm(AX)/(-obj(1))/(normC); end\n end\n trXZ = blktrace(blk,X,Z,parbarrier); \n if (nn > 0); mu = trXZ/nn; else; mu = gap/ops(X,'getM'); end\n normX = ops(X,'norm');\n%%\n runhist.pobj(iter+1) = obj(1); \n runhist.dobj(iter+1) = obj(2); \n runhist.gap(iter+1) = gap;\n runhist.relgap(iter+1) = relgap;\n runhist.pinfeas(iter+1) = prim_infeas;\n runhist.dinfeas(iter+1) = dual_infeas;\n runhist.infeas(iter+1) = infeas;\n runhist.pstep(iter+1) = pstep; \n runhist.dstep(iter+1) = dstep; \n runhist.step(iter+1) = min(pstep,dstep); \n runhist.normX(iter+1) = normX; \n runhist.cputime(iter+1) = etime(clock,tstart); \n timenew = clock;\n ttime.misc = ttime.misc + etime(timenew,timeold); timeold = timenew; \n [hh,mm,ss] = mytime(sum(runhist.cputime)); \n if (printlevel>=3)\n fprintf('\\n%2.0f|%4.3f|%4.3f',iter,pstep,dstep);\n fprintf('|%2.1e|%2.1e|%2.1e|',prim_infeas,dual_infeas,gap);\n fprintf('%- 7.6e %- 7.6e| %s:%s:%s|',obj(1),obj(2),hh,mm,ss);\n end\n%%--------------------------------------------------\n%% check convergence\n%%--------------------------------------------------\n param.use_LU = use_LU; \n param.stoplevel = stoplevel; \n param.termcode = termcode; \n param.iter = iter; \n param.obj = obj;\n param.gap = gap; \n param.relgap = relgap; \n param.prim_infeas = prim_infeas;\n param.dual_infeas = dual_infeas;\n param.mu = mu; \n param.homRd = homRd; \n param.homrp = homrp; \n param.AX = AX; \n param.ZpATynorm = ZpATynorm;\n param.normX = ops(X,'norm'); \n param.normZ = ops(Z,'norm'); \n param.numpertdiagschur = numpertdiagschur; \n if (~breakyes)\n [param,breakyes,restart,msg2] = sqlpcheckconvg(param,runhist); \n end\n if (restart)\n [X,y,Z] = infeaspt(blk,At,C,b,2,1e5); \n rp = b-AXfun(blk,At,par.permA,X); \n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n Rd = ops(C,'-',ZpATy); \n trXZ = blktrace(blk,X,Z,parbarrier); \n mu = trXZ/nn;\n gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n prim_infeas = norm(rp)/normb2;\n dual_infeas = ops(Rd,'norm')/normC2;\n infeas = max(prim_infeas,dual_infeas); \n [Xchol,indef(1)] = blkcholfun(blk,X); \n [Zchol,indef(2)] = blkcholfun(blk,Z); \n stoplevel = 3;\n end\n%%--------------------------------------------------\n%% check for break\n%%--------------------------------------------------\n if ((prim_infeas < 1.5*prim_infeas_best) ... \n | (max(relgap,infeas) < 0.8*max(relgap_best,infeas_best))) ...\n & (max(relgap,dual_infeas) < 0.8*max(relgap_best,dual_infeas_best)) \n Xbest = X; ybest = y; Zbest = Z; \n prim_infeas_best = prim_infeas; \n dual_infeas_best = dual_infeas; \n relgap_best = relgap; infeas_best = infeas; \n update_best(iter+1) = 1; \n %%fprintf('#')\n else\n update_best(iter+1) = 0; \n end \n if (max(relgap_best,infeas_best) < 1e-4 ...\n & norm(update_best(max(1,iter-1):iter+1)) == 0)\n msg = 'lack of progress in infeas'; \n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -9; \n breakyes = 1; \n end\n if (breakyes); break; end\n end\n%%---------------------------------------------------------------\n%% end of main loop\n%%---------------------------------------------------------------\n%%\n use_bestiter = 1; \n if (use_bestiter) & (param.termcode <= 0)\n X = Xbest; y = ybest; Z = Zbest; \n Xchol = blkcholfun(blk,X); \n Zchol = blkcholfun(blk,Z); \n AX = AXfun(blk,At,par.permA,X); \n rp = b-AX;\n ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));\n Rd = ops(C,'-',ZpATy);\n objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0; \n obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd; \n gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);\n relgap = gap/(1+sum(abs(obj)));\n prim_infeas = norm(rp)/normb2; \n dual_infeas = ops(Rd,'norm')/normC2; \n infeas = max(prim_infeas,dual_infeas); \n runhist.pobj(iter+1) = obj(1); \n runhist.dobj(iter+1) = obj(2); \n runhist.gap(iter+1) = gap;\n runhist.relgap(iter+1) = relgap;\n runhist.pinfeas(iter+1) = prim_infeas;\n runhist.dinfeas(iter+1) = dual_infeas;\n runhist.infeas(iter+1) = infeas; \n end\n%%---------------------------------------------------------------\n%% unscale and produce infeasibility certificates if appropriate\n%%---------------------------------------------------------------\n if (iter >= 1)\n [X,y,Z,termcode,resid,reldist,msg3] = ...\n sqlpmisc(blk,At,C,b,X,y,Z,par.permZ,param); \n end\n%%---------------------------------------------------------------\n%% recover unrestricted blk from linear blk\n%%---------------------------------------------------------------\n%% \n for p = 1:size(blk,1)\n if (u2lblk(p) == 1)\n n = blk{p,2}/2; \n X{p} = X{p}(1:n)-X{p}(n+[1:n]); \n Z{p} = Z{p}(1:n); \n end\n end\n for p = 1:size(ublkidx,1) \n if ~isempty(ublkidx{p,2})\n n0 = ublkidx{p,1}; idxB = setdiff([1:n0]',ublkidx{p,2});\n tmp = zeros(n0,1); tmp(idxB) = X{p}; X{p} = tmp; \n tmp = zeros(n0,1); tmp(idxB) = Z{p}; Z{p} = tmp; \n end\n end\n if (analytic_prob)\n X = X(1:numblkold); Z = Z(1:numblkold); \n end\n%%---------------------------------------------------------------\n%% print summary\n%%---------------------------------------------------------------\n%%\n maxC = 1+ops(ops(C,'abs'),'max'); \n maxb = 1+max(abs(b)); \n if (scale_data)\n dimacs = [infeas_org(1)*normb2/maxb; 0; infeas_org(2)*normC2/maxC; 0]; \n else\n dimacs = [prim_infeas*normb2/maxb; 0; dual_infeas*normC2/maxC; 0];\n end\n dimacs = [dimacs; [-diff(obj); gap]/(1+sum(abs(obj)))];\n info.dimacs = dimacs; \n info.termcode = termcode;\n info.iter = iter; \n info.obj = obj; \n info.gap = gap; \n info.relgap = relgap;\n info.pinfeas = prim_infeas;\n info.dinfeas = dual_infeas;\n info.cputime = sum(runhist.cputime); \n info.time = ttime; \n info.resid = resid;\n info.reldist = reldist; \n info.normX = ops(X,'norm'); \n info.normy = norm(y); \n info.normZ = ops(Z,'norm'); \n info.normb = normb2; info.maxb = maxb; \n info.normC = normC2; info.maxC = maxC; \n info.normA = normA2;\n info.msg1 = msg; \n info.msg2 = msg2;\n info.msg3 = msg3;\n sqlpsummary(info,ttime,infeas_org,printlevel);\n%%*****************************************************************************\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/SDPT3-4.0/SDPT3-4.0/Solver/sqlpmain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.029760095129186245, "lm_q1q2_score": 0.014531360294006089}} {"text": "function [data, warns] = psse_parse(records, sections, verbose, rev)\n%PSSE_PARSE Parses the data from a PSS/E RAW data file.\n% DATA = PSSE_PARSE(RECORDS, SECTIONS)\n% DATA = PSSE_PARSE(RECORDS, SECTIONS, VERBOSE)\n% DATA = PSSE_PARSE(RECORDS, SECTIONS, VERBOSE, REV)\n% [DATA, WARNINGS] = PSSE_PARSE(RECORDS, SECTIONS, ...)\n%\n% Parses the data from a PSS/E RAW data file (as read by PSSE_READ)\n% into a struct.\n%\n% Inputs:\n% RECORDS : cell array of strings, corresponding to the lines\n% in the RAW file\n% SECTIONS : struct array with indices marking the beginning\n% and end of each section, and the name of the\n% section, fields are:\n% first : index into RECORDS of first line of section\n% last : index into RECORDS of last line of section\n% name : name of the section, as extracted from the\n% END OF ... DATA comments\n% VERBOSE : 1 (default) to display progress info, 0 otherwise\n% REV : (optional) assume the input file is of this\n% PSS/E revision number, attempts to determine\n% REV from the file by default\n%\n% Output(s):\n% DATA : a struct with the following fields, each with two\n% sub-fields, 'num' and 'txt' containing the numeric and\n% text data read from the file for the corresponding section\n% id\n% bus\n% load\n% gen\n% shunt\n% branch\n% trans2\n% trans3\n% area\n% twodc\n% swshunt\n% WARNINGS : cell array of strings containing accumulated\n% warning messages\n%\n% See also PSSE2MPC, PSSE_READ, PSSE_PARSE_SECTION, PSSE_PARSE_LINE\n\n% MATPOWER\n% Copyright (c) 2014-2016, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% Based on mpreadraw.m, written by: Yujia Zhu, Jan 2014, yzhu54@asu.edu.\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% default args\nif nargin < 4\n rev = 0;\n if nargin < 3\n verbose = 0;\n end\nend\ndefaultrev = 23;\n\n%% inititialize section counter\ns = 1;\nwarns = {};\n\n%%----- case identification data -----\n%% In some files, SBASE is followed by a comment with the REV number such as:\n%% / PSS/E-29.0\n%% / PSS(tm)E-30 RAW\nif verbose\n if rev\n fprintf('Forcing interpretation as PSS/E revision %d\\n', rev);\n else\n fprintf('Attempting to determine PSS/E revision from content.\\n');\n end\n fprintf('Parsing case identification data ...');\nend\nif rev\n warns{end+1} = sprintf('Conversion explicitly using PSS/E revision %d', rev);\nend\n[d, c] = psse_parse_line(records{1}, 'dfdfff');\nnn = length(d);\ndata.id.IC = d{1};\nif isempty(d{2}) || d{2} <= 0\n error('ERROR: Probable corrupt file, unable to read a valid SBASE value from the first line.');\nelse\n data.id.SBASE = d{2};\nend\nif ~isempty(d{3})\n data.id.REV = d{3};\nelse %% attempt to extract revision from comment\n tmp = regexp(c, 'PSS(/|\\(tm\\))E-(?\\d+)', 'tokens');\n if ~isempty(tmp) && size(tmp{1}, 2) == 2\n data.id.REV = str2num(tmp{1}{2});\n else\n data.id.REV = 0;\n end\nend\nif ~isempty(d{4})\n data.id.XFRRAT = d{4};\nelse\n data.id.XFRRAT = 0;\nend\nif ~isempty(d{5})\n data.id.NXFRAT = d{5};\nelse\n data.id.NXFRAT = 0;\nend\nif ~isempty(d{6})\n data.id.BASFRQ = d{6};\nelse\n data.id.BASFRQ = 0;\nend\ndata.id.comment0 = c;\ndata.id.comment1 = records{2};\ndata.id.comment2 = records{3};\nif verbose\n if rev\n if data.id.REV\n fprintf('.. override detected rev %2d w/%2d ... done.\\n', data.id.REV, rev);\n else\n fprintf('...... unknown rev, using rev %2d ... done.\\n', rev);\n end\n else\n if data.id.REV\n fprintf('......... rev %2d format detected ... done.\\n', data.id.REV);\n else\n fprintf('...... unknown rev, using rev %2d ... done.\\n', defaultrev);\n end\n end\nend\nif ~rev\n if data.id.REV\n rev = data.id.REV; %% use detected value\n else\n rev = defaultrev; %% none detected, use default value\n data.id.REV = defaultrev;\n warns{end+1} = sprintf('Unknown REV, using REV %2d format.', defaultrev);\n end\nelse\n data.id.REV = rev; %% use override value\nend\nif isempty(data.id.IC) || data.id.IC ~= 0\n warns{end+1} = sprintf('IC = %d indicates that this may be a change case, rather than base case\\n PSSE2MPC is NOT designed to handle change cases.', data.id.IC);\n if verbose\n fprintf('WARNING : %s\\n', warns{end});\n end\nend\ns = s + 1;\n\n%%----- bus data -----\nif rev < 24 %% includes load data \n [data.bus, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'bus', 'ddffffdffsfd');\nelseif rev < 31 %% includes fixed shunt data, load separate\n [data.bus, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'bus', 'dsfdffddffd');\nelse %% fixed shunt and load data separate\n [data.bus, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'bus', 'dsfddddffff..');\n% 'bus', 'dsfddddffffff');\nend\ns = s + 1;\n\n%%----- load data -----\nif rev >= 24\n [data.load, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'load', 'd.d..ffffff...');\n% 'load', 'dsdddffffffddd');\n s = s + 1;\nend\n\n%%----- fixed shunt data -----\nif rev > 30 %% fixed shunt data is included in bus data for rev <= 30\n [data.shunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'fixed shunt', 'd.dff');\n% 'fixed shunt', 'dsdff');\n s = s + 1;\nend\n\n%%----- generator data -----\n[data.gen, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'generator', 'd.fffff.f.....d.ff...........');\n% 'generator', 'dsfffffdffffffdfffdfdfdfdfsdf');\ns = s + 1;\n\n%%----- branch data -----\nif rev <= 27 %% includes transformer ratio, angle\n [data.branch, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'branch', 'dd.ffffffffffffd');\n% 'branch', 'dddffffffffffffd');\nelseif rev < 31\n [data.branch, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'branch', 'dd.ffffffffffd');\n% 'branch', 'ddsffffffffffdfdfdfdfdf');\nelse\n [data.branch, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'branch', 'dd.ffffffffffd');\n% 'branch', 'ddsffffffffffddfdfdfdfdf');\nend\ns = s + 1;\n\n%%----- skip transformer adjustment data -----\nif rev <= 27\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'transformer adjustment');\nend\n\n%%----- transformer data -----\nif rev > 27\n %% PSS/E stores two winding and three winding transformer data in the same\n %% section in RAW file. We read in 2 passes, first pass determines the type of\n %% each, second pass reads the data.\n label = 'transformer';\n if ~isempty(sections(s).name) && ~strcmpi(label, sections(s).name)\n if verbose > 1\n fprintf('----- WARNING: Expected section labeled: ''%s''\\n', upper(label));\n fprintf('----- Found section labeled: ''%s''\\n', sections(s).name);\n end\n end\n\n %% Step 1 : Count and collect transformer types\n if verbose\n fprintf('Analyzing transformer types ...');\n end\n\n %% estimate max number of transformers by number of lines in section\n nt2 = round((sections(s).last - sections(s).first + 1) / 4);\n nt3 = round((sections(s).last - sections(s).first + 1) / 5);\n\n %% initialize indices for transformer types\n idx2 = zeros(nt2, 1);\n idx3 = zeros(nt3, 1);\n\n %% set up counters\n i = sections(s).first; %% initialize record index\n i2 = 0;\n i3 = 0;\n\n while i <= sections(s).last\n %% determine transformer type\n pat = '[^''\",\\s/]+\\s*(,|\\s)\\s*[^''\",\\s/]+\\s*(,|\\s)\\s*([^''\",\\s/]+)';\n m = regexp(records{i}, pat, 'tokens', 'once');\n if length(m) ~= 3\n disp(m);\n error('m should be length 3');\n end\n if length(m{3}) == 1 && m{3}(1) == '0' %% two-winding\n i2 = i2 + 1;\n idx2(i2) = i;\n i = i + 4;\n else %% three-winding\n i3 = i3 + 1;\n idx3(i3) = i;\n i = i + 5;\n end\n end\n nt2 = i2;\n nt3 = i3;\n\n if verbose\n str = sprintf(' %d(%d) two(three)-winding.', nt2, nt3);\n spacers = repmat('.', 1, 36-length(str));\n fprintf('%s %s ... done.\\n', spacers, str);\n end\n\n %% trim index vectors down to size\n idx2 = idx2(1:nt2);\n idx3 = idx3(1:nt3);\n\n %% parse record 1 (cols 1-20)\n [t2_1, warns] = psse_parse_section(warns, records(idx2), verbose, ...\n '2-winding transformers (1)', 'dd..ddd....d........');\n% '2-winding transformers (1)', 'dddsdddffdsddfdfdfdf');\n [t3_1, warns] = psse_parse_section(warns, records(idx3), verbose, ...\n '3-winding transformers (1)', 'ddd.ddd....d........');\n% '3-winding transformers (1)', 'dddsdddffdsddfdfdfdf');\n\n %% two-winding\n %% parse record 2 (cols 21-23)\n [t2_2, warns] = psse_parse_section(warns, records(idx2+1), verbose, ...\n '2-winding transformers (2)', 'fff');\n\n %% parse record 3 (cols 24-39)\n %% parse up to CX1, should warn if CNXA1 is present and non-zero\n [t2_3, warns] = psse_parse_section(warns, records(idx2+2), verbose, ...\n '2-winding transformers (3)', 'ffffff..........');\n% '2-winding transformers (3)', 'ffffffddffffddff');\n\n %% parse record 4 (cols 40-41)\n [t2_4, warns] = psse_parse_section(warns, records(idx2+3), verbose, ...\n '2-winding transformers (4)', 'ff');\n\n %% three-winding\n %% parse record 2 (cols 21-31)\n [t3_2, warns] = psse_parse_section(warns, records(idx3+1), verbose, ...\n '3-winding transformers (2)', 'fffffffffff');\n% '3-winding transformers (2)', 'fffffffffff');\n\n %% parse record 3 (cols 32-47)\n %% parse up to CX1, should warn if CNXA1 is present and non-zero\n [t3_3, warns] = psse_parse_section(warns, records(idx3+2), verbose, ...\n '3-winding transformers (3)', 'ffffff..........');\n% '3-winding transformers (3)', 'ffffffddffffddff');\n\n %% parse record 4 (cols 48-63)\n %% parse up to CX2\n [t3_4, warns] = psse_parse_section(warns, records(idx3+3), verbose, ...\n '3-winding transformers (4)', 'ffffff..........');\n% '3-winding transformers (4)', 'ffffffddffffddff');\n\n %% parse record 5 (cols 64-79)\n %% parse up to CX3\n [t3_5, warns] = psse_parse_section(warns, records(idx3+4), verbose, ...\n '3-winding transformers (5)', 'ffffff..........');\n% '3-winding transformers (5)', 'ffffffddffffddff');\n\n %% assemble two-winding transformer records\n data.trans2.num = [t2_1.num(:, 1:20) t2_2.num(:, 1:3) t2_3.num(:, 1:16) t2_4.num(:, 1:2)];\n data.trans2.txt = [t2_1.txt(:, 1:20) t2_2.txt(:, 1:3) t2_3.txt(:, 1:16) t2_4.txt(:, 1:2)];\n\n %% assemble three-winding transformer records\n data.trans3.num = [t3_1.num(:, 1:20) t3_2.num(:, 1:11) t3_3.num(:, 1:16) t3_4.num(:, 1:16) t3_5.num(:, 1:16)];\n data.trans3.txt = [t3_1.txt(:, 1:20) t3_2.txt(:, 1:11) t3_3.txt(:, 1:16) t3_4.txt(:, 1:16) t3_5.txt(:, 1:16)];\n\n % if verbose\n % fprintf('%s\\n', upper(label));\n % fprintf('%s\\n', sections(s).name);\n % end\n s = s + 1;\nend\n\n%%----- area interchange data -----\n[data.area, warns] = psse_parse_section(warns, records, sections, s, verbose, 'area', 'ddffs');\ns = s + 1;\n\n%%----- two-terminal DC transmission line data -----\nlabel = 'two-terminal DC';\nif ~isempty(sections(s).name) && ~strcmpi(label, sections(s).name)\n if verbose > 1\n fprintf('----- WARNING: Expected section labeled: ''%s''\\n', upper(label));\n fprintf('----- Found section labeled: ''%s''\\n', sections(s).name);\n end\nend\nidx = sections(s).first:3:sections(s).last;\nif rev < 31\n [dc1, warns] = psse_parse_section(warns, records(idx), verbose, ...\n 'two-terminal DC (1)', '.d.ff.......');\n% 'two-terminal DC (1)', 'ddffffffsfdf');\n [dc2, warns] = psse_parse_section(warns, records(idx+1), verbose, ...\n 'two-terminal DC (2)', 'd.ff.............');\n% 'two-terminal DC (2)', 'ddffffffffffdddsf');\n [dc3, warns] = psse_parse_section(warns, records(idx+2), verbose, ...\n 'two-terminal DC (3)', 'd.ff.............');\n% 'two-terminal DC (3)', 'ddffffffffffdddsf');\nelse\n [dc1, warns] = psse_parse_section(warns, records(idx), verbose, ...\n 'two-terminal DC (1)', '.d.ff.......');\n% 'two-terminal DC (1)', 'sdffffffsfdf');\n [dc2, warns] = psse_parse_section(warns, records(idx+1), verbose, ...\n 'two-terminal DC (2)', 'd.ff.............');\n% 'two-terminal DC (2)', 'ddffffffffffdddDf');\n [dc3, warns] = psse_parse_section(warns, records(idx+2), verbose, ...\n 'two-terminal DC (3)', 'd.ff.............');\n% 'two-terminal DC (3)', 'ddffffffffffdddDf');\nend\n\n%% assemble two-terminal DC transmission line\ndata.twodc.num = [dc1.num dc2.num dc3.num];\ndata.twodc.txt = [dc1.txt dc2.txt dc3.txt];\n% if verbose\n% fprintf('%s\\n', upper(label));\n% fprintf('%s\\n', sections(s).name);\n% end\ns = s + 1;\n\n%%----- skip voltage source converter data -----\nif rev > 28\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'voltage source converter');\nend\n\n%%----- switched shunt data -----\nif rev < 31\n %% parse up to B1\n if rev <= 27\n [data.swshunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'switched shunt', 'd....f');\n% 'switched shunt', 'ddffdfdfdfdfdfdfdfdfdf');\n elseif rev <= 29\n [data.swshunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'switched shunt', 'd.....f');\n% 'switched shunt', 'ddffdsfdfdfdfdfdfdfdfdf');\n else %% rev == 30\n [data.swshunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'switched shunt', 'd......f');\n% 'switched shunt', 'ddffdfsfdfdfdfdfdfdfdfdf');\n end\n s = s + 1;\nend\n\n%%----- skip impedance correction data -----\n[s, warns] = psse_skip_section(warns, sections, s, verbose, 'impedance correction');\n\n%%----- skip multi-terminal DC data -----\n[s, warns] = psse_skip_section(warns, sections, s, verbose, 'multi-terminal DC');\n\n%%----- skip multi-section line data -----\n[s, warns] = psse_skip_section(warns, sections, s, verbose, 'multi-section line');\n\n%%----- skip zone data -----\n[s, warns] = psse_skip_section(warns, sections, s, verbose, 'zone');\n\n%%----- skip inter-area transfer data -----\n[s, warns] = psse_skip_section(warns, sections, s, verbose, 'inter-area transfer');\n\n%%----- skip owner data -----\nif rev > 24\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'owner');\nend\n\n%%----- skip FACTS control device data -----\nif rev > 25\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'FACTS control device');\nend\n\n%%----- switched shunt data -----\nif rev > 30\n %% parse up to B1\n if rev < 32\n [data.swshunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'switched shunt', 'd......f');\n% 'switched shunt', 'ddffdfsfdfdfdfdfdfdfdfdf');\n else\n [data.swshunt, warns] = psse_parse_section(warns, records, sections, s, verbose, ...\n 'switched shunt', 'd........f');\n% 'switched shunt', 'ddddffdfsfdfdfdfdfdfdfdfdf');\n end\n s = s + 1;\nend\n\n%%----- skip GNE device data -----\nif rev > 31\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'GNE device');\nend\n\n%%----- skip induction machine data -----\nif rev > 32\n [s, warns] = psse_skip_section(warns, sections, s, verbose, 'induction machine');\nend\n\n%%----- check for extra sections -----\nif s <= length(sections)\n warns{end+1} = sprintf('Found %d additional section(s)', length(sections)-s+1);\n if verbose > 1\n fprintf('----- WARNING: Found %d additional section(s):\\n', length(sections)-s+1);\n end\nend\nwhile s <= length(sections)\n n = sections(s).last - sections(s).first + 1;\n if n\n str = sprintf('with %d line(s)', n);\n else\n str = sprintf('(empty)');\n end\n if isempty(sections(s).name)\n warns{end+1} = sprintf(' unlabeled section %s', str);\n if verbose > 1\n fprintf('----- unlabeled section %s\\n', str);\n end\n else\n warns{end+1} = sprintf(' ''%s DATA'' %s', sections(s).name, str);\n if verbose > 1\n fprintf('----- ''%s DATA'' %s\\n', sections(s).name, str);\n end\n end\n s = s + 1;\nend\n\n\n\n%%---------------------------------------------------------------------\nfunction [s, warns] = psse_skip_section(warns, sections, s, verbose, label)\n%PSSE_SKIP_SECTION Skips over a section without extracting any data.\n% [SIDX, WARNINGS] = PSSE_SKIP_SECTION(WARNINGS, SECTIONS, SIDX, VERBOSE, LABEL)\n\nif s > length(sections)\n if verbose\n spacers = repmat('.', 1, 58-length(label));\n fprintf('No %s data read %s done.\\n', label, spacers);\n end\nelse\n nr = sections(s).last - sections(s).first + 1;\n if nr > 1\n ss = 'lines';\n else\n ss = 'line';\n end\n if nr\n warns{end+1} = sprintf('Skipped %d %s of %s data.', nr, ss, label);\n end\n if ~isempty(sections(s).name) && ~strcmp(upper(label), sections(s).name)\n warns{end+1} = sprintf('Section label mismatch, found ''%s'', expected ''%s''', ...\n sections(s).name, upper(label));\n if verbose\n fprintf('----- WARNING: Found section labeled: ''%s''\\n', sections(s).name);\n fprintf('----- Expected section labeled: ''%s''\\n', upper(label));\n end\n end\n if verbose && nr\n spacers = repmat('.', 1, 47-length(ss)-length(label));\n fprintf('Skipping%6d %s of %s data %s done.\\n', nr, ss, label, spacers);\n end\n s = s + 1;\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/psse_parse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.038466188849255296, "lm_q1q2_score": 0.014522550125455672}} {"text": "function [ output_meta ] = meta2sicd_nisar( HDF5_fid )\n%META2SICD_NISAR Converts NISAR SLC HDF5 into a SICD-style metadata structure\n%\n% Takes as input a file identifier to an open HDF5 file-- as is returned by\n% H5F.open\n%\n% Note that MATLAB's h5disp is generally a good tool for manually browsing\n% through HDF5 metadata like that found in NISAR format.\n%\n% Known issues with simulated NISAR data (from UAVSAR) to date:\n%\n% 1) ISCEVersion not populated\n% 2) Doppler rate provided is positive. JPL says will it fix in future\n% update.\n% 3) processedAzimuthBandwidth is acknowledged by JPL to be wrong and will\n% be fixed in a future update.\n% 4) Weighting description is currently a placeholder, not an accurate\n% description of UAVSAR data used for simulated data foramt.\n%\n% Written by: Wade Schwartzkopf, NGA/Research\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\nSECONDS_IN_A_DAY = 24*60*60;\n\n% Query for frequencies and polarization (each of which would create its\n% own SICD)\nfreqs_id = H5D.open(HDF5_fid,'/science/LSAR/identification/listOfFrequencies');\nfreqs = H5D.read(freqs_id);\nfreqs = freqs(1,:);\nH5D.close(freqs_id);\nfor i=1:numel(freqs)\n pol_id = H5D.open(HDF5_fid,['/science/LSAR/SLC/swaths/frequency' freqs(i) '/listOfPolarizations']);\n pols{i} = H5D.read(pol_id)';\n H5D.close(pol_id);\nend\n\n%% CollectionInfo\n% CollectorName could also be deblank(get_hdf_data(HDF5_fid,'/science/LSAR/identification','missionId')')\noutput_meta.CollectionInfo.CollectorName=get_hdf_attribute(HDF5_fid,'/','mission_name');\n% JPL suggested this as best way to form unique string for each collection\noutput_meta.CollectionInfo.CoreName=[...\n num2str(get_hdf_data(HDF5_fid,'/science/LSAR/identification','absoluteOrbitNumber'),'%07u') ...\n get_hdf_data(HDF5_fid,'/science/LSAR/identification','trackNumber')'];\noutput_meta.CollectionInfo.CollectType='MONOSTATIC';\noutput_meta.CollectionInfo.RadarMode.ModeType='STRIPMAP';\noutput_meta.CollectionInfo.Classification='UNCLASSIFIED';\n\n%% ImageCreation\ntry\n % TODO: UNTESTED\n % Sample data did not have valid values for this\n output_meta.ImageCreation.Application=['ISCE ' ...\n deblank(get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/processingInformation/algorithms','ISCEVersion')')];\nend\noutput_meta.ImageCreation.Profile='Prototype';\n\n%% ImageData\noutput_meta.ImageData=struct(); % Just a placeholder\n% Most subfields added below in \"per band\" section\n% Used for computing SCP later\n\n%% GeoData\noutput_meta.GeoData.EarthModel='WGS_84';\n% Initially, we just seed this with a very rough value. Later we will\n% put in something more precise.\npoly_str = get_hdf_data(HDF5_fid,'/science/LSAR/identification','boundingPolygon')';\npoly_str(isletter(poly_str)|poly_str=='('|poly_str==')')='';\npoly_str(poly_str==',')=';';\nbound_poly=str2num(poly_str);\nbound_poly=bound_poly(1:(end-1),:);\nrough_center = mean(bound_poly);\noutput_meta.GeoData.SCP.LLH.Lat=rough_center(2);\noutput_meta.GeoData.SCP.LLH.Lon=rough_center(1);\noutput_meta.GeoData.SCP.LLH.HAE=...\n mean(get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/processingInformation/parameters/','referenceTerrainHeight'));\n% NISAR stores this as single, which is sufficient for storage, but we need\n% double precision for some of the computations later on, to include\n% geopositioning of exact SCP.\noutput_meta.GeoData.SCP.LLH.HAE=double(output_meta.GeoData.SCP.LLH.HAE);\necf=geodetic_to_ecf([output_meta.GeoData.SCP.LLH.Lat output_meta.GeoData.SCP.LLH.Lon output_meta.GeoData.SCP.LLH.HAE]);\noutput_meta.GeoData.SCP.ECF.X=ecf(1);\noutput_meta.GeoData.SCP.ECF.Y=ecf(2);\noutput_meta.GeoData.SCP.ECF.Z=ecf(3);\n% Calling derived_sicd_fields at the end will populate these fields\n% with the sensor model, so we don't need to do it here.\n% latlon=get_hdf_attribute(dset_id(i),'Top Left Geodetic Coordinates');\n% output_meta.GeoData.ImageCorners.ICP.FRFC.Lat=bound_poly(1,1);\n% output_meta.GeoData.ImageCorners.ICP.FRFC.Lon=bound_poly(1,2);\n% latlon=get_hdf_attribute(dset_id(i),'Bottom Left Geodetic Coordinates');\n% output_meta.GeoData.ImageCorners.ICP.FRLC.Lat=bound_poly(2,1);\n% output_meta.GeoData.ImageCorners.ICP.FRLC.Lon=bound_poly(2,2);\n% latlon=get_hdf_attribute(dset_id(i),'Bottom Right Geodetic Coordinates');\n% output_meta.GeoData.ImageCorners.ICP.LRLC.Lat=bound_poly(3,1);\n% output_meta.GeoData.ImageCorners.ICP.LRLC.Lon=bound_poly(3,2);\n% latlon=get_hdf_attribute(dset_id(i),'Top Right Geodetic Coordinates');\n% output_meta.GeoData.ImageCorners.ICP.LRFC.Lat=bound_poly(4,1);\n% output_meta.GeoData.ImageCorners.ICP.LRFC.Lon=bound_poly(4,2);\n\n%% Grid\noutput_meta.Grid.ImagePlane='SLANT';\noutput_meta.Grid.Type='RGZERO';\noutput_meta.Grid.Row.Sgn=-1; % Always true for NISAR\noutput_meta.Grid.Col.Sgn=-1; % Always true for NISAR\noutput_meta.Grid.Col.KCtr=0;\noutput_meta.Grid.Row.DeltaKCOAPoly=0;\n% TODO: JPL states that uniform weighting in data simulated from UAVSAR is\n% placeholder, not an accurate description of the data. At this point, it\n% is not clear what the final weighting description for NISAR will be.\noutput_meta.Grid.Row.WgtFunct = get_hdf_data(HDF5_fid,...\n '/science/LSAR/SLC/metadata/processingInformation/parameters','rangeChirpWeighting');\nif all(output_meta.Grid.Row.WgtFunct(1)==output_meta.Grid.Row.WgtFunct)\n output_meta.Grid.Row.WgtType.WindowName = 'UNIFORM'; % In the sample datasets\nelse\n output_meta.Grid.Row.WgtType.WindowName = 'UNKNOWN';\nend\noutput_meta.Grid.Col.WgtFunct = get_hdf_data(HDF5_fid,...\n '/science/LSAR/SLC/metadata/processingInformation/parameters','azimuthChirpWeighting');\nif all(output_meta.Grid.Col.WgtFunct(1)==output_meta.Grid.Col.WgtFunct)\n output_meta.Grid.Col.WgtType.WindowName = 'UNIFORM'; % In the sample datasets\nelse\n output_meta.Grid.Col.WgtType.WindowName = 'UNKNOWN';\nend\n% More subfields added below in \"per band\" section\n\n%% Timeline\n% Using zero Doppler times. Pulse transmission likely started before this\n[collectStart, collectStartFrac]=datenum_w_frac(...\n deblank(get_hdf_data(HDF5_fid, '/science/LSAR/identification', ...\n 'zeroDopplerStartTime')'));\n[collectEnd, collectEndFrac]=datenum_w_frac(...\n deblank(get_hdf_data(HDF5_fid, '/science/LSAR/identification', ...\n 'zeroDopplerEndTime')'));\noutput_meta.Timeline.CollectStart=collectStart + (collectStartFrac/SECONDS_IN_A_DAY);\noutput_meta.Timeline.CollectDuration=...\n round((collectEnd-collectStart)*SECONDS_IN_A_DAY) + ... % Convert days to seconds\n (collectEndFrac-collectStartFrac); % Handle fractional seconds\noutput_meta.Timeline.IPP.Set.TStart=0;\noutput_meta.Timeline.IPP.Set.TEnd=0; % Apply real value later. Just a placeholder.\noutput_meta.Timeline.IPP.Set.IPPStart=uint32(0);\n% More subfields added below in \"per band\" section\n\n%% Position\n% Compute polynomial from state vectors\n% Get reference time\nref_time = get_ref_time(HDF5_fid,'/science/LSAR/SLC/metadata/orbit/time');\n% Times in SICD are with respect to time from start of collect.\nref_time_offset = round((ref_time-collectStart)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n collectStartFrac; % Handle fractional seconds\nstate_vector_T = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/orbit','time')';\nstate_vector_T = state_vector_T + ref_time_offset; % Make with respect to Timeline.CollectStart\nstate_vector_pos = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/orbit','position');\n% sv2poly.m shows ways to determine best polynomial order, but we just use 6th here\npolyorder=min(6, numel(state_vector_T) - 1);\nold_state = warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');\nP_x = polyfit(state_vector_T, state_vector_pos(1,:), polyorder);\nP_y = polyfit(state_vector_T, state_vector_pos(2,:), polyorder);\nP_z = polyfit(state_vector_T, state_vector_pos(3,:), polyorder);\n% We don't use these since they are derivable from the position polynomial\n% state_vector_vel = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/orbit','velocity');\n% state_vector_acc = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/orbit','acceleration');\n% P_vx = polyfit(state_vector_T, state_vector_vel(1,:), polyorder);\n% P_vy = polyfit(state_vector_T, state_vector_vel(2,:), polyorder);\n% P_vz = polyfit(state_vector_T, state_vector_vel(3,:), polyorder);\n% P_ax = polyfit(state_vector_T, state_vector_acc(1,:), polyorder);\n% P_ay = polyfit(state_vector_T, state_vector_acc(2,:), polyorder);\n% P_az = polyfit(state_vector_T, state_vector_acc(3,:), polyorder);\nwarning(old_state);\n% Store position polynomial\noutput_meta.Position.ARPPoly.X = P_x(end:-1:1).';\noutput_meta.Position.ARPPoly.Y = P_y(end:-1:1).';\noutput_meta.Position.ARPPoly.Z = P_z(end:-1:1).';\n\n%% SCPCOA\n% This should almost always be left looking for NISAR.\noutput_meta.SCPCOA.SideOfTrack=get_hdf_data(HDF5_fid,'/science/LSAR/identification','lookDirection');\noutput_meta.SCPCOA.SideOfTrack=upper(output_meta.SCPCOA.SideOfTrack(1));\n% Most subfields added below in \"per band\" section.\n\n%% ImageFormation\noutput_meta.ImageFormation.RcvChanProc=struct('NumChanProc',1,'PRFScaleFactor',1);\noutput_meta.ImageFormation.ImageFormAlgo='RMA';\noutput_meta.ImageFormation.TStartProc=0;\noutput_meta.ImageFormation.TEndProc=output_meta.Timeline.CollectDuration;\noutput_meta.ImageFormation.STBeamComp='NO';\noutput_meta.ImageFormation.ImageBeamComp='SV';\noutput_meta.ImageFormation.AzAutofocus='NO';\noutput_meta.ImageFormation.RgAutofocus='NO';\n% More subfields added below in \"per band\" section\noutput_meta.RMA.RMAlgoType='OMEGA_K';\noutput_meta.RMA.ImageType='INCA';\noutput_meta.RMA.INCA.DopCentroidCOA=true;\n% Get reference time\nref_time = get_ref_time(HDF5_fid,'/science/LSAR/SLC/swaths/zeroDopplerTime');\n% Times in SICD are with respect to time from start of collect.\nref_time_offset = round((ref_time-collectStart)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n collectStartFrac; % Handle fractional seconds\nzd_t = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/swaths','zeroDopplerTime') + ref_time_offset;\nss_az_s = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/swaths','zeroDopplerTimeSpacing');\nif output_meta.SCPCOA.SideOfTrack(1)=='L'\n zd_t = zd_t(end:-1:1);\n ss_az_s = -ss_az_s;\nend\ngrid_r = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/processingInformation/parameters','slantRange');\n% Get reference time\nref_time = get_ref_time(HDF5_fid,'/science/LSAR/SLC/metadata/processingInformation/parameters/zeroDopplerTime');\n% Times in SICD are with respect to time from start of collect.\nref_time_offset = round((ref_time-collectStart)*SECONDS_IN_A_DAY) + ... % Convert from days to secs\n collectStartFrac; % Handle fractional seconds\ngrid_zd = get_hdf_data(HDF5_fid,'/science/LSAR/SLC/metadata/processingInformation/parameters','zeroDopplerTime') + ref_time_offset;\n\n%% Radiometric\ncal_fields = {'beta0','gamma0','sigma0'};\nsicd_cal_fields = {'BetaZeroSFPoly','GammaZeroSFPoly','SigmaZeroSFPoly'};\ncal_data = cell(3,1); % beta0, gamma0, sigma0\nfor i = 1:numel(cal_fields)\n cal_data{i} = get_hdf_data(HDF5_fid, '/science/LSAR/SLC/metadata/calibrationInformation/geometry',cal_fields{i}).';\n % Get fill value\n gid = H5G.open(HDF5_fid, '/science/LSAR/SLC/metadata/calibrationInformation/geometry/');\n data = H5D.open(gid, cal_fields{i});\n H5G.close(gid);\n attribute = H5A.open(data, '_FillValue');\n H5D.close(data);\n fill = H5A.read(attribute,H5A.get_type(attribute));\n H5A.close(attribute);\n fill = cast(fill,class(cal_data{i}));\n cal_data{i}(cal_data{i}==fill) = NaN;\n if any(diff(cal_data{i}(isfinite(cal_data{i}))))\n % We expect NISAR to be constant beta, although simulated data from\n % UAVSAR is constant sigma\n if strcmp(cal_fields{i},'beta0')\n warning('META2SICD_NISAR:unexpectedCalibrationValues',...\n 'Beta-0 values expected to be constant.');\n end\n else\n output_meta.Radiometric.(sicd_cal_fields{i}) = mean(cal_data{i}(:),'omitnan');\n end\n % We will derive non-constant Radiometric fields from the constant one\n % (likely beta).\nend\noutput_meta.Radiometric.NoiseLevel.NoiseLevelType = 'ABSOLUTE';\n\n%% Process fields specific to each polarimetric band\nband_independent_meta=output_meta; % Values that are consistent across all bands\ngrouped_meta=cell(sum(cellfun(@(x) size(x,1),pols)),1);\nmeta_i=0;\nfor i=1:numel(freqs)\n freq_meta = band_independent_meta;\n\n freq_id=H5G.open(HDF5_fid,['/science/LSAR/SLC/swaths/frequency' freqs(i)]);\n \n %% Grid\n row_ss_id=H5D.open(freq_id,'slantRangeSpacing');\n freq_meta.Grid.Row.SS=H5D.read(row_ss_id);\n H5D.close(row_ss_id);\n % Col.SS is derived after DRateSFPoly below, rather than used from this\n % given field, so that SICD metadata can be internally consistent:\n % col_ss_id=H5D.open(freq_id,'sceneCenterAlongTrackSpacing');\n % output_meta.Grid.Col.SS=H5D.read(col_ss_id);\n % H5D.close(col_ss_id);\n proc_bw_id=H5D.open(freq_id,'processedRangeBandwidth');\n freq_meta.Grid.Row.ImpRespBW=2*H5D.read(proc_bw_id)/SPEED_OF_LIGHT;\n H5D.close(proc_bw_id);\n freq_meta.Grid.Row.DeltaK1=-freq_meta.Grid.Row.ImpRespBW/2;\n freq_meta.Grid.Row.DeltaK2=-freq_meta.Grid.Row.DeltaK1;\n\n %% Timeline\n prf_id=H5D.open(freq_id,'nominalAcquisitionPRF');\n prf=H5D.read(prf_id);\n H5D.close(prf_id);\n freq_meta.Timeline.IPP.Set.IPPEnd=uint32(floor(prf*band_independent_meta.Timeline.CollectDuration));\n freq_meta.Timeline.IPP.Set.IPPPoly=[0; prf];\n freq_meta.Timeline.IPP.Set.TEnd=freq_meta.Timeline.CollectDuration;\n\n %% RadarCollection\n fc_id=H5D.open(freq_id,'acquiredCenterFrequency');\n fc=H5D.read(fc_id);\n H5D.close(fc_id);\n bw_id=H5D.open(freq_id,'acquiredRangeBandwidth');\n bw=H5D.read(bw_id);\n H5D.close(bw_id);\n freq_meta.RadarCollection.TxFrequency.Min=fc-(bw/2);\n freq_meta.RadarCollection.TxFrequency.Max=fc+(bw/2);\n % No waveform parameters provided\n for j=1:size(pols{i},1)\n freq_meta.RadarCollection.RcvChannels.ChanParameters(j).TxRcvPolarization=[pols{i}(j,1) ':' pols{i}(j,2)];\n end\n tx_pol = unique(pols{i}(:,1));\n if numel(tx_pol)==1\n freq_meta.RadarCollection.TxPolarization = tx_pol;\n else\n freq_meta.RadarCollection.TxPolarization = 'SEQUENCE';\n for j = 1:numel(tx_pol)\n freq_meta.RadarCollection.TxSequence.TxStep(j).WFIndex = j;\n freq_meta.RadarCollection.TxSequence.TxStep(j).TxPolarization = tx_pol(j);\n end\n end\n\n %% ImageFormation\n fc_id=H5D.open(freq_id,'processedCenterFrequency');\n fc=H5D.read(fc_id);\n H5D.close(fc_id);\n bw_id=H5D.open(freq_id,'processedRangeBandwidth');\n bw=H5D.read(bw_id);\n H5D.close(bw_id);\n freq_meta.ImageFormation.TxFrequencyProc.MinProc=fc-(bw/2);\n freq_meta.ImageFormation.TxFrequencyProc.MaxProc=fc+(bw/2);\n range_id=H5D.open(freq_id,'slantRange');\n r_ca_sampled=H5D.read(range_id);\n H5D.close(range_id);\n % TODO: processedAzimuthBandwidth acknowledged by JPL to be wrong in\n % simulated datasets.\n dop_bw_id=H5D.open(freq_id,'processedAzimuthBandwidth');\n dop_bw=H5D.read(dop_bw_id);\n H5D.close(dop_bw_id);\n H5G.close(freq_id);\n dopcentroid_sampled = get_hdf_data(HDF5_fid,[...\n '/science/LSAR/SLC/metadata/processingInformation/parameters/frequency' freqs(i)], ...\n 'dopplerCentroid').';\n doprate_sampled = get_hdf_data(HDF5_fid,[...\n '/science/LSAR/SLC/metadata/processingInformation/parameters/frequency' freqs(i)], ...\n 'azimuthFMRate').';\n\n for j=1:size(pols{i},1)\n pol_meta=freq_meta;\n\n %% ImageData\n dset_id=H5D.open(HDF5_fid,['/science/LSAR/SLC/swaths/frequency' freqs(i) '/' pols{i}(j,:)]);\n dspace_id=H5D.get_space(dset_id);\n [~, datasize] = H5S.get_simple_extent_dims(dspace_id);\n pol_meta.ImageData.NumCols=uint32(datasize(1));\n pol_meta.ImageData.NumRows=uint32(datasize(2));\n pol_meta.ImageData.FullImage=pol_meta.ImageData;\n if (H5T.get_class(H5D.get_type(dset_id)) == H5ML.get_constant_value('H5T_COMPOUND'))\n if (H5T.get_member_class(H5D.get_type(dset_id),0) == H5ML.get_constant_value('H5T_FLOAT'))\n % Could be either 16- or 32-bit float. Either way it will\n % cast to this SICD type.\n pol_meta.ImageData.PixelType='RE32F_IM32F';\n elseif (H5T.get_member_class(H5D.get_type(dset_id),0) == H5ML.get_constant_value('H5T_INTEGER')) && ...\n H5T.get_size(H5D.get_type(dset_id)) == 4\n pol_meta.ImageData.PixelType='RE16I_IM16I';\n else\n error('META2SICD_NISAR:unrecognizedDataType','Must be 16- or 32-bit complex float.');\n end\n else\n error('META2SICD_NISAR:unrecognizedDataType','Must be 16- or 32-bit complex float.');\n end\n H5S.close(dspace_id);\n H5D.close(dset_id);\n pol_meta.ImageData.FirstRow=uint32(0); pol_meta.ImageData.FirstCol=uint32(0);\n % SCP pick is arbitrary. Just pick something near center.\n pol_meta.ImageData.SCPPixel.Col = floor(datasize(1)/2);\n pol_meta.ImageData.SCPPixel.Row = floor(datasize(2)/2);\n\n %% ImageFormation\n pol_meta.ImageFormation.RcvChanProc.ChanIndex=meta_i;\n pol_meta.ImageFormation.TxRcvPolarizationProc=...\n freq_meta.RadarCollection.RcvChannels.ChanParameters(j).TxRcvPolarization;\n \n %% RMA\n pol_meta.RMA.INCA.R_CA_SCP = r_ca_sampled(pol_meta.ImageData.SCPPixel.Row+1);\n scp_ca_time = zd_t(pol_meta.ImageData.SCPPixel.Col+1);\n % Compute DRateSFPoly\n % For the purposes of the DRateSFPoly computation, we ignore any\n % changes in velocity or doppler rate over the azimuth dimension.\n pos_coefs = [P_x(:) P_y(:) P_z(:)];\n % Velocity is derivate of position.\n vel_coefs=pos_coefs(1:end-1,:).*repmat(((size(pos_coefs,1)-1):-1:1)',[1 3]);\n vel_x = polyval(vel_coefs(:,1), scp_ca_time);\n vel_y = polyval(vel_coefs(:,2), scp_ca_time);\n vel_z = polyval(vel_coefs(:,3), scp_ca_time);\n vm_ca_sq = vel_x.^2 + vel_y.^2 + vel_z.^2; % Magnitude of the velocity squared\n r_ca_poly = [pol_meta.RMA.INCA.R_CA_SCP; 1]; % Polynomial representing range as a function of range distance from SCP\n [~, min_ind] = min(abs(grid_zd - scp_ca_time)); % Closest Doppler rate polynomial to SCP\n coords_rg_m = grid_r - pol_meta.RMA.INCA.R_CA_SCP;\n % TODO: Is it the NISAR convention to give the absolute value of\n % Doppler rate? (It should be negative.) Sample datasets appear\n % this way.\n old_warning_state=warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');\n dop_rate_poly=polyfit(coords_rg_m, -doprate_sampled(min_ind,:).', 4);\n warning(old_warning_state);\n % figure; plot(r,dop_rate(:,min_ind),r,polyval(dop_rate_poly,r)); % Show closeness of fit\n dop_rate_poly = dop_rate_poly(end:-1:1);\n pol_meta.RMA.INCA.DRateSFPoly = - conv(dop_rate_poly,r_ca_poly) * ... % Multiplication of two polynomials is just a convolution of their coefficients\n SPEED_OF_LIGHT / (2 * fc * vm_ca_sq(1)); % Assumes a SGN of -1\n % Fields dependent on Doppler rate\n pol_meta.Grid.Col.SS = sqrt(vm_ca_sq(1)) * abs(ss_az_s) * pol_meta.RMA.INCA.DRateSFPoly(1,1);\n % Should be close to this:\n % colss_id=H5D.open(freq_id,'sceneCenterAlongTrackSpacing');\n % pol_meta.Grid.Col.SS = H5D.read(colss_id)\n % H5D.close(colss_id);\n pol_meta.Grid.Col.ImpRespBW = ... % Convert to azimuth spatial bandwidth (cycles per meter)\n min(dop_bw*abs(ss_az_s),1)/pol_meta.Grid.Col.SS; % Can't have more bandwidth in data than sample spacing\n pol_meta.RMA.INCA.TimeCAPoly = [scp_ca_time; ... % With respect to start of collect\n ss_az_s/pol_meta.Grid.Col.SS]; % Convert zero doppler spacing from sec/pixels to sec/meters\n % TimeCOAPoly/DopCentroidPoly/DeltaKCOAPoly\n POLY_ORDER = 3; % Order of polynomial which we want to compute\n coords_az_m = (grid_zd - scp_ca_time) * pol_meta.Grid.Col.SS / ss_az_s;\n timeca_sampled = repmat(grid_zd,[1 numel(grid_r)]);\n % TimeCOAPoly=TimeCA+(DopCentroid/dop_rate)\n timecoa_sampled = timeca_sampled+(dopcentroid_sampled./doprate_sampled);\n pol_meta.RMA.INCA.DopCentroidPoly=polyfit2d(dopcentroid_sampled, coords_az_m, coords_rg_m, POLY_ORDER);\n pol_meta.Grid.Col.DeltaKCOAPoly=...\n pol_meta.RMA.INCA.DopCentroidPoly*ss_az_s/pol_meta.Grid.Col.SS;\n pol_meta.Grid.TimeCOAPoly=polyfit2d(timecoa_sampled, coords_az_m, coords_rg_m, POLY_ORDER);\n\n %% Radiometric\n % In the simulated data (from UAVSAR), we expect these noise values\n % to be only valid for the same incidence angle as NISAR (small\n % part of swath). We also expect the values to be in dB, not\n % linear.\n nesz = get_hdf_data(HDF5_fid,['/science/LSAR/SLC/metadata/calibrationInformation/frequency' freqs(i) '/' pols{i}(j,:)], 'nes0').';\n sigma0sf = cal_data{3};\n noise_samples = nesz - (10*log10(sigma0sf));\n pol_meta.Radiometric.NoiseLevel.NoisePoly = ...\n polyfit2d(noise_samples, coords_az_m, coords_rg_m, POLY_ORDER);\n % The conversion between radiometric fields in simulated data don't\n % seem to be valid, so we will skip using the non-constant terms\n % for now. But this is how one would do it:\n % Fit polynomial only to valid data in image\n % az_bounds1 = [-double(pol_meta.ImageData.SCPPixel.Col) ...\n % double(pol_meta.ImageData.NumCols - pol_meta.ImageData.SCPPixel.Col - 1)] *...\n % pol_meta.Grid.Col.SS;\n % rg_bounds1 = [-double(pol_meta.ImageData.SCPPixel.Row) ...\n % double(pol_meta.ImageData.NumRows - pol_meta.ImageData.SCPPixel.Row - 1)] *...\n % pol_meta.Grid.Row.SS;\n % for k = 1:numel(cal_fields)\n % % Only fit valid values\n % rg_val = all(isfinite(cal_data{k}),1)&coords_rg_m'>rg_bounds1(1)&coords_rg_m' 0\n% 2nd column: change set probability\n% 3rd column: table to be modified (1:bus, 2:gen, 3:branch) or\n% 4: bus area changes, apply to all gens/buses/branches in\n% a given area; 5: gen table area changes apply to all\n% generators in a given area; or 6: branch area changes apply\n% to all branches connected to buses in a given area.\n% 4th column: row of table to be modified (if 3rd col is 1-3),\n% or area number for overall changes (if 3rd column is 4-6).\n% 5th column: column of table to be modified. It is best to use the\n% named column index defined in the corresponding idx_bus,\n% idx_gen, idx_branch or idx_cost M-files in MATPOWER.\n% 6th column: type of change: 1: absolute (replace)\n% 2: relative (multiply by factor)\n% 3: additive (add to value)\n% 7th column: new value or multiplicative or additive factor\n%\n% Examples:\n%\n% chgtab = [ ...\n% 1 0.1 CT_TGEN 2 GEN_STATUS CT_REP 0;\n% 2 0.05 CT_TGEN 3 PMAX CT_REP 100;\n% 3 0.2 CT_TBRCH 2 BR_STATUS CT_REP 0;\n% 4 0.1 CT_TAREALOAD 2 CT_LOAD_ALL_P CT_REL 1.1;\n% ];\n%\n% Description of each change set:\n% 1. Turn off generator 2, 10% probability.\n% 2. Set generator 3's max output to 100 MW, 5% probability.\n% 3. Take branch 2 out of service, 20% probability.\n% 4. Scale all loads in area 2 (real & reactive, fixed and dispatchable)\n% by a factor of 1.1, 10% probability.\n%\n% See IDX_CT.\n\n% To do:\n% - check for valid row number\n\n% MATPOWER\n% Copyright (c) 2000-2016, Power Systems Engineering Research Center (PSERC)\n% by Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Nacional de Colombia\n% and Ray Zimmerman, PSERC Cornell\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% define named indices into data matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n[CT_LABEL, CT_PROB, CT_TABLE, CT_TBUS, CT_TGEN, CT_TBRCH, CT_TAREABUS, ...\n CT_TAREAGEN, CT_TAREABRCH, CT_ROW, CT_COL, CT_CHGTYPE, CT_REP, ...\n CT_REL, CT_ADD, CT_NEWVAL, CT_TLOAD, CT_TAREALOAD, CT_LOAD_ALL_PQ, ...\n CT_LOAD_FIX_PQ, CT_LOAD_DIS_PQ, CT_LOAD_ALL_P, CT_LOAD_FIX_P, ...\n CT_LOAD_DIS_P, CT_TGENCOST, CT_TAREAGENCOST, CT_MODCOST_F, ...\n CT_MODCOST_X] = idx_ct;\n\n%% find the change set to be applied\nif numel(label) > 1\n error('apply_changes: LABEL must be a scalar');\nend\nkk = find(label == chgtab(:, CT_LABEL));\nif isempty(kk)\n error('apply_changes: LABEL %d not found in CHGTAB', label);\nend\n\n%% create map of external bus numbers to bus indices\ni2e = mpc.bus(:, BUS_I);\ne2i = sparse(max(i2e), 1);\ne2i(i2e) = (1:size(mpc.bus, 1))';\n\nfor c = 1:length(kk)\n %% extract data for individual change to be applied\n %% (c-th change in specified change set)\n change = num2cell(chgtab(kk(c), :));\n [tbl, row, col, typ, val] = ...\n deal(change{[CT_TABLE, CT_ROW, CT_COL, CT_CHGTYPE, CT_NEWVAL]});\n\n %% apply the change\n if tbl == CT_TBUS %% modify bus table\n if ~any(col == [PD QD GS BS VMAX VMIN])\n error('apply_changes: modification to column %d of bus table not supported', col);\n end\n if row == 0 %% modify all rows\n if typ == CT_REP %% replace\n mpc.bus(:, col) = val * ones(size(mpc.bus, 1), 1);\n elseif typ == CT_REL %% scale\n mpc.bus(:, col) = val * mpc.bus(:, col);\n elseif typ == CT_ADD %% shift\n mpc.bus(:, col) = val + mpc.bus(:, col);\n else\n error('apply_changes: unsupported modification type %d for bus table', typ);\n end\n else %% modify single row\n if typ == CT_REP %% replace\n mpc.bus(row, col) = val;\n elseif typ == CT_REL %% scale\n mpc.bus(row, col) = val * mpc.bus(row, col);\n elseif typ == CT_ADD %% shift\n mpc.bus(row, col) = val + mpc.bus(row, col); \n else\n error('apply_changes: unsupported modification type %d for bus table', typ);\n end\n end\n elseif tbl == CT_TBRCH %% modify branch table\n if ~any(col == ...\n [BR_R BR_X BR_B RATE_A RATE_B RATE_C TAP SHIFT BR_STATUS ANGMIN ANGMAX])\n error('apply_changes: modification to column %d of branch table not supported', col);\n end\n if row == 0 %% modify all rows\n if typ == CT_REP %% replace\n mpc.branch(:, col) = val * ones(size(mpc.branch, 1), 1);\n elseif typ == CT_REL %% scale\n mpc.branch(:, col) = val * mpc.branch(:, col);\n elseif typ == CT_ADD %% shift\n mpc.branch(:, col) = val + mpc.branch(:, col);\n else\n error('apply_changes: unsupported modification type %d for branch table', typ);\n end\n else %% modify single row\n if typ == CT_REP %% replace\n mpc.branch(row, col) = val;\n elseif typ == CT_REL %% scale\n mpc.branch(row, col) = val * mpc.branch(row, col);\n elseif typ == CT_ADD %% shift\n mpc.branch(row, col) = val + mpc.branch(row, col);\n else\n error('apply_changes: unsupported modification type %d for branch table', typ);\n end\n end\n elseif tbl == CT_TGEN %% modify gen table\n if ~any(col == ...\n [QMAX QMIN GEN_STATUS PMAX PMIN PC1 PC2 QC1MIN QC1MAX QC2MIN QC2MAX ...\n RAMP_AGC RAMP_10 RAMP_30 RAMP_Q APF])\n error('apply_changes: modification to column %d of gen table not supported', col);\n end\n if row == 0 %% modify all rows\n if typ == CT_REP %% replace\n mpc.gen(:, col) = val * ones(size(mpc.gen, 1), 1);\n elseif typ == CT_REL %% scale\n mpc.gen(:, col) = val * mpc.gen(:, col);\n elseif typ == CT_ADD %% shift\n mpc.gen(:, col) = val + mpc.gen(:, col);\n else\n error('apply_changes: unsupported modification type %d for gen table', typ);\n end\n else %% modify single row\n if typ == CT_REP %% replace\n mpc.gen(row, col) = val;\n elseif typ == CT_REL %% scale\n mpc.gen(row, col) = val * mpc.gen(row, col);\n elseif typ == CT_ADD %% shift\n mpc.gen(row, col) = val + mpc.gen(row, col);\n else\n error('apply_changes: unsupported modification type %d for gen table', typ);\n end\n end\n elseif tbl == CT_TGENCOST %% modify gencost table\n if col == CT_MODCOST_F || col == CT_MODCOST_X %% use modcost to scale/shift cost\n if typ == CT_REL\n if col == CT_MODCOST_F\n modcost_type = 'SCALE_F';\n else %% col == CT_MODCOST_X\n modcost_type = 'SCALE_X';\n end\n elseif typ == CT_ADD\n if col == CT_MODCOST_F\n modcost_type = 'SHIFT_F';\n else %% col == CT_MODCOST_X\n modcost_type = 'SHIFT_X';\n end\n else\n error('apply_changes: unsupported modification type %d for gencost table CT_MODCOST_F/X modification', typ);\n end\n if row == 0\n mpc.gencost = modcost(mpc.gencost, val, modcost_type);\n else\n mpc.gencost(row, :) = modcost(mpc.gencost(row, :), val, modcost_type);\n end\n else %% normal individual column mod\n if col < 1 || fix(col) ~= col %% needs to be positive integer\n error('apply_changes: modification to column %d of gencost table not supported', col);\n end\n if row == 0 %% modify all rows\n if typ == CT_REP %% replace\n mpc.gencost(:, col) = val * ones(size(mpc.gencost, 1), 1);\n elseif typ == CT_REL %% scale\n mpc.gencost(:, col) = val * mpc.gencost(:, col);\n elseif typ == CT_ADD %% shift\n mpc.gencost(:, col) = val + mpc.gencost(:, col);\n else\n error('apply_changes: unsupported modification type %d for gencost table', typ);\n end\n else %% modify single row\n if typ == CT_REP %% replace\n mpc.gencost(row, col) = val;\n elseif typ == CT_REL %% scale\n mpc.gencost(row, col) = val * mpc.gencost(row, col);\n elseif typ == CT_ADD %% shift\n mpc.gencost(row, col) = val + mpc.gencost(row, col);\n else\n error('apply_changes: unsupported modification type %d for gencost table', typ);\n end\n end\n end\n elseif tbl == CT_TAREABUS %% area-wide mod to bus table\n if ~any(col == [PD QD GS BS VMAX VMIN])\n error('apply_changes: area-wide modification to column %d of bus table not supported', col);\n end\n jj = find(mpc.bus(:, BUS_AREA) == row);\n if typ == CT_REP %% replace\n mpc.bus(jj, col) = val * ones(size(jj));\n elseif typ == CT_REL %% scale\n mpc.bus(jj, col) = val * mpc.bus(jj, col);\n elseif typ == CT_ADD %% shift\n mpc.bus(jj, col) = val + mpc.bus(jj, col);\n else\n error('apply_changes: unsupported area-wide modification type %d for bus table', typ);\n end\n elseif tbl == CT_TAREABRCH %% area-wide mod to branch table\n if ~any(col == ...\n [BR_R BR_X BR_B RATE_A RATE_B RATE_C TAP SHIFT BR_STATUS ANGMIN ANGMAX])\n error('apply_changes: area-wide modification to column %d of branch table not supported', col);\n end\n jj = find((row == mpc.bus(e2i(mpc.branch(:, F_BUS)), BUS_AREA)) | ...\n (row == mpc.bus(e2i(mpc.branch(:, T_BUS)), BUS_AREA)) );\n if typ == CT_REP %% replace\n mpc.branch(jj, col) = val * ones(size(jj));\n elseif typ == CT_REL %% scale\n mpc.branch(jj, col) = val * mpc.branch(jj, col);\n elseif typ == CT_ADD %% shift\n mpc.branch(jj, col) = val + mpc.branch(jj, col);\n else\n error('apply_changes: unsupported area-wide modification type %d for branch table', typ);\n end\n elseif tbl == CT_TAREAGEN %% area-wide mod to gen table\n if ~any(col == ...\n [QMAX QMIN GEN_STATUS PMAX PMIN PC1 PC2 QC1MIN QC1MAX QC2MIN QC2MAX ...\n RAMP_AGC RAMP_10 RAMP_30 RAMP_Q APF])\n error('apply_changes: area-wide modification to column %d of gen table not supported', col);\n end\n jj = find(row == mpc.bus(e2i(mpc.gen(:, GEN_BUS)), BUS_AREA));\n if typ == CT_REP %% replace\n mpc.gen(jj, col) = val * ones(size(jj));\n elseif typ == CT_REL %% scale\n mpc.gen(jj, col) = val * mpc.gen(jj, col);\n elseif typ == CT_ADD %% shift\n mpc.gen(jj, col) = val + mpc.gen(jj, col);\n else\n error('apply_changes: unsupported area-wide modification type %d for gen table', typ);\n end\n elseif tbl == CT_TAREAGENCOST %% area-wide mod to gencost table\n jj = find(row == mpc.bus(e2i(mpc.gen(:, GEN_BUS)), BUS_AREA));\n if col == CT_MODCOST_F || col == CT_MODCOST_X\n if typ == CT_REL\n if col == CT_MODCOST_F\n modcost_type = 'SCALE_F';\n else %% col == CT_MODCOST_X\n modcost_type = 'SCALE_X';\n end\n elseif typ == CT_ADD\n if col == CT_MODCOST_F\n modcost_type = 'SHIFT_F';\n else %% col == CT_MODCOST_X\n modcost_type = 'SHIFT_X';\n end\n else\n error('apply_changes: unsupported area-wide modification type %d for gencost table CT_MODCOST_F/X modification', typ);\n end\n mpc.gencost(jj, :) = modcost(mpc.gencost(jj, :), val, modcost_type);\n else\n if col < 1 || fix(col) ~= col %% needs to be positive integer\n error('apply_changes: area-wide modification to column %d of gencost table not supported', col);\n end\n if typ == CT_REP %% replace\n mpc.gencost(jj, col) = val * ones(size(jj));\n elseif typ == CT_REL %% scale\n mpc.gencost(jj, col) = val * mpc.gencost(jj, col);\n elseif typ == CT_ADD %% shift\n mpc.gencost(jj, col) = val + mpc.gencost(jj, col);\n else\n error('apply_changes: unsupported area-wide modification type %d for gencost table', typ);\n end\n end\n elseif tbl == CT_TLOAD || tbl == CT_TAREALOAD %% modify loads\n if ~any(abs(col) == (CT_LOAD_ALL_PQ:CT_LOAD_DIS_P))\n error('apply_changes: column=%d for load modifications is not supported', col);\n end\n switch abs(col)\n case {CT_LOAD_ALL_PQ, CT_LOAD_FIX_PQ, CT_LOAD_DIS_PQ}\n opt.pq = 'PQ';\n case {CT_LOAD_ALL_P, CT_LOAD_FIX_P, CT_LOAD_DIS_P}\n opt.pq = 'P';\n end\n switch abs(col)\n case {CT_LOAD_ALL_PQ, CT_LOAD_ALL_P}\n opt.which = 'BOTH';\n case {CT_LOAD_FIX_PQ, CT_LOAD_FIX_P}\n opt.which = 'FIXED';\n case {CT_LOAD_DIS_PQ, CT_LOAD_DIS_P}\n opt.which = 'DISPATCHABLE';\n end\n\n %% define load_zone\n if tbl == CT_TLOAD\n nb = size(mpc.bus, 1);\n if row == 0 %% modify load at all buses\n load_zone = ones(nb, 1);\n else %% modify load at single bus\n load_zone = zeros(nb, 1);\n load_zone(row) = 1;\n end\n elseif tbl == CT_TAREALOAD\n load_zone = double(mpc.bus(:, BUS_AREA) == row); %% modify load in single area\n end\n\n switch typ\n case CT_REP %% replace\n opt.scale = 'QUANTITY';\n dmd = val;\n case CT_REL %% scale\n opt.scale = 'FACTOR';\n dmd = val;\n case CT_ADD %% shift\n opt.scale = 'QUANTITY';\n old_val = total_load(mpc, load_zone);\n dmd = old_val + val;\n otherwise\n error('apply_changes: unsupported modification type %d for loads', typ);\n end\n %% scale the loads ...\n if col < 0 %% ... including dispatchable load costs\n [mpc.bus, mpc.gen, mpc.gencost] = scale_load(dmd, mpc.bus, mpc.gen, load_zone, opt, mpc.gencost);\n else %% ... not including dispatchable load costs\n [mpc.bus, mpc.gen] = scale_load(dmd, mpc.bus, mpc.gen, load_zone, opt);\n end\n else\n error('apply_changes: CHGTAB attempts to modify unsupported table type')\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/apply_changes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782568056728001, "lm_q2_score": 0.05108273623474417, "lm_q1q2_score": 0.014214119009706113}} {"text": "%KWAVEGRID Class definition for k-Wave grid structure.\n%\n% DESCRIPTION:\n% See makeGrid for function arguments.\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 22nd July 2010\n% last update - 29th August 2012\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\nclassdef kWaveGrid \n \n % define the private properties (these parameters are stored and cannot\n % be altered by the user after the object is created, but they can be\n % accessed) \n properties (GetAccess = public, SetAccess = private)\n \n % grid dimensions in grid points\n Nx = 0;\n Ny = 0;\n Nz = 0;\n \n % grid point spacing in metres\n \tdx = 0;\n dy = 0;\n dz = 0;\n \n % wavenumber grids\n kx_vec = 0;\n ky_vec = 0;\n kz_vec = 0; \n k = 0;\n \n % maximum supported spatial frequency\n kx_max = 0;\n ky_max = 0;\n kz_max = 0;\n k_max = 0;\n \n % number of dimensions\n dim = 0; \n \n % non-uniform grid\n nonuniform = false;\n \n end\n \n % define the public properties (these parameters are stored and can be\n % both accessed and altered by the user after the object is created)\n properties (GetAccess = public, SetAccess = public)\n \n % time array\n t_array = 'auto';\n \n end \n \n % define the dependent properties (these parameters are not stored but\n % re-computed each time they are needed)\n properties(Dependent = true, GetAccess = public, SetAccess = private)\n \n % 3D plaid Cartesian spatial grids\n x;\n y;\n z;\n \n % 3D plaid wavenumber grids\n kx;\n ky;\n kz;\n \n % 1D spatial grids\n x_vec;\n y_vec;\n z_vec; \n \n % Cartesian grid size\n x_size;\n z_size;\n y_size;\n \n % time step and number of time points\n dt;\n Nt;\n \n % total number of grid points\n total_grid_points;\n \n end\n \n % define the staggered grid properties (these can be accessed but not\n % altered by the user after the object is created, the parameters are\n % also hidden from view)\n properties (Hidden = true, GetAccess = public, SetAccess = private)\n \n % position vectors for the staggered grid points in [0, 1]\n xn_vec = 0;\n yn_vec = 0;\n zn_vec = 0;\n xn_vec_sgx = 0;\n yn_vec_sgy = 0;\n zn_vec_sgz = 0; \n \n % transformation gradients between uniform and staggered grids\n dxudxn = 0;\n dyudyn = 0;\n dzudzn = 0;\n dxudxn_sgx = 0;\n dyudyn_sgy = 0;\n dzudzn_sgz = 0; \n \n end\n \n % define the dependent staggered grid properties (these parameters are\n % not stored but re-computed each time they are needed, the parameters\n % are also hidden from view)\n properties(Dependent = true, Hidden = true, GetAccess = public, SetAccess = private)\n \n % 3D plaid non-uniform spatial grids\n xn;\n yn;\n zn;\n \n end\n \n % constructor function\n methods\n function kgrid = kWaveGrid(varargin)\n \n % assign the input values to the grid object\n switch nargin\n \n case 6\n \n % 3D uniform grid\n kgrid.Nx = varargin{1};\n kgrid.dx = varargin{2};\n kgrid.Ny = varargin{3};\n kgrid.dy = varargin{4};\n kgrid.Nz = varargin{5};\n kgrid.dz = varargin{6};\n\n % set the number of dimensions\n kgrid.dim = 3;\n \n case 4\n \n % 2D uniform grid\n kgrid.Nx = varargin{1};\n kgrid.dx = varargin{2};\n kgrid.Ny = varargin{3};\n kgrid.dy = varargin{4};\n\n % set the number of dimensions\n kgrid.dim = 2;\n \n case 2\n \n % 1D uniform grid\n kgrid.Nx = varargin{1};\n kgrid.dx = varargin{2};\n \n % set the number of dimensions\n kgrid.dim = 1;\n \n otherwise\n error('Incorrect number of input arguments');\n end\n \n switch kgrid.dim\n case 1\n \n % assign the grid parameters for the x spatial direction\n kgrid.kx_vec = kgrid.makeDim(kgrid.Nx, kgrid.dx);\n \n % define the scalar wavenumber based on the wavenumber components\n kgrid.k = abs(kgrid.kx_vec);\n \n % define maximum supported frequency\n kgrid.kx_max = max(abs(kgrid.kx_vec(:)));\n kgrid.k_max = kgrid.kx_max;\n \n case 2\n \n % assign the grid parameters for the x and z spatial directions\n kgrid.kx_vec = kgrid.makeDim(kgrid.Nx, kgrid.dx);\n kgrid.ky_vec = kgrid.makeDim(kgrid.Ny, kgrid.dy);\n\n % define the wavenumber based on the wavenumber components\n % (using bsxfun saves memory by avoiding ndgrid)\n kgrid.k = zeros(kgrid.Nx, kgrid.Ny);\n kgrid.k = bsxfun(@plus, (reshape(kgrid.kx_vec, [], 1, 1).^2), kgrid.k);\n kgrid.k = bsxfun(@plus, (reshape(kgrid.ky_vec, 1, [], 1).^2), kgrid.k);\n kgrid.k = sqrt(kgrid.k);\n \n % define maximum supported frequency\n kgrid.kx_max = max(abs(kgrid.kx_vec(:)));\n kgrid.ky_max = max(abs(kgrid.ky_vec(:)));\n kgrid.k_max = min([kgrid.kx_max, kgrid.ky_max]); \n \n case 3\n \n % assign the grid parameters for the x ,y and z spatial directions\n kgrid.kx_vec = kgrid.makeDim(kgrid.Nx, kgrid.dx);\n kgrid.ky_vec = kgrid.makeDim(kgrid.Ny, kgrid.dy);\n kgrid.kz_vec = kgrid.makeDim(kgrid.Nz, kgrid.dz);\n\n % define the wavenumber based on the wavenumber components\n % (using bsxfun saves memory by avoiding ndgrid)\n kgrid.k = zeros(kgrid.Nx, kgrid.Ny, kgrid.Nz);\n kgrid.k = bsxfun(@plus, (reshape(kgrid.kx_vec, [], 1, 1).^2), kgrid.k);\n kgrid.k = bsxfun(@plus, (reshape(kgrid.ky_vec, 1, [], 1).^2), kgrid.k);\n kgrid.k = bsxfun(@plus, (reshape(kgrid.kz_vec, 1, 1, []).^2), kgrid.k);\n kgrid.k = sqrt(kgrid.k); \n \n % define maximum supported frequency\n kgrid.kx_max = max(abs(kgrid.kx_vec(:)));\n kgrid.ky_max = max(abs(kgrid.ky_vec(:)));\n kgrid.kz_max = max(abs(kgrid.kz_vec(:)));\n kgrid.k_max = min([kgrid.kx_max, kgrid.ky_max, kgrid.kz_max]); \n \n end\n end\n end\n \n % functions for dependent variables that only run when queried\n methods\n \n function x = get.x(obj)\n % calculate x based on kx\n x = obj.x_size*obj.kx*obj.dx/(2*pi);\n end\n \n function y = get.y(obj)\n % calculate y based on ky\n y = obj.y_size*obj.ky*obj.dy/(2*pi);\n end\n \n function z = get.z(obj)\n % calculate z based on kz\n z = obj.z_size*obj.kz*obj.dz/(2*pi);\n end \n \n function kx = get.kx(obj)\n % duplicate kx vector\n switch obj.dim\n case 1\n kx = obj.kx_vec;\n case 2\n kx = repmat(obj.kx_vec, [1, obj.Ny]);\n case 3\n kx = repmat(obj.kx_vec, [1, obj.Ny, obj.Nz]);\n end\n end\n \n function ky = get.ky(obj)\n % rotate ky vector to y direction then duplicate\n switch obj.dim\n case 1\n ky = 0;\n case 2\n ky = repmat(obj.ky_vec.', [obj.Nx, 1]);\n case 3\n ky = repmat(obj.ky_vec.', [obj.Nx, 1, obj.Nz]);\n end\n end \n \n function kz = get.kz(obj)\n % permute kz vector to z direction then duplicate\n switch obj.dim\n case 1\n kz = 0;\n case 2\n kz = 0;\n case 3\n kz = repmat(permute(obj.kz_vec, [2 3 1]), [obj.Nx, obj.Ny, 1]);\n end\n end\n \n function x_vec = get.x_vec(obj)\n % calculate x_vec based on kx_vec\n x_vec = obj.x_size*obj.kx_vec*obj.dx/(2*pi);\n end\n \n function y_vec = get.y_vec(obj)\n % calculate y_vec based on ky_vec\n y_vec = obj.y_size*obj.ky_vec*obj.dy/(2*pi);\n end\n \n function z_vec = get.z_vec(obj)\n % calculate z_vec based on kz_vec\n z_vec = obj.z_size*obj.kz_vec*obj.dz/(2*pi);\n end \n \n function x_size = get.x_size(obj)\n % calculate x_size based on Nx and dx\n x_size = obj.Nx*obj.dx;\n end\n \n function y_size = get.y_size(obj)\n % calculate y_size based on Ny and dy\n y_size = obj.Ny*obj.dy;\n end\n \n function z_size = get.z_size(obj)\n % calculate z_size based on Nz and dz\n z_size = obj.Nz*obj.dz;\n end \n \n function dt = get.dt(obj)\n % extract dt from the time array\n if strcmp(obj.t_array, 'auto')\n dt = 'auto';\n else\n dt = obj.t_array(2) - obj.t_array(1);\n end\n end \n \n function Nt = get.Nt(obj)\n % extract dt from the time array\n if strcmp(obj.t_array, 'auto')\n Nt = 'auto';\n else\n Nt = length(obj.t_array);\n end\n end \n \n function N = get.total_grid_points(obj)\n % calculate the total number of points in the grid\n switch obj.dim\n case 1\n N = obj.Nx;\n case 2\n N = obj.Nx*obj.Ny;\n case 3\n N = obj.Nx*obj.Ny*obj.Nz;\n end\n end\n end\n \n % functions that can only be accessed by class members\n methods (Access = 'protected', Static = true) \n \n % subfunction to create the grid parameters for a single spatial direction\n function kx_vec = makeDim(Nx, dx)\n\n % define the discretisation of the spatial dimension such that there is\n % always a DC component\n if rem(Nx, 2) == 0\n % grid dimension has an even number of points\n nx = ((-Nx/2:Nx/2-1)/Nx).';\n else\n % grid dimension has an odd number of points\n nx = ((-(Nx-1)/2:(Nx-1)/2)/Nx).';\n end\n\n % force middle value to be zero in case 1/Nx is a recurring\n % number and the series doesn't give exactly zero\n nx(floor(Nx/2) + 1) = 0;\n \n % define the wavenumber vector components\n kx_vec = (2*pi/dx).*nx; \n end\n \n end\n \n % functions for non-uniform grids\n methods\n \n % subfunction to return plaid xn matrix\n function xn = get.xn(obj)\n if obj.nonuniform\n % duplicate xn vector\n switch obj.dim\n case 1\n xn = obj.xn_vec;\n case 2\n xn = repmat(obj.xn_vec, [1, obj.Ny]);\n case 3\n xn = repmat(obj.xn_vec, [1, obj.Ny, obj.Nz]);\n end\n else\n xn = 0;\n end\n end\n \n % subfunction to return plaid yn matrix\n function yn = get.yn(obj)\n if obj.nonuniform \n % rotate yn vector to y direction then duplicate\n switch obj.dim\n case 1\n yn = 0;\n case 2\n yn = repmat(obj.yn_vec.', [obj.Nx, 1]);\n case 3\n yn = repmat(obj.yn_vec.', [obj.Nx, 1, obj.Nz]);\n end\n else\n yn = 0;\n end\n end \n \n % subfunction to return plaid zn matrix\n function zn = get.zn(obj)\n if obj.nonuniform \n % permute kz vector to z direction then duplicate\n switch obj.dim\n case 1\n zn = 0;\n case 2\n zn = 0;\n case 3\n zn = repmat(permute(obj.zn_vec, [2 3 1]), [obj.Nx, obj.Ny, 1]);\n end\n else\n zn = 0;\n end\n end \n \n % subfunction to set non-uniform grid parameters in specified\n % dimension\n function obj = setNUGrid(obj, dim, xn_vec, dxudxn, xn_vec_sgx, dxudxn_sgx)\n \n % check the dimension to set the nonuniform grid is appropriate\n if dim > obj.dim\n error(['Cannot set nonuniform parameters for dimension ' num2str(dim) ' of ' num2str(obj.dim) '-dimensional grid']);\n end\n \n % force non-uniform grid spacing to be column vectors, and the\n % gradients to be in the correct direction for use with bsxfun\n switch dim\n case 1\n obj.xn_vec = reshape(xn_vec, [], 1);\n obj.dxudxn = reshape(dxudxn, [], 1);\n obj.xn_vec_sgx = reshape(xn_vec_sgx, [], 1);\n obj.dxudxn_sgx = reshape(dxudxn_sgx, [], 1);\n case 2\n obj.yn_vec = reshape(xn_vec, [], 1);\n obj.dyudyn = reshape(dxudxn, 1, []);\n obj.yn_vec_sgy = reshape(xn_vec_sgx, [], 1);\n obj.dyudyn_sgy = reshape(dxudxn_sgx, 1, []);\n case 3\n obj.zn_vec = reshape(xn_vec, [], 1);\n obj.dzudzn = reshape(dxudxn, 1, 1, []);\n obj.zn_vec_sgz = reshape(xn_vec_sgx, [], 1);\n obj.dzdzn_sgz = reshape(dxudxn_sgx, 1, 1, []);\n end\n \n % set non-uniform flag\n obj.nonuniform = true;\n \n end\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/kWaveGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.03258974500092467, "lm_q1q2_score": 0.014143345273086822}} {"text": "function [group_metrics individual_metrics values gwcsf gwcsfmean gwcsf_l2norm] = qc_metrics_second_level(obj, varargin)\n%\n% Quality metrics for a 2nd-level analysis (set of images from different subjects)\n% The goal is to obtain measures that are simple and scale invariant, and\n% so can be compared across image datasets\n%\n% :Usage:\n% ::\n%\n% [group_metrics individual_metrics values gwcsf gwcsfmean gwcsf_l2norm] = qc_metrics_second_level(list inputs here, [optional inputs])\n%\n% For objects: Type methods(object_name) for a list of special commands\n% Type help object_name.method_name for help on specific\n% methods.\n%\n% ..\n% Author and copyright information:\n%\n% Copyright (C) 2016 Tor Wager\n%\n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n% ..\n%\n% :Inputs:\n%\n% **obj:**\n% An fmri_data object with a set of images\n% Intended to be individual-participant beta or contrast images from\n% first-level analyses.\n%\n% :Optional Inputs:\n% **noverbose:**\n% Turn off text display reporting of warnings and metrics\n%\n% **param2:**\n% description of param2\n%\n% :Outputs:\n%\n% **group_metrics:**\n% Quality metrics indicating potential problems, as described below\n%\n% **individual_metrics:**\n% Individual image-level values for quality metrics\n% These can be used to identify individuals with problematic images\n% or as covariates in analyses.\n%\n% **values:**\n% Grand Mean Gray, white, and CSF values - one number per metric per\n% image\n%\n% **gwcsf:**\n% Gray, white, and CSF image objects with values for all images\n%\n% **gwcsfmean:**\n% Gray, white, and CSF image objects mean values across images\n%\n% **gwcsfl2norm:**\n% L2 norm of Gray, white, and CSF components for each image\n%\n% :References:\n% None.\n%\n%\n% --------------------------------------------------------------------------------\n% Coverage: Percentage of standard MNI gray-matter mask with non-zero/non-nan values\n% NOT IMPLEMENTED YET\n% Range: [0 100], 100 is good (full coverage). Low values indicate\n% dropout due to artifacts or space mis-match\n%\n% Template match: Dice coefficient (point-biserial r?) with standard MNI gray-matter mask\n% NOT IMPLEMENTED YET\n% Range: [0 100], 100 is good (full coverage). Low values indicate\n% dropout due to artifacts or space mis-match\n%\n% Bright-edge bias: \"brightedge\"\n% NOT IMPLEMENTED YET\n% High inter-image variability around edge of brain\n% median absolute deviation (MAD) in brain edge-mask / MAD in center\n% of brain.\n% Range: [0 Inf], 1 is good (homogeneous). High values may indicate\n% head movement artifacts\n%\n% Signal in ventricles: \"csf_to_gm_signal_ratio\"\n% In most contrast maps, there should be less non-zero signal in the CSF space (e.g., ventricles)\n% than in gray matter. This measures the ratio of mean absolute signal in CSF / GM.\n% Range: [0 Inf]. Values < 1 indicate low ventricle signal, which is good.\n% Higher values are worse.\n% Apply to: Individual or group. Contrast images (differences across conditions) for a series of individual participants\n%\n% Effect size in ventricles: \"global_d_ventricles\"\n% d = Mean / standard error (STD) of whole-ventricle average signal\n% Indicates a shift towards global activation or deactivation of the\n% ventricles in the group.\n% Range: [-Inf Inf], farther from zero is bad.\n% Apply to: Group. Contrast images (differences across conditions) for group of participants\n%\n% Significant global activation of ventricles: \"global_logp_ventricles\"\n% -log(p-value) in ventricle global mean across subjects, divided by -log(0.05)\n% Any value > 1 indicates a significant global activation in the\n% ventricles.\n% Range: [0 Inf], higher is worse. Values > 1 are bad.\n% Apply to: Group. Contrast images (differences across conditions) for group of participants\n%\n% Effect size in white matter: \"global_d_wm\"\n% d = Mean / standard error (STD) of whole-WM average signal\n% Indicates a shift towards global activation or deactivation of the\n% WM in the group. This is not completely redundant with CSF, because\n% some artifacts can affect one tissue compartment but not another.\n% WM values are, however, more likely to be influenced by true\n% signal.\n% Range: [-Inf Inf], farther from zero is bad.\n%\n% Significant global activation of WM: \"global_logp_wm\"\n% -log(p-value) in WM global mean across subjects, divided by -log(0.05)\n% Any value > 1 indicates a significant global activation in WM.\n% Range: [0 Inf], higher is worse. Values > 1 are bad.\n%\n% Non-spatially specific signal contamination: \"r2_explained_by_csf\"\n% Variance in individual differences in whole-gray-matter activity\n% Range: [-1 1], usually [0 1]. Farther from zero is bad.\n% Apply to: Group. Contrast images (differences across conditions) for group of participants\n%\n% Scale inhomogeneity across participants: \"csf_scale_inhom\"\n% Assumption: Subjects should be on the same scale (e.g., if you look\n% at histograms of contrast images for each subject). We assume that\n% the signal in gray matter may vary for meaningful reasons, but the\n% scale of the signal in CSF (and maybe WM?) should be similar across\n% participants.\n% Measure: The coefficient of variation of the L1-norm across CSF voxels for each participant.\n% The L1-norm is a measure of scale (across voxels, for each observation/image)\n% that is more robust than the variance.\n% High variability in these individual scale parameters is a sign of inhomogeneity.\n% The coefficient of variation is the standard dev. of this whole-image scale value divided by its mean.\n% This is a scale-invariant measure of inhomogeneity across images.\n% It also avoids the instability that occurs by dividing by values that may\n% be near zero, such as the mean.\n% Range: [0 Inf]. Lower is better.\n% Apply to: Group. Condition images (betas) for group of participants\n%\n% Scale inhomogeneity across participants in gray matter: \"gm_scale_inhom\"\n% The coefficient of variation of the L1-norm across GM voxels for each participant.\n% The L1-norm is a measure of scale (across voxels, for each observation/image)\n% that is more robust than the variance.\n% High variability in these individual scale parameters is a sign of inhomogeneity.\n% The coefficient of variation is the standard dev. of this whole-image scale value divided by its mean.\n% This is a scale-invariant measure of inhomogeneity across images.\n% It also avoids the instability that occurs by dividing by values that may\n% be near zero, such as the mean.\n% Range: [0 Inf]. Lower is better, but GM values may also be influenced by large differences in true signal.\n%\n% :Examples:\n% ::\n% % Load sample images\n% obj = load_image_set('emotionreg');\n%\n% % Run QC metrics\n% [group_metrics individual_metrics] = qc_metrics_second_level(obj);\n%\n% % Plot histograms of gray, white, CSF values\n% hist_han = histogram(obj, 'byimage', 'by_tissue_type');\n%\n% :See also:\n% - extract_gray_white_csf, histogram\n%\n\n\n% ..\n% DEFAULTS AND INPUTS\n% ..\n\n\ndoverbose = 1;\n\n% optional inputs with default values\nfor i = 1:length(varargin)\n if ischar(varargin{i})\n switch varargin{i}\n \n case 'noverbose', doverbose = 0;\n \n otherwise, warning(['Unknown input string option:' varargin{i}]);\n end\n end\nend\n\n\n[values, components, gwcsf, gwcsf_l2norm] = extract_gray_white_csf(obj);\n\n% Get mean signal in each tissue compartment for visualization, if desired\n% -------------------------------------------------------------------------\ngwcsfmean = mean(gwcsf{1}); \ngwcsfmean = replace_empty(gwcsfmean); \nfor i = 2:3\n m = mean(gwcsf{i}); \n m = replace_empty(m);\n gwcsfmean.dat(:, i) = m.dat;\nend\n\n\n% -------------------------------------------------------------------------\n% METRICS\n% -------------------------------------------------------------------------\n\n% Get coverage of gray-matter a priori mask space (do we have data in all vox?)\n% -------------------------------------------------------------------------\n\nobjmasked = apply_mask(obj, mean(gwcsf{1}));\n\nwh = isnan(objmasked.dat) | objmasked.dat == 0;\nindividual_metrics.gray_matter_coverage = sum(~wh) ./ size(objmasked.dat, 1);\ngroup_metrics.mean_gray_matter_coverage = mean(individual_metrics.gray_matter_coverage);\n\n\n%brightedge\n% NOT DONE YET\n\n% Global activation/deactivation in CSF and white matter\n% -------------------------------------------------------------------------\n\nindividual_metrics.global_ventricle_values = mean(values(:, 3));\n\ngroup_metrics.global_d_ventricles = mean(values(:, 3)) ./ std(values(:, 3));\n\nn = size(values, 1);\nt = group_metrics.global_d_ventricles .* sqrt(n); % t-value\np = 2 .* min(tcdf(t, n - 1), tcdf(-t, n - 1)); % two-tailed\n\ngroup_metrics.global_logp_ventricles = -log(p) ./ (-log(.05));\n\n% --- wm ---\nindividual_metrics.global_white_matter_values = mean(values(:, 2));\n\ngroup_metrics.global_d_wm = mean(values(:, 2)) ./ std(values(:, 2));\n\nt = group_metrics.global_d_wm .* sqrt(n); % t-value\np = 2 .* min(tcdf(t, n - 1), tcdf(-t, n - 1)); % two-tailed\n\ngroup_metrics.global_logp_wm = -log(p) ./ (-log(.05));\n\n\n% Gray-matter signal explained by CSF\n% -------------------------------------------------------------------------\n\n[r, p] = corr(values(:, 1), values(:, 3));\n\ngroup_metrics.gm_explained_by_csf_pvalue = p;\ngroup_metrics.r2_explained_by_csf = r .^ 2;\n\n% Gray-matter scale (l2 norm) explained by CSF scale\n% -------------------------------------------------------------------------\n\n[r, p] = corr(gwcsf_l2norm(:, 1), gwcsf_l2norm(:, 3));\n\ngroup_metrics.gm_l2norm_explained_by_csf_pvalue = p;\ngroup_metrics.r2_l2norm_explained_by_csf = r .^ 2;\n\n% Signal in ventricles\n% -------------------------------------------------------------------------\n\ncsfsignal = mean(abs(gwcsf{3}.dat)) ./ mean(abs(gwcsf{1}.dat));\ngroup_metrics.csf_to_gm_signal_ratio = mean(csfsignal);\nindividual_metrics.csf_to_gm_signal_ratio = csfsignal;\n\n% Scale Inhomogeneity\n% -------------------------------------------------------------------------\n\nL1norm = sum(abs(gwcsf{1}.dat))';\ngroup_metrics.gm_scale_inhom = std(L1norm) ./ mean(L1norm);\nindividual_metrics.gm_L1norm = L1norm;\n\nL1norm = sum(abs(gwcsf{3}.dat))';\ngroup_metrics.csf_scale_inhom = std(L1norm) ./ mean(L1norm);\nindividual_metrics.csf_L1norm = L1norm;\n\n% Add warnings\n% -------------------------------------------------------------------------\ngroup_metrics.warnings = {};\n\nif any(individual_metrics.gray_matter_coverage < .9)\n group_metrics.warnings{end + 1} = sprintf('Warning: Incomplete coverage, missing gray-matter data in some images.\\n - Mean coverage is d = %3.2f%%\\n', group_metrics.mean_gray_matter_coverage .* 100);\nend\n\nif group_metrics.global_logp_ventricles > 1\n group_metrics.warnings{end + 1} = sprintf('Warning: Significant global activation in CSF space/ventricles.\\n - Effect size is d = %3.2f\\n', group_metrics.global_d_ventricles);\nend\n\nif group_metrics.global_logp_wm > 1\n group_metrics.warnings{end + 1} = sprintf('Warning: Significant global activation in white matter.\\n - Effect size is d = %3.2f\\n', group_metrics.global_d_wm);\nend\n\nif group_metrics.gm_explained_by_csf_pvalue < .05\n group_metrics.warnings{end + 1} = sprintf('Warning: Gray-matter individual diffs significantly correlated with mean CSF value.\\n - Var explained (r^2) = %3.2f%%', group_metrics.r2_explained_by_csf .* 100);\nend\n\nif group_metrics.gm_l2norm_explained_by_csf_pvalue < .05\n group_metrics.warnings{end + 1} = sprintf('Warning: Gray-matter scale (L2 norm) significantly correlated with mean CSF L2 norm.\\n - Var explained (r^2) = %3.2f%%', group_metrics.r2_l2norm_explained_by_csf .* 100);\nend\n\nif group_metrics.csf_to_gm_signal_ratio > 1\n group_metrics.warnings{end + 1} = sprintf('Warning: Strong non-zero signal in CSF relative to gray matter.\\n - Ratio is = %3.2f', group_metrics.csf_to_gm_signal_ratio);\nend\n\nif group_metrics.csf_scale_inhom > .3\n group_metrics.warnings{end + 1} = sprintf('Warning: High individual diffs in image scaling estimated from CSF.\\n - CV is = %3.2f', group_metrics.csf_scale_inhom);\nend\n\n\n\n% Display warnings\n% -------------------------------------------------------------------------\n\nif doverbose\n \n disp(' ');\n disp(group_metrics)\n disp(char(group_metrics.warnings{:}))\n \nend\n\nend % function\n\n\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/@image_vector/qc_metrics_second_level.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.03210070914766809, "lm_q1q2_score": 0.013931112777148901}} {"text": "function [names, ids] = getMultiSpeciesModelId(modelJoint, nameTagsModels, nameTagHost, metTagRe, rxnTagRe, compCom, compHost)\n% Get names and IDs for metabolites and exchange reactions in the [u] and [b] space\n%\n% USAGE:\n%\n% [names, ids] = getMultiSpeciesModelId(modelJoint, nameTagsModels, nameTagHost, metTagRe, rxnTagRe, compCom, compHost)\n%\n% INPUTS:\n% modelJoint: COBRA multi-organism model\n% nameTagsModels: cell array of tags for species to identify the respective\n% reactions and metabolites from `modelJoint.rxns` and `.mets`\n%\n% OPTIONAL INPUTS:\n% nameTagHost: string of tag for the host model if exist. Input [] if no host is present\n% metTagRe: a regular expression to identify the tag in nameTagsModels from `modelJoint.mets`.\n% Use '%s' for the tag in `nameTagsModels` for each species.\n% Default '^%s', the beginning of the string. In this case, if the tag for species 1 is\n% 'SP1', then mets with id 'SP1glc-D[e]' will be identified as belonging to species 1.\n% E.g., 'met[compartment_SP1]' where 'SP1' is the tag for species 1, input '\\[[^_]+_%s\\]$'.\n% rxnTagRe: a regular expression to idenify the tag in `nameTagsModels` from `modelJoint.rxns`.\n% Default '^%s', the beginning of the string\n% compCom: compartment Id for the community exchange compartment. Default 'u'\n% compHost: compartment Id for the exchange compartment specific to the host. Default 'b'\n%\n% OUTPUTS:\n% names: structure of reaction/metabolite name (.rxns/.mets) with the following fields:\n%\n% * spAbbr - species abbreviation (= `nameTags`). Host put at the end\n% * EXcom - #met[u]-by-1 cell. Exchange reactions for community metabolites `met[u]`\n% * EXhost - #met[b]-by-1 cell. Exchange reactions for host-specific exchange metabolites `met[b]`\n% * EXsp - #met[u]-by-#species cell. `EXsp(i,j)` is the species-community exchange reactions\n% for the i-th met[u] and the j-th species\n% * Mcom - #met[u]-by-1 cell. All community metabolites `met[u]`\n% * Mhost - #met[u]-by-1 cell. Host-specific exchange metabolites `met[b]`\n% * Msp - #met[u]-by-#species cell. `Msp(i,j)` is the metabolite in `met[e]` of the `j`-th species\n% participating in reaction `EXsp(i,j)`\n% * rxnSps - #rxns-by-1 cell. `rxnSps(i)` would be `spAbbr(j)` if the `i`-th reaction belongs to the `j`-th species\n% * metSps - #mets-by-1 cell. `metSps(i)` would be `spAbbr(j)` if the i-th metabolite belongs to the `j`-th species\n%\n% ids: structure of reaction/metabolite index with the same fields as names except without `spAbbr`\n\nif nargin < 7 || isempty(compHost)\n compHost = 'b';\nend\nif nargin < 6 || isempty(compCom)\n compCom = 'u';\nend\ncompHost = regexprep(compHost, '^\\[(.*)\\]$', '$1');\ncompCom = regexprep(compCom, '^\\[(.*)\\]$', '$1');\n% regular expression for identifying species\nif nargin < 5 || isempty(rxnTagRe)\n rxnTagRe = '^%s';\nend\nif nargin < 4 || isempty(metTagRe)\n metTagRe = '^%s';\nend\nmetCompartment = getCompartment(modelJoint.mets);\n% mets in the common exchange space ([u]) or the biomass (use biomass[c] to be consistent with createMultipleSpeciesModel)\nmetCom = strcmp(metCompartment, compCom) | strcmp(modelJoint.mets, 'biomass[c]');\n% mets in exchange space accessible only by the host ([b])\nmetHost = strcmp(metCompartment, compHost);\nhostExist = any(metHost) && nargin >= 3 && ~isempty(nameTagHost); % use && to avoid error if nameTagHost not given\nif hostExist && iscell(nameTagHost)\n nameTagHost = nameTagHost{1};\nend\nif ischar(nameTagsModels)\n nameTagsModels = {nameTagsModels};\nend\n% get the regular expression of identifiers for species-specific mets and rxns\nnSp = numel(nameTagsModels);\n[metTagReSp, rxnTagReSp] = deal(repmat({''}, nSp + hostExist, 1));\nfor jSp = 1:nSp\n metTagReSp{jSp} = strrep(metTagRe, '%s', nameTagsModels{jSp});\n rxnTagReSp{jSp} = strrep(rxnTagRe, '%s', nameTagsModels{jSp});\nend\nmetHost = find(metHost);\nif hostExist\n % add regular expression for host\n metTagReSp{nSp + 1} = strrep(metTagRe, '%s', nameTagHost);\n rxnTagReSp{nSp + 1} = strrep(rxnTagRe, '%s', nameTagHost);\n % try to sort metHost to have the same order as metCom by comparing met names\n metHostName = regexprep(modelJoint.mets(metHost), metTagReSp{nSp + 1}, '');\n metHostName = strrep(metHostName, ['[' compHost ']'], '');\n metComName = strrep(modelJoint.mets(metCom), ['[' compCom ']'], '');\n [yn, id] = ismember(metComName, metHostName);\n if all(yn) && numel(union(metComName, metHostName)) == numel(metComName)\n % one-to-one mapping exists. Reorder\n metHost = metHost(id);\n end\nend\n\n% get system exchange rxns\nrxnEX = find(sum(modelJoint.S ~= 0, 1) == 1);\n% exchange rxns for mets in [u], in the same order as metCom\n[EXcom, ~] = find(modelJoint.S(metCom, rxnEX)');\nEXcom = rxnEX(EXcom);\n% exchange rxns for mets in [b], in the same order as metHost\n[EXhost, ~] = find(modelJoint.S(metHost, rxnEX)');\nEXhost = rxnEX(EXhost);\n\n% Get the species number for each met and rxn. 0 for those in [u]\n[nMets, nRxns] = size(modelJoint.S);\nmetSps = zeros(nMets, 1);\nrxnSps = zeros(nRxns, 1);\nfor jSp = 1:nSp\n metSps(~cellfun(@isempty, regexp(modelJoint.mets, metTagReSp{jSp}, 'once')) & ~metCom) = jSp;\n rxnSps(~cellfun(@isempty, regexp(modelJoint.rxns, rxnTagReSp{jSp}, 'once'))) = jSp;\n % metSps(strncmp(modelJoint.mets, nameTagsModels{j}, numel(nameTagsModels{j})) & ~metCom) = j;\n % rxnSps(strncmp(modelJoint.rxns, nameTagsModels{j}, numel(nameTagsModels{j}))) = j;\n rxnSps(EXcom) = 0; % in case some mets or exchange rxns in [u] have prefix equal to the name tags\n % check if the model is properly compartmentalized.\n if nnz(modelJoint.S(metSps == jSp, rxnSps ~= jSp)) > 0 ...\n || nnz(modelJoint.S(metSps ~= jSp & metSps > 0, rxnSps == jSp)) > 0\n error('The model for species %s is not correctly compartmentalized. Check the name tags.');\n end\nend\nif hostExist\n metSps(~cellfun(@isempty, regexp(modelJoint.mets, metTagReSp{nSp + 1}, 'once')) & ~metCom) = nSp + 1;\n rxnSps(~cellfun(@isempty, regexp(modelJoint.rxns, rxnTagReSp{nSp + 1}, 'once'))) = nSp + 1;\n % metSps(strncmp(modelJoint.mets, nameTagHost, numel(nameTagHost))) = nSp + 1;\n % rxnSps(strncmp(modelJoint.rxns, nameTagHost, numel(nameTagHost))) = nSp + 1;\nend\n\n% species-community exchange rxns (between members' [e] and [u])\nEXeu = any(modelJoint.S(metCom, :), 1);\nEXeu(EXcom) = false; % exclude system input/output exchange rxns\nEXeu = find(EXeu);\n% EXsp is a #met[u] x #species matrix with (i,j)-entry being the index for exchange reactionn\n% for the i-th met in [u] between [u] and [e] of the j-th organism.\n% Msp similar but the index for the exchanged metabolite in [e] of the organism\n[EXsp, Msp] = deal(zeros(sum(metCom), nSp + hostExist));\nfor j = 1:numel(EXeu)\n mJcom = find(modelJoint.S(:, EXeu(j)) ~= 0 & metCom); % met in [u]\n mJsp = find(modelJoint.S(:, EXeu(j)) ~= 0 & ~metCom); % met in [e]\n EXsp(sum(metCom(1:mJcom)), rxnSps(EXeu(j))) = EXeu(j);\n Msp(sum(metCom(1:mJcom)), rxnSps(EXeu(j))) = mJsp;\nend\n% store all rxns/mets and their ids\nnames.spAbbr = nameTagsModels(:); % species abbreviation\nif hostExist\n names.spAbbr = [names.spAbbr; {nameTagHost}];\nend\nnames.spName = names.spAbbr;\nnames.EXcom = modelJoint.rxns(EXcom);\nids.EXcom = EXcom(:);\nnames.EXhost = modelJoint.rxns(EXhost);\nids.EXhost = EXhost(:);\nnames.EXsp = repmat({''}, size(EXsp, 1), size(EXsp, 2));\nnames.EXsp(EXsp ~= 0) = modelJoint.rxns(EXsp(EXsp ~= 0));\nids.EXsp = EXsp;\nnames.Mcom = modelJoint.mets(metCom);\nids.Mcom = find(metCom);\nnames.Mhost = modelJoint.mets(metHost);\nids.Mhost = metHost;\nnames.Msp = repmat({''}, size(EXsp, 1), size(EXsp, 2));\nnames.Msp(Msp ~= 0) = modelJoint.mets(Msp(Msp ~= 0));\nids.Msp = Msp;\nnames.rxnSps = cell(nRxns, 1);\nnames.rxnSps(rxnSps > 0) = names.spAbbr(rxnSps(rxnSps > 0));\nnames.rxnSps(rxnSps == 0) = {'com'};\nids.rxnSps = rxnSps;\nnames.metSps = cell(nMets, 1);\nnames.metSps(metSps > 0) = names.spAbbr(metSps(metSps > 0));\nnames.metSps(metSps == 0) = {'com'};\nids.metSps = metSps;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/multiSpecies/microbiomeModelingToolbox/pairwiseInteractionModeling/getMultiSpeciesModelId.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.032589741947233596, "lm_q1q2_score": 0.013893710687656375}} {"text": "function xf = compact_fourier_coeff(xf)\n\n% Creates a compact fourier series representation by removing the strict right\n% half plane.\n\nif iscell(xf)\n xf = cellfun(@(xf) xf(:,1:(size(xf,2)+1)/2,:), xf, 'uniformoutput', false);\nelse\n xf = xf(:,1:(size(xf,2)+1)/2,:);\nend", "meta": {"author": "martin-danelljan", "repo": "ECO", "sha": "27e8ae565cd63ec14bafcaad8b5b993bec8f3e69", "save_path": "github-repos/MATLAB/martin-danelljan-ECO", "path": "github-repos/MATLAB/martin-danelljan-ECO/ECO-27e8ae565cd63ec14bafcaad8b5b993bec8f3e69/implementation/fourier_tools/compact_fourier_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.03567854933968074, "lm_q1q2_score": 0.0137331064349279}} {"text": "function [tissueModel, cRes] = pruningModel(model, rankNonCore, coreRxn, zeroExpRxns, precursorMets, eta, tol)\n% Prunes the reactions of the model based on their expression,\n% connectivity to core and confidence score.\n%\n% USAGE:\n% [tissueModel, cRes] = pruningModel(model, rankNonCore, coreRxn, zeroExpRxns, precursorMets, eta, tol)\n%\n% INPUTS:\n% model: input model (COBRA model structure)\n% rankNonCore: order for reaction removal\n%\tcoreRxn: core reactions in model\n%\tzeroExpRxns: reactions with zero expression (i.e., measured zero, not just\n% missing from expression data)\n% precursorMets: list of metabolites involved in the\n% reactions defined in protected reactions\n% eta: tradeoff between removing core and zero-expression\n% reactions (default value: 1/3)\n% tol: minimum flux threshold for \"expressed\" reactions\n% (default 1e-8)\n%\n% OUTPUTS:\n%\ttissueModel: pruned, context-specific model\n%\tcRes: result of model checks (consistency/function)\n% - vs. +: reaction r removed from generic model or\n% not\n% 1 vs. 2: reaction r had zero or non-zero expression evidence\n% -x.y: removal of reaction r corresponded with removal of y (num.) total\n% core reactions\n% +x.1 vs. x.0: precursor production possible after removal of \n% reaction r or not\n% 3: removal of reaction r by itself prevented production of required\n% metabolites (therefore was not removed)\n%\n%\n% Authors: - This script is an adapted version of the implementation from\n% https://github.com/jaeddy/mcadre.\n% - Modified and commented by S. Opdam and A. Richelle,May 2017\n \n tissueModel = model;\n R_P = model.rxns;\n nonCoreRemoved = 0; \n coreRemoved = 0;\n cRes = zeros(3000, 1);\n count = 1;\n \n paramConsistency.epsilon=tol;\n paramConsistency.modeFlag=0;\n paramConsistency.method='fastcc';\n \n while numel(rankNonCore) > 0\n \n display(['Reaction no. ', num2str(count)])\n r = rankNonCore(1);\n display(['Attempting to remove reaction ', r{:}, '...'])\n modelR = removeRxns(tissueModel, r);\n\n % First check precursor production; if this test fails, no need to\n % check model consistency with FVA (time-saving step)\n rStatus = checkModelFunction(modelR, precursorMets);\n\n if rStatus\n\n % Check for inactive reactions after removal of r\n if numel(r)\n % Remove reaction r from the model\n model_rem = removeRxns(tissueModel, r);\n end\n % Check for inactive reactions after removal of r\n try\n [fluxConsistentMetBool,fluxConsistentRxnBool] = findFluxConsistentSubset(model_rem,paramConsistency);\n rStatus_and_not_error = true;\n catch\n rStatus_and_not_error = false;\n end\n else\n rStatus_and_not_error = false;\n end\n \n if rStatus_and_not_error\n inactive_G= [ r; model_rem.rxns(fluxConsistentRxnBool==0)];\n \n inactiveCore = intersect(inactive_G, coreRxn);\n inactiveNonCore = setdiff(inactive_G, inactiveCore);\n\n % Remove reactions with zero expression (previously penalized in\n % rank_reactions) and corresponding inactive core reactions, only if\n % sufficiently more non-core reactions are removed\n if ismember(r, zeroExpRxns)\n \n display('Zero-expression evidence for reaction...')\n\n % Check model function with all inactive reactions removed\n modelTmp = removeRxns(tissueModel, inactive_G);\n tmpStatus = checkModelFunction(modelTmp, precursorMets);\n\n if (numel(inactiveCore) / numel(inactiveNonCore) <= eta) && tmpStatus\n \n R_P = setdiff(R_P, inactive_G);\n tissueModel = removeRxns(tissueModel, inactive_G);\n\n rankNonCore(ismember(rankNonCore, inactive_G)) = [];\n\n nonCoreRemoved = nonCoreRemoved + numel(inactiveNonCore);\n coreRemoved = coreRemoved + numel(inactiveCore);\n num_removed = nonCoreRemoved + coreRemoved;\n \n display('Removed all inactive reactions')\n\n % result = -1.x indicates that reaction r had zero\n % expression evidence and was removed along with any\n % consequently inactivated reactions; x indicates the number of\n % core reactions removed\n if numel(inactiveCore) > 100\n removed_C_indicator = numel(inactiveCore) / 100;\n else\n removed_C_indicator = numel(inactiveCore) / 10;\n end\n result = -1 - removed_C_indicator;\n \n else\n % Note: no reactions (core or otherwise) are actually\n % removed in this step, but it is necessary to update the\n % total number of removed reactions to avoid errors below\n num_removed = nonCoreRemoved + coreRemoved;\n rankNonCore(1) = [];\n\n display('No reactions removed')\n\n % result = 1.x indicates that no reactions were removed\n % because removal of r either led to a ratio of inactivated\n % core vs. non-core reactions above the specified threshold\n % eta (x = 1) or the removal of r and consequently\n % inactivated reactions prevented production of required\n % metabolites (x = 0)\n result = 1 + tmpStatus / 10;\n end\n\n % If reaction has expression evidence, only attempt to remove\n % inactive non-core reactions\n else\n % Check model function with non-core inactive reactions removed\n modelTmp = removeRxns(tissueModel, inactiveNonCore);\n tmpStatus = checkModelFunction(modelTmp, precursorMets);\n\n if numel(inactiveCore) == 0 && tmpStatus\n R_P = setdiff(R_P, inactiveNonCore);\n tissueModel = removeRxns(tissueModel, inactiveNonCore);\n \n rankNonCore(ismember(rankNonCore, inactiveNonCore)) = [];\n \n nonCoreRemoved = nonCoreRemoved + numel(inactiveNonCore);\n num_removed = nonCoreRemoved + coreRemoved;\n display('Removed non-core inactive reactions')\n\n % result = -2 indicates that reaction r had expression.\n % evidence and was removed along with (only) non-core\n % inactivated reactions; x indicates the number of\n % core reactions removed (should be zero!)\n if numel(inactiveCore) > 100\n removed_C_indicator = numel(inactiveCore) / 100;\n else\n removed_C_indicator = numel(inactiveCore) / 10;\n end\n result = -2 - removed_C_indicator;\n \n else\n num_removed = nonCoreRemoved + coreRemoved;\n rankNonCore(1) = [];\n\n display('No reactions removed')\n\n % result = 2.x indicates that no reactions were removed\n % because removal of r either led to inactivated core\n % reactions (x = 1) or the removal of r and consequently\n % inactivated reactions prevented production of required\n % metabolites (x = 0)\n result = 2 + tmpStatus / 10;\n end\n end\n else\n num_removed = nonCoreRemoved + coreRemoved;\n rankNonCore(1) = [];\n\n % result = 3 indicates that no reactions were removed because\n % removal of r by itself prevented production of required\n % metabolites\n result = 3;\n end\n\n cRes(count) = result;\n count = count + 1;\n display(sprintf(['Num. removed: ', num2str(num_removed), ...\n ' (', num2str(coreRemoved), ' core, ', ...\n num2str(nonCoreRemoved), ' non-core); ', ...\n 'Num. remaining: ', num2str(numel(rankNonCore)), '\\n']))\n end\n cRes(count:end) = [];\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/dataIntegration/mCADRE/pruningModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.030214586630765136, "lm_q1q2_score": 0.01369511892698321}} {"text": "function C = mrdivide(A, B)\n%/ CHEBOP right division.\n% C = A/B, where ones of a A is a CHEBOP and is B a scalar is equivalent\n% to A*(1/B), repectively.\n%\n% All other instances returns an error.\n%\n% See also CHEBOP/MTIMES, CHEBOP/RDIVIDE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isnumeric(B) )\n C = mtimes(A, 1./B);\nelse\n error('CHEBOP:MRDIVIDE:NotSupported', '%s/%s is not supported.', ...\n class(A), class(B));\nend\n \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop/mrdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.02800752172154158, "lm_q1q2_score": 0.013675607800016162}} {"text": "function [Gamma,Gammasum,Xi,LL] = hsinference(data,T,hmm,residuals,options,XX,Gamma0,Xi0,cv)\n%\n% inference engine for HMMs.\n%\n% INPUT\n%\n% data Observations - a struct with X (time series) and C (classes)\n% T Number of time points for each time series\n% hmm hmm data structure\n% residuals in case we train on residuals, the value of those.\n% XX optionally, XX, as computed by setxx.m, can be supplied\n% Gamma0 initial Gamma (only used for ehmm model)\n% cv is this called from a CV routine? \n%\n% OUTPUT\n%\n% Gamma Probability of hidden state given the data\n% Gammasum sum of Gamma over t\n% Xi joint Prob. of child and parent states given the data\n% LL Log-likelihood, summed across time points\n%\n% Author: Diego Vidaurre, OHBA, University of Oxford\n\nif length(hmm.train.embeddedlags_batched) > 1\n [Gamma,Gammasum,Xi,LL] = hsinference_batched(T,hmm,residuals,XX);\n return\nend\n \nN = length(T);\nK = hmm.K;\np = hmm.train.lowrank; do_HMM_pca = (p > 0);\nif nargin < 7, Gamma0 = []; end\nif nargin < 8, Xi0 = []; end\nif nargin < 9, cv = 0; end\nif ~isfield(hmm,'train')\n if nargin<5 || isempty(options)\n error('You must specify the field options if hmm.train is missing');\n end\n hmm.train = checkoptions(options,data.X,T,0);\nend\nmixture_model = isfield(hmm.train,'id_mixture') && hmm.train.id_mixture;\nif isfield(hmm.train,'episodic'), episodic = hmm.train.episodic; \nelse, episodic = 0; \nend\nif episodic, rangeK = 1:K+1; else, rangeK = 1:K; end\norder = hmm.train.maxorder;\n\nif iscell(data)\n data = cell2mat(data);\nend\nif ~isstruct(data)\n data = struct('X',data);\n data.C = NaN(size(data.X,1)-order*length(T),K);\nend\n\nif do_HMM_pca\n ndim = size(data.X,2);\nelseif nargin<4 || isempty(residuals)\n ndim = size(data.X,2);\n if ~isfield(hmm.train,'Sind')\n orders = formorders(hmm.train.order,hmm.train.orderoffset,hmm.train.timelag,hmm.train.exptimelag);\n hmm.train.Sind = formindexes(orders,hmm.train.S) == 1;\n if ~hmm.train.zeromean, hmm.train.Sind = [true(1,ndim); hmm.train.Sind]; end\n end\n residuals = getresiduals(data.X,T,hmm.train.S,hmm.train.maxorder,hmm.train.order,...\n hmm.train.orderoffset,hmm.train.timelag,hmm.train.exptimelag,hmm.train.zeromean);\nelse\n ndim = size(residuals,2);\nend\n\nif (episodic && ~isfield(hmm.state(1),'P')) || (~episodic && ~isfield(hmm,'P'))\n hmm = hmmhsinit(hmm);\nend\n\nif nargin<6 || isempty(XX)\n setxx;\nend\n\nif ~hmm.train.acrosstrial_constrained\n Gamma = cell(N,1);\n LL = cell(N,1);\nend\nGammasum = zeros(N,K);\nif ~mixture_model\n Xi = cell(N,1);\nelse\n Xi = [];\nend\n\nsetstateoptions;\n% Cache shared results for use in obslike\nfor k = rangeK\n %hmm.cache = struct();\n hmm.cache.train{k} = train;\n %hmm.cache.order{k} = order;\n %hmm.cache.orders{k} = orders;\n %hmm.cache.Sind{k} = Sind;\n %hmm.cache.S{k} = S;\n if do_HMM_pca\n W = hmm.state(k).W.Mu_W;\n v = hmm.Omega.Gam_rate / hmm.Omega.Gam_shape;\n C = W * W' + v * eye(ndim); \n ldetWishB = 0.5*logdet(C); PsiWish_alphasum = 0;\n elseif k == 1 && strcmp(train.covtype,'uniquediag') || strcmp(train.covtype,'shareddiag') \n ldetWishB = 0;\n PsiWish_alphasum = 0;\n for n = 1:ndim\n if ~regressed(n), continue; end\n ldetWishB = ldetWishB+0.5*log(hmm.Omega.Gam_rate(n));\n PsiWish_alphasum = PsiWish_alphasum+0.5*psi(hmm.Omega.Gam_shape);\n end\n C = hmm.Omega.Gam_shape ./ hmm.Omega.Gam_rate;\n elseif k == 1 && strcmp(train.covtype,'uniquefull') || strcmp(train.covtype,'sharedfull')\n ldetWishB = 0.5*logdet(hmm.Omega.Gam_rate(regressed,regressed));\n PsiWish_alphasum = 0;\n for n = 1:sum(regressed)\n PsiWish_alphasum = PsiWish_alphasum+psi(hmm.Omega.Gam_shape/2+0.5-n/2);\n end\n PsiWish_alphasum=PsiWish_alphasum*0.5;\n C = hmm.Omega.Gam_shape * hmm.Omega.Gam_irate;\n for kk = rangeK\n [hmm.cache.WishTrace{kk},hmm.cache.codevals] = computeWishTrace(hmm,regressed,XX,C,kk);\n end\n elseif strcmp(train.covtype,'diag')\n ldetWishB=0;\n PsiWish_alphasum = 0;\n for n = 1:ndim\n if ~regressed(n), continue; end\n ldetWishB = ldetWishB+0.5*log(hmm.state(k).Omega.Gam_rate(n));\n PsiWish_alphasum = PsiWish_alphasum+0.5*psi(hmm.state(k).Omega.Gam_shape);\n end\n C = hmm.state(k).Omega.Gam_shape ./ hmm.state(k).Omega.Gam_rate;\n if episodic, iC = hmm.state(k).Omega.Gam_rate / hmm.state(k).Omega.Gam_shape; end\n elseif strcmp(train.covtype,'full')\n ldetWishB = 0.5*logdet(hmm.state(k).Omega.Gam_rate(regressed,regressed));\n PsiWish_alphasum = 0;\n for n = 1:sum(regressed)\n PsiWish_alphasum = PsiWish_alphasum+0.5*psi(hmm.state(k).Omega.Gam_shape/2+0.5-n/2);\n end\n C = hmm.state(k).Omega.Gam_shape * hmm.state(k).Omega.Gam_irate;\n if episodic, iC = hmm.state(k).Omega.Gam_rate / hmm.state(k).Omega.Gam_shape; end\n [hmm.cache.WishTrace{k},hmm.cache.codevals] = computeWishTrace(hmm,regressed,XX,C,k);\n end\n % Set up cache\n if ~isfield(train,'distribution') || strcmp(train.distribution,'Gaussian')\n hmm.cache.ldetWishB{k} = ldetWishB;\n hmm.cache.PsiWish_alphasum{k} = PsiWish_alphasum;\n hmm.cache.C{k} = C;\n if episodic && (strcmp(train.covtype,'diag') || strcmp(train.covtype,'full')) \n hmm.cache.iC{k} = iC; \n end\n end\nend\n\nif hmm.train.acrosstrial_constrained % state probabilities are shared across trials\n \n ttrial = T(1)-order; L = zeros(N*ttrial,K);\n if episodic\n [Gammastar,Xistar,LL] = fb_Gamma_inference_ehmm(XX,hmm,residuals,Gamma0,Xi0,T);\n else\n for j = 1:N\n t = (1:ttrial) + (j-1)*ttrial;\n t2 = (1:ttrial+order) + (j-1)*(ttrial+order);\n try\n L(t2,:) = obslike([],hmm,residuals(t,:),XX(t,:),hmm.cache,cv);\n catch\n error('obslike function is giving trouble - Out of precision?')\n end\n end\n L = squeeze(sum(reshape(L,[ttrial+order,N,K]),2));\n if mixture_model\n Gammastar = id_Gamma_inference(L,hmm.Pi,order); Xistar = [];\n else\n [Gammastar,Xistar,LL] = fb_Gamma_inference_sub(L,hmm.P,hmm.Pi,T(1),...\n order,hmm.train.Gamma_constraint);\n end\n end\n Gamma = zeros(ttrial,N,K); \n if episodic\n Xi = zeros(ttrial-1,N,K,4);\n elseif mixture_model\n Xi = zeros(ttrial-1,N,K,K);\n end\n for t = 1:ttrial\n Gamma(t,:,:) = repmat(Gammastar(t,:),N,1); \n if t==ttrial, break; end\n if episodic\n Xi(t,:,:,:) = reshape(repmat(Xistar(t,:,:),N,1),[1,N,K,4]);\n elseif mixture_model\n Xi(t,:,:,:) = reshape(repmat(Xistar(t,:,:),N,1),[1,N,K,K]);\n end\n end\n Gamma = reshape(Gamma,ttrial*N,K);\n if episodic\n Xi = reshape(Xi,(ttrial-1)*N,K,2,2);\n elseif mixture_model\n Xi = reshape(Xi,(ttrial-1)*N,K,K);\n end\n\nelseif hmm.train.useParallel==1 && N>1\n \n % to duplicate this code is really ugly but there doesn't seem to be\n % any other way - more Matlab's fault than mine\n\n % to avoid the entire data being copied entirely in each parfor loop\n XX_copy = cell(N,1); residuals_copy = cell(N,1); \n Gamma0_copy = cell(N,1); Xi0_copy = cell(N,1);\n C_copy = cell(N,1);\n for j = 1:N\n t0 = sum(T(1:j-1)); s0 = t0 - order*(j-1); s02 = t0 - (order+1)*(j-1);\n XX_copy{j} = XX(s0+1:s0+T(j)-order,:);\n if ~do_HMM_pca\n residuals_copy{j} = residuals(s0+1:s0+T(j)-order,:);\n end\n if isfield(data,'C')\n C_copy{j} = data.C(s0+1:s0+T(j)-order,:);\n end\n if ~isempty(Gamma0)\n Gamma0_copy{j} = Gamma0(s0+1:s0+T(j)-order,:);\n end\n if ~isempty(Xi0)\n Xi0_copy{j} = Xi(s02+1:s02+T(j)-order-1,:,:,:);\n end \n end; clear data; clear Gamma0; clear Xi0; clear XX; clear residuals\n \n parfor j = 1:N\n xit = []; llt = [];\n if order>0\n R = [zeros(order,size(residuals_copy{j},2)); residuals_copy{j}];\n if ~isempty(C_copy{j})\n C = [zeros(order,K); C_copy{j}];\n else\n C = NaN(size(R,1),K);\n end\n else\n if do_HMM_pca\n R = XX_copy{j};\n else\n R = residuals_copy{j};\n end\n if ~isempty(C_copy{j})\n C = C_copy{j};\n else\n C = NaN(size(R,1),K);\n end\n end\n % we jump over the fixed parts of the chain\n t = order+1;\n nsegments = computeNoSegments(T(j),t,C);\n xi = cell(nsegments,1); gamma = cell(nsegments,1);\n ll = cell(nsegments,1); ns = 1;\n while t <= T(j)\n if isnan(C(t,1)), no_c = find(~isnan(C(t:T(j),1)));\n else, no_c = find(isnan(C(t:T(j),1)));\n end\n if t>order+1\n if isempty(no_c), slicer = (t-1):T(j); %slice = (t-order-1):T(in);\n else, slicer = (t-1):(no_c(1)+t-2); %slice = (t-order-1):(no_c(1)+t-2);\n end\n else\n if isempty(no_c), slicer = t:T(j); %slice = (t-order):T(in);\n else, slicer = t:(no_c(1)+t-2); %slice = (t-order):(no_c(1)+t-2);\n end\n end\n slicepoints = slicer - order;\n XXt = XX_copy{j}(slicepoints,:); \n if isnan(C(t,1))\n if episodic\n slicer2 = slicer(1:end-1);\n Gamma0t = Gamma0_copy{j}(slicer,:);\n Xi0t = []; if ~isempty(Xi0_copy{j}), Xi0t = Xi0_copy{j}(slicer2,:); end\n [gammat,xit,llt] = fb_Gamma_inference_ehmm(XXt,hmm,R(slicer,:),Gamma0t,Xi0t);\n else\n [gammat,xit,llt] = ...\n fb_Gamma_inference(XXt,hmm,R(slicer,:),slicepoints,hmm.train.Gamma_constraint,cv);\n end\n else\n gammat = zeros(length(slicer),K);\n if t==order+1, gammat(1,:) = C(slicer(1),:); end\n if ~mixture_model\n if episodic, xit = zeros(length(slicer)-1, K, 4);\n else, xit = zeros(length(slicer)-1, K^2);\n end\n end\n for i = 2:length(slicer)\n gammat(i,:) = C(slicer(i),:);\n if ~mixture_model\n if episodic\n for k = 1:K\n gg = [gammat(i-1,k) (1-gammat(i-1,k))];\n xitr = gg' * gg; \n xit(i-1,k,:) = xitr(:)';\n end\n else\n xitr = gammat(i-1,:)' * gammat(i,:) ;\n xit(i-1,:) = xitr(:)';\n end\n end\n end\n end\n if t>order+1\n gammat = gammat(2:end,:);\n end\n if ~mixture_model\n xi{ns} = xit;\n end\n gamma{ns} = gammat;\n ll{ns} = llt;\n ns = ns + 1;\n if isempty(no_c), break;\n else, t = no_c(1)+t-1;\n end\n end\n Gamma{j} = cell2mat(gamma);\n Gammasum(j,:) = sum(Gamma{j});\n LL{j} = cell2mat(ll);\n if ~mixture_model\n if episodic\n Xi{j} = reshape(cell2mat(xi),T(j)-order-1,K,2,2);\n else\n Xi{j} = reshape(cell2mat(xi),T(j)-order-1,K,K);\n end\n end\n end\n \nelse\n \n for j = 1:N % this is exactly the same than the code above but changing parfor by for\n \n t0 = sum(T(1:j-1)); s0 = t0 - order*(j-1); s02 = t0 - (order+1)*(j-1);\n if order > 0\n R = [zeros(order,size(residuals,2)); residuals(s0+1:s0+T(j)-order,:)];\n if isfield(data,'C')\n C = [zeros(order,K); data.C(s0+1:s0+T(j)-order,:)];\n else\n C = NaN(size(R,1),K);\n end\n else %s0==t0\n if do_HMM_pca\n R = XX(s0+1:s0+T(j),:);\n else\n R = residuals(s0+1:s0+T(j),:);\n end\n if isfield(data,'C')\n C = data.C(s0+1:s0+T(j),:);\n else\n C = NaN(size(R,1),K);\n end\n end\n % we jump over the fixed parts of the chain\n t = order+1;\n nsegments = computeNoSegments(T(j),t,C);\n xi = cell(nsegments,1); gamma = cell(nsegments,1);\n ll = cell(nsegments,1); ns = 1; \n while t <= T(j)\n if isnan(C(t,1)), no_c = find(~isnan(C(t:T(j),1)));\n else, no_c = find(isnan(C(t:T(j),1)));\n end\n if t > order+1\n if isempty(no_c), slicer = (t-1):T(j); %slice = (t-order-1):T(in);\n else, slicer = (t-1):(no_c(1)+t-2); %slice = (t-order-1):(no_c(1)+t-2);\n end\n else\n if isempty(no_c), slicer = t:T(j); %slice = (t-order):T(in);\n else, slicer = t:(no_c(1)+t-2); %slice = (t-order):(no_c(1)+t-2);\n end\n end\n slicepoints = slicer + s0 - order;\n XXt = XX(slicepoints,:);\n if isnan(C(t,1))\n if episodic\n slicepoints2 = slicer(1:end-1) + s02 - order;\n Gamma0t = Gamma0(slicepoints,:);\n Xi0t = []; if ~isempty(Xi0), Xi0t = Xi0(slicepoints2,:,:,:); end\n [gammat,xit,llt] = ...\n fb_Gamma_inference_ehmm(XXt,hmm,R(slicer,:),Gamma0t,Xi0t);\n else\n [gammat,xit,llt] = ...\n fb_Gamma_inference(XXt,hmm,R(slicer,:),slicepoints,hmm.train.Gamma_constraint,cv);\n end\n if any(isnan(gammat(:))) % this will never come up - we treat it within fb_Gamma_inference\n error(['State time course inference returned NaN (out of precision). ' ...\n 'There are probably extreme events in the data'])\n end\n else\n gammat = zeros(length(slicer),K);\n llt = NaN(length(slicer),1);\n if t==order+1, gammat(1,:) = C(slicer(1),:); end\n if ~mixture_model\n if episodic, xit = zeros(length(slicer)-1, K, 4);\n else, xit = zeros(length(slicer)-1, K^2);\n end\n end\n for i = 2:length(slicer)\n gammat(i,:) = C(slicer(i),:);\n if ~mixture_model\n if episodic\n for k = 1:K\n gg = [gammat(i-1,k) (1-gammat(i-1,k))];\n xitr = gg' * gg;\n xit(i-1,k,:) = xitr(:)';\n end\n else\n xitr = gammat(i-1,:)' * gammat(i,:) ;\n xit(i-1,:) = xitr(:)';\n end\n end\n end\n end\n if t > order+1\n gammat = gammat(2:end,:);\n end\n if ~mixture_model\n xi{ns} = xit; \n end\n gamma{ns} = gammat;\n ll{ns} = llt;\n ns = ns + 1; \n if isempty(no_c), break;\n else, t = no_c(1)+t-1;\n end\n end\n Gamma{j} = cell2mat(gamma);\n Gammasum(j,:) = sum(Gamma{j});\n LL{j} = cell2mat(ll);\n if ~mixture_model\n if episodic\n Xi{j} = reshape(cell2mat(xi),T(j)-order-1,K,2,2);\n else\n Xi{j} = reshape(cell2mat(xi),T(j)-order-1,K,K);\n end\n end\n end\n \nend\n\n% join\nif ~hmm.train.acrosstrial_constrained\n Gamma = cell2mat(Gamma);\n LL = cell2mat(LL);\n if ~mixture_model, Xi = cell2mat(Xi); end\nend\n\n% orthogonalise = 1; \n% Gamma0 = Gamma; \n% if orthogonalise && hmm.train.tuda\n% T = length(Gamma) / length(T) * ones(length(T),1); \n% Gamma = reshape(Gamma,[T(1) length(T) size(Gamma,2) ]);\n% Y = reshape(residuals(:,end),[T(1) length(T)]);\n% for t = 1:T(1)\n% y = Y(t,:)'; \n% for k = 1:size(Gamma,3)\n% x = Gamma(t,:,k)';\n% b = y \\ x;\n% Gamma(t,:,k) = Gamma(t,:,k) - (y * b)';\n% end\n% end\n% Gamma = reshape(Gamma,[T(1)*length(T) size(Gamma,3) ]);\n% Gamma = rdiv(Gamma,sum(Gamma,2));\n% Gamma = Gamma - min(Gamma(:));\n% Gamma = rdiv(Gamma,sum(Gamma,2));\n% end\n\nend\n\n\nfunction nsegments = computeNoSegments(Tj,t0,C)\nt = t0; nsegments = 0;\nwhile t <= Tj\n if isnan(C(t,1)), no_c = find(~isnan(C(t:Tj,1)));\n else, no_c = find(isnan(C(t:Tj,1)));\n end\n nsegments = nsegments + 1;\n if isempty(no_c), break;\n else, t = no_c(1)+t-1;\n end\nend\nend", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/train/hsinference.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.028007519896090505, "lm_q1q2_score": 0.013566284847657635}} {"text": "function exit_reason = checkSimulationStopConditions(n_cells, Phis_t, cs_bar_t, T_t, param)\n% checkSimulationStopConditions checks if a particular stop condition for the simulation is met\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\nexit_reason = 0;\n% Check stop conditions for each cell\nfor i=1:n_cells\n Phis_pos_cc_t = 1.5*Phis_t{i}(end,1) - 0.5*Phis_t{i}(end,2);\n Phis_neg_cc_t = 1.5*Phis_t{i}(end,end) - 0.5*Phis_t{i}(end,end-1);\n voltage = Phis_pos_cc_t - Phis_neg_cc_t;\n Sout = internalSOCestimate(cs_bar_t,param,i);\n max_layer_temperature = max(T_t{1}(end,:));\n % Break conditions.\n if(voltageparam{i}.CutoverVoltage)\n if param{i}.suppress_status_prints == 0\n fprintf('\\nCell #%d above its Cutover voltage. Stopping ...\\n',i);\n end\n if exit_reason==0\n exit_reason=[];\n end\n exit_reason = [exit_reason;2];\n end\n \n if(Soutparam{i}.CutoverSOC)\n if param{i}.suppress_status_prints == 0\n fprintf('\\nCell #%d above its Cutover SOC. Stopping ...\\n',i);\n end\n if exit_reason==0\n exit_reason=[];\n end\n exit_reason = [exit_reason;4];\n end\n \n if(max_layer_temperature > 0.99*param{i}.Tmax)\n if param{i}.suppress_status_prints == 0\n fprintf('\\nCell #%d above its Maximum Permitted Temperature. Stopping ...\\n',i);\n end\n if exit_reason==0\n exit_reason=[];\n end\n exit_reason = [exit_reason;5];\n end\n \n if(param{i}.enable_csneg_Saturation_limit == 1)\n if(param{i}.SolidPhaseDiffusion~=3)\n max_cs_surface_neg = max(cs_bar_t{i}(end,param{i}.Np+1:end));\n else\n max_cs_surface_neg = max(cs_bar_t{i}(end, (param{i}.Np*param{i}.Nr_p) +1:end));\n end\n \n if (max_cs_surface_neg > param{i}.cs_sat_thresh*param{i}.cs_neg_saturation)\n if param{i}.suppress_status_prints == 0\n fprintf('\\n\\nCell #%d above its safe surface concentration (saturation threshold) Stopping ...\\n\\n',i);\n end\n if exit_reason==0\n exit_reason=[];\n end\n exit_reason = [exit_reason;6];\n end\n end\nend\nend\n", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/simulator_tools/checkSimulationStopConditions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.04885778121892747, "lm_q1q2_score": 0.013442228434156635}} {"text": "function varargout = Echo_cancel(varargin)\n% ECHO_CANCEL MATLAB code for Echo_cancel.fig\n% ECHO_CANCEL, by itself, creates a new ECHO_CANCEL or raises the existing\n% singleton*.\n%\n% H = ECHO_CANCEL returns the handle to a new ECHO_CANCEL or the handle to\n% the existing singleton*.\n%\n% ECHO_CANCEL('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in ECHO_CANCEL.M with the given input arguments.\n%\n% ECHO_CANCEL('Property','Value',...) creates a new ECHO_CANCEL or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before Echo_cancel_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to Echo_cancel_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help Echo_cancel\n\n% Last Modified by GUIDE v2.5 30-Nov-2017 13:55:03\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @Echo_cancel_OpeningFcn, ...\n 'gui_OutputFcn', @Echo_cancel_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before Echo_cancel is made visible.\nfunction Echo_cancel_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to Echo_cancel (see VARARGIN)\n\n% Choose default command line output for Echo_cancel\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\nglobal FilterType;\nFilterType=0;\nglobal std_rls;\nglobal std_lms;\nglobal std_fxlms;\nglobal std_nlms;\nglobal std_ap;\nstd_rls=0;\nstd_lms=0;\nstd_fxlms=0;\nstd_nlms=0;\nstd_ap=0;\nglobal corr_rls;\nglobal corr_lms;\nglobal corr_fxlms;\nglobal corr_nlms;\nglobal corr_ap;\ncorr_rls=0;\ncorr_lms=0;\ncorr_fxlms=0;\ncorr_nlms=0;\ncorr_ap=0;\n\n% UIWAIT makes Echo_cancel wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = Echo_cancel_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal x;\nglobal y;\nglobal res;\nglobal Fs;\nglobal std_rls;\nglobal std_lms;\nglobal std_fxlms;\nglobal std_nlms;\nglobal std_ap;\nglobal corr_rls;\nglobal corr_lms;\nglobal corr_fxlms;\nglobal corr_nlms;\nglobal corr_ap;\n[x,Fs] = audioread('handel.wav');\n[y,Fs]=audioread('handel_echo.wav');\nlength=get(handles.edit1,'String');\nlength=str2num(length);\nff=get(handles.edit2,'String');\nff=str2double(ff);\nmu=get(handles.edit3,'String');\nmu=str2double(mu);\nglobal FilterType;\nswitch FilterType\n case 0\n ha=dsp.RLSFilter('Length',length,'ForgettingFactor',ff);\n [res,e] = ha(x,y);\n std_rls=std(e,1);\n corr_rls=corr(x,res);\n case 1\n ha=dsp.LMSFilter('Length',length,'StepSize',mu);\n [res,e] = ha(x,y);\n std_lms=std(e,1);\n corr_lms=corr(x,res);\n case 2\n ha=dsp.FilteredXLMSFilter('Length',length,'StepSize',mu);\n [res,e] = ha(x,y);\n std_fxlms=std(e,1);\n corr_fxlms=corr(x,res);\n case 3\n ha=dsp.LMSFilter('Length',length,'Method','Normalized LMS','StepSize',mu);\n [res,e] = ha(x,y);\n std_nlms=std(e,1);\n corr_nlms=corr(x,res);\n case 4\n ha=dsp.AffineProjectionFilter('Length',length,'StepSize',mu);\n [res,e] = ha(x,y);\n std_ap=std(e,1);\n corr_ap=corr(x,res);\nend\naudiowrite('handle Regenerated.wav',res,Fs);\nset(handles.pushbutton4,'Enable','on');\nset(handles.radiobutton1,'Enable','on');\nset(handles.radiobutton1,'Value',0);\n%axes(handles.axes1);\n%spectrogram(x);\nplot(handles.axes1,x);\ntitle(handles.axes1,'Original Signal');\nxlabel(handles.axes1,'Time Index'); ylabel(handles.axes1,'Signal Value');\nplot(handles.axes2,y);\ntitle(handles.axes2,'Echoed Signal');\nxlabel(handles.axes2,'Time Index'); ylabel(handles.axes2,'Signal Value');\nplot(handles.axes3,res);\ntitle(handles.axes3,'Regenerated Signal');\nxlabel(handles.axes3,'Time Index'); ylabel(handles.axes3,'Signal Value');\nstd_all=[std_rls,std_lms,std_nlms,std_fxlms,std_ap];\ncorr_all=[corr_rls,corr_lms,corr_nlms,corr_fxlms,corr_ap];\n%bar(handles.axes4,mse_all);\nbar(handles.axes4,std_all,0.4);\ngap1=get(handles.axes4,'YTick');\nylength1=get(handles.axes4,'YLim');\nylim(handles.axes4,[0 ylength1(1,2)*1.1]);\nif std_rls>0\n text(handles.axes4,1-0.3,std_rls+gap1(1,2)*0.3,'RLS');\nend\nif std_lms>0\n text(handles.axes4,2-0.3,std_lms+gap1(1,2)*0.3,'LMS');\nend\nif std_fxlms>0\n text(handles.axes4,4-0.3,std_fxlms+gap1(1,2)*0.3,'FX');\nend\nif std_nlms>0\n text(handles.axes4,3-0.4,std_nlms+gap1(1,2)*0.3,'NLMS');\nend\nif std_ap>0\n text(handles.axes4,5-0.3,std_ap+gap1(1,2)*0.3,'Affine');\nend\ntitle(handles.axes4,{'Standard deviation';'the smaller the better'});\nxlabel(handles.axes4,'Filter type'); ylabel(handles.axes4,'Value');\n\nbar(handles.axes5,corr_all,0.4);\ngap2=get(handles.axes5,'YTick');\nylength2=get(handles.axes5,'YLim');\nylim(handles.axes5,[0 ylength2(1,2)*1.1]);\nif corr_rls>0\n text(handles.axes5,1-0.3,corr_rls+gap2(1,2)*0.3,'RLS');\nend\nif corr_lms>0\n text(handles.axes5,2-0.3,corr_lms+gap2(1,2)*0.3,'LMS');\nend\nif corr_fxlms>0\n text(handles.axes5,4-0.3,corr_fxlms+gap2(1,2)*0.3,'FX');\nend\nif corr_nlms>0\n text(handles.axes5,3-0.5,corr_nlms+gap2(1,2)*0.3,'NLMS');\nend\nif corr_ap>0\n text(handles.axes5,5-0.3,corr_ap+gap2(1,2)*0.3,'Affine');\nend\ntitle(handles.axes5,{'Correlation coefficient';'the bigger the better'});\nxlabel(handles.axes5,'Filter type'); ylabel(handles.axes5,'Value');\n\n\n\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal x;\nglobal Fs;\nsound(x,Fs);\npause(10);\n\n\n% --- Executes on button press in pushbutton3.\nfunction pushbutton3_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal y;\nglobal Fs;\nsound(y,Fs);\npause(10);\n\n\n% --- Executes on button press in pushbutton4.\nfunction pushbutton4_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal res;\nglobal Fs;\nsound(res,Fs);\npause(10);\n\n\n% --- Executes on button press in radiobutton1.\nfunction radiobutton1_Callback(hObject, eventdata, handles)\n% hObject handle to radiobutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of radiobutton1\nglobal x;\nglobal y;\nglobal res;\nif get(handles.radiobutton1,'Value')\n axes(handles.axes1);\n spectrogram(x);\n title('Original Signal');\n axes(handles.axes2);\n spectrogram(y);\n title('Echoed Signal');\n axes(handles.axes3);\n spectrogram(res);\n title('Regenerated Signal');\nelse\n plot(handles.axes1,x);\n title(handles.axes1,'Original Signal');\n xlabel(handles.axes1,'Time Index'); ylabel(handles.axes1,'Signal Value');\n plot(handles.axes2,y);\n title(handles.axes2,'Echoed Signal');\n xlabel(handles.axes2,'Time Index'); ylabel(handles.axes2,'Signal Value');\n plot(handles.axes3,res);\n title(handles.axes3,'Regenerated Signal');\n xlabel(handles.axes3,'Time Index'); ylabel(handles.axes3,'Signal Value');\nend\nguidata(hObject,handles)\n\n% --- Executes on selection change in popupmenu1.\nfunction popupmenu1_Callback(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% Determine the selected data set.\nglobal FilterType;\nset(handles.pushbutton4,'Enable','off');\nset(handles.radiobutton1,'Enable','off');\nstr = get(hObject, 'String');\nval = get(hObject,'Value');\n% Set current data to the selected data set.\nswitch str{val}\n case 'RLS' % User selects peaks.\n FilterType=0;\n set(handles.edit1,'String','4');\n set(handles.edit2,'String','1');\n set(handles.edit2,'Enable','on');\n set(handles.edit3,'Enable','off');\n case 'LMS' % User selects membrane.\n FilterType=1;\n set(handles.edit1,'String','2');\n set(handles.edit3,'String','0.022');\n set(handles.edit2,'Enable','off');\n set(handles.edit3,'Enable','on');\n case 'FilteredXLMS' % User selects sinc.\n FilterType=2;\n set(handles.edit1,'String','2');\n set(handles.edit3,'String','0.002');\n set(handles.edit2,'Enable','off');\n set(handles.edit3,'Enable','on');\n case 'NLMS' % User selects membrane.\n FilterType=3;\n set(handles.edit1,'String','4');\n set(handles.edit3,'String','0.022');\n set(handles.edit2,'Enable','off');\n set(handles.edit3,'Enable','on');\n case 'AffineProjectionFilter' % User selects membrane.\n FilterType=4;\n set(handles.edit1,'String','2');\n set(handles.edit3,'String','0.022');\n set(handles.edit2,'Enable','off');\n set(handles.edit3,'Enable','on');\nend\n% Save the handles structure.\nguidata(hObject,handles)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from popupmenu1\n\n\n% --- Executes during object creation, after setting all properties.\nfunction popupmenu1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\nvalue = str2double(get(handles.edit1,'String'));\nflag = value > 0 \nif ~flag\n set(handles.edit1,'String','');\n warndlg('Value should be positive !! Please Enter Again');\n% else\n% msgbox('Got the value, On it!');\nend\nset(handles.pushbutton4,'Enable','off');\nset(handles.radiobutton1,'Enable','off');\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\nvalue = str2double(get(handles.edit2,'String'));\nflag = value >= 0 && value <= 1\nif ~flag\n set(handles.edit2,'String','');\n warndlg('Value should be between 0 and 1 !! Please Enter Again');\n% else\n% msgbox('Got the value, On it!');\nend\nset(handles.pushbutton4,'Enable','off');\nset(handles.radiobutton1,'Enable','off');\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\nvalue = str2double(get(handles.edit3,'String'));\nflag = value > 0 \nif ~flag\n set(handles.edit3,'String','');\n warndlg('Value should be positive !! Please Enter Again');\n% else\n% msgbox('Got the value, On it!');\nend\nset(handles.pushbutton4,'Enable','off');\nset(handles.radiobutton1,'Enable','off');\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes during object creation, after setting all properties.\nfunction axes1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to axes1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: place code in OpeningFcn to populate axes1\n\n\n% --- Executes on button press in pushbutton5.\nfunction pushbutton5_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nplot(handles.axes1,5);% To override colorbar of spectrogram\ncla(handles.axes1);\nreset(handles.axes1);\nplot(handles.axes2,5);\ncla(handles.axes2);\nreset(handles.axes2);\nplot(handles.axes3,5);\ncla(handles.axes3);\nreset(handles.axes3);\ncla(handles.axes4);\nreset(handles.axes4);\ncla(handles.axes5);\nreset(handles.axes5);\nset(handles.popupmenu1,'Value',1);\nset(handles.edit2,'Enable','on');\nset(handles.edit3,'Enable','off');\nset(handles.pushbutton4,'Enable','off');\nset(handles.radiobutton1,'Enable','off');\nglobal FilterType;\nFilterType=0;\nglobal std_rls;\nglobal std_lms;\nglobal std_fxlms;\nglobal std_nlms;\nglobal std_ap;\nstd_rls=0;\nstd_lms=0;\nstd_fxlms=0;\nstd_nlms=0;\nstd_ap=0;\nglobal corr_rls;\nglobal corr_lms;\nglobal corr_fxlms;\nglobal corr_nlms;\nglobal corr_ap;\ncorr_rls=0;\ncorr_lms=0;\ncorr_fxlms=0;\ncorr_nlms=0;\ncorr_ap=0;\nset(handles.edit1,'String','4');\nset(handles.edit2,'String','1');\nset(handles.edit3,'String','0.022');\n\n\n% --- Executes during object deletion, before destroying properties.\nfunction axes3_DeleteFcn(hObject, eventdata, handles)\n% hObject handle to axes3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n", "meta": {"author": "Spritea", "repo": "AEC", "sha": "d19979c1a47f8d322d8a2702f59f053e8e8886d3", "save_path": "github-repos/MATLAB/Spritea-AEC", "path": "github-repos/MATLAB/Spritea-AEC/AEC-d19979c1a47f8d322d8a2702f59f053e8e8886d3/AEC_V2.5/Echo_cancel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.03161876989213464, "lm_q1q2_score": 0.012998819974407378}} {"text": "function [isrcs, idets, measures, measure_type] = nst_unformat_channels(channel_labels, warn_bad_channels)\n% NST_UNFORMAT_CHANNELS extract sources, dectectors and measures information \n% from channel labels with *homogeneous* type (eg wavelength or Hb).\n%\n% [ISRCS, IDETS, MEAS, CHAN_TYPE] = NST_UNFORMAT_CHANNELS(CHANNEL_LABELS)\n% CHANNEL_LABELS (cell array of str): \n% each str is formatted as 'SxDyWLz' or 'SxDyHbt', where:\n% x: source index\n% y: detector index\n% z: wavelength\n% t: Hb type (O, R, T).\n% Consistency is asserted so that:\n% - channels are unique\n% - channel type is homogeneous\n% Warning is issued if:\n% - the number of measures per pair is not homogeneous\n% eg one pair has only one wavelength\n%\n% Examples: S1D2WL685, S01D7WL830, S3D01HbR\n% \n%\n% ISRCS (array of int): extracted source indexes\n% IDETS (array of int): extracted detector indexes\n% MEAS (array of int | cell array of str): extracted measure values\n% CHAN_TYPE (array of int): channel type (see NST_CHANNEL_TYPES for enum).\n%\n% See also NST_UNFORMAT_CHANNEL, NST_CHANNEL_TYPES, NST_FORMAT_CHANNEL\n\nassert(iscellstr(channel_labels));\n\nif nargin < 2\n warn_bad_channels = 0;\nend\n \n\nnb_channels = length(channel_labels);\nisrcs = zeros(1, nb_channels);\nidets = zeros(1, nb_channels);\nmeasures = cell(1, nb_channels);\nmtypes = zeros(1, nb_channels);\nreformated_channels = cell(1, nb_channels);\nfor ichan=1:nb_channels\n [isrc, idet, meas, mtype] = nst_unformat_channel(channel_labels{ichan}, warn_bad_channels);\n isrcs(ichan) = isrc;\n idets(ichan) = idet;\n measures{ichan} = meas;\n mtypes(ichan) = mtype;\n if ~isnan(isrc) && ~isnan(idet)\n % reformat channels to make sure formatting is consistent\n % -> allow proper duplicate detection after\n reformated_channels{ichan} = nst_format_channel(isrc, idet, meas);\n else\n reformated_channels{ichan} = '';\n end\nend\n\n% check uniqueness\n[~, i_unique] = unique(reformated_channels);\nduplicates = reformated_channels;\nduplicates(i_unique) = [];\nduplicates(strcmp(duplicates, '')) = []; %remove unrecognized channels\ni_duplicates = ismember(reformated_channels, unique(duplicates));\nif ~isempty(duplicates)\n msg = sprintf('Duplicated channels: \"%s\". Indexes: %s', ...\n strjoin(channel_labels(i_duplicates), ', '), num2str(i_duplicates));\n throw(MException('NIRSTORM:NonUniqueChannels', msg));\nend\n\n% check homogeneity of channel type\nmtypes = mtypes(~isnan(mtypes));\nif length(unique(mtypes)) > 1\n throw(MException('NIRSTORM:NonHomogeneousMeasure', 'Measure type is not homogeneous.'));\nend\n\nmeasure_types = nst_measure_types();\nmeasure_type = mtypes(1);\nif measure_type == measure_types.WAVELENGTH\n measures = cell2mat(measures);\nend\n\n%% Check number of measures per pair\nmax_idet = (max(idets)+1);\npairs_hash = isrcs(~isnan(isrcs)) * max_idet + idets(~isnan(isrcs));\nunique_pairs_hash = unique(pairs_hash);\nmcounts = sparse(ones(1, length(unique_pairs_hash)), unique_pairs_hash, ...\n ones(1, length(unique_pairs_hash)), 1, max(unique_pairs_hash), ...\n nb_channels);\nif ~iscell(measures) \n all_measures = unique(measures(~isnan(measures)));\nelse\n all_measures = unique(measures(cellfun(@(e) ischar(e) || ~isnan(e), measures))); \nend\nfor ichan=1:nb_channels\n if ~isnan(isrcs(ichan))\n if measure_type == measure_types.WAVELENGTH\n measure_hash = find(measures(ichan)==all_measures);\n elseif measure_type == measure_types.HB\n measure_hash = find(strcmp(measures(ichan),all_measures));\n end\n h_idx = isrcs(ichan) * max_idet + idets(ichan);\n mcounts(h_idx) = mcounts(h_idx) + measure_hash;\n end\nend\n\n% pairs with too many measures:\ni_inconsistant_measures = (mcounts ~= sum(1:length(all_measures)) + 1) & (mcounts ~= 0);\n\nif nnz(i_inconsistant_measures) > 0\n [isrc_incon,idet_incon,counts] = find(i_inconsistant_measures);\n inconsistent_pairs = cell(1, length(isrc_incon));\n for ipair=1:length(isrc_incon)\n inconsistent_pairs{ipair} = sprintf('S%dD%d', isrc_incon(ipair), idet_incon(ipair));\n end \n warning('Inconsistent measure(s) for pair(s): %s', strjoin(inconsistent_pairs, ', '));\nend\n\nend\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/io/private/nst_unformat_channels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.02716922907409646, "lm_q1q2_score": 0.012842445655840858}} {"text": "%RNA Decay\n%\n% @wholeCellModelID Process_RNADecay\n% @name RNA Decay\n% @description\n% Biology\n% ===============\n% In presence of ribonucleases such as ribonuclease R (MG_104_MONOMER) RNAs\n% have relatively short half lives compared to that of other macromolecules\n% (eg. protein, DNA) and the M. genitalium cell cycle length. The relatively\n% short half lives of RNAs enables the small M. genitalium with its very small\n% pool of RNAs and particularly mRNAs to sample a broader range of\n% configurations of the RNA pool over a shorter period that would be possible\n% with longer half lifes. This helps the cell more finely tune the expression\n% of proteins, more efficiently execute cell-cycle dependent events, and\n% respond to the external environment. This enhanced fitness due to short RNA\n% half lifes comes at a large energetic cost however.\n%\n% In addition to ribonucleases, aminoacylated RNAs require peptidyl tRNA\n% hydrolase (MG_083_MONOMER) to release their conjugated amino acids.\n%\n% This process decays all species of RNA, and at all maturation states\n% including aminoacylated states.\n%\n% Knowledge Base\n% ===============\n% The knowledge base contains experimentally measured half lifes of many RNA\n% species measured largely in E. coli and mapped to M. genitalium by homology.\n% These half lifes are refined, by simulation.fitConstants to make them\n% consistent with other experimental data used to fit the model. Prior to\n% fitting missing half lifes are imputed either as the average of that of all\n% measured RNA species.\n%\n% Type Avg Half Life (m)\n% ==== =================\n% mRNA 4.5 +/- 2.0\n% rRNA 150\n% sRNA 89\n% tRNA 45\n%\n% Representation\n% ===============\n% The substrates, enzymes, and RNAs properties represent the counts of\n% metabolites, ribonuclease R and peptidyl tRNA hydrolase enzymes, and RNAs.\n% This process contains no intermediate representation of RNA degradation; RNA\n% degradation is treated as an all-or-nothing event that either proceeds to\n% complete with a time step or doesn't progress at all.\n%\n% decayRates represents the decay rate of each RNA species in seconds.\n% decayRates is informed by experimentally measured RNA half lifes organized\n% in the knowledge base, and fit by simulation.fitConstants. decayReactions\n% represents the metabolites required to decay each RNA species, and the\n% metabolic byproducts of the decay of each RNA species. decayReactions is\n% computed by the knowledge RNA classes based on the sequence, processing, and\n% modifications of each RNA species.\n%\n% Initialization\n% ===============\n% All RNAs are initialized to the mature state. This is accomplished by the\n% simulation class initializeState method.\n%\n% Simulation\n% ===============\n% This process models RNA decay as an enyzme-dependent poisson process with\n% rate parameter:\n% lambda = RNAs .* decayRates * stepSizeSec\n%\n% Algorithm\n% +++++++++++++++\n% 1. Stochastically select RNAs to decay based on poission distribution with\n% lambda = RNAs .* decayRates * stepSizeSec\n% 2. (Ignore limits to decay posed by availability of metabolite reactants\n% since the only reactant is water, and water is abundantly available)\n% 3. Limit RNA decay by available enzyme activity\n% a. All RNAs require ribonuclease R to decay\n% b. Additionally, only decay aminoacylated tRNAs up to the limit of\n% available peptidyl tRNA hydrolase activity.\n% 4. Update counts of RNAs\n% 5. Update counts of metabolic byproducts of RNA decay\n%\n% Author: Markus Covert, mcovert@stanford.edu\n% Author: Jayodita Sanghvi, jayodita@stanford.edu\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 7/30/2010\nclassdef RNADecay < edu.stanford.covert.cell.sim.Process\n\n %property annotations\n properties (Constant)\n optionNames__ = {}; %names of option properties\n fixedConstantNames__ = { %names of fixed constant properties\n\t\t 'peptidylTRNAHydrolaseSpecificRate';\n 'ribonucleaseRFragmentLength';\n 'decayReactions';\n };\t\t\t\n fittedConstantNames__ = {}; %names of fitted constant properties\n localStateNames__ = { %names of simulation state properties redundant with timecourses in this or other processes or the simulation\n 'RNAs'};\n end\n\n %IDs, names, and local indices\n properties\n stimuliWholeCellModelIDs = {}; %whole cell model IDs of stimuli\n\n substrateWholeCellModelIDs = {}; %whole cell model IDs of substrates\n substrateIndexs_hydrogen %index within substrates of hydrogen\n substrateIndexs_water %index within substrates of water\n substrateIndexs_methionine %index within substrates of methionine\n substrateIndexs_fmethionine %index within substrates of formylmethionine\n substrateIndexs_glutamate %index within substrates of glutamate\n substrateIndexs_glutamine %index within substrates of glutamine\n substrateIndexs_formate %index within substrates of formate\n substrateIndexs_ammonia %index within substrates of ammonia\n substrateIndexs_aminoAcids %index within substrates of amino acids\n substrateIndexs_nmps %index within substrates of NMPs\n\n enzymeWholeCellModelIDs = { %enzyme whole cell model ids\n 'MG_104_MONOMER'; %ribonuclease R\n 'MG_083_MONOMER'}; %peptidyl-tRNA hydrolase\n enzymeIndexs_ribonucleaseR = 1; %index within enzymes of ribonuclease R\n enzymeIndexs_peptidylTRNAHydrolase = 2; %index within enzymes of peptidyl-tRNA hydrolase\n \n matureTRNAIndexs %indices of mature tRNAs within RNAs\n matureTMRNAIndexs %indices of mature tmRNAs within RNAs\n end\n \n %fixed biological constants\n properties\n peptidylTRNAHydrolaseSpecificRate %0.700 [PUB_0026]\n ribonucleaseRFragmentLength %5 [PUB_0039]\n decayReactions %adjacency matrix -- RNAs X (reactants and products of RNA decay)\n end\n\n %global state (copied locally for convenience)\n properties\n RNAs %counts of RNAs\n end\n \n %global state (referenced locally for convenience)\n properties\n transcripts %New Transcripts state class\n end\n\n %constructor\n methods\n function this = RNADecay(wholeCellModelID, name)\n this = this@edu.stanford.covert.cell.sim.Process(wholeCellModelID, name);\n end\n end\n\n %communication between process/simulation\n methods\n %set references to state objects\n function storeObjectReferences(this, simulation)\n this.storeObjectReferences@edu.stanford.covert.cell.sim.Process(simulation);\n \n this.transcripts = simulation.state('Transcript');\n this.states = [this.states; {this.transcripts}];\n end\n \n %initialize constants\n function initializeConstants(this, knowledgeBase, simulation, varargin)\n s = this.rna;\n g = this.gene;\n \n %include all metabolites involved in RNA decay\n decayReactions_nascentRNA = knowledgeBase.nascentRNAs.decayReactions;\n decayReactions_processedRNA = knowledgeBase.processedRNAs.decayReactions;\n decayReactions_intergenicRNA = knowledgeBase.intergenicRNAs.decayReactions;\n decayReactions_matureRNA = knowledgeBase.matureRNAs.decayReactions;\n decayReactions_aminoacylatedRNA = knowledgeBase.aminoacylatedRNAs.decayReactions; \n \n this.substrateWholeCellModelIDs = unique([simulation.state('Metabolite').wholeCellModelIDs(...\n any(decayReactions_nascentRNA, 1) | ...\n any(decayReactions_processedRNA, 1) | ...\n any(decayReactions_intergenicRNA, 1) | ...\n any(decayReactions_matureRNA, 1) | ...\n any(decayReactions_aminoacylatedRNA, 1));\n 'H';'H2O';'NH3';'FOR';\n 'ALA';'ARG';'ASN';'ASP';'CYS';'GLN';'GLU';'GLY';'HIS';'ILE';'LEU';'LYS';'MET';'PHE';'PRO';'SER';'THR';'TRP';'TYR';'VAL';'FMET']);\n\n %super class method\n this.initializeConstants@edu.stanford.covert.cell.sim.Process(...\n knowledgeBase, simulation, varargin{:});\n \n %substrate indices\n this.substrateIndexs_hydrogen = this.substrateIndexs({'H'});\n this.substrateIndexs_water = this.substrateIndexs({'H2O'});\n this.substrateIndexs_methionine = this.substrateIndexs({'MET'});\n this.substrateIndexs_fmethionine = this.substrateIndexs({'FMET'});\n this.substrateIndexs_glutamate = this.substrateIndexs({'GLU'});\n this.substrateIndexs_glutamine = this.substrateIndexs({'GLN'});\n this.substrateIndexs_ammonia = this.substrateIndexs({'NH3'});\n this.substrateIndexs_formate = this.substrateIndexs({'FOR'});\n this.substrateIndexs_aminoAcids = this.substrateIndexs({'ALA';'ARG';'ASN';'ASP';'CYS';'GLN';'GLU';'GLY';'HIS';'ILE';'LEU';'LYS';'MET';'PHE';'PRO';'SER';'THR';'TRP';'TYR';'VAL';'FMET'});\n this.substrateIndexs_nmps = this.substrateIndexs({'AMP';'CMP';'GMP';'UMP'});\n \n this.matureTRNAIndexs = find(any(s.matureRNAGeneComposition(g.tRNAIndexs, :), 1))';\n this.matureTMRNAIndexs = s.getIndexs('MG_0004');\n \n this.decayReactions = zeros(numel(this.rna.wholeCellModelIDs), numel(this.substrateWholeCellModelIDs));\n this.decayReactions(s.nascentIndexs, :) = decayReactions_nascentRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.processedIndexs, :) = decayReactions_processedRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.intergenicIndexs, :) = decayReactions_intergenicRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.matureIndexs, :) = decayReactions_matureRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.boundIndexs, :) = decayReactions_matureRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.misfoldedIndexs, :) = decayReactions_matureRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.damagedIndexs, :) = decayReactions_matureRNA(:, this.substrateMetaboliteGlobalIndexs);\n this.decayReactions(s.aminoacylatedIndexs, :) = decayReactions_aminoacylatedRNA(:, this.substrateMetaboliteGlobalIndexs); \n end\n\n %retrieve state from simulation\n function copyFromState(this)\n this.copyFromState@edu.stanford.covert.cell.sim.Process();\n\n this.RNAs = this.rna.counts(:, this.compartment.cytosolIndexs, :);\n end\n\n %send state to simulation\n function copyToState(this)\n this.copyToState@edu.stanford.covert.cell.sim.Process();\n\n this.rna.counts(:, this.compartment.cytosolIndexs, :) = this.RNAs;\n end\n end\n \n %memory alloction for state\n methods\n function allocateMemoryForState(this, numTimePoints)\n this.allocateMemoryForState@edu.stanford.covert.cell.sim.Process(numTimePoints);\n \n this.RNAs = zeros(size(this.rna.counts, 1), 1, numTimePoints);\n end\n end\n\n %model\n methods\n %Calculate\n %- contribution to FBA objective\n %- minimum expression consistent with cell cycle length\n function [bmProd, byProd, minEnzExp, maxEnzExp] = calcResourceRequirements_LifeCycle(this, ~, states)\n import edu.stanford.covert.util.ComputationUtil;\n invMat = this.rna.intergenicRNAMatrix * ...\n ComputationUtil.invertCompositionMatrix(this.rna.nascentRNAMatureRNAComposition);\n \n %% substrate and byproducts\n %data\n matureRNAReactions = this.decayReactions(this.rna.aminoacylatedIndexs, :); %same as mature for (m,r)RNA and for non-aminoacylated sRNA\n intergenicRNAReactions = this.decayReactions(this.rna.intergenicIndexs, :);\n intergenicRNADecays = invMat * states.rnaProductions;\n\n %RNA decay\n bmProd = ...\n + max(0, -matureRNAReactions)' * states.rnaDecays ...\n + max(0, -intergenicRNAReactions)' * intergenicRNADecays;\n byProd = ...\n + max(0, matureRNAReactions)' * states.rnaDecays ...\n + max(0, intergenicRNAReactions)' * intergenicRNADecays;\n \n %% enzymes\n \n %data\n rnaDecays = states.rnaDecays0;\n aminoacylatedRNADecays = rnaDecays([this.matureTRNAIndexs; this.matureTMRNAIndexs]);\n intergenicRNADecays = invMat * states.rnaProductions0;\n\n %RNA decay\n minEnzExp = zeros(size(this.enzymeWholeCellModelIDs));\n minEnzExp(this.enzymeIndexs_ribonucleaseR) = ...\n 2 * (sum(rnaDecays) + sum(intergenicRNADecays));\n minEnzExp(this.enzymeIndexs_peptidylTRNAHydrolase) = ...\n 2 * sum(aminoacylatedRNADecays) / this.peptidylTRNAHydrolaseSpecificRate;\n maxEnzExp = Inf(size(this.enzymeWholeCellModelIDs));\n end\n\n %initialization: RNAs intialized to mature/aminoacylated state by\n %simulation intializeState method\n function initializeState(~)\n end\n\n %resource requirements\n function result = calcResourceRequirements_Current(this)\n if this.enzymes(this.enzymeIndexs_ribonucleaseR) == 0\n result = zeros(size(this.substrates));\n return;\n end\n \n result = max(0, -this.decayReactions' * (min(1, this.rna.decayRates) .* this.RNAs));\n if ~isempty(this.transcripts.abortedTranscripts)\n result(this.substrateIndexs_water) = ...\n + result(this.substrateIndexs_water) ...\n + sum(this.transcripts.abortedTranscripts(:, 2) - 1);\n end\n end\n\n %simulation\n function evolveState(this)\n % import classes\n import edu.stanford.covert.cell.kb.ssRNA;\n \n % numbers of enzymes\n ribonucleaseR = this.enzymes(this.enzymeIndexs_ribonucleaseR);\n peptidylTRNAHydrolase = this.randStream.stochasticRound(...\n this.enzymes(this.enzymeIndexs_peptidylTRNAHydrolase) ...\n * this.peptidylTRNAHydrolaseSpecificRate ...\n * this.stepSizeSec);\n \n %Ribonuclease R required for decay, terminate early if no ribonuclease R\n if ribonucleaseR == 0\n return;\n end\n \n %% decay all aborted transcripts\n abortedSeqs = this.transcripts.abortedSequences;\n abortedTfs = false(size(abortedSeqs));\n for i = 1:numel(abortedSeqs)\n substrateCost = ssRNA.computeDecayReaction(ssRNA.computeBaseCount(...\n abortedSeqs{i}, numel(this.substrates), this.substrateIndexs_nmps), ...\n numel(abortedSeqs{i}), 'linear', ...\n this.substrateIndexs_water, this.substrateIndexs_hydrogen)';\n if any(this.substrates < -substrateCost)\n break;\n end\n abortedTfs(i) = true;\n this.substrates = this.substrates + substrateCost;\n end\n this.transcripts.abortedTranscripts = this.transcripts.abortedTranscripts(~abortedTfs, :);\n \n %% Stochastically decay free RNA as poisson process\n decayingRNAs = min(this.randStream.random('poisson', ...\n this.RNAs .* min(1e6, this.rna.decayRates * this.stepSizeSec)), ...\n this.RNAs);\n if ~any(decayingRNAs)\n return;\n end\n \n %Require peptidyl tRNA hydrolase to decay aminoacylated tRNAs\n tmp = decayingRNAs(this.rna.aminoacylatedIndexs);\n tmp2 = zeros(size(tmp));\n while any(tmp)\n if peptidylTRNAHydrolase <= 0\n break;\n end\n idx = this.randStream.randsample(numel(tmp), 1, true, tmp);\n tmp(idx) = tmp(idx) - 1;\n tmp2(idx) = tmp2(idx) + 1;\n peptidylTRNAHydrolase = peptidylTRNAHydrolase - 1;\n end\n decayingRNAs(this.rna.aminoacylatedIndexs) = tmp2;\n \n %require substrates (water) to decay RNAs\n tmp = decayingRNAs;\n tmp2 = zeros(size(tmp));\n water = this.substrates(this.substrateIndexs_water);\n waterReqs = max(0, -this.decayReactions(:, this.substrateIndexs_water));\n while any(tmp)\n idx = this.randStream.randsample(numel(tmp), 1, true, tmp);\n if water < waterReqs(idx);\n break;\n end\n water = water - waterReqs(idx);\n tmp(idx) = tmp(idx) - 1;\n tmp2(idx) = tmp2(idx) + 1;\n end\n decayingRNAs = tmp2;\n \n %update numbers of RNAs\n this.RNAs = this.RNAs - decayingRNAs;\n \n %update metabolites\n %- water, hydrogen for hydrolysis\n %- nucleotide monophosphate salvage\n this.substrates = this.substrates + this.decayReactions' * decayingRNAs;\n \n this.rna.counts(:, this.compartment.cytosolIndexs) = this.RNAs;\n if any(any(this.rna.updateExternalState(-decayingRNAs, true)))\n throw(MException('RNADecay:error', 'All RNAs should have been degraded'));\n end\n this.RNAs = this.rna.counts(:, this.compartment.cytosolIndexs);\n end\n end\n\n %get methods of dependent local state\n methods\n function value = getDryWeight(this)\n if size(this.RNAs, 3) == 1\n value = this.getDryWeight@edu.stanford.covert.cell.sim.Process() + ...\n this.rna.molecularWeights' * this.RNAs / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n else\n value = this.getDryWeight@edu.stanford.covert.cell.sim.Process() + ...\n permute(this.rna.molecularWeights' * permute(this.RNAs,[1 3 2]),[1 3 2]) / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n end\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+process/RNADecay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.032100706022533954, "lm_q1q2_score": 0.01283423594377512}} {"text": "function C = rdivide(A, B)\n%./ CHEBOP right division.\n% C = A./B, where ones of a A is a CHEBOP and is B a scalar is equivalent\n% to A*(1/B), repectively.\n%\n% All other instances returns an error.\n%\n% See also CHEBOP/MTIMES, CHEBOP/MRDIVIDE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isnumeric(B) )\n C = mtimes(A, 1./B);\nelse\n error('CHEBOP:RDIVIDE:NotSupported', '%s./%s is not supported.', ...\n class(A), class(B));\nend\n \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop/rdivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.029312231705318298, "lm_q1q2_score": 0.012833583852068706}} {"text": "function [psth] = ft_spike_psth(cfg, spike)\n\n% FT_SPIKE_PSTH computes the peristimulus histogram of spiketrains.\n%\n% Use as\n% [psth] = ft_spike_psth(cfg, spike)\n%\n% The input SPIKE should be organised as either the spike datatype,\n% obtained from FT_SPIKE_MAKETRIALS, or the raw datatype, containing binary\n% spike trains, obtained from FT_APPENDSPIKE or FT_CHECKDATA. In this case\n% the raw datatype is converted to the spike datatype.\n%\n% Configurations:\n% cfg.binsize = [binsize] in sec or string.\n% If 'scott', we estimate the optimal bin width\n% using Scott's formula (1979). If 'sqrt', we take\n% the number of bins as the square root of the\n% number of observations. The optimal bin width is\n% derived over all neurons; thus, this procedure\n% works best if the input contains only one neuron\n% at a time.\n% cfg.outputunit = 'rate' (default) or 'spikecount' or\n% 'proportion'. If 'rate', we\n% convert the output per trial to firing rates\n% (spikes/sec). If 'spikecount', we count the\n% number spikes per trial. If 'proportion', we\n% normalize the area under the PSTH to 1.\n% cfg.spikechannel = See FT_CHANNELSELECTION for details. cfg.trials\n% is vector of indices (e.g., 1:2:10)\n% logical selection of trials (e.g., [1010101010])\n% 'all' (default), selects all trials\n% cfg.vartriallen = 'yes' (default)\n% Accept variable trial lengths and use all\n% available trials and the samples in every trial.\n% Missing values will be ignored in the\n% computation of the average and the variance and\n% stored as NaNs in the output psth.trial. 'no'\n% Only select those trials that fully cover the\n% window as specified by cfg.latency and discard\n% those trials that do not.\n% cfg.latency = [begin end] in seconds\n% 'maxperiod' (default), i.e., maximum period\n% available 'minperiod', i.e., the minimal period\n% all trials share, 'prestim' (all t<=0) 'poststim'\n% (all t>=0).\n% cfg.keeptrials = 'yes' or 'no' (default)\n% cfg.trials = numeric or logical selection of trials (default = 'all')\n%\n% Outputs:\n% Psth is a timelock datatype (see FT_DATATYPE_TIMELOCK)\n% Psth.time = center histogram bin points\n%\t Psth.fsample = 1/binsize;\n% Psth.avg = contains average PSTH per unit\n% Psth.trial = contains PSTH per unit per trial\n% Psth.var = contains variance of PSTH per unit across trials\n%\n% For subsequent processing you can use\n% FT_SPIKE_PLOT_PSTH : plot only the PSTH, for a single neuron\n% FT_TIMELOCKSTATISTICS : compute statistics on the PSTH\n% FT_SPIKE_PLOT_RASTER : plot PSTH with raster for one or more neurons\n% FT_SPIKE_JPSTH : compute the JPSTH\n\n% Copyright (C) 2010-2013, Martin Vinck\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\n% these are used by the ft_preamble/ft_postamble function and scripts\nft_revision = '$Id$';\nft_nargin = nargin;\nft_nargout = nargout;\n\n% do the general setup of the function\nft_defaults\nft_preamble init\nft_preamble provenance spike\n\n\n% control input spike structure and convert to spike if raw structure\nspike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes');\n\n% get the default options\ncfg.outputunit = ft_getopt(cfg, 'outputunit','rate');\ncfg.binsize = ft_getopt(cfg, 'binsize','scott');\ncfg.spikechannel = ft_getopt(cfg, 'spikechannel', 'all');\ncfg.trials = ft_getopt(cfg, 'trials', 'all');\ncfg.latency = ft_getopt(cfg, 'latency','maxperiod');\ncfg.vartriallen = ft_getopt(cfg, 'vartriallen', 'yes');\ncfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'no');\n\n% ensure that the options are valid\ncfg = ft_checkopt(cfg,'outputunit', 'char', {'rate', 'spikecount'});\ncfg = ft_checkopt(cfg,'binsize', {'char', 'doublescalar'});\ncfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'});\ncfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'});\ncfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'});\ncfg = ft_checkopt(cfg,'vartriallen' , 'char', {'yes', 'no'});\ncfg = ft_checkopt(cfg,'keeptrials' , 'char', {'yes', 'no'});\n\ncfg = ft_checkconfig(cfg, 'allowed', {'outputunit', 'binsize', 'spikechannel', 'trials', 'latency', 'vartriallen', 'keeptrials'});\n\n% get the number of trials or convert to indices\ncfg = trialselection(cfg,spike);\n\n% select the unit - this should be done with channelselection function\ncfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label);\nspikesel = match_str(spike.label, cfg.spikechannel);\nnUnits = length(spikesel);\nif nUnits==0, error('no spikechannel selected by means of cfg.spikechannel'); end\n\n% determine the duration of each trial\nbegTrialLatency = spike.trialtime(cfg.trials,1); % remember: already selected on trial here\nendTrialLatency = spike.trialtime(cfg.trials,2);\ntrialDur \t \t= endTrialLatency - begTrialLatency;\n\n% select the latencies, use the same modular function in all the scripts\ncfg = latencyselection(cfg,begTrialLatency,endTrialLatency);\n\n% compute the optimal bin width if desired\nif ischar(cfg.binsize)\n h = zeros(1,nUnits);\n for iUnit = 1:nUnits\n unitIndx = spikesel(iUnit); % select the unit\n spikesInWin = spike.time{unitIndx}>=cfg.latency(1) & spike.time{unitIndx}<=cfg.latency(2); % get spikes in trial\n \n % automatically determine an 'optimal' binwidth\n N = sum(spikesInWin);\n if strcmp(cfg.binsize,'scott')\n sd = nanstd(spike.time{unitIndx}(spikesInWin));\n h(iUnit) = 3.49*sd./(N^(1/3));\n elseif strcmp(cfg.binsize,'sqrt')\n k = ceil(sqrt(N));\n h(iUnit) = (cfg.latency(2)-cfg.latency(1))/k;\n else\n error('unsupported option for cfg.binsize');\n end\n end\n cfg.binsize = nanmean(h);\nend\n\n% do some error checking on the binsize\nif cfg.binsize<=0 || cfg.binsize>(cfg.latency(2)-cfg.latency(1))\n error('cfg.binsize should be greater than zero and not exceed the trialduration');\nend\n\n% end of trial should be late enough, beginning should be early enough\nfullDur = trialDur>=cfg.binsize; % trials which have full duration\noverlaps = endTrialLatency>=(cfg.latency(1)+cfg.binsize) & begTrialLatency<=(cfg.latency(2)-cfg.binsize);\nif strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window\n startsLater = single(begTrialLatency) > (single(cfg.latency(1)) + 0.0001); % last factor just for rounding errors\n endsEarlier = single(endTrialLatency) < (single(cfg.latency(2)) - 0.0001);\n hasWindow = ~(startsLater | endsEarlier); % it should not start later or end earlier\nelse\n hasWindow = ones(1,length(cfg.trials));\nend\ntrialSel = fullDur(:) & overlaps(:) & hasWindow(:);\ncfg.trials = cfg.trials(trialSel); % note that endTrialLatency was of length cfg.trials\nif isempty(cfg.trials), warning('No trials were selected after latency selection'); end\nnTrials = length(cfg.trials);\nbegTrialLatency = begTrialLatency(trialSel); % note that begTrialLatency was of length cfg.trials here\nendTrialLatency = endTrialLatency(trialSel);\n\n% create the bins, we start arbitrarily at cfg.latency(1)\nbins = cfg.latency(1) : cfg.binsize : cfg.latency(end);\nnBins = length(bins);\n\n% preallocate before computing the psth, otherwise, compute stuff 'on the run'\nif strcmp(cfg.keeptrials,'yes'), singleTrials = NaN(nTrials,nUnits,nBins-1); end\n[s,ss] = deal(zeros(nUnits, nBins-1)); %sum, and sum of squared in the loop, to get mean & var\n\n% preallocate and compute degrees of freedom\nallStartEarlier = all(begTrialLatency<=cfg.latency(1));\nallEndLater = all(endTrialLatency>=cfg.latency(2));\nif ~ (allStartEarlier && allEndLater),\n dof = zeros(1,nBins-1);\nelse\n dof = ones(1,nBins-1)*nTrials; % if all exceed latency, then this is dof\nend\n\nfor iTrial = 1:nTrials\n origTrial = cfg.trials(iTrial);\n if ~ (allStartEarlier && allEndLater) % select bins and count dof + 1\n binSel = begTrialLatency(iTrial)<=bins(1:end-1) & endTrialLatency(iTrial)>=bins(2:end);\n dof(binSel) = dof(binSel) + 1;\n else\n binSel = 1:(nBins-1); % always deselect the last bin\n end\n \n for iUnit = 1:nUnits\n unitIndx = spikesel(iUnit); % select the unit\n spikesInTrial = (spike.trial{unitIndx}==origTrial); % get spikes in trial\n spikeTimes = spike.time{unitIndx}(spikesInTrial);\n \n % compute the psth\n trialPsth = histc(spikeTimes(:), bins); % we deselect the last bin per default\n trialPsth = trialPsth(:)'; % force into row vec\n if isempty(trialPsth), trialPsth = zeros(1,length(bins)); end\n \n % convert to firing rates if requested, with spikecount do nothing\n if strcmp(cfg.outputunit,'rate'),\n trialPsth = trialPsth/cfg.binsize;\n elseif strcmp(cfg.outputunit,'proportion'),\n trialPsth = trialPsth./nansum(trialPsth);\n end\n \n % compute the sum and the sum of squares for the var and the mean on the fly\n s(iUnit,binSel) = s(iUnit,binSel) + trialPsth(binSel); % last bin is single value\n ss(iUnit,binSel) = ss(iUnit,binSel) + trialPsth(binSel).^2;\n \n if strcmp(cfg.keeptrials,'yes'),\n singleTrials(iTrial,iUnit,binSel) = trialPsth(binSel);\n end\n end\nend\n\n% get the results\ndof = dof(ones(nUnits,1),:);\npsth.avg = s ./ dof;\npsth.var = (ss - s.^2./dof)./(dof-1); % since sumPsth.^2 ./ dof = dof .* (sumPsth/dof).^2\npsth.dof = dof; % combined with psth.var we can get SEM\npsth.fsample = 1/(cfg.binsize); % might be more compatible with feeding psth in other funcs\npsth.time = bins(1:end-1) + 0.5*cfg.binsize;\npsth.label = spike.label(spikesel);\nif (strcmp(cfg.keeptrials,'yes'))\n psth.trial = singleTrials;\n psth.dimord = 'rpt_chan_time';\nelse\n psth.dimord = 'chan_time';\nend\nif isfield(spike,'sampleinfo'), psth.sampleinfo = spike.sampleinfo(cfg.trials,:); end\nif isfield(spike,'trialinfo'), psth.trialinfo = spike.trialinfo(cfg.trials,:); end\n\n% do the general cleanup and bookkeeping at the end of the function\n\nft_postamble previous spike\nft_postamble provenance psth\nft_postamble history psth\n\n\n%%%%%%%%% SUB FUNCTIONS %%%%%%%%%\nfunction [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency)\n\nif strcmp(cfg.latency,'minperiod')\n cfg.latency = [max(begTrialLatency) min(endTrialLatency)];\nelseif strcmp(cfg.latency,'maxperiod')\n cfg.latency = [min(begTrialLatency) max(endTrialLatency)];\nelseif strcmp(cfg.latency,'prestim')\n cfg.latency = [min(begTrialLatency) 0];\nelseif strcmp(cfg.latency,'poststim')\n cfg.latency = [0 max(endTrialLatency)];\nend\n% check whether the time window fits with the data\nif (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency);\n warning('Correcting begin latency because it is before all trial beginnings');\nend\nif (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency);\n warning('Correcting end latency because it is after all trial ends');\nend\n\n\nfunction [cfg] = trialselection(cfg,spike)\n\nnTrials = size(spike.trialtime,1);\nif strcmp(cfg.trials,'all')\n cfg.trials = 1:nTrials;\nelseif islogical(cfg.trials) || all(cfg.trials==0 | cfg.trials==1)\n cfg.trials = find(cfg.trials);\nend\ncfg.trials = sort(cfg.trials(:));\nif max(cfg.trials)>nTrials,\n error('maximum trial number in cfg.trials should not exceed number of rows of spike.trialtime');\nend\nif isempty(cfg.trials), error('No trials were selected by you, rien ne va plus'); end\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/contrib/spike/ft_spike_psth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.027585285424500023, "lm_q1q2_score": 0.012610246403673349}} {"text": "function [wrongTable, absentModelTable, absentMapTable, duplicateTable] = compareModelMapFormulas(model, map, excelName)\n% Checks the errors in a given map using a given base model by\n% comparing the reactions formulas. As different errors can exist, the\n% output is separated in 4 different tables that can later be exported\n% into Excel spreadsheets (see commented lines at the end).\n%\n% USAGE:\n%\n% [wrongTable, absentModelTable, absentMapTable, duplicateTable] = compareModelMapFormulas(model, map, excelName)\n%\n% INPUTS:\n% model: COBRA structure of a model\n% map: MATLAB structure of the map obtained from the\n% function `transformXML2Map`.\n%\n% OPTIONAL INPUT:\n% excelName: Name of the excel file in which to export the info\n%\n% OUTPUTS:\n% wrongTable: Table containing the information on wrong\n% reactions. The fields are arranged as\n% followed:\n%\n% * rxnName - Name of the reaction in the map\n% * rxnID - ID of the reaction in the map\n% * modelFormula - Formula of the reaction from the model\n% * mapFormula - Formula of the reaction from the map\n%\n% absentModelTable: Table containing the information on\n% reactions present in the map but absent\n% from the model. The fields are arranged as\n% followed:\n%\n% * rxnName - Name of the reaction in the map\n% * rxnID - ID of the reaction in the map\n% * mapFormula - Formula of the reaction from the map\n%\n% absentMapTable: Table containing the information on\n% reactions present in the model but absent\n% from the map. The fields are arranged as\n% followed:\n%\n% * rxnName - Name of the reaction in the model\n% * modelFormula - Formula of the reaction from the model\n%\n% duplicateTable: Table containing the information on\n% duplicated reactions in the map. The fields\n% are arranged as followed:\n%\n% * rxnName - Name of the reaction in the model\n% * rxnID - ID of the reaction in the map\n% * modelFormula - Formula of the reaction from the model\n% * mapFormula - Formula of the reaction from the map\n%\n% .. Author: - N.Sompairac - Institut Curie, Paris, 25/07/2017.\n\nmodelReactionNameList = model.rxns; % Getting names from model and map\nmapReactionNameList = map.rxnName;\n\n% Getting the formulas from the model and the map for further comparison\nmodelFormulasList = printRxnFormula(model, modelReactionNameList,0);\n[mapFormulasList, mapReactionNameList] = mapFormula(map, mapReactionNameList);\n\n% Deleting the stoechiometric numbers from the model formulas\nmodelFormulasList = regexprep(modelFormulasList, '[0-9.]+ ', '');\n\n% Initialising lists that will contain corresponding info on reactions\nwrong = 1;\nwrongList = [];\ndupl = 1;\nduplicateList = [];\nabs = 1;\nabsentMapList = [];\n\n% Looping over the model's reaction names\nfor rxn = 1:length(modelReactionNameList)\n % Test if the reaction name is contained in the map\n if any(strcmp(modelReactionNameList{rxn}, mapReactionNameList))\n % Getting the index of the model reaction name in the map list\n index = find(strcmp(modelReactionNameList{rxn}, mapReactionNameList));\n % Test if there is only one reaction with this name in the map\n if length(index) == 1\n % Deleting the stoechiometric numbers from the model formula\n % Splitting the model formula for further comparison\n modelFormulaSplit = strsplit(modelFormulasList{rxn}, {'<=>', '->'});\n leftModel = strtrim(strsplit(modelFormulaSplit{1}, '+'));\n rightModel = strtrim(strsplit(modelFormulaSplit{2}, '+'));\n % Splitting the map formula for further comparison\n mapFormulaSplit = strsplit(mapFormulasList{index}, {'<=>', '->'});\n leftMap = strtrim(strsplit(mapFormulaSplit{1}, '+'));\n rightMap = strtrim(strsplit(mapFormulaSplit{2}, '+'));\n % Testing if the formulas are different and storing the info\n leftTest = setxor(leftModel, leftMap);\n rightTest = setxor(rightModel, rightMap);\n if ~isempty(leftTest) || ~isempty(rightTest)\n wrongList.name{wrong} = mapReactionNameList{index};\n wrongList.ID{wrong} = map.rxnID{strcmp(modelReactionNameList{rxn}, map.rxnName)};\n wrongList.modelFormula{wrong} = modelFormulasList{rxn};\n wrongList.mapFormula{wrong} = mapFormulasList{index};\n wrong = wrong + 1;\n end\n % Case where a reaction name is duplicated in the map\n else\n % Finding the IDs of the duplicated reactions in the map\n duplicateIDs = map.rxnID(strcmp(modelReactionNameList{rxn}, map.rxnName));\n % Looping over the duplicates to get the relevant info\n for d = 1:length(index)\n duplicateList.name{dupl} = modelReactionNameList{rxn};\n duplicateList.modelFormula{dupl} = modelFormulasList{rxn};\n duplicateList.mapFormula{dupl} = mapFormulasList{index(d)};\n duplicateList.ID{dupl} = duplicateIDs{d};\n dupl = dupl + 1;\n end\n end\n % Case where reactions are absent in the map and present in the model\n else\n absentMapList.name{abs} = modelReactionNameList{rxn};\n absentMapList.modelFormula{abs} = modelFormulasList{rxn};\n abs = abs + 1;\n end\nend\n\nif ~isempty(wrongList)\n \n wrongTable = table(wrongList.name', wrongList.ID', wrongList.modelFormula', wrongList.mapFormula');\n wrongTable.Properties.VariableNames = {'rxnName', 'rxnID', 'modelFormula', 'mapFormula'};\n \nelse\n \n wrongTable = [];\n \nend\n\nif ~isempty(duplicateList)\n duplicateTable = table(duplicateList.name', duplicateList.ID', duplicateList.modelFormula', duplicateList.mapFormula');\n duplicateTable.Properties.VariableNames = {'rxnName', 'rxnID', 'modelFormula', 'mapFormula'};\nelse\n duplicateTable = [];\nend\n\nif ~isempty(absentMapList)\n absentMapTable = table(absentMapList.name', absentMapList.modelFormula');\n absentMapTable.Properties.VariableNames = {'rxnName', 'modelFormula'};\nelse\n absentMapTable = [];\nend\n\n% Finding reaction names in the map that are not present in the model\ndifferentMapRxnNamesList = setdiff(mapReactionNameList, modelReactionNameList);\n\nif ~isempty(differentMapRxnNamesList)\n % Finding reaction names in the map in case of multiple presence\n differentMapRxnNamesList = map.rxnName(ismember(map.rxnName, differentMapRxnNamesList));\n % Finding reaction ID in the map that are not present in the model\n differentMapRxnIdList = map.rxnID(ismember(map.rxnName, differentMapRxnNamesList));\n % Finding reaction formulas in the map that are not present in the model\n differentMapRxnFormulasList = mapFormulasList(ismember(mapReactionNameList, differentMapRxnNamesList));\n \n % Storing the relevant info on missing reactions in the model from the map\n absentModelTable = table(differentMapRxnNamesList, differentMapRxnIdList, differentMapRxnFormulasList);\n absentModelTable.Properties.VariableNames = {'rxnName', 'rxnID', 'mapFormula'};\nelse\n absentModelTable = [];\nend\n\nif nargin == 3\n % Commented part to use a possible Excel output.\n fileName = excelName;\n warning('off', 'MATLAB:xlswrite:AddSheet');\n if ~isempty(wrongTable)\n writetable(wrongTable, fileName, 'Sheet', 'wrongReactions')\n end\n if ~isempty(absentMapTable)\n writetable(absentMapTable, fileName, 'Sheet', 'absentFromMapReactions')\n end\n if ~isempty(absentModelTable)\n writetable(absentModelTable, fileName, 'Sheet', 'absentFromModelReactions')\n end\n if ~isempty(duplicateTable)\n writetable(duplicateTable, fileName, 'Sheet', 'duplicatedReactions')\n end\nend\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/visualization/metabolicCartography/compareModelMapFormulas.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.03161876498735074, "lm_q1q2_score": 0.012523185817590965}} {"text": "function test_example_ft_realtime_hilbert\n\n% MEM 4gb\n% WALLTIME 00:10:00\n\n%\n%% Realtime neurofeedback application based on Hilbert phase estimation\n%\n% This page describes the neurofeedback application that was developed by Marco Rotonda for his MSc thesis **\"Controllo volontario della sincronizzazione di fase intraemisferica nella banda gamma eeg mediante neurofeedback\"** (Voluntary control of intrahemispheric phase sychronization in the EEG gamma band using neurofeedback).\n%\n% The thesis (in Italian) which describes all details and the results is available [here](/assets/pdf/example/rt_hilbert/rotonda_thesis_msc.pdf).\n%\n% The signal analysis details are available [here](/assets/pdf/example/gamma_analisys.pdf).\n%\n% Neurofeedback, as the word suggest, is feeding back to the subject it's neuronal activity analyzed by it's EEG activity in (almost) real time. In this training we give back to the subjest a visual stimulation (vertical bars) when it's gamma phase synchronization between F3-P3 and F4-P4 increased over the baseline (bars up) or decreased (bars down).\n% Here is the feedback\n%\n%\n% If you scroll the script you can see that this image is a particular point of view of a 3D visualization. I you change the POV you could see all the data from the last 3 minutes.\n%\n%% # Procedure\n%\n% Get the FieldTripBufferDemo from the workshop_bci2000 folder on the FieldTrip FTP server and . Start BCI2000 and modifiy the config. The script works originally with 40 channels (see the variable 'lab' in the realtime_hilbert script), the samplingrate used is 1000Hz. Use a blocksize of 1000 samples. Ensure BCI2000 runs for more than 2 minutes in the application tab. Set config and start BCI2000.\n% Start MATLAB and in the shell type realtime_hilbert.\n%\n% Now it will start the function realtime_baseline that for 2 minutes will record the subject baseline and store the results for realtime_hilbert.\n% Basically there are 12 channels: 4 for EEG (I used F3-P3-F4-P4), 4 for the EOG, 4 for the EMG (front and neck). In this script, those are selected from the forty originally recorded channels you can find in the variable 'lab'.\n% The algorithm will care to take away both EOG and EMG artifacts.\n%\n%% # MATLAB code for ft_realtime_hilbert\n%\nfunction ft_realtime_hilbert()\n\n% FT_REALTIME_HILBERT is a neurofeedback application based on Hilbert phase estimation.\n%\n% Use as\n% ft_realtime_hilbert()\n% with the following configuration options that are coded inside the function\n% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'gui')\n% cfg.foilim = [Flow Fhigh] (default = [0 120])\n% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)\n% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'first')\n%\n% The source of the data is configured as\n% cfg.dataset = string\n% or alternatively to obtain more low-level control as\n% cfg.datafile = string ( es: cfg.datafile='buffer://localhost:1972';)\n% cfg.headerfile = string ( es: cfg.headerfile='buffer://localhost:1972';)\n% cfg.filename = string ( es: cfg.filename = 'buffer://localhost:1972';)\n% cfg.eventfile = string ( es: cfg.eventfile = 'buffer://localhost:1972';)\n% cfg.dataformat = string, default is determined automatic\n% cfg.headerformat = string, default is determined automatic\n% cfg.eventformat = string, default is determined automatic\n%\n% To stop the realtime function, you have to press Ctrl-C\n\n% Take off the warning message to avoid problems with ATAN2 and hilbert.\nwarning off all;\n\n% This is to save subject data\nstarttime= DATESTR(now, 30);\nsubjname = input('Insert the subject name.>>>>>', 's');\ntrialdata=strcat(starttime,subjname);\n\nrealtime_baseline(); %This it will launch the baseline script\n\nload means; % get means from file created by realtime_baseline\n\ncfg = [];\ncfg.datafile = 'buffer://localhost:1972';\ncfg.headerfile = 'buffer://localhost:1972';\ncfg.filename = 'buffer://localhost:1972';\n\n% set the default configuration options\nif ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically\nif ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically\nif ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically\nif ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % in seconds\nif ~isfield(cfg, 'overlap'), cfg.overlap = 0.5; end % in seconds\nif ~isfield(cfg, 'channel'), cfg.channel = {'all', '-Fp1', '-Fp2',...\n '-F7','-Fz','-F8','-FT7', '-FC3', '-FCz',...\n '-FC4', '-FT8', '-T3', '-C3', '-Cz', '-C4','-T4','-TP7',...\n '-CP3', '-CPz', '-CP4','-TP8','-A1', '-T5', '-Pz',...\n '-T6','-A2', '-O1', '-Oz', '-O2'};\nend % This will select F3 F4 P3 P4 for EEG\n % X1 X2 X3 X4 for EMG\n % X5 X6 X7 X8 for EOG\nif ~isfield(cfg, 'foilim'), cfg.foilim = [0.1 100]; end\nif ~isfield(cfg, 'bufferdata'), cfg.bufferdata='last'; end\n\n% translate dataset into datafile+headerfile\ncfg = ft_checkconfig(cfg, 'dataset2files', 'yes');\ncfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});\n\n% ensure that the persistent variables related to caching are cleared\nclear ft_read_header\n\n% start by reading the header from the realtime buffer\nhdr = ft_read_header(cfg.headerfile, 'cache', true);\n\n% define a subset of channels for reading\nlab=['X1 '; 'X2 '; 'Fp1'; 'Fp2'; 'X3 '; 'X4 '; 'F7 '; 'F3 '; 'Fz '; 'F4 ';...\n 'F8 ';'FT7'; 'FC3'; 'FCz'; 'FC4'; 'FT8'; 'T3 '; 'C3 '; 'Cz '; 'C4 ';...\n 'T4 ';'TP7'; 'CP3'; 'CPz'; 'CP4'; 'TP8'; 'A1 '; 'T5 '; 'P3 '; 'Pz ';...\n 'P4 '; 'T6 ';'A2 '; 'O1 '; 'Oz '; 'O2 '; 'X5 '; 'X6 '; 'X7 '; 'X8 '];\nlabel=cellstr(lab);\ncfg.channel = ft_channelselection(cfg.channel, label);\nchanindx = match_str(label, cfg.channel);\nnchan = length(chanindx);\nif nchan==0\n error('no channels were selected');\nend\n\n% determine the size of blocks to process\nblocksize = cfg.blocksize * hdr.Fs;\noverlap = cfg.overlap * hdr.Fs;\nprevSample = 0;\ncount = 0;\n\n% Create arrays that contains the rhos found\nvectordim = 360; % vector dimention for the lasts 3 minutes of data\nvl=zeros(vectordim,1); % the visual vector of data for left synchrony\nvr=zeros(vectordim,1); % the visual vector of data for right synchrony\nvl1=vl(1); % the first element of the vector for the visual feedback\nvr1=vr(1); % the first element of the vector for the visual feedback\n\n% This is the ratio above which accept the coherence\nmeanl = baselinel; % It has to be calculated from the baseline\nmeanr = baseliner; % It has to be calculated from the baseline\n\n% This is the mean above which no EMG feedback has given\nmeanf = baselinef+(stf*2); % It has to be calculated from the baseline\nmeann = baselinen+(stn*2); % It has to be calculated from the baseline\n\n% This is used to plot the feedback step\nfullscreen = get(0,'ScreenSize');\nfig1 = figure('NumberTitle','off', ...\n 'MenuBar','none', ...\n 'Units','pixels', ...\n 'Position',[0 0 fullscreen(3) fullscreen(4)]);\n\n% plot the feedback on the second monitor\n% set(gcf,'position',[1025,1,1024,768]);\n\n% fig2=figure;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% this is the general BCI loop where realtime incoming data is handled\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhile true\n\n % Create a matrix that contains the rhos found\n M = [vl vr]; %#ok``\n\n % Create a matrix for the visual feedback\n K = [vl1 vr1];\n\n % determine number of samples available in buffer\n hdr = ft_read_header(cfg.headerfile, 'cache', true);\n\n % see whether new samples are available\n newsamples = (hdr.nSamples*hdr.nTrials-prevSample);\n\n if newsamples>=blocksize\n\n % determine the samples to process\n if strcmp(cfg.bufferdata, 'last') && count==0\n begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;\n endsample = hdr.nSamples*hdr.nTrials;\n elseif strcmp(cfg.bufferdata, 'last')\n begsample = prevSample+1;\n endsample = prevSample+blocksize ;\n elseif strcmp(cfg.bufferdata, 'first')\n begsample = prevSample+1;\n endsample = prevSample+blocksize ;\n else\n error('unsupported value for cfg.bufferdata');\n end\n\n % this allows overlapping data segments\n if overlap && (begsample>overlap) %#ok``\n begsample = begsample - overlap;\n endsample = endsample - overlap;\n end\n\n % remember up to where the data was read\n prevSample = endsample;\n count = count + 1;\n % fprintf('processing segment %d from sample %d to %d\\n', count, begsample, endsample);\n\n % read data segment from buffer\n dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample,...\n 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % from here onward it is specific to the hilbert phase sinchronisation from the data %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % put the data in a fieldtrip-like raw structure\n data.trial{1} = dat;\n data.time{1} = offset2time(begsample, hdr.Fs, endsample-begsample+1);\n data.label = hdr.label(chanindx);\n data.hdr = hdr;\n data.fsample = hdr.Fs;\n\n % correction of EOG based on algoritm fro\n % Author: German Gomez-Herrero\n % german.gomezherrero@ieee.org\n % http://www.cs.tut.fi/~gomezher/index.htm\n % Institute of Signal Processing\n % Tampere University of Technology, 2007\n % Reference\n % [1] P. He et al., Med. Biol. Comput. 42 (2004), 407-412\n % [2] S. Haykin. Adaptive Filter Theory, (1996), Prentice Hall\n\n data.trial{2}(9,:)=data.trial{1}(9,:)-data.trial{1}(10,:);\n data.trial{2}(11,:)=data.trial{1}(11,:)-data.trial{1}(12,:);\n opt.refdata=[data.trial{2}(9,:);data.trial{2}(11,:)];\n [data.trial{3}] = crls_regression(data.trial{1}(5:8,:), opt);\n\n % Build a FIR filter for EMG correction\n N = 150; % Order\n gammaband = [35 45];\n emgband = [60 80];\n emgfnband = [60 499];\n flag = 'scale'; % Sampling Flag\n Beta = 0.9; % Window Parameter\n win = kaiser(N+1, Beta);\n\n % Correction between EMG and EEG based on Sheer D.E. \"Biofeedback training\n % of 40-Hz eeg and behavior\", pp. 325-362, on Behavior and\n % brain electrical activity (1975), Plenum Press. New York\n\n gammafilter = fir1(N, gammaband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltgamma1 = filtfilt(gammafilter,1,data.trial{1}(5,:));\n datfiltgamma2 = filtfilt(gammafilter,1,data.trial{1}(6,:));\n datfiltgamma3 = filtfilt(gammafilter,1,data.trial{1}(7,:));\n datfiltgamma4 = filtfilt(gammafilter,1,data.trial{1}(8,:));\n datfiltgamma = [datfiltgamma1; datfiltgamma2; datfiltgamma3; datfiltgamma4];\n\n emgfilter = fir1(N, emgband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltemg1 = filtfilt(emgfilter,1,data.trial{1}(5,:));\n datfiltemg2 = filtfilt(emgfilter,1,data.trial{1}(6,:));\n datfiltemg3 = filtfilt(emgfilter,1,data.trial{1}(7,:));\n datfiltemg4 = filtfilt(emgfilter,1,data.trial{1}(8,:));\n datfiltemg = [datfiltemg1; datfiltemg2; datfiltemg3; datfiltemg4];\n\n datfiltemgsqr = datfiltemg.^2;\n datfiltgammasqr = datfiltgamma.^2;\n datfiltcrossqr = (datfiltemg.*datfiltgamma).^2;\n\n correction = datfiltgammasqr-(datfiltcrossqr./datfiltemgsqr);\n\n data.trial{3}(5:8,:) = datfiltgamma - correction;\n\n % Find the EMG on forehead and neck\n data.trial{2}(1,:)=data.trial{1}(1,:)-data.trial{1}(2,:); % Frontal electrods\n data.trial{2}(3,:)=data.trial{1}(3,:)-data.trial{1}(4,:); % Neck electrods\n emgfnfilter = fir1(N, emgfnband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltemgf = filter(emgfnfilter,1,data.trial{2}(1,:));\n datfiltemgn = filter(emgfnfilter,1,data.trial{2}(3,:));\n datfiltemgf = abs(datfiltemgf);\n datfiltemgn = abs(datfiltemgn);\n extrMaxValuef = datfiltemgf(find(diff(sign(diff(datfiltemgf)))==-2)+1);\n extrMaxValuen = datfiltemgn(find(diff(sign(diff(datfiltemgn)))==-2)+1);\n extrMaxIndexf = find(diff(sign(diff(datfiltemgf)))==-2)+1;\n extrMaxIndexn = find(diff(sign(diff(datfiltemgn)))==-2)+1;\n upf = extrMaxValuef;\n upn = extrMaxValuen;\n upf_t = data.time{1}(extrMaxIndexf);\n upn_t = data.time{1}(extrMaxIndexn);\n upf = interp1(upf_t,upf,data.time{1},'linear');\n upn = interp1(upn_t,upn,data.time{1},'linear');\n emgfmean = nanmean (upf'); %#ok``\n emgnmean = nanmean (upn'); %#ok``\n % plot(data.time{1},upf,'r')\n\n%\n % Istantaneous (proto)phase difference found via Hilbert\n % Based on Pikovsky, A. R. (2001). Synchronization. A Universal\n % Concept In Nonlinear Sciences. Cambridge: Cambridge University\n % Press, pag. 368 A2.7\n\n % crate the data needed for phase coherence index\n chan1=data.trial{3}(5,:); % F3\n chan2=data.trial{3}(6,:); % F4\n chan3=data.trial{3}(7,:); % P3\n chan4=data.trial{3}(8,:); % P4\n chan1h = hilbert(chan1);\n chan2h = hilbert(chan2);\n chan3h = hilbert(chan3);\n chan4h = hilbert(chan4);\n chan1hi = imag(chan1h);\n chan2hi = imag(chan2h);\n chan3hi = imag(chan3h);\n chan4hi = imag(chan4h);\n\n % find the istantaneous left hemisphere (proto)phase difference\n phil = atan2(((chan1hi .* chan3)-(chan1 .* chan3hi)),...\n ((chan1 .* chan3)+(chan1hi .* chan3hi)));\n\n % find the istantaneous right hemisphere (proto)phase difference\n phir = atan2(((chan2hi .* chan4)-(chan2 .* chan4hi)),...\n ((chan2 .* chan4)+(chan2hi .* chan4hi)));\n\n % find the right hemisphere synchronization index\n sumsinr = sum(sin(phir))/blocksize;\n sumcosr = sum(cos(phir))/blocksize;\n rhor = sqrt(sumsinr.^2 + sumcosr.^2);\n\n % find the left hemisphere synchronization index\n sumsinl = sum(sin(phil))/blocksize;\n sumcosl = sum(cos(phil))/blocksize;\n rhol = sqrt(sumsinl.^2 + sumcosl.^2);\n\n % Give the visual feedback\n if (meanf>emgfmean) && (meann>emgnmean)\n clf;\n visual = bar3(K,0.3);\n view([-90 0]);\n grid off;\n shading interp;\n for i = 1:length(visual)\n zdata = get(visual(i),'Zdata');\n set(visual(i),'Cdata',zdata,'EdgeColor','none')\n colormap hot;\n end\n set(gca,'ZColor',[0.8 0.8 0.8],'Zlim',[-1 1],'YColor',[0.8 0.8 0.8],...\n 'Ylim',[0 3],'XColor',[0.8 0.8 0.8],'Xlim',[0.85 1.15],...\n 'Color',[0.8 0.8 0.8],'CLim', [-1 1]);\n\n % Create colorbar\n colorbar([0.5 0.148 0.02 0.73],'ZColor',[0.8 0.8 0.8],'YTick',[],...\n 'YColor',[0.8 0.8 0.8],'XColor',[0.8 0.8 0.8]);\n\n % Create textboxes\n annotation('textbox',[0.496 0.89 0.03 0.04],'String',{'+'},...\n 'HorizontalAlignment','center','FontSize',20,'FitBoxToText','off','EdgeColor','none');\n annotation('textbox',[0.50 0.11 0.02 0.04],'String',{'-'},...\n 'HorizontalAlignment','center','FontSize',20,'FitBoxToText','off','EdgeColor','none');\n annotation('textbox',[0.25 0.49 0.05 0.07],'String',{'Emisfero','sinistro'},...\n 'HorizontalAlignment','center','FontSize',14,'FitBoxToText','off','EdgeColor','none');\n annotation('textbox',[0.735 0.49 0.05 0.07],'String',{'Emisfero','destro'},...\n 'HorizontalAlignment','center','FontSize',14,'FitBoxToText','off','EdgeColor','none');\n\n %create a copy of the plot for the experimenter\n % h1=gcf;\n % h2=figure;\n % objects=allchild(h1);\n % fig2=copyobj(get(h1,'children'),h2);\n\n % force MATLAB to update the figure\n drawnow ;\n\n % add the step to the array for the feedback and upgrade the M\n % for the final performance plot\n\n vl = vl([end 1:end-1]);\n vl(1)=rhol-meanl;\n vl1=vl(1);\n\n vr = vr([end 1:end-1]);\n vr(1)=rhor-meanr;\n vr1=vr(1);\n\n elseif emgfmean>meanf\n clf;\n set(gca,'ZColor',[0.8 0.8 0.8],'Zlim',[0 1],'YColor',[0.8 0.8 0.8],...\n 'Ylim',[0 3],'XColor',[0.8 0.8 0.8],'Xlim',[0.85 1.15],...\n 'OuterPosition', [-0.0175 0.185 1 0.605],...\n 'Color',[0.8 0.8 0.8],'CLim', [-50 50]);\n annotation(fig1,'textbox',[0.20 0.35 0.6292 0.1929],...\n 'String',{'Rilassa i muscoli della fronte'},...\n 'HorizontalAlignment','center','FontSize',20,'FitBoxToText','off','EdgeColor','none',...\n 'Color',[1 0 0]);\n drawnow ;\n\n elseif emgnmean>meann\n clf;\n set(gca,'ZColor',[0.8 0.8 0.8],'Zlim',[0 1],'YColor',[0.8 0.8 0.8],...\n 'Ylim',[0 3],'XColor',[0.8 0.8 0.8],'Xlim',[0.85 1.15],...\n 'OuterPosition', [-0.0175 0.185 1 0.605],...\n 'Color',[0.8 0.8 0.8],'CLim', [-1 1]);\n annotation(fig1,'textbox',[0.20 0.35 0.6292 0.1929],...\n 'String',{'Rilassa i muscoli del collo'},...\n 'HorizontalAlignment','center','FontSize',20,'FitBoxToText','off','EdgeColor','none',...\n 'Color',[1 0 0]);\n drawnow ;\n\n end % end feedbacks\n\n end % if enough new samples\n\n if count > vectordim\n cd 'C:\\TEST\\hilbert\\risultati';\n save (trialdata);\n save hilbert.mat;\n close all hidden;\n cd 'C:\\TEST';\n break;\n end\n\nend % while true\n\n%% # MATLAB code for ft_realtime_baseline\n%\nfunction ft_realtime_baseline()\n\n% FT_REALTIME_BASELINE is a neurofeedback application based on Hilbert phase estimation.\n%\n% Use as\n% ft_realtime_baseline()\n% with the following configuration options that are coded inside the function\n% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'gui')\n% cfg.foilim = [Flow Fhigh] (default = [0 120])\n% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)\n% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'first')\n%\n% The source of the data is configured as\n% cfg.dataset = string\n% or alternatively to obtain more low-level control as\n% cfg.datafile = string ( es: cfg.datafile='buffer://localhost:1972';)\n% cfg.headerfile = string ( es: cfg.headerfile='buffer://localhost:1972';)\n% cfg.filename = string ( es: cfg.filename = 'buffer://localhost:1972';)\n% cfg.eventfile = string ( es: cfg.eventfile = 'buffer://localhost:1972';)\n% cfg.dataformat = string, default is determined automatic\n% cfg.headerformat = string, default is determined automatic\n% cfg.eventformat = string, default is determined automatic\n%\n% To stop the realtime function, you have to press Ctrl-C\n\n%Take off the warning message to avoid problems with ATAN2 and hilbert.\nwarning off all;\n\ncfg = [];\ncfg.datafile = 'buffer://localhost:1972';\ncfg.headerfile = 'buffer://localhost:1972';\ncfg.filename = 'buffer://localhost:1972';\n\n% set the default configuration options\nif ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically\nif ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically\nif ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically\nif ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % in seconds\nif ~isfield(cfg, 'overlap'), cfg.overlap = 0.5; end % in seconds\nif ~isfield(cfg, 'channel'), cfg.channel = {'all', '-Fp1', '-Fp2',...\n '-F7','-Fz','-F8','-FT7', '-FC3', '-FCz',...\n '-FC4', '-FT8', '-T3', '-C3', '-Cz', '-C4','-T4','-TP7',...\n '-CP3', '-CPz', '-CP4','-TP8','-A1', '-T5', '-Pz',...\n '-T6','-A2', '-O1', '-Oz', '-O2'};\nend % This will select F3 F4 P3 P4 for EEG\n % X1 X2 X3 X4 for EMG\n % X5 X6 X7 X8 for EOG\nif ~isfield(cfg, 'foilim'), cfg.foilim = [0.1 100]; end\nif ~isfield(cfg, 'bufferdata'), cfg.bufferdata='last'; end\n\n% translate dataset into datafile+headerfile\ncfg = checkconfig(cfg, 'dataset2files', 'yes');\ncfg = checkconfig(cfg, 'required', {'datafile' 'headerfile'});\n\n% ensure that the persistent variables related to caching are cleared\nclear ft_read_header\n\n% start by reading the header from the realtime buffer\nhdr = ft_read_header(cfg.headerfile, 'cache', true);\n\n% define a subset of channels for reading\nlab=['X1 '; 'X2 '; 'Fp1'; 'Fp2'; 'X3 '; 'X4 '; 'F7 '; 'F3 '; 'Fz '; 'F4 ';...\n 'F8 ';'FT7'; 'FC3'; 'FCz'; 'FC4'; 'FT8'; 'T3 '; 'C3 '; 'Cz '; 'C4 ';...\n 'T4 ';'TP7'; 'CP3'; 'CPz'; 'CP4'; 'TP8'; 'A1 '; 'T5 '; 'P3 '; 'Pz ';...\n 'P4 '; 'T6 ';'A2 '; 'O1 '; 'Oz '; 'O2 '; 'X5 '; 'X6 '; 'X7 '; 'X8 '];\nlabel=cellstr(lab);\ncfg.channel = ft_channelselection(cfg.channel, label);\nchanindx = match_str(label, cfg.channel);\nnchan = length(chanindx);\nif nchan==0\n error('no channels were selected');\nend\n\n% determine the size of blocks to process\nblocksize = cfg.blocksize * hdr.Fs;\noverlap = cfg.overlap * hdr.Fs;\nprevSample = 0;\ncount = 0;\n\n% Create arrays that contains the rhos found\nnummaxarray = 240; % the step is 500ms so 240 are 2 minutes\ni=1;\nvlmean=zeros(1,nummaxarray);\nvrmean=zeros(1,nummaxarray);\nfrontmeans=zeros(1,nummaxarray);\nneckmeans=zeros(1,nummaxarray);\n\n% This is used to plot the screen for the subject\nfullscreen = get(0,'ScreenSize');\nfig1 = figure('NumberTitle','off', ...\n 'MenuBar','none', ...\n 'Units','pixels', ...\n 'Position',[0 0 fullscreen(3) fullscreen(4)]);\n\n% plot the feedback on the second monitor\n% set(gcf,'position',[1025,1,1024,768]);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% this is the general BCI loop where realtime incoming data is handled\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nwhile true\n\n % determine number of samples available in buffer\n hdr = ft_read_header(cfg.headerfile, 'cache', true);\n\n % see whether new samples are available\n newsamples = (hdr.nSamples*hdr.nTrials-prevSample);\n\n if newsamples>=blocksize\n\n % determine the samples to process\n if strcmp(cfg.bufferdata, 'last') && count==0\n begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;\n endsample = hdr.nSamples*hdr.nTrials;\n elseif strcmp(cfg.bufferdata, 'last')\n begsample = prevSample+1;\n endsample = prevSample+blocksize ;\n elseif strcmp(cfg.bufferdata, 'first')\n begsample = prevSample+1;\n endsample = prevSample+blocksize ;\n else\n error('unsupported value for cfg.bufferdata');\n end\n\n % this allows overlapping data segments\n if overlap && (begsample>overlap) %#ok``\n begsample = begsample - overlap;\n endsample = endsample - overlap;\n end\n\n % remember up to where the data was read\n prevSample = endsample;\n count = count + 1;\n % fprintf('processing segment %d from sample %d to %d\\n', count, begsample, endsample);\n\n % read data segment from buffer\n dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % from here onward it is specific to the hilbert phase sinchronisation from the data %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n % put the data in a fieldtrip-like raw structure\n data.trial{1} = dat;\n data.time{1} = offset2time(begsample, hdr.Fs, endsample-begsample+1);\n data.label = hdr.label(chanindx);\n data.hdr = hdr;\n data.fsample = hdr.Fs;\n\n % correction of EOG based on algoritm fro\n % Author: German Gomez-Herrero\n % german.gomezherrero@ieee.org\n % http://www.cs.tut.fi/~gomezher/index.htm\n % Institute of Signal Processing\n % Tampere University of Technology, 2007\n % Reference\n % [1] P. He et al., Med. Biol. Comput. 42 (2004), 407-412\n % [2] S. Haykin. Adaptive Filter Theory, (1996), Prentice Hall\n\n data.trial{2}(9,:)=data.trial{1}(9,:)-data.trial{1}(10,:);\n data.trial{2}(11,:)=data.trial{1}(11,:)-data.trial{1}(12,:);\n opt.refdata=[data.trial{2}(9,:);data.trial{2}(11,:)];\n [data.trial{3}] = crls_regression(data.trial{1}(5:8,:), opt);\n\n % Build a FIR filter for EMG correction\n N = 150; % Order\n gammaband = [35 45];\n emgband = [60 80];\n emgfnband = [60 499];\n flag = 'scale'; % Sampling Flag\n Beta = 0.9; % Window Parameter\n win = kaiser(N+1, Beta);\n\n % Correction between EMG and EEG based on Sheer D.E. \"Biofeedback training\n % of 40-Hz eeg and behavior\", pp. 325-362, on Behavior and\n % brain electrical activity (1975), Plenum Press. New York\n\n gammafilter = fir1(N, gammaband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltgamma1 = filtfilt(gammafilter,1,data.trial{1}(5,:));\n datfiltgamma2 = filtfilt(gammafilter,1,data.trial{1}(6,:));\n datfiltgamma3 = filtfilt(gammafilter,1,data.trial{1}(7,:));\n datfiltgamma4 = filtfilt(gammafilter,1,data.trial{1}(8,:));\n datfiltgamma = [datfiltgamma1; datfiltgamma2; datfiltgamma3; datfiltgamma4];\n\n emgfilter = fir1(N, emgband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltemg1 = filtfilt(emgfilter,1,data.trial{1}(5,:));\n datfiltemg2 = filtfilt(emgfilter,1,data.trial{1}(6,:));\n datfiltemg3 = filtfilt(emgfilter,1,data.trial{1}(7,:));\n datfiltemg4 = filtfilt(emgfilter,1,data.trial{1}(8,:));\n datfiltemg = [datfiltemg1; datfiltemg2; datfiltemg3; datfiltemg4];\n\n datfiltemgsqr = datfiltemg.^2;\n datfiltgammasqr = datfiltgamma.^2;\n datfiltcrossqr = (datfiltemg.*datfiltgamma).^2;\n\n correction = datfiltgammasqr-(datfiltcrossqr./datfiltemgsqr);\n\n data.trial{3}(5:8,:) = datfiltgamma - correction;\n\n % Find the EMG on forehead and neck\n data.trial{2}(1,:)=data.trial{1}(1,:)-data.trial{1}(2,:); % Frontal electrods\n data.trial{2}(3,:)=data.trial{1}(3,:)-data.trial{1}(4,:); % Neck electrods\n emgfnfilter = fir1(N, emgfnband/(hdr.Fs/2), 'bandpass', win, flag);\n datfiltemgf = filter(emgfnfilter,1,data.trial{2}(1,:));\n datfiltemgn = filter(emgfnfilter,1,data.trial{2}(3,:));\n datfiltemgf = abs(datfiltemgf);\n datfiltemgn = abs(datfiltemgn);\n extrMaxValuef = datfiltemgf(find(diff(sign(diff(datfiltemgf)))==-2)+1);\n extrMaxValuen = datfiltemgn(find(diff(sign(diff(datfiltemgn)))==-2)+1);\n extrMaxIndexf = find(diff(sign(diff(datfiltemgf)))==-2)+1;\n extrMaxIndexn = find(diff(sign(diff(datfiltemgn)))==-2)+1;\n upf = extrMaxValuef;\n upn = extrMaxValuen;\n upf_t = data.time{1}(extrMaxIndexf);\n upn_t = data.time{1}(extrMaxIndexn);\n upf = interp1(upf_t,upf,data.time{1},'linear');\n upn = interp1(upn_t,upn,data.time{1},'linear');\n emgfmean = nanmean (upf'); %#ok``\n emgnmean = nanmean (upn'); %#ok``\n % plot(data.time{1},upf,'r')\n\n%\n % Istantaneous (proto)phase difference found via Hilbert\n % Based on Pikovsky, A. R. (2001). Synchronization. A Universal\n % Concept In Nonlinear Sciences. Cambridge: Cambridge University\n % Press, pag. 368 A2.7\n\n % crate the data needed for phase coherence index\n chan1=data.trial{3}(5,:); % F3\n chan2=data.trial{3}(6,:); % F4\n chan3=data.trial{3}(7,:); % P3\n chan4=data.trial{3}(8,:); % P4\n chan1h = hilbert(chan1);\n chan2h = hilbert(chan2);\n chan3h = hilbert(chan3);\n chan4h = hilbert(chan4);\n chan1hi = imag(chan1h);\n chan2hi = imag(chan2h);\n chan3hi = imag(chan3h);\n chan4hi = imag(chan4h);\n\n % find the istantaneous left hemisphere (proto)phase difference\n phil = atan2(((chan1hi .* chan3)-(chan1 .* chan3hi)),...\n ((chan1 .* chan3)+(chan1hi .* chan3hi)));\n\n % find the istantaneous right hemisphere (proto)phase difference\n phir = atan2(((chan2hi .* chan4)-(chan2 .* chan4hi)),...\n ((chan2 .* chan4)+(chan2hi .* chan4hi)));\n\n % find the right hemisphere synchronization index\n sumsinr = sum(sin(phir))/blocksize;\n sumcosr = sum(cos(phir))/blocksize;\n rhor = sqrt(sumsinr.^2 + sumcosr.^2);\n\n % find the left hemisphere synchronization index\n sumsinl = sum(sin(phil))/blocksize;\n sumcosl = sum(cos(phil))/blocksize;\n rhol = sqrt(sumsinl.^2 + sumcosl.^2);\n\n % update the array for the mean\n vlmean(i)=rhol;\n vrmean(i)=rhor;\n frontmeans(i)=emgfmean;\n neckmeans(i)=emgnmean;\n\n i=i+1;\n\n end % if enough new samples\n\n % screen for the subject\n clf;\n set(gca,'ZColor',[0.8 0.8 0.8],'Zlim',[-50 50],'YColor',[0.8 0.8 0.8],...\n 'Ylim',[0 3],'XColor',[0.8 0.8 0.8],'Xlim',[0.85 1.15],...\n 'DataAspectRatio',[0.2 0.1 3],'OuterPosition', [-0.0175 0.185 1 0.605],...\n 'Color',[0.8 0.8 0.8],'CLim', [-50 50]);\n annotation(fig1,'textbox',[0.18 0.35 0.6292 0.1929],...\n 'String',{'Rilassati mantenendo gli occhi aperti'},...\n 'HorizontalAlignment','center','FontSize',20,'FitBoxToText','off','EdgeColor','none',...\n 'Color',[1 0 0]);\n drawnow ;\n\n if count > (nummaxarray-1)\n close all hidden;\n break;\n end\n\nend % while true\n\n% print the mean baseline\nbaselinel = mean (vlmean);\nfprintf ('mean baseline left= %d \\n', baselinel);\nbaseliner = mean (vrmean);\nfprintf ('mean baseline right= %d \\n', baseliner);\nbaselinef = mean (frontmeans);\nfprintf ('mean baseline forehead= %d \\n', baselinef);\nbaselinen = mean (neckmeans);\nfprintf ('mean baseline neck= %d \\n', baselinen);\nstf = std(frontmeans);\nfprintf ('Std baseline front= %d \\n', stf);\nstn = std(neckmeans);\nfprintf ('Std baseline neck= %d \\n', stn);\n\nsave means.mat; % save to the working folder - (edit jonaweber 2010)\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_example_ft_realtime_hilbert20220113.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.029760096957802195, "lm_q1q2_score": 0.012460460186622778}} {"text": "%% AI Clinician Building MIMIC-III dataset \n\n% (c) Matthieu Komorowski, Imperial College London 2015-2019\n% as seen in publication: https://www.nature.com/articles/s41591-018-0213-5\n\n% version 16 Feb 19\n% uses the sepsis-3 cohort previously defined\n% builds the MIMIC-III dataset\n\n% This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE\n\n%% ########################################################################\n% INITIAL REFORMAT WITH CHARTEVENTS, LABS AND MECHVENT\n% ########################################################################\n\n% gives an array with all unique charttime (1 per row) and all items in columns.\n% ################## IMPORTANT !!!!!!!!!!!!!!!!!!\n% Here i use -24 -> +48 because that's for the MDP\n\n\nreformat=NaN(2000000,68); %final table \nqstime=zeros(100000,4);\nwinb4=25; %lower limit for inclusion of data (48h before time flag)\nwinaft=49; % upper limit (24h after)\nirow=1; %recording row for summary table\nh = waitbar(0,'Initializing waitbar...');\n\ntic\nfor icustayidrow=1:size(sepsis,1)\n \nqst=sepsis.sepsis_time(icustayidrow);%,3); %flag for presumed infection\nicustayid=sepsis.icustayid(icustayidrow)-200000;\nwaitbar(icustayidrow/size(sepsis,1),h,icustayidrow/size(sepsis,1)*100) %moved here to save some time\n\n\n% CHARTEVENTS\n if icustayid<10000\n temp=ce010(ce010(:,1)==icustayid+200000,:);\n elseif icustayid>=10000 & icustayid<20000\n temp=ce1020(ce1020(:,1)==icustayid+200000,:);\n elseif icustayid>=20000 & icustayid<30000\n temp=ce2030(ce2030(:,1)==icustayid+200000,:);\n elseif icustayid>=30000 && icustayid<40000\n temp=ce3040(ce3040(:,1)==icustayid+200000,:);\n elseif icustayid>=40000 & icustayid<50000\n temp=ce4050(ce4050(:,1)==icustayid+200000,:);\n elseif icustayid>=50000 & icustayid<60000\n temp=ce5060(ce5060(:,1)==icustayid+200000,:);\n elseif icustayid>=60000 & icustayid<70000\n temp=ce6070(ce6070(:,1)==icustayid+200000,:);\n elseif icustayid>=70000 & icustayid<80000\n temp=ce7080(ce7080(:,1)==icustayid+200000,:);\n elseif icustayid>=80000 & icustayid<90000\n temp=ce8090(ce8090(:,1)==icustayid+200000,:);\n elseif icustayid>=90000\n temp=ce90100(ce90100(:,1)==icustayid+200000,:);\n end\n\nii=temp(:,2)>= qst-(winb4+4)*3600 & temp(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp=temp(ii,:); %only time period of interest\n\n%LABEVENTS\nii=labU(:,1)==icustayid+200000;\ntemp2=labU(ii,:);\nii=temp2(:,2)>= qst-(winb4+4)*3600 & temp2(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp2=temp2(ii,:); %only time period of interest\n\n%Mech Vent + ?extubated\nii=MV(:,1)==icustayid+200000;\ntemp3=MV(ii,:);\nii=temp3(:,2)>= qst-(winb4+4)*3600 & temp3(:,2)<=qst+(winaft+4)*3600; %time period of interest -4h and +4h\ntemp3=temp3(ii,:); %only time period of interest\n\nt=unique([temp(:,2);temp2(:,2); temp3(:,2)]); %list of unique timestamps from all 3 sources / sorted in ascending order\n\nif t\nfor i=1:numel(t)\n \n %CHARTEVENTS\n ii=temp(:,2)==t(i);\n col=temp(ii,3);\n value=temp(ii,4); \n reformat(irow,1)=i; %timestep \n reformat(irow,2)=icustayid;\n reformat(irow,3)=t(i); %charttime\n reformat(irow,3+col)=value; %store available values\n \n %LAB VALUES\n ii=temp2(:,2)==t(i);\n col=temp2(ii,3);\n value=temp2(ii,4);\n reformat(irow,31+col)=value; %store available values\n \n %MV \n ii=temp3(:,2)==t(i);\n if nansum(ii)>0\n value=temp3(ii,3:4);\n reformat(irow,67:68)=value; %store available values\n else\n reformat(irow,67:68)=NaN;\n end\n \n irow=irow+1;\n \nend\n\nqstime(icustayid,1)=qst; %time of sepsis\n%HERE I SAVE FIRST and LAST TIMESTAMPS, in QSTIME, for each ICUSTAYID\nqstime(icustayid,2)=t(1); %first timestamp\nqstime(icustayid,3)=t(end); %last timestamp\nqstime(icustayid,4)=table2array(demog(demog.icustay_id==icustayid+200000,5)); % discharge time\n\nend\n\n% end\nend\ntoc\n\nclose(h);\nreformat(irow:end,:)=[]; %delete extra unused rows\n\n\n%% ########################################################################\n% OUTLIERS \n% ########################################################################\n\n%weight\nreformat=deloutabove(reformat,5,300); %delete outlier above a threshold (300 kg), for variable # 5\n\n%HR\nreformat=deloutabove(reformat,8,250);\n\n%BP\nreformat=deloutabove(reformat,9,300);\nreformat=deloutbelow(reformat,10,0);\nreformat=deloutabove(reformat,10,200);\nreformat=deloutbelow(reformat,11,0);\nreformat=deloutabove(reformat,11,200);\n\n%RR\nreformat=deloutabove(reformat,12,80);\n\n%SpO2\nreformat=deloutabove(reformat,13,150);\nii=reformat(:,13)>100;reformat(ii,13)=100;\nreformat=deloutbelow(reformat,13,50);\n\n%temp\nii=reformat(:,14)>90 & isnan(reformat(:,15));reformat(ii,15)=reformat(ii,14);\nreformat=deloutabove(reformat,14,90);\nreformat=deloutbelow(reformat,14,25);\n\n%interface / is in col 22\n\n% FiO2\nreformat=deloutabove(reformat,23,100);\nii=reformat(:,23)<1;reformat(ii,23)=reformat(ii,23)*100;\nreformat=deloutbelow(reformat,23,20);\nreformat=deloutabove(reformat,24,1.5);\n\n% O2 FLOW\nreformat=deloutabove(reformat,25,70);\n\n%PEEP\nreformat=deloutbelow(reformat,26,0);\nreformat=deloutabove(reformat,26,40);\n\n%TV\nreformat=deloutabove(reformat,27,1800);\n\n%MV\nreformat=deloutabove(reformat,28,50);\n\n%K+\nreformat=deloutbelow(reformat,32,1);\nreformat=deloutabove(reformat,32,15);\n\n%Na\nreformat=deloutbelow(reformat,33,95);\nreformat=deloutabove(reformat,33,178);\n\n%Cl\nreformat=deloutbelow(reformat,34,70);\nreformat=deloutabove(reformat,34,150);\n\n%Glc\nreformat=deloutbelow(reformat,35,1);\nreformat=deloutabove(reformat,35,1000);\n\n%Creat\nreformat=deloutabove(reformat,37,150);\n\n%Mg\nreformat=deloutabove(reformat,38,10);\n\n%Ca\nreformat=deloutabove(reformat,39,20);\n\n%ionized Ca\nreformat=deloutabove(reformat,40,5);\n\n%CO2\nreformat=deloutabove(reformat,41,120);\n\n%SGPT/SGOT\nreformat=deloutabove(reformat,42,10000);\nreformat=deloutabove(reformat,43,10000);\n\n%Hb/Ht\nreformat=deloutabove(reformat,50,20);\nreformat=deloutabove(reformat,51,65);\n\n%WBC\nreformat=deloutabove(reformat,53,500);\n\n%plt\nreformat=deloutabove(reformat,54,2000);\n\n%INR\nreformat=deloutabove(reformat,58,20);\n\n%pH\nreformat=deloutbelow(reformat,59,6.7);\nreformat=deloutabove(reformat,59,8);\n\n%po2\nreformat=deloutabove(reformat,60,700);\n\n%pco2\nreformat=deloutabove(reformat,61,200);\n\n%BE\nreformat=deloutbelow(reformat,62,-50);\n\n%lactate\nreformat=deloutabove(reformat,63,30);\n\n% ####################################################################\n% some more data manip / imputation from existing values\n\n% estimate GCS from RASS - data from Wesley JAMA 2003\nii=isnan(reformat(:,6))&reformat(:,7)>=0;\nreformat(ii,6)=15;\nii=isnan(reformat(:,6))&reformat(:,7)==-1;\nreformat(ii,6)=14;\nii=isnan(reformat(:,6))&reformat(:,7)==-2;\nreformat(ii,6)=12;\nii=isnan(reformat(:,6))&reformat(:,7)==-3;\nreformat(ii,6)=11;\nii=isnan(reformat(:,6))&reformat(:,7)==-4;\nreformat(ii,6)=6;\nii=isnan(reformat(:,6))&reformat(:,7)==-5;\nreformat(ii,6)=3;\n\n\n% FiO2\nii=~isnan(reformat(:,23)) & isnan(reformat(:,24));\nreformat(ii,24)=reformat(ii,23)./100;\nii=~isnan(reformat(:,24)) & isnan(reformat(:,23));\nreformat(ii,23)=reformat(ii,24).*100;\n\n\n%ESTIMATE FiO2 /// with use of interface / device (cannula, mask, ventilator....)\n\nreformatsah=SAH(reformat,sample_and_hold); % do SAH first to handle this task\n\n%NO FiO2, YES O2 flow, no interface OR cannula\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&(reformatsah(:,22)==0|reformatsah(:,22)==2)); \nreformat(ii(reformatsah(ii,25)<=15),23)=70;\nreformat(ii(reformatsah(ii,25)<=12),23)=62;\nreformat(ii(reformatsah(ii,25)<=10),23)=55;\nreformat(ii(reformatsah(ii,25)<=8),23)=50;\nreformat(ii(reformatsah(ii,25)<=6),23)=44;\nreformat(ii(reformatsah(ii,25)<=5),23)=40;\nreformat(ii(reformatsah(ii,25)<=4),23)=36;\nreformat(ii(reformatsah(ii,25)<=3),23)=32;\nreformat(ii(reformatsah(ii,25)<=2),23)=28;\nreformat(ii(reformatsah(ii,25)<=1),23)=24;\n\n%NO FiO2, NO O2 flow, no interface OR cannula\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&(reformatsah(:,22)==0|reformatsah(:,22)==2)); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=21;\n\n%NO FiO2, YES O2 flow, face mask OR.... OR ventilator (assume it's face mask)\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&(reformatsah(:,22)==NaN|reformatsah(:,22)==1|reformatsah(:,22)==3|reformatsah(:,22)==4|reformatsah(:,22)==5|reformatsah(:,22)==6|reformatsah(:,22)==9|reformatsah(:,22)==10)); \nreformat(ii(reformatsah(ii,25)<=15),23)=75;\nreformat(ii(reformatsah(ii,25)<=12),23)=69;\nreformat(ii(reformatsah(ii,25)<=10),23)=66;\nreformat(ii(reformatsah(ii,25)<=8),23)=58;\nreformat(ii(reformatsah(ii,25)<=6),23)=40;\nreformat(ii(reformatsah(ii,25)<=4),23)=36;\n\n%NO FiO2, NO O2 flow, face mask OR ....OR ventilator\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&(reformatsah(:,22)==NaN|reformatsah(:,22)==1|reformatsah(:,22)==3|reformatsah(:,22)==4|reformatsah(:,22)==5|reformatsah(:,22)==6|reformatsah(:,22)==9|reformatsah(:,22)==10)); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=NaN;\n\n%NO FiO2, YES O2 flow, Non rebreather mask\nii=find(isnan(reformatsah(:,23))&~isnan(reformatsah(:,25))&reformatsah(:,22)==7); \nreformat(ii(reformatsah(ii,25)>=10),23)=90;\nreformat(ii(reformatsah(ii,25)>=15),23)=100;\nreformat(ii(reformatsah(ii,25)<10),23)=80;\nreformat(ii(reformatsah(ii,25)<=8),23)=70;\nreformat(ii(reformatsah(ii,25)<=6),23)=60;\n\n%NO FiO2, NO O2 flow, NRM\nii=find(isnan(reformatsah(:,23))&isnan(reformatsah(:,25))&reformatsah(:,22)==7); %no fio2 given and o2flow given, no interface OR cannula\nreformat(ii,23)=NaN;\n\n% update again FiO2 columns\nii=~isnan(reformat(:,23)) & isnan(reformat(:,24));\nreformat(ii,24)=reformat(ii,23)./100;\nii=~isnan(reformat(:,24)) & isnan(reformat(:,23));\nreformat(ii,23)=reformat(ii,24).*100;\n\n%BP\nii=~isnan(reformat(:,9))&~isnan(reformat(:,10)) & isnan(reformat(:,11));\nreformat(ii,11)=(3*reformat(ii,10)-reformat(ii,9))./2;\nii=~isnan(reformat(:,09))&~isnan(reformat(:,11)) & isnan(reformat(:,10));\nreformat(ii,10)=(reformat(ii,9)+2*reformat(ii,11))./3;\nii=~isnan(reformat(:,10))&~isnan(reformat(:,11)) & isnan(reformat(:,9));\nreformat(ii,9)=3*reformat(ii,10)-2*reformat(ii,11);\n\n%TEMP\n%some values recorded in the wrong column\nii=reformat(:,15)>25&reformat(:,15)<45; %tempF close to 37deg??!\nreformat(ii,14)=reformat(ii,15);\nreformat(ii,15)=NaN;\nii=reformat(:,14)>70; %tempC > 70?!!! probably degF\nreformat(ii,15)=reformat(ii,14);\nreformat(ii,14)=NaN;\nii=~isnan(reformat(:,14)) & isnan(reformat(:,15));\nreformat(ii,15)=reformat(ii,14)*1.8+32;\nii=~isnan(reformat(:,15)) & isnan(reformat(:,14));\nreformat(ii,14)=(reformat(ii,15)-32)./1.8;\n\n% Hb/Ht\nii=~isnan(reformat(:,50)) & isnan(reformat(:,51));\nreformat(ii,51)=(reformat(ii,50)*2.862)+1.216;\nii=~isnan(reformat(:,51)) & isnan(reformat(:,50));\nreformat(ii,50)=(reformat(ii,51)-1.216)./2.862;\n\n%BILI\nii=~isnan(reformat(:,44)) & isnan(reformat(:,45));\nreformat(ii,45)=(reformat(ii,44)*0.6934)-0.1752;\nii=~isnan(reformat(:,45)) & isnan(reformat(:,44));\nreformat(ii,44)=(reformat(ii,45)+0.1752)./0.6934;\n\n\n%% ########################################################################\n% SAMPLE AND HOLD on RAW DATA\n% ########################################################################\n\nreformat=SAH(reformat(:,1:68),sample_and_hold);\n\n\n%% ########################################################################\n% DATA COMBINATION\n% ########################################################################\n\ntic\n save('D:\\BACKUP MIT PC\\Data_100219.mat', '-v7.3');\ntoc\n\n\n% WARNING: the time window of interest has been defined above (here -48 -> +24)! \n\ntimestep=4; %resolution of timesteps, in hours\nirow=1;\nicustayidlist=unique(reformat(:,2));\nreformat2=nan(size(reformat,1),84); %output array\nh = waitbar(0,'Initializing waitbar...');\nnpt=numel(icustayidlist); %number of patients\n% Adding 2 empty cols for future shock index=HR/SBP and P/F\nreformat(:,69:70)=NaN(size(reformat,1),2);\n\ntic\nfor i=1:npt\n \n icustayid=icustayidlist(i); %1 to 100000, NOT 200 to 300K!\n \n %CHARTEVENTS AND LAB VALUES\n temp=reformat(reformat(:,2)==icustayid,:); %subtable of interest\n beg=temp(1,3); %timestamp of first record\n \n % IV FLUID STUFF\n iv=find(inputMV(:,1)==icustayid+200000); %rows of interest in inputMV\n input=inputMV(iv,:); %subset of interest\n iv=find(inputCV(:,1)==icustayid+200000); %rows of interest in inputCV\n input2=inputCV(iv,:); %subset of interest\n startt=input(:,2); %start of all infusions and boluses\n endt=input(:,3); %end of all infusions and boluses\n rate=input(:,8); %rate of infusion (is NaN for boluses)\n \n pread=inputpreadm(inputpreadm(:,1)==icustayid+200000,2) ;%preadmission volume\n if ~isempty(pread) %store the value, if available\n totvol=nansum(pread);\n waitbar(i/npt,h,i/npt*100) %moved here to save some time\n else\n totvol=0; %if not documented: it's zero\n end\n \n % compute volume of fluid given before start of record!!!\n t0=0;\n t1=beg;\n %input from MV (4 ways to compute)\n infu= nansum(rate.*(endt-startt).*(endt<=t1&startt>=t0)/3600 + rate.*(endt-t0).*(startt<=t0&endt<=t1&endt>=t0)/3600 + rate.*(t1-startt).*(startt>=t0&endt>=t1&startt<=t1)/3600 + rate.*(t1-t0).*(endt>=t1&startt<=t0) /3600);\n %all boluses received during this timestep, from inputMV (need to check rate is NaN) and inputCV (simpler):\n bolus=nansum(input(isnan(input(:,6))& input(:,2)>=t0&input(:,2)<=t1,7)) + nansum(input2(input2(:,2)>=t0&input2(:,2)<=t1,5)); \n totvol=nansum([totvol,infu,bolus]); \n \n %VASOPRESSORS \n iv=find(vasoMV(:,1)==icustayid+200000); %rows of interest in vasoMV\n vaso1=vasoMV(iv,:); %subset of interest\n iv=find(vasoCV(:,1)==icustayid+200000); %rows of interest in vasoCV\n vaso2=vasoCV(iv,:); %subset of interest\n startv=vaso1(:,3); %start of VP infusion\n endv=vaso1(:,4); %end of VP infusions\n ratev=vaso1(:,5); %rate of VP infusion\n \n\n %DEMOGRAPHICS / gender, age, elixhauser, re-admit, died in hosp?, died within\n %48h of out_time (likely in ICU or soon after), died within 90d after admission? \n demogi=find(demog.icustay_id==icustayid+200000); \n dem=[ demog.gender(demogi) ; demog.age(demogi) ;demog.elixhauser(demogi) ; demog.adm_order(demogi)>1 ; demog.morta_hosp(demogi); abs(demog.dod(demogi)-demog.outtime(demogi))<(24*3600*2); demog.morta_90(demogi) ; (qstime(icustayid,4)-qstime(icustayid,3))/3600]; \n \n \n % URINE OUTPUT\n iu=find(UO(:,1)==icustayid+200000); %rows of interest in inputMV\n output=UO(iu,:); %subset of interest\n pread=UOpreadm(UOpreadm(:,1)==icustayid,4) ;%preadmission UO\n if ~isempty(pread) %store the value, if available\n UOtot=nansum(pread);\n else\n UOtot=0;\n end\n % adding the volume of urine produced before start of recording! \n UOnow=nansum(output(output(:,2)>=t0&output(:,2)<=t1,4)); %t0 and t1 defined above\n UOtot=nansum([UOtot UOnow]);\n \n \n for j=0:timestep:79 % -28 until +52 = 80 hours in total\n t0=3600*j+ beg; %left limit of time window\n t1=3600*(j+timestep)+beg; %right limit of time window\n ii=temp(:,3)>=t0 & temp(:,3)<=t1; %index of items in this time period\n if sum(ii)>0\n \n \n %ICUSTAY_ID, OUTCOMES, DEMOGRAPHICS\n reformat2(irow,1)=(j/timestep)+1; %'bloc' = timestep (1,2,3...)\n reformat2(irow,2)=icustayid; %icustay_ID\n reformat2(irow,3)=3600*j+ beg; %t0 = lower limit of time window\n reformat2(irow,4:11)=dem; %demographics and outcomes\n \n \n %CHARTEVENTS and LAB VALUES (+ includes empty cols for shock index and P/F)\n value=temp(ii,:);%records all values in this timestep\n \n if sum(ii)==1 %if only 1 row of values at this timestep\n reformat2(irow,12:78)=value(:,4:end);\n else\n reformat2(irow,12:78)=nanmean(value(:,4:end)); %mean of all available values\n \n end\n \n \n %VASOPRESSORS\n % for CV: dose at timestamps.\n % for MV: 4 possibles cases, each one needing a different way to compute the dose of VP actually administered:\n %----t0---start----end-----t1----\n %----start---t0----end----t1----\n %-----t0---start---t1---end\n %----start---t0----t1---end----\n\n \n %MV\n v=(endv>=t0&endv<=t1)|(startv>=t0&endv<=t1)|(startv>=t0&startv<=t1)|(startv<=t0&endv>=t1);\n %CV\n v2=vaso2(vaso2(:,3)>=t0&vaso2(:,3)<=t1,4);\n v1=nanmedian([ratev(v); v2]);\n v2=nanmax([ratev(v); v2]);\n if ~isempty(v1)&~isnan(v1)&~isempty(v2)&~isnan(v2)\n reformat2(irow,79)=v1; %median of dose of VP\n reformat2(irow,80)=v2; %max dose of VP\n end\n \n %INPUT FLUID\n %input from MV (4 ways to compute)\n infu= nansum(rate.*(endt-startt).*(endt<=t1&startt>=t0)/3600 + rate.*(endt-t0).*(startt<=t0&endt<=t1&endt>=t0)/3600 + rate.*(t1-startt).*(startt>=t0&endt>=t1&startt<=t1)/3600 + rate.*(t1-t0).*(endt>=t1&startt<=t0) /3600);\n %all boluses received during this timestep, from inputMV (need to check rate is NaN) and inputCV (simpler):\n bolus=nansum(input(isnan(input(:,6))& input(:,2)>=t0&input(:,2)<=t1,7)) + nansum(input2(input2(:,2)>=t0&input2(:,2)<=t1,5)); \n \n %sum fluid given\n totvol=nansum([totvol,infu,bolus]);\n reformat2(irow,81)=totvol; %total fluid given\n reformat2(irow,82)=nansum([infu,bolus]); %fluid given at this step\n \n %UO\n UOnow=nansum(output(output(:,2)>=t0&output(:,2)<=t1,4)); \n UOtot=nansum([UOtot UOnow]);\n reformat2(irow,83)=UOtot; %total UO\n reformat2(irow,84)=nansum(UOnow); %UO at this step\n\n %CUMULATED BALANCE\n reformat2(irow,85)=totvol-UOtot; %cumulated balance\n\n irow=irow+1;\n end\n end\nend\ntoc\n\nreformat2(irow:end,:)=[];\nclose(h);\n\n\ntic\n save('D:\\BACKUP MIT PC\\Data_110219.mat', '-v7.3');\ntoc\n\n%% ########################################################################\n% CONVERT TO TABLE AND KEEP ONLY WANTED VARIABLE\n% ########################################################################\n\ndataheaders=[sample_and_hold(1,:) {'Shock_Index' 'PaO2_FiO2'}]; \ndataheaders=regexprep(dataheaders,'['']','');\ndataheaders = ['bloc','icustayid','charttime','gender','age','elixhauser','re_admission', 'died_in_hosp', 'died_within_48h_of_out_time','mortality_90d','delay_end_of_record_and_discharge_or_death',...\n dataheaders, 'median_dose_vaso','max_dose_vaso','input_total','input_4hourly','output_total','output_4hourly','cumulated_balance'];\n\nreformat2t=array2table(reformat2);\nreformat2t.Properties.VariableNames=dataheaders;\n\n% headers I want to keep\ndataheaders5 = {'bloc','icustayid','charttime','gender','age','elixhauser','re_admission', 'died_in_hosp', 'died_within_48h_of_out_time','mortality_90d','delay_end_of_record_and_discharge_or_death','SOFA','SIRS',...\n 'Weight_kg','GCS','HR','SysBP','MeanBP','DiaBP','RR','SpO2','Temp_C','FiO2_1','Potassium','Sodium','Chloride','Glucose',...\n 'BUN','Creatinine','Magnesium','Calcium','Ionised_Ca','CO2_mEqL','SGOT','SGPT','Total_bili','Albumin','Hb','WBC_count','Platelets_count','PTT','PT','INR',...\n 'Arterial_pH','paO2','paCO2','Arterial_BE','HCO3','Arterial_lactate','mechvent','Shock_Index','PaO2_FiO2',...\n 'median_dose_vaso','max_dose_vaso','input_total','input_4hourly','output_total','output_4hourly','cumulated_balance'};\n\nii=find(ismember(reformat2t.Properties.VariableNames,dataheaders5));\nreformat3t=reformat2t(:,ii); \n\n\n%% SOME DATA MANIP BEFORE IMPUTATION\n\n% CORRECT GENDER\nreformat3t.gender=reformat3t.gender-1; \n\n%CORRECT AGE > 200 yo\nii=reformat3t.age>150*365.25;\nreformat3t.age(ii)=91.4*365.25;\n\n% FIX MECHVENT\nreformat3t.mechvent(isnan(reformat3t.mechvent))=0;\nreformat3t.mechvent(reformat3t.mechvent>0)=1;\n\n% FIX Elixhauser missing values\nreformat3t.elixhauser(isnan(reformat3t.elixhauser))=nanmedian(reformat3t.elixhauser); %use the median value / only a few missing data points \n\n%vasopressors / no NAN\na=find(ismember(reformat3t.Properties.VariableNames,{'median_dose_vaso'}));\nii=isnan(table2array(reformat3t(:,a)));\nreformat3t(ii,a)=array2table(zeros(sum(ii),1));\na=find(ismember(reformat3t.Properties.VariableNames,{'max_dose_vaso'}));\nii=isnan(table2array(reformat3t(:,a)));\nreformat3t(ii,a)=array2table(zeros(sum(ii),1));\n\n% check prop of missingness here\nmiss=array2table(sum(isnan(table2array(reformat3t)))./size(reformat3t,1));\nmiss.Properties.VariableNames=reformat3t.Properties.VariableNames;\nfigure; bar(sum(isnan(table2array(reformat3t)))./size(reformat3t,1))\n\n% I fill the values temporarily with zeros, otherwise kNN imp doesnt work\nreformat3t.Shock_Index=zeros(size(reformat3t,1),1);\nreformat3t.PaO2_FiO2=zeros(size(reformat3t,1),1);\n\n\n%% ########################################################################\n% HANDLING OF MISSING VALUES & CREATE REFORMAT4T\n% ########################################################################\n\n% Do linear interpol where missingness is low (kNN imputation doesnt work if all rows have missing values)\nreformat3=table2array(reformat3t);\nmiss=sum(isnan((reformat3)))./size(reformat3,1);\nii=miss>0&miss<0.05; %less than 5% missingness\nmechventcol=find(ismember(reformat3t.Properties.VariableNames,{'mechvent'}));\n\nfor i=11:mechventcol-1 % correct col by col, otherwise it does it wrongly\n if ii(i)==1\n reformat3(:,i)=fixgaps(reformat3(:,i));\n end\nend\n\nreformat3t(:,11:mechventcol-1)=array2table(reformat3(:,11:mechventcol-1));\n\n% KNN IMPUTATION - Done on chunks of 10K records.\n\nmechventcol=find(ismember(reformat3t.Properties.VariableNames,{'mechvent'}));\nref=reformat3(:,11:mechventcol-1); %columns of interest\n\ntic\nfor i=1:10000:size(reformat3,1)-9999 %dataset divided in 5K rows chunks (otherwise too large)\n i\n ref(i:i+9999,:)=knnimpute(ref(i:i+9999,:)',1, 'distance','seuclidean')';\nend\n\nref(end-9999:end,:)=knnimpute(ref(end-9999:end,:)',1, 'distance','seuclidean')'; %the last bit is imputed from the last 10K rows\n\ntoc\n\n% I paste the data interpolated, but not the demographics and the treatments\nreformat3t(:,11:mechventcol-1)=array2table(ref); \n\nreformat4t=reformat3t;\nreformat4=table2array(reformat4t);\n\n%% ########################################################################\n% COMPUTE SOME DERIVED VARIABLES: P/F, Shock Index, SOFA, SIRS...\n% ########################################################################\n\n\n% re-compute P/F with no missing values...\np=find(ismember(reformat4t.Properties.VariableNames,{'paO2'}));\nf=find(ismember(reformat4t.Properties.VariableNames,{'FiO2_1'}));\na=find(ismember(reformat4t.Properties.VariableNames,{'PaO2_FiO2'}));\nreformat4t(:,a)=array2table(reformat4(:,p)./reformat4(:,f)); \n\n%recompute SHOCK INDEX without NAN and INF\np=find(ismember(reformat4t.Properties.VariableNames,{'HR'}));\nf=find(ismember(reformat4t.Properties.VariableNames,{'SysBP'}));\na=find(ismember(reformat4t.Properties.VariableNames,{'Shock_Index'}));\nreformat4(:,a)=reformat4(:,p)./reformat4(:,f); \nreformat4(isinf(reformat4(:,a)),a)=NaN;\nd=nanmean(reformat4(:,a));\nreformat4(isnan(reformat4(:,a)),a)=d; %replace NaN with average value ~ 0.8\nreformat4t(:,a)=array2table(reformat4(:,a));\nii=reformat4t.Shock_Index>=quantile(reformat4t.Shock_Index,0.999); %replace outliers with 99.9th percentile\nreformat4t.Shock_Index(ii)=quantile(reformat4t.Shock_Index,0.999);\n\n% SOFA - at each timepoint\n% need (in this order): P/F MV PLT TOT_BILI MAP NORAD(max) GCS CR UO\na=zeros(8,1); % indices of vars used in SOFA\na(1)=find(ismember(reformat4t.Properties.VariableNames,{'PaO2_FiO2'}));\na(2)=find(ismember(reformat4t.Properties.VariableNames,{'Platelets_count'}));\na(3)=find(ismember(reformat4t.Properties.VariableNames,{'Total_bili'}));\na(4)=find(ismember(reformat4t.Properties.VariableNames,{'MeanBP'}));\na(5)=find(ismember(reformat4t.Properties.VariableNames,{'max_dose_vaso'}));\na(6)=find(ismember(reformat4t.Properties.VariableNames,{'GCS'}));\na(7)=find(ismember(reformat4t.Properties.VariableNames,{'Creatinine'}));\na(8)=find(ismember(reformat4t.Properties.VariableNames,{'output_4hourly'}));\ns=table2array(reformat4t(:,a)); \n\np=[0 1 2 3 4];\n\ns1=[s(:,1)>400 s(:,1)>=300 &s(:,1)<400 s(:,1)>=200 &s(:,1)<300 s(:,1)>=100 &s(:,1)<200 s(:,1)<100 ]; %count of points for all 6 criteria of sofa\ns2=[s(:,2)>150 s(:,2)>=100 &s(:,2)<150 s(:,2)>=50 &s(:,2)<100 s(:,2)>=20 &s(:,2)<50 s(:,2)<20 ];\ns3=[s(:,3)<1.2 s(:,3)>=1.2 &s(:,3)<2 s(:,3)>=2 &s(:,3)<6 s(:,3)>=6 &s(:,3)<12 s(:,3)>12 ];\ns4=[s(:,4)>=70 s(:,4)<70&s(:,4)>=65 s(:,4)<65 s(:,5)>0 &s(:,5)<=0.1 s(:,5)>0.1 ];\ns5=[s(:,6)>14 s(:,6)>12 &s(:,6)<=14 s(:,6)>9 &s(:,6)<=12 s(:,6)>5 &s(:,6)<=9 s(:,6)<=5 ];\ns6=[s(:,7)<1.2 s(:,7)>=1.2 &s(:,7)<2 s(:,7)>=2 &s(:,7)<3.5 (s(:,7)>=3.5 &s(:,7)<5)|(s(:,8)<84) (s(:,7)>5)|(s(:,8)<34) ];\n\nnrcol=size(reformat4,2); %nr of variables in data\nreformat4(1,nrcol+1:nrcol+7)=0; \nfor i=1:size(reformat4,1) \n t=max(p(s1(i,:)))+max(p(s2(i,:)))+max(p(s3(i,:)))+max(p(s4(i,:)))+max(p(s5(i,:)))+max(p(s6(i,:))); %SUM OF ALL 6 CRITERIA\n \n if t\n reformat4(i,nrcol+1:nrcol+7)= [max(p(s1(i,:))) max(p(s2(i,:))) max(p(s3(i,:))) max(p(s4(i,:))) max(p(s5(i,:))) max(p(s6(i,:))) t];\n end\nend\n\n% SIRS - at each timepoint | need: temp HR RR PaCO2 WBC \na=zeros(5,1); % indices of vars used in SOFA\na(1)=find(ismember(reformat4t.Properties.VariableNames,{'Temp_C'}));\na(2)=find(ismember(reformat4t.Properties.VariableNames,{'HR'}));\na(3)=find(ismember(reformat4t.Properties.VariableNames,{'RR'}));\na(4)=find(ismember(reformat4t.Properties.VariableNames,{'paCO2'}));\na(5)=find(ismember(reformat4t.Properties.VariableNames,{'WBC_count'}));\ns=table2array(reformat4t(:,a)); \n\ns1=[s(:,1)>=38| s(:,1)<=36]; %count of points for all criteria of SIRS\ns2=[s(:,2)>90 ];\ns3=[s(:,3)>=20|s(:,4)<=32];\ns4=[s(:,5)>=12| s(:,5)<4];\nreformat4(:,nrcol+8)=s1+s2+s3+s4;\n\n% adds 2 cols for SOFA and SIRS, if necessary\nif sum(ismember(reformat4t.Properties.VariableNames,{'SIRS'}))== 0\nreformat4t(:,end+1:end+2)=array2table(0);\nreformat4t.Properties.VariableNames(end-1:end)= {'SOFA','SIRS'}; \nend\n\n% more IO corrections\n ii=reformat4t.input_total<0;\n reformat4t.input_total(ii)=0;\n ii=reformat4t.input_4hourly<0;\n reformat4t.input_4hourly(ii)=0;\n\n% records values\nreformat4t(:,end-1)=array2table(reformat4(:,end-1));\nreformat4t(:,end)=array2table(reformat4(:,end));\n\n\n%% ########################################################################\n% CREATE FINAL MIMIC_TABLE\n% ########################################################################\n\nMIMICtable = reformat4t;\n\n", "meta": {"author": "matthieukomorowski", "repo": "AI_Clinician", "sha": "0669f8907e65503641857ca76aa46938641e513f", "save_path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician", "path": "github-repos/MATLAB/matthieukomorowski-AI_Clinician/AI_Clinician-0669f8907e65503641857ca76aa46938641e513f/AIClinician_mimic3_dataset_160219.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.02716923419419264, "lm_q1q2_score": 0.01242005451825053}} {"text": "%test_VAcPlant(t, ID) is an example, which shows how to use the VAModel in MATLAB\n%In this example, Luyben's multi-loop control structure is implemented and tested\n%Eight process disturbances are available and transients are generated at the end of simulation\n%On a PIII-1GHz PC, the VA plant model runs approaximately 80 times faster than the real time\n%To use this example: \n% t sets the simulation time (in munite) \n% ID is an integer selected between 0 and 8\n% 0: no disturbance \n% 1: setpoint of the reactor outlet temperature decreases 8 degC (from 159 to 151)\n% 2: setpoint of the reactor outlet temperature increases 6 degC (from 159 to 165)\n% 3: setpoint of the H2O composition in the column bottom increases 9% (from 9% to 18%)\n% 4: the vaporizer liqiud inlet flowrate increases 0.44 kmol/min (from 2.2 to 2.64)\n% 5: HAc fresh feed stream lost for 5 minutes\n% 6: O2 fresh feed stream lost for 5 minutes\n% 7: C2H6 composition changes from 0.001 to 0.003 in the C2H4 fresh feed stream\n% 8: column feed lost for 5 minutes\n% Note: in this example, all the disturbances occur at 10 minute after the simulation starts\n%-----------------------------------------------------------------------------\n%Copyright: Rong Chen and Kedar David, June 2002\n%-----------------------------------------------------------------------------\nfunction test_VAcPlant(minute,selected_ID)\n\n%-----------------------------------------------------------------------------\nclose all\nformat short g\n%-----------------------------------------------------------------------------\n\n%-----------------------------------------------------------------------------\n%The recommended simulation sampling time is 1/3 second, which corresponds to a frequency of 180 samples in one minute \nmodel_sampling_frequency=180; \n%The recommended historical data sampling time is 1 minute, which corresponds to a frequency of 1 sample in one minute \nstorage_sampling_frequency=1;\n%The recommended display sampling time is 1 minute, which corresponds to a frequency of 1 sample in one minute \ndisplay_sampling_frequency=1;\n%-----------------------------------------------------------------------------\n\n%-----------------------------------------------------------------------------\n% Inintialze process states and MV's\n% 246 state variables\nstates=zeros(246,1);\n% 26 manipulated variables\nMVs=zeros(26,1);\n% set the current process time to 0 (in minute)\ntime=0;\n% set initialization flag 1\nis_initial=1;\n% set disturbance_ID 0\ndisturbance_ID=0;\n% get the base operation\n[dstatedt,states,MVs,y_ss]=VAModel(states,MVs,time,is_initial,disturbance_ID);\n%-----------------------------------------------------------------------------\n\n%-----------------------------------------------------------------------------\n% Implement Luyben and Tyreus's control structure for the VA plant\n% Note that: in this example, \n% 1. for each transmitter, a 3 second time lag is used\n% 2. for two analyzer transmitters (on the gas recycle and column bottom), a 10 minute deadtime is used\n% 3. for other transmitters, no deadtime is used\n% 4. for three controllers using analyzers on the gas recycle and column bottom, a 10 minute sampling time is used\n% 5. for other controllers, a 1 second sampling time is used\n% 6. for each transmitter, a 1 second sampling time is used\n%-----------------------------------------------------------------------------\ntransmitter_lag=0.05; %in minute\ntransmitter_deadtime=[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 0 10 0 0 0 0 0 0]; %in minute\ntransmitter_sampling_frequency=[60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60];\ncontroller_sampling_frequency=[60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 0.1 0.1 60 0.1 60 60 60 60 60 60];\n%-----------------------------------------------------------------------------\n%transmitter and controller initialization\n%SP: setpoint (not scaled)\n%K: controller gain which is dimentionless\n%Ti: reset time (in minute)\n%act: 1 if positive process gain, -1 if negative process gain \n%mode: 1 for automatic, 2 for manual\n%Ponly: 1 for proportional only control, 0 for PI control\n%hc: controller sampling time (in minute), should be 1/\"controller_sampling_frequency\"\n%ht: transmitter sampling time (in minute), should be 1/\"transmitter_sampling_frequency\"\n%uLO: low limit of MV\n%uHI: high limit of MV\n%ded: should be \"transmitter_deadtime\" defined above\n%tau: should be \"transmitter_lag\" defined above\n%yLO: low limit of measurement\n%yHI: high limit of measurement\n%Nded: measurement deadtime storage, which should be 1+transmitter_deadtime*transmitter_sampling_frequency\n%Ntau: measurement time constant storage, which should be 1 all the time\n%-----------------------------------------------------------------------------\n%MV1: F_O2 - O2 composition\nSP_O2=0.075;\nK_O2=5;\nTi_O2=10; \nact_O2=1;\nmode_O2=1;\nPonly_O2=0;\nht_O2=1/transmitter_sampling_frequency(1);\nhc_O2=1/controller_sampling_frequency(1);\nuLO_O2=0;\nuHI_O2=2.268;\nded_O2=transmitter_deadtime(1);\ntau_O2=transmitter_lag;\nyLO_O2=0;\nyHI_O2=0.2;\nNded_O2=1+transmitter_deadtime(1)*transmitter_sampling_frequency(1);\nNtau_O2=1;\nxxx_O2(1)= (y_ss(37) -yLO_O2) / (yHI_O2 -yLO_O2);\nfor i=2:Nded_O2\n xxx_O2(i)=xxx_O2(1);\nend\nfor i=1:Ntau_O2\n yyy_O2(i)= xxx_O2(Nded_O2);\nend\nxi_O2= (MVs(1) - uLO_O2) /(uHI_O2 -uLO_O2)-K_O2*act_O2*((SP_O2-yLO_O2)/(yHI_O2-yLO_O2)-yyy_O2(Ntau_O2));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV2: F_C2H4 - Recycle Pressure\nSP_C2H4=128;\nK_C2H4=0.3;\nTi_C2H4=20; \nact_C2H4=1;\nmode_C2H4=1;\nPonly_C2H4=0;\nht_C2H4=1/transmitter_sampling_frequency(2);\nhc_C2H4=1/controller_sampling_frequency(2);\nuLO_C2H4=0;\nuHI_C2H4=7.56;\nded_C2H4=transmitter_deadtime(2);\ntau_C2H4=transmitter_lag;\nyLO_C2H4=0;\nyHI_C2H4=200;\nNded_C2H4=1+transmitter_deadtime(2)*transmitter_sampling_frequency(2);\nNtau_C2H4=1;\nxxx_C2H4(1)= (y_ss(12) -yLO_C2H4) / (yHI_C2H4 -yLO_C2H4);\nfor i=2:Nded_C2H4\n xxx_C2H4(i)= xxx_C2H4(1);\nend\nfor i=1:Ntau_C2H4\n yyy_C2H4(i)= xxx_C2H4(Nded_C2H4);\nend\nxi_C2H4= (MVs(2) - uLO_C2H4) /(uHI_C2H4 -uLO_C2H4)-K_C2H4*act_C2H4*((SP_C2H4-yLO_C2H4)/(yHI_C2H4-yLO_C2H4)-yyy_C2H4(Ntau_C2H4));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV3: HAc feed stream - HAc tank level\nSP_HAc=0.5;\nK_HAc=2;\nTi_HAc=100; \nact_HAc=1;\nmode_HAc=1;\nPonly_HAc=1;\nht_HAc=1/transmitter_sampling_frequency(3);\nhc_HAc=1/controller_sampling_frequency(3);\nuLO_HAc=0;\nuHI_HAc=4.536;\nded_HAc=transmitter_deadtime(3);\ntau_HAc=transmitter_lag;\nyLO_HAc=0;\nyHI_HAc=1;\nNded_HAc=1+transmitter_deadtime(3)*transmitter_sampling_frequency(3);\nNtau_HAc=1;\nxxx_HAc(1)= (y_ss(23) -yLO_HAc) / (yHI_HAc -yLO_HAc);\nfor i=2:Nded_HAc\n xxx_HAc(i)= xxx_HAc(1);\nend\nfor i=1:Ntau_HAc\n yyy_HAc(i)= xxx_HAc(Nded_HAc);\nend\nxi_HAc= (MVs(3) - uLO_HAc) /(uHI_HAc -uLO_HAc)-K_HAc*act_HAc*((SP_HAc-yLO_HAc)/(yHI_HAc-yLO_HAc)-yyy_HAc(Ntau_HAc));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV4: Qv - Level\nSP_LevelVap=0.7;\nK_LevelVap=0.1;\nTi_LevelVap=30; \nact_LevelVap=-1;\nmode_LevelVap=1;\nPonly_LevelVap=0;\nht_LevelVap=1/transmitter_sampling_frequency(4);\nhc_LevelVap=1/controller_sampling_frequency(4);\nuLO_LevelVap=0;\nuHI_LevelVap=1433400; \nded_LevelVap=transmitter_deadtime(4);\ntau_LevelVap=transmitter_lag;\nyLO_LevelVap=0;\nyHI_LevelVap=1;\nNded_LevelVap=1+transmitter_deadtime(4)*transmitter_sampling_frequency(4);\nNtau_LevelVap=1;\nxxx_LevelVap(1)= (y_ss(2) -yLO_LevelVap) / (yHI_LevelVap -yLO_LevelVap);\nfor i=2:Nded_LevelVap\n xxx_LevelVap(i)= xxx_LevelVap(1);\nend\nfor i=1:Ntau_LevelVap\n yyy_LevelVap(i)= xxx_LevelVap(Nded_LevelVap);\nend\nxi_LevelVap= (MVs(4) - uLO_LevelVap) /(uHI_LevelVap -uLO_LevelVap)-K_LevelVap*act_LevelVap*((SP_LevelVap-yLO_LevelVap)/(yHI_LevelVap-yLO_LevelVap)-yyy_LevelVap(Ntau_LevelVap));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV5: F_Vaporizer - Vaporizer Pressure\nSP_PresVap=128;\nK_PresVap=5;\nTi_PresVap=10;\nact_PresVap=-1;\nmode_PresVap=1;\nPonly_PresVap=0;\nht_PresVap=1/transmitter_sampling_frequency(5);\nhc_PresVap=1/controller_sampling_frequency(5);\nuLO_PresVap=0;\nuHI_PresVap=50;\nded_PresVap=transmitter_deadtime(5);\ntau_PresVap=transmitter_lag;\nyLO_PresVap=0;\nyHI_PresVap=200;\nNded_PresVap=1+transmitter_deadtime(5)*transmitter_sampling_frequency(5);\nNtau_PresVap=1;\nxxx_PresVap(1)= (y_ss(1) -yLO_PresVap) / (yHI_PresVap -yLO_PresVap);\nfor i=2:Nded_PresVap\n xxx_PresVap(i)= xxx_PresVap(1);\nend\nfor i=1:Ntau_PresVap\n yyy_PresVap(i)= xxx_PresVap(Nded_PresVap);\nend\nxi_PresVap= (MVs(5) - uLO_PresVap) /(uHI_PresVap -uLO_PresVap)-K_PresVap*act_PresVap*((SP_PresVap-yLO_PresVap)/(yHI_PresVap-yLO_PresVap)-yyy_PresVap(Ntau_PresVap));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV6: Q_heater - Vaporizer Outlet Temperature\nSP_ReactorInletTemp=150;\nK_ReactorInletTemp=1;\nTi_ReactorInletTemp=5; \nact_ReactorInletTemp=1;\nmode_ReactorInletTemp=1;\nPonly_ReactorInletTemp=0;\nht_ReactorInletTemp=1/transmitter_sampling_frequency(6);\nhc_ReactorInletTemp=1/controller_sampling_frequency(6);\nuLO_ReactorInletTemp=0;\nuHI_ReactorInletTemp=15000;\nded_ReactorInletTemp=transmitter_deadtime(6);\ntau_ReactorInletTemp=transmitter_lag;\nyLO_ReactorInletTemp=120;\nyHI_ReactorInletTemp=170;\nNded_ReactorInletTemp=1+transmitter_deadtime(6)*transmitter_sampling_frequency(6);\nNtau_ReactorInletTemp=1;\nxxx_ReactorInletTemp(1)= (y_ss(4) -yLO_ReactorInletTemp) / (yHI_ReactorInletTemp -yLO_ReactorInletTemp);\nfor i=2:Nded_ReactorInletTemp\n xxx_ReactorInletTemp(i)= xxx_ReactorInletTemp(1);\nend\nfor i=1:Ntau_ReactorInletTemp\n yyy_ReactorInletTemp(i)= xxx_ReactorInletTemp(Nded_ReactorInletTemp);\nend\nxi_ReactorInletTemp= (MVs(6) - uLO_ReactorInletTemp) /(uHI_ReactorInletTemp -uLO_ReactorInletTemp)-K_ReactorInletTemp*act_ReactorInletTemp*((SP_ReactorInletTemp-yLO_ReactorInletTemp)/(yHI_ReactorInletTemp-yLO_ReactorInletTemp)-yyy_ReactorInletTemp(Ntau_ReactorInletTemp));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV7: T_Shell - T_RCTOUT\nSP_TRCT=159.17;\nK_TRCT=3;\nTi_TRCT=10; \nact_TRCT=1;\nmode_TRCT=1;\nPonly_TRCT=0;\nht_TRCT=1/transmitter_sampling_frequency(7);\nhc_TRCT=1/controller_sampling_frequency(7);\nuLO_TRCT=110;\nuHI_TRCT=150;\nded_TRCT=transmitter_deadtime(7);\ntau_TRCT=transmitter_lag;\nyLO_TRCT=0;\nyHI_TRCT=200;\nNded_TRCT=1+transmitter_deadtime(7)*transmitter_sampling_frequency(7);\nNtau_TRCT=1;\nxxx_TRCT(1)= (y_ss(5)-yLO_TRCT) / (yHI_TRCT -yLO_TRCT);\nfor i=2:Nded_TRCT\n xxx_TRCT(i)= xxx_TRCT(1);\nend\nfor i=1:Ntau_TRCT\n yyy_TRCT(i)= xxx_TRCT(Nded_TRCT);\nend\nxi_TRCT= (MVs(7) - uLO_TRCT) /(uHI_TRCT -uLO_TRCT)-K_TRCT*act_TRCT*((SP_TRCT-yLO_TRCT)/(yHI_TRCT-yLO_TRCT)-yyy_TRCT(Ntau_TRCT));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV8: Separator Liquid Exit - Separator Level\nSP_LevelSep=0.5;\nK_LevelSep=5;\nTi_LevelSep=100; \nact_LevelSep=-1;\nmode_LevelSep=1;\nPonly_LevelSep=1;\nht_LevelSep=1/transmitter_sampling_frequency(8);\nhc_LevelSep=1/controller_sampling_frequency(8);\nuLO_LevelSep=0;\nuHI_LevelSep=4.536;\nded_LevelSep=transmitter_deadtime(8);\ntau_LevelSep=transmitter_lag;\nyLO_LevelSep=0; \nyHI_LevelSep=1; \nNded_LevelSep=1+transmitter_deadtime(8)*transmitter_sampling_frequency(8);\nNtau_LevelSep=1;\nxxx_LevelSep(1)= (y_ss(9)-yLO_LevelSep) / (yHI_LevelSep -yLO_LevelSep);\nfor i=2:Nded_LevelSep\n xxx_LevelSep(i)= xxx_LevelSep(1);\nend\nfor i=1:Ntau_LevelSep\n yyy_LevelSep(i)= xxx_LevelSep(Nded_LevelSep);\nend\nxi_LevelSep= (MVs(8) - uLO_LevelSep) /(uHI_LevelSep -uLO_LevelSep)-K_LevelSep*act_LevelSep*((SP_LevelSep-yLO_LevelSep)/(yHI_LevelSep-yLO_LevelSep)-yyy_LevelSep(Ntau_LevelSep));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV9: T_Shell_Separator - Separator Liquid Temperature\nSP_TempSep=40;\nK_TempSep=5;\nTi_TempSep=20; \nact_TempSep=-1;\nmode_TempSep=1;\nPonly_TempSep=0;\nht_TempSep=1/transmitter_sampling_frequency(9);\nhc_TempSep=1/controller_sampling_frequency(9);\nuLO_TempSep=0;\nuHI_TempSep=80;\nded_TempSep=transmitter_deadtime(9);\ntau_TempSep=transmitter_lag;\nyLO_TempSep=0; \nyHI_TempSep=80; \nNded_TempSep=1+transmitter_deadtime(9)*transmitter_sampling_frequency(9);\nNtau_TempSep=1;\nxxx_TempSep(1)= (y_ss(10)-yLO_TempSep) / (yHI_TempSep -yLO_TempSep);\nfor i=2:Nded_TempSep\n xxx_TempSep(i)= xxx_TempSep(1);\nend\nfor i=1:Ntau_TempSep\n yyy_TempSep(i)= xxx_TempSep(Nded_TempSep);\nend\nxi_TempSep= (MVs(9) - uLO_TempSep) /(uHI_TempSep -uLO_TempSep)-K_TempSep*act_TempSep*((SP_TempSep-yLO_TempSep)/(yHI_TempSep-yLO_TempSep)-yyy_TempSep(Ntau_TempSep));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV10: Separator Vapor Exit is fixed at 16.1026 kmol/min\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV11: Q_Compressor_Cooler - Compressor Outlet Temperature (80degC)\nSP_CompOutletTemp=80;\nK_CompOutletTemp=1;\nTi_CompOutletTemp=5; \nact_CompOutletTemp=-1;\nmode_CompOutletTemp=1;\nPonly_CompOutletTemp=0;\nht_CompOutletTemp=1/transmitter_sampling_frequency(11);\nhc_CompOutletTemp=1/controller_sampling_frequency(11);\nuLO_CompOutletTemp=0;\nuHI_CompOutletTemp=50000;\nded_CompOutletTemp=transmitter_deadtime(11);\ntau_CompOutletTemp=transmitter_lag;\nyLO_CompOutletTemp=70;\nyHI_CompOutletTemp=90;\nNded_CompOutletTemp=1+transmitter_deadtime(11)*transmitter_sampling_frequency(11);\nNtau_CompOutletTemp=1;\nxxx_CompOutletTemp(1)= (y_ss(11) -yLO_CompOutletTemp) / (yHI_CompOutletTemp -yLO_CompOutletTemp);\nfor i=2:Nded_CompOutletTemp\n xxx_CompOutletTemp(i)= xxx_CompOutletTemp(1);\nend\nfor i=1:Ntau_CompOutletTemp\n yyy_CompOutletTemp(i)= xxx_CompOutletTemp(Nded_CompOutletTemp);\nend\nxi_CompOutletTemp= (MVs(11) - uLO_CompOutletTemp) /(uHI_CompOutletTemp -uLO_CompOutletTemp)-K_CompOutletTemp*act_CompOutletTemp*((SP_CompOutletTemp-yLO_CompOutletTemp)/(yHI_CompOutletTemp-yLO_CompOutletTemp)-yyy_CompOutletTemp(Ntau_CompOutletTemp));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV12: Absorber Liquid Exit - Absorber Level\nSP_LevelAbs=0.5;\nK_LevelAbs=5;\nTi_LevelAbs=100; \nact_LevelAbs=-1;\nmode_LevelAbs=1;\nPonly_LevelAbs=1;\nht_LevelAbs=1/transmitter_sampling_frequency(12);\nhc_LevelAbs=1/controller_sampling_frequency(12);\nuLO_LevelAbs=0;\nuHI_LevelAbs=4.536;\nded_LevelAbs=transmitter_deadtime(12);\ntau_LevelAbs=transmitter_lag;\nyLO_LevelAbs=0;\nyHI_LevelAbs=1;\nNded_LevelAbs=1+transmitter_deadtime(12)*transmitter_sampling_frequency(12);\nNtau_LevelAbs=1;\nxxx_LevelAbs(1)= (y_ss(13)-yLO_LevelAbs) / (yHI_LevelAbs -yLO_LevelAbs);\nfor i=2:Nded_LevelAbs\n xxx_LevelAbs(i)= xxx_LevelAbs(1);\nend\nfor i=1:Ntau_LevelAbs\n yyy_LevelAbs(i)= xxx_LevelAbs(Nded_LevelAbs);\nend\nxi_LevelAbs= (MVs(12) - uLO_LevelAbs) /(uHI_LevelAbs -uLO_LevelAbs)-K_LevelAbs*act_LevelAbs*((SP_LevelAbs-yLO_LevelAbs)/(yHI_LevelAbs-yLO_LevelAbs)-yyy_LevelAbs(Ntau_LevelAbs));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV13: Circulation Flowrate is fixed to 15.1198 kmol/min\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV14: Q_Cooler_Circulation - Circulation Temperature\nSP_CircOutletTemp=25;\nK_CircOutletTemp=1;\nTi_CircOutletTemp=5; \nact_CircOutletTemp=-1;\nmode_CircOutletTemp=1;\nPonly_CircOutletTemp=0;\nht_CircOutletTemp=1/transmitter_sampling_frequency(14);\nhc_CircOutletTemp=1/controller_sampling_frequency(14);\nuLO_CircOutletTemp=0;\nuHI_CircOutletTemp=30000;\nded_CircOutletTemp=transmitter_deadtime(14);\ntau_CircOutletTemp=transmitter_lag;\nyLO_CircOutletTemp=10;\nyHI_CircOutletTemp=40;\nNded_CircOutletTemp=1+transmitter_deadtime(14)*transmitter_sampling_frequency(14);\nNtau_CircOutletTemp=1;\nxxx_CircOutletTemp(1)= (y_ss(14) -yLO_CircOutletTemp) / (yHI_CircOutletTemp -yLO_CircOutletTemp);\nfor i=2:Nded_CircOutletTemp\n xxx_CircOutletTemp(i)= xxx_CircOutletTemp(1);\nend\nfor i=1:Ntau_CircOutletTemp\n yyy_CircOutletTemp(i)= xxx_CircOutletTemp(Nded_CircOutletTemp);\nend\nxi_CircOutletTemp= (MVs(14) - uLO_CircOutletTemp) /(uHI_CircOutletTemp -uLO_CircOutletTemp)-K_CircOutletTemp*act_CircOutletTemp*((SP_CircOutletTemp-yLO_CircOutletTemp)/(yHI_CircOutletTemp-yLO_CircOutletTemp)-yyy_CircOutletTemp(Ntau_CircOutletTemp));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV15: Scrub Flowrate is fixed to 0.756 kmol/min\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV16: Q_Cooler_Scrub - Scrub Temperature\nSP_ScrubOutletTemp=25;\nK_ScrubOutletTemp=1;\nTi_ScrubOutletTemp=5; \nact_ScrubOutletTemp=-1;\nmode_ScrubOutletTemp=1;\nPonly_ScrubOutletTemp=0;\nht_ScrubOutletTemp=1/transmitter_sampling_frequency(16);\nhc_ScrubOutletTemp=1/controller_sampling_frequency(16);\nuLO_ScrubOutletTemp=0;\nuHI_ScrubOutletTemp=5000;\nded_ScrubOutletTemp=transmitter_deadtime(16);\ntau_ScrubOutletTemp=transmitter_lag;\nyLO_ScrubOutletTemp=10;\nyHI_ScrubOutletTemp=40;\nNded_ScrubOutletTemp=1+transmitter_deadtime(16)*transmitter_sampling_frequency(16);\nNtau_ScrubOutletTemp=1;\nxxx_ScrubOutletTemp(1)= (y_ss(15) -yLO_ScrubOutletTemp) / (yHI_ScrubOutletTemp -yLO_ScrubOutletTemp);\nfor i=2:Nded_ScrubOutletTemp\n xxx_ScrubOutletTemp(i)= xxx_ScrubOutletTemp(1);\nend\nfor i=1:Ntau_ScrubOutletTemp\n yyy_ScrubOutletTemp(i)= xxx_ScrubOutletTemp(Nded_ScrubOutletTemp);\nend\nxi_ScrubOutletTemp= (MVs(16) - uLO_ScrubOutletTemp) /(uHI_ScrubOutletTemp -uLO_ScrubOutletTemp)-K_ScrubOutletTemp*act_ScrubOutletTemp*((SP_ScrubOutletTemp-yLO_ScrubOutletTemp)/(yHI_ScrubOutletTemp-yLO_ScrubOutletTemp)-yyy_ScrubOutletTemp(Ntau_ScrubOutletTemp));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV17: CO2 - CO2 composition\nSP_CO2=0.0076393;\nK_CO2=1;\nTi_CO2=100; \nact_CO2=-1;\nmode_CO2=1;\nPonly_CO2=1;\nht_CO2=1/transmitter_sampling_frequency(17);\nhc_CO2=1/controller_sampling_frequency(17);\nuLO_CO2=0;\nuHI_CO2=22.68;\nded_CO2=transmitter_deadtime(17);\ntau_CO2=transmitter_lag;\nyLO_CO2=0;\nyHI_CO2=0.5;\nNded_CO2=1+transmitter_deadtime(17)*transmitter_sampling_frequency(17);\nNtau_CO2=1;\nxxx_CO2(1)= (y_ss(31) -yLO_CO2) / (yHI_CO2 -yLO_CO2);\nfor i=2:Nded_CO2\n xxx_CO2(i)= xxx_CO2(1);\nend\nfor i=1:Ntau_CO2\n yyy_CO2(i)= xxx_CO2(Nded_CO2);\nend\nxi_CO2= (MVs(17) - uLO_CO2) /(uHI_CO2 -uLO_CO2)-K_CO2*act_CO2*((SP_CO2-yLO_CO2)/(yHI_CO2-yLO_CO2)-yyy_CO2(Ntau_CO2));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV18: Purge - C2H6 composition\nSP_C2H6=0.25;\nK_C2H6=1;\nTi_C2H6=100; \nact_C2H6=-1;\nmode_C2H6=1;\nPonly_C2H6=1;\nht_C2H6=1/transmitter_sampling_frequency(18);\nhc_C2H6=1/controller_sampling_frequency(18);\nuLO_C2H6=0;\nuHI_C2H6=0.02268;\nded_C2H6=transmitter_deadtime(18);\ntau_C2H6=transmitter_lag;\nyLO_C2H6=0;\nyHI_C2H6=1;\nNded_C2H6=1+transmitter_deadtime(18)*transmitter_sampling_frequency(18);\nNtau_C2H6=1;\nxxx_C2H6(1)= (y_ss(33) -yLO_C2H6) / (yHI_C2H6 -yLO_C2H6);\nfor i=2:Nded_C2H6\n xxx_C2H6(i)= xxx_C2H6(1);\nend\nfor i=1:Ntau_C2H6\n yyy_C2H6(i)= xxx_C2H6(Nded_C2H6);\nend\nxi_C2H6= (MVs(18) - uLO_C2H6) /(uHI_C2H6 -uLO_C2H6)-K_C2H6*act_C2H6*((SP_C2H6-yLO_C2H6)/(yHI_C2H6-yLO_C2H6)-yyy_C2H6(Ntau_C2H6));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV19: bypass - FEHE Cold Exit Temp\nSP_FEHE=134;\nK_FEHE=5;\nTi_FEHE=10; \nact_FEHE=1;\nmode_FEHE=1;\nPonly_FEHE=0;\nht_FEHE=1/transmitter_sampling_frequency(19);\nhc_FEHE=1/controller_sampling_frequency(19);\nuLO_FEHE=0;\nuHI_FEHE=1;\nded_FEHE=transmitter_deadtime(19);\ntau_FEHE=transmitter_lag;\nyLO_FEHE=0;\nyHI_FEHE=200;\nNded_FEHE=1+transmitter_deadtime(19)*transmitter_sampling_frequency(19);\nNtau_FEHE=1;\nxxx_FEHE(1)= (y_ss(8) -yLO_FEHE) / (yHI_FEHE -yLO_FEHE);\nfor i=2:Nded_FEHE\n xxx_FEHE(i)= xxx_FEHE(1);\nend\nfor i=1:Ntau_FEHE\n yyy_FEHE(i)= xxx_FEHE(Nded_FEHE);\nend\nxi_FEHE= (MVs(19) - uLO_FEHE) /(uHI_FEHE -uLO_FEHE)-K_FEHE*act_FEHE*((SP_FEHE-yLO_FEHE)/(yHI_FEHE-yLO_FEHE)-yyy_FEHE(Ntau_FEHE));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV20: LR - %H2O in bottom\nSP_H2OCol=0.09344;\nK_H2OCol=0.5;\nTi_H2OCol=60;\nact_H2OCol=-1;\nmode_H2OCol=1;\nPonly_H2OCol=0;\nht_H2OCol=1/transmitter_sampling_frequency(20);\nhc_H2OCol=1/controller_sampling_frequency(20);\nuLO_H2OCol=0;\nuHI_H2OCol=7.56;\nded_H2OCol=transmitter_deadtime(20);\ntau_H2OCol=transmitter_lag;\nyLO_H2OCol=0;\nyHI_H2OCol=0.2;\nNded_H2OCol=1+transmitter_deadtime(20)*transmitter_sampling_frequency(20);\nNtau_H2OCol=1;\nxxx_H2OCol(1)= (y_ss(28) -yLO_H2OCol) / (yHI_H2OCol -yLO_H2OCol);\nfor i=2:Nded_H2OCol\n xxx_H2OCol(i)= xxx_H2OCol(1);\nend\nfor i=1:Ntau_H2OCol\n yyy_H2OCol(i)= xxx_H2OCol(Nded_H2OCol);\nend\nxi_H2OCol= (MVs(20) - uLO_H2OCol) /(uHI_H2OCol -uLO_H2OCol)-K_H2OCol*act_H2OCol*((SP_H2OCol-yLO_H2OCol)/(yHI_H2OCol-yLO_H2OCol)-yyy_H2OCol(Ntau_H2OCol));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV21: Qr - Temp\nSP_TempCol=110;\nK_TempCol=20;\nTi_TempCol=30;\nact_TempCol=1;\nmode_TempCol=1;\nPonly_TempCol=0;\nht_TempCol=1/transmitter_sampling_frequency(21);\nhc_TempCol=1/controller_sampling_frequency(21);\nuLO_TempCol=0;\nuHI_TempCol=100000;\nded_TempCol=transmitter_deadtime(21);\ntau_TempCol=transmitter_lag;\nyLO_TempCol=0;\nyHI_TempCol=120;\nNded_TempCol=1+transmitter_deadtime(21)*transmitter_sampling_frequency(21);\nNtau_TempCol=1;\nxxx_TempCol(1)= (y_ss(22) -yLO_TempCol) / (yHI_TempCol -yLO_TempCol);\nfor i=2:Nded_TempCol\n xxx_TempCol(i)= xxx_TempCol(1);\nend\nfor i=1:Ntau_TempCol\n yyy_TempCol(i)= xxx_TempCol(Nded_TempCol);\nend\nxi_TempCol= (MVs(21) - uLO_TempCol) /(uHI_TempCol -uLO_TempCol)-K_TempCol*act_TempCol*((SP_TempCol-yLO_TempCol)/(yHI_TempCol-yLO_TempCol)-yyy_TempCol(Ntau_TempCol));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV22: Q_Condenser - Decanter Temperature (45.845 degC) is perfetly controlled in the code\nSP_DecanterTemp=45.845;\nK_DecanterTemp=1;\nTi_DecanterTemp=5; \nact_DecanterTemp=-1;\nmode_DecanterTemp=1;\nPonly_DecanterTemp=0;\nht_DecanterTemp=1/transmitter_sampling_frequency(22);\nhc_DecanterTemp=1/controller_sampling_frequency(22);\nuLO_DecanterTemp=0;\nuHI_DecanterTemp=150000;\nded_DecanterTemp=transmitter_deadtime(22);\ntau_DecanterTemp=transmitter_lag;\nyLO_DecanterTemp=40;\nyHI_DecanterTemp=50;\nNded_DecanterTemp=1+transmitter_deadtime(22)*transmitter_sampling_frequency(25);\nNtau_DecanterTemp=1;\nxxx_DecanterTemp(1)= (y_ss(20) -yLO_DecanterTemp) / (yHI_DecanterTemp -yLO_DecanterTemp);\nfor i=2:Nded_DecanterTemp\n xxx_DecanterTemp(i)= xxx_DecanterTemp(1);\nend\nfor i=1:Ntau_DecanterTemp\n yyy_DecanterTemp(i)= xxx_DecanterTemp(Nded_DecanterTemp);\nend\nxi_DecanterTemp= (MVs(22) - uLO_DecanterTemp) /(uHI_DecanterTemp -uLO_DecanterTemp)-K_DecanterTemp*act_DecanterTemp*((SP_DecanterTemp-yLO_DecanterTemp)/(yHI_DecanterTemp-yLO_DecanterTemp)-yyy_DecanterTemp(Ntau_DecanterTemp));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV22: Organic Level is controlled by Organic Product Flow at 0.5\nSP_Organic=0.5;\nK_Organic=1;\nTi_Organic=100; \nact_Organic=-1;\nmode_Organic=1;\nPonly_Organic=1;\nht_Organic=1/transmitter_sampling_frequency(23);\nhc_Organic=1/controller_sampling_frequency(23);\nuLO_Organic=0;\nuHI_Organic=2.4;\nded_Organic=transmitter_deadtime(23);\ntau_Organic=transmitter_lag;\nyLO_Organic=0; \nyHI_Organic=1; \nNded_Organic=1+transmitter_deadtime(23)*transmitter_sampling_frequency(23);\nNtau_Organic=1;\nxxx_Organic(1)= (y_ss(18)-yLO_Organic) / (yHI_Organic -yLO_Organic);\nfor i=2:Nded_Organic\n xxx_Organic(i)= xxx_Organic(1);\nend\nfor i=1:Ntau_Organic\n yyy_Organic(i)= xxx_Organic(Nded_Organic);\nend\nxi_Organic= (MVs(23) - uLO_Organic) /(uHI_Organic -uLO_Organic)-K_Organic*act_Organic*((SP_Organic-yLO_Organic)/(yHI_Organic-yLO_Organic)-yyy_Organic(Ntau_Organic));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV23: Aqueous Level is controlled by Aqueous Product Flow at 0.5\nSP_Aqueous=0.5;\nK_Aqueous=1;\nTi_Aqueous=100; \nact_Aqueous=-1;\nmode_Aqueous=1;\nPonly_Aqueous=1;\nht_Aqueous=1/transmitter_sampling_frequency(24);\nhc_Aqueous=1/controller_sampling_frequency(24);\nuLO_Aqueous=0;\nuHI_Aqueous=2.4;\nded_Aqueous=transmitter_deadtime(24);\ntau_Aqueous=transmitter_lag;\nyLO_Aqueous=0; \nyHI_Aqueous=1; \nNded_Aqueous=1+transmitter_deadtime(24)*transmitter_sampling_frequency(24);\nNtau_Aqueous=1;\nxxx_Aqueous(1)= (y_ss(19)-yLO_Aqueous) / (yHI_Aqueous -yLO_Aqueous);\nfor i=2:Nded_Aqueous\n xxx_Aqueous(i)= xxx_Aqueous(1);\nend\nfor i=1:Ntau_Aqueous\n yyy_Aqueous(i)= xxx_Aqueous(Nded_Aqueous);\nend\nxi_Aqueous= (MVs(24) - uLO_Aqueous) /(uHI_Aqueous -uLO_Aqueous)-K_Aqueous*act_Aqueous*((SP_Aqueous-yLO_Aqueous)/(yHI_Aqueous-yLO_Aqueous)-yyy_Aqueous(Ntau_Aqueous));\n%-----------------------------------------------------------------------------\n%MV24: Column Bottom Exit is used to control the Column Bottom Level\nSP_ColButtom=0.5;\nK_ColButtom=1;\nTi_ColButtom=100; \nact_ColButtom=-1;\nmode_ColButtom=1;\nPonly_ColButtom=1;\nht_ColButtom=1/transmitter_sampling_frequency(25);\nhc_ColButtom=1/controller_sampling_frequency(25);\nuLO_ColButtom=0;\nuHI_ColButtom=4.536;\nded_ColButtom=transmitter_deadtime(25);\ntau_ColButtom=transmitter_lag;\nyLO_ColButtom=0; \nyHI_ColButtom=1; \nNded_ColButtom=1+transmitter_deadtime(25)*transmitter_sampling_frequency(25);\nNtau_ColButtom=1;\nxxx_ColButtom(1)= (y_ss(21)-yLO_ColButtom) / (yHI_ColButtom -yLO_ColButtom);\nfor i=2:Nded_ColButtom\n xxx_ColButtom(i)= xxx_ColButtom(1);\nend\nfor i=1:Ntau_ColButtom\n yyy_ColButtom(i)= xxx_ColButtom(Nded_ColButtom);\nend\nxi_ColButtom= (MVs(25) - uLO_ColButtom) /(uHI_ColButtom -uLO_ColButtom)-K_ColButtom*act_ColButtom*((SP_ColButtom-yLO_ColButtom)/(yHI_ColButtom-yLO_ColButtom)-yyy_ColButtom(Ntau_ColButtom));\n%-----------------------------------------------------------------------------\n%controller initialization\n%MV26: Vaporizer Liquid Inlet is fixed at 2.1924 kmol/min\n%-----------------------------------------------------------------------------\n\n%-----------------------------------------------------------------------------\n%initialize historical data vectors\nx_history=[];\ny_history=[];\nu_history=[];\ndx_history=[];\n%initialize simulation parameters\ntic\ntimer=0;\nis_initial=0;\ndisturbance_ID=0;\n%start simulation\nfor k=0:(model_sampling_frequency*minute)\n time=k/model_sampling_frequency; %in minute\n %initialize disturbances\n if (k/model_sampling_frequency)>=10\n switch selected_ID\n case 0\n ;\n case 1\n SP_TRCT=151;\n case 2\n SP_TRCT=165;\n case 3\n SP_H2OCol=0.18;\n case 4\n MVs(26)=2.64;\n case 5\n if (k/model_sampling_frequency)<15\n MVs(3)=0;\n end\n case 6\n if (k/model_sampling_frequency)<15\n MVs(1)=0;\n end\n case 7 \n disturbance_ID=1;\n case 8 \n if (k/model_sampling_frequency)<15\n disturbance_ID=2;\n else\n disturbance_ID=0;\n end\n end\n end\n %calculate state derivatives and measurements\n [dstatedt,states,MVs,y_ss]=VAModel(states,MVs,time,is_initial,disturbance_ID);\n %in this example, we assume the setpoint of the vaporizer pressure control is given by the current gas recycle pressure\n SP_PresVap=y_ss(12);\n %command window display refreshing rate\n if rem(k,display_sampling_frequency*model_sampling_frequency)==0\n [error, indx]=max(abs(dstatedt./states));\n% info=['minute: ' num2str(time) ' max_dxdt_error: ' num2str(error) ' location: ' num2str(indx)];\n % disp(info);\n end\n %save information\n if rem(k,storage_sampling_frequency*model_sampling_frequency)==0\n x_history=[x_history;states'];\n y_history=[y_history;[y_ss(37);y_ss(12);y_ss(23);y_ss(2);y_ss(1);y_ss(4);y_ss(5);y_ss(9);y_ss(10);MVs(10);y_ss(11);y_ss(13);MVs(13);y_ss(14);MVs(15);y_ss(15);y_ss(31);y_ss(33);y_ss(8);y_ss(28);y_ss(22);y_ss(20);y_ss(18);y_ss(19);y_ss(21);MVs(26);y_ss(27)]'];\n u_history=[u_history;MVs'];\n dx_history=[dx_history;dstatedt'];\n end\n %update states\n states=states+(1/model_sampling_frequency)*dstatedt;\n %controller action\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(1))==0 & k~=0\n [xxx_O2, yyy_O2]=Transmit(y_ss(37), xxx_O2, yyy_O2, ded_O2, tau_O2, Nded_O2, Ntau_O2, ht_O2, yLO_O2, yHI_O2);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(1))==0 & k~=0\n [MVs(1),xi_O2,flag_O2]=controller(SP_O2, yyy_O2(Ntau_O2), MVs(1), xi_O2, mode_O2, K_O2, Ti_O2, hc_O2,...\n yLO_O2, yHI_O2, uLO_O2, uHI_O2, act_O2, Ponly_O2, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(2))==0 & k~=0\n [xxx_C2H4, yyy_C2H4]=Transmit(y_ss(12), xxx_C2H4, yyy_C2H4, ded_C2H4, tau_C2H4, Nded_C2H4, Ntau_C2H4, ht_C2H4, yLO_C2H4, yHI_C2H4);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(2))==0 & k~=0\n [MVs(2),xi_C2H4,flag_C2H4]=controller(SP_C2H4, yyy_C2H4(Ntau_C2H4), MVs(2), xi_C2H4, mode_C2H4, K_C2H4, Ti_C2H4, hc_C2H4,...\n yLO_C2H4, yHI_C2H4, uLO_C2H4, uHI_C2H4, act_C2H4, Ponly_C2H4, 0, 0, 0, 0);\n end\n \n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(3))==0 & k~=0\n [xxx_HAc, yyy_HAc]=Transmit(y_ss(23), xxx_HAc, yyy_HAc, ded_HAc, tau_HAc, Nded_HAc, Ntau_HAc, ht_HAc, yLO_HAc, yHI_HAc);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(3))==0 & k~=0\n [MVs(3),xi_HAc,flag_HAc]=controller(SP_HAc, yyy_HAc(Ntau_HAc), MVs(3), xi_HAc, mode_HAc, K_HAc, Ti_HAc, hc_HAc,...\n yLO_HAc, yHI_HAc, uLO_HAc, uHI_HAc, act_HAc, Ponly_HAc, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(4))==0 & k~=0\n [xxx_LevelVap, yyy_LevelVap]=Transmit(y_ss(2), xxx_LevelVap, yyy_LevelVap, ded_LevelVap, tau_LevelVap, Nded_LevelVap, Ntau_LevelVap, ht_LevelVap, yLO_LevelVap, yHI_LevelVap);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(4))==0 & k~=0\n [MVs(4),xi_LevelVap,flag_LevelVap]=controller(SP_LevelVap, yyy_LevelVap(Ntau_LevelVap), MVs(4), xi_LevelVap, mode_LevelVap, K_LevelVap, Ti_LevelVap, hc_LevelVap,...\n yLO_LevelVap, yHI_LevelVap, uLO_LevelVap, uHI_LevelVap, act_LevelVap, Ponly_LevelVap, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(5))==0 & k~=0\n [xxx_PresVap, yyy_PresVap]=Transmit(y_ss(1), xxx_PresVap, yyy_PresVap, ded_PresVap, tau_PresVap, Nded_PresVap, Ntau_PresVap, ht_PresVap, yLO_PresVap, yHI_PresVap);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(5))==0 & k~=0\n [MVs(5),xi_PresVap,flag_PresVap]=controller(SP_PresVap, yyy_PresVap(Ntau_PresVap), MVs(5), xi_PresVap, mode_PresVap, K_PresVap, Ti_PresVap, hc_PresVap,...\n yLO_PresVap, yHI_PresVap, uLO_PresVap, uHI_PresVap, act_PresVap, Ponly_PresVap, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(6))==0 & k~=0\n [xxx_ReactorInletTemp, yyy_ReactorInletTemp]=Transmit(y_ss(4), xxx_ReactorInletTemp, yyy_ReactorInletTemp, ded_ReactorInletTemp, tau_ReactorInletTemp, Nded_ReactorInletTemp, Ntau_ReactorInletTemp, ht_ReactorInletTemp, yLO_ReactorInletTemp, yHI_ReactorInletTemp);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(6))==0 & k~=0\n [MVs(6),xi_ReactorInletTemp,flag_ReactorInletTemp]=controller(SP_ReactorInletTemp, yyy_ReactorInletTemp(Ntau_ReactorInletTemp), MVs(6), xi_ReactorInletTemp, mode_ReactorInletTemp, K_ReactorInletTemp, Ti_ReactorInletTemp, hc_ReactorInletTemp,...\n yLO_ReactorInletTemp, yHI_ReactorInletTemp, uLO_ReactorInletTemp, uHI_ReactorInletTemp, act_ReactorInletTemp, Ponly_ReactorInletTemp, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(7))==0 & k~=0\n [xxx_TRCT, yyy_TRCT]=Transmit(y_ss(5), xxx_TRCT, yyy_TRCT, ded_TRCT, tau_TRCT, Nded_TRCT, Ntau_TRCT, ht_TRCT, yLO_TRCT, yHI_TRCT);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(7))==0 & k~=0\n [MVs(7),xi_TRCT,flag_TRCT]=controller(SP_TRCT, yyy_TRCT(Ntau_TRCT), MVs(7), xi_TRCT, mode_TRCT, K_TRCT, Ti_TRCT, hc_TRCT,...\n yLO_TRCT, yHI_TRCT, uLO_TRCT, uHI_TRCT, act_TRCT, Ponly_TRCT, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(8))==0 & k~=0\n [xxx_LevelSep, yyy_LevelSep]=Transmit(y_ss(9), xxx_LevelSep, yyy_LevelSep, ded_LevelSep, tau_LevelSep, Nded_LevelSep, Ntau_LevelSep, ht_LevelSep, yLO_LevelSep, yHI_LevelSep);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(8))==0 & k~=0\n [MVs(8),xi_LevelSep,flag_LevelSep]=controller(SP_LevelSep, yyy_LevelSep(Ntau_LevelSep), MVs(8), xi_LevelSep, mode_LevelSep, K_LevelSep, Ti_LevelSep, hc_LevelSep,...\n yLO_LevelSep, yHI_LevelSep, uLO_LevelSep, uHI_LevelSep, act_LevelSep, Ponly_LevelSep, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(9))==0 & k~=0\n [xxx_TempSep, yyy_TempSep]=Transmit(y_ss(10), xxx_TempSep, yyy_TempSep, ded_TempSep, tau_TempSep, Nded_TempSep, Ntau_TempSep, ht_TempSep, yLO_TempSep, yHI_TempSep);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(9))==0 & k~=0\n [MVs(9),xi_TempSep,flag_TempSep]=controller(SP_TempSep, yyy_TempSep(Ntau_TempSep), MVs(9), xi_TempSep, mode_TempSep, K_TempSep, Ti_TempSep, hc_TempSep,...\n yLO_TempSep, yHI_TempSep, uLO_TempSep, uHI_TempSep, act_TempSep, Ponly_TempSep, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(11))==0 & k~=0\n [xxx_CompOutletTemp, yyy_CompOutletTemp]=Transmit(y_ss(11), xxx_CompOutletTemp, yyy_CompOutletTemp, ded_CompOutletTemp, tau_CompOutletTemp, Nded_CompOutletTemp, Ntau_CompOutletTemp, ht_CompOutletTemp, yLO_CompOutletTemp, yHI_CompOutletTemp);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(11))==0 & k~=0\n [MVs(11),xi_CompOutletTemp,flag_CompOutletTemp]=controller(SP_CompOutletTemp, yyy_CompOutletTemp(Ntau_CompOutletTemp), MVs(11), xi_CompOutletTemp, mode_CompOutletTemp, K_CompOutletTemp, Ti_CompOutletTemp, hc_CompOutletTemp,...\n yLO_CompOutletTemp, yHI_CompOutletTemp, uLO_CompOutletTemp, uHI_CompOutletTemp, act_CompOutletTemp, Ponly_CompOutletTemp, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(12))==0 & k~=0\n [xxx_LevelAbs, yyy_LevelAbs]=Transmit(y_ss(13), xxx_LevelAbs, yyy_LevelAbs, ded_LevelAbs, tau_LevelAbs, Nded_LevelAbs, Ntau_LevelAbs, ht_LevelAbs, yLO_LevelAbs, yHI_LevelAbs);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(12))==0 & k~=0\n [MVs(12),xi_LevelAbs,flag_LevelAbs]=controller(SP_LevelAbs, yyy_LevelAbs(Ntau_LevelAbs), MVs(12), xi_LevelAbs, mode_LevelAbs, K_LevelAbs, Ti_LevelAbs, hc_LevelAbs,...\n yLO_LevelAbs, yHI_LevelAbs, uLO_LevelAbs, uHI_LevelAbs, act_LevelAbs, Ponly_LevelAbs, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(14))==0 & k~=0\n [xxx_CircOutletTemp, yyy_CircOutletTemp]=Transmit(y_ss(14), xxx_CircOutletTemp, yyy_CircOutletTemp, ded_CircOutletTemp, tau_CircOutletTemp, Nded_CircOutletTemp, Ntau_CircOutletTemp, ht_CircOutletTemp, yLO_CircOutletTemp, yHI_CircOutletTemp);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(14))==0 & k~=0\n [MVs(14),xi_CircOutletTemp,flag_CircOutletTemp]=controller(SP_CircOutletTemp, yyy_CircOutletTemp(Ntau_CircOutletTemp), MVs(14), xi_CircOutletTemp, mode_CircOutletTemp, K_CircOutletTemp, Ti_CircOutletTemp, hc_CircOutletTemp,...\n yLO_CircOutletTemp, yHI_CircOutletTemp, uLO_CircOutletTemp, uHI_CircOutletTemp, act_CircOutletTemp, Ponly_CircOutletTemp, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(16))==0 & k~=0\n [xxx_ScrubOutletTemp, yyy_ScrubOutletTemp]=Transmit(y_ss(15), xxx_ScrubOutletTemp, yyy_ScrubOutletTemp, ded_ScrubOutletTemp, tau_ScrubOutletTemp, Nded_ScrubOutletTemp, Ntau_ScrubOutletTemp, ht_ScrubOutletTemp, yLO_ScrubOutletTemp, yHI_ScrubOutletTemp);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(16))==0 & k~=0\n [MVs(16),xi_ScrubOutletTemp,flag_ScrubOutletTemp]=controller(SP_ScrubOutletTemp, yyy_ScrubOutletTemp(Ntau_ScrubOutletTemp), MVs(16), xi_ScrubOutletTemp, mode_ScrubOutletTemp, K_ScrubOutletTemp, Ti_ScrubOutletTemp, hc_ScrubOutletTemp,...\n yLO_ScrubOutletTemp, yHI_ScrubOutletTemp, uLO_ScrubOutletTemp, uHI_ScrubOutletTemp, act_ScrubOutletTemp, Ponly_ScrubOutletTemp, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(17))==0 & k~=0\n [xxx_CO2, yyy_CO2]=Transmit(y_ss(31), xxx_CO2, yyy_CO2, ded_CO2, tau_CO2, Nded_CO2, Ntau_CO2, ht_CO2, yLO_CO2, yHI_CO2);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(17))==0 & k~=0\n [MVs(17),xi_CO2,flag_CO2]=controller(SP_CO2, yyy_CO2(Ntau_CO2), MVs(17), xi_CO2, mode_CO2, K_CO2, Ti_CO2, hc_CO2,...\n yLO_CO2, yHI_CO2, uLO_CO2, uHI_CO2, act_CO2, Ponly_CO2, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(18))==0 & k~=0\n [xxx_C2H6, yyy_C2H6]=Transmit(y_ss(33), xxx_C2H6, yyy_C2H6, ded_C2H6, tau_C2H6, Nded_C2H6, Ntau_C2H6, ht_C2H6, yLO_C2H6, yHI_C2H6);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(18))==0 & k~=0\n [MVs(18),xi_C2H6,flag_C2H6]=controller(SP_C2H6, yyy_C2H6(Ntau_C2H6), MVs(18), xi_C2H6, mode_C2H6, K_C2H6, Ti_C2H6, hc_C2H6,...\n yLO_C2H6, yHI_C2H6, uLO_C2H6, uHI_C2H6, act_C2H6, Ponly_C2H6, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(19))==0 & k~=0\n [xxx_FEHE, yyy_FEHE]=Transmit(y_ss(8), xxx_FEHE, yyy_FEHE, ded_FEHE, tau_FEHE, Nded_FEHE, Ntau_FEHE, ht_FEHE, yLO_FEHE, yHI_FEHE);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(19))==0 & k~=0\n [MVs(19),xi_FEHE,flag_FEHE]=controller(SP_FEHE, yyy_FEHE(Ntau_FEHE), MVs(19), xi_FEHE, mode_FEHE, K_FEHE, Ti_FEHE, hc_FEHE,...\n yLO_FEHE, yHI_FEHE, uLO_FEHE, uHI_FEHE, act_FEHE, Ponly_FEHE, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(20))==0 & k~=0\n [xxx_H2OCol, yyy_H2OCol]=Transmit(y_ss(28), xxx_H2OCol, yyy_H2OCol, ded_H2OCol, tau_H2OCol, Nded_H2OCol, Ntau_H2OCol, ht_H2OCol, yLO_H2OCol, yHI_H2OCol);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(20))==0 & k~=0\n [MVs(20),xi_H2OCol,flag_H2OCol]=controller(SP_H2OCol, yyy_H2OCol(Ntau_H2OCol), MVs(20), xi_H2OCol, mode_H2OCol, K_H2OCol, Ti_H2OCol, hc_H2OCol,...\n yLO_H2OCol, yHI_H2OCol, uLO_H2OCol, uHI_H2OCol, act_H2OCol, Ponly_H2OCol, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(21))==0 & k~=0\n [xxx_TempCol, yyy_TempCol]=Transmit(y_ss(22), xxx_TempCol, yyy_TempCol, ded_TempCol, tau_TempCol, Nded_TempCol, Ntau_TempCol, ht_TempCol, yLO_TempCol, yHI_TempCol);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(21))==0 & k~=0\n [MVs(21),xi_TempCol,flag_TempCol]=controller(SP_TempCol, yyy_TempCol(Ntau_TempCol), MVs(21), xi_TempCol, mode_TempCol, K_TempCol, Ti_TempCol, hc_TempCol,...\n yLO_TempCol, yHI_TempCol, uLO_TempCol, uHI_TempCol, act_TempCol, Ponly_TempCol, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(22))==0 & k~=0\n [xxx_DecanterTemp, yyy_DecanterTemp]=Transmit(y_ss(20), xxx_DecanterTemp, yyy_DecanterTemp, ded_DecanterTemp, tau_DecanterTemp, Nded_DecanterTemp, Ntau_DecanterTemp, ht_DecanterTemp, yLO_DecanterTemp, yHI_DecanterTemp);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(22))==0 & k~=0\n [MVs(22),xi_DecanterTemp,flag_DecanterTemp]=controller(SP_DecanterTemp, yyy_DecanterTemp(Ntau_DecanterTemp), MVs(22), xi_DecanterTemp, mode_DecanterTemp, K_DecanterTemp, Ti_DecanterTemp, hc_DecanterTemp,...\n yLO_DecanterTemp, yHI_DecanterTemp, uLO_DecanterTemp, uHI_DecanterTemp, act_DecanterTemp, Ponly_DecanterTemp, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(23))==0 & k~=0\n [xxx_Organic, yyy_Organic]=Transmit(y_ss(18), xxx_Organic, yyy_Organic, ded_Organic, tau_Organic, Nded_Organic, Ntau_Organic, ht_Organic, yLO_Organic, yHI_Organic);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(23))==0 & k~=0\n [MVs(23),xi_Organic,flag_Organic]=controller(SP_Organic, yyy_Organic(Ntau_Organic), MVs(23), xi_Organic, mode_Organic, K_Organic, Ti_Organic, hc_Organic,...\n yLO_Organic, yHI_Organic, uLO_Organic, uHI_Organic, act_Organic, Ponly_Organic, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(24))==0 & k~=0\n [xxx_Aqueous, yyy_Aqueous]=Transmit(y_ss(19), xxx_Aqueous, yyy_Aqueous, ded_Aqueous, tau_Aqueous, Nded_Aqueous, Ntau_Aqueous, ht_Aqueous, yLO_Aqueous, yHI_Aqueous);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(24))==0 & k~=0\n [MVs(24),xi_Aqueous,flag_Aqueous]=controller(SP_Aqueous, yyy_Aqueous(Ntau_Aqueous), MVs(24), xi_Aqueous, mode_Aqueous, K_Aqueous, Ti_Aqueous, hc_Aqueous,...\n yLO_Aqueous, yHI_Aqueous, uLO_Aqueous, uHI_Aqueous, act_Aqueous, Ponly_Aqueous, 0, 0, 0, 0);\n end\n\n if rem(k,model_sampling_frequency/transmitter_sampling_frequency(25))==0 & k~=0\n [xxx_ColButtom, yyy_ColButtom]=Transmit(y_ss(21), xxx_ColButtom, yyy_ColButtom, ded_ColButtom, tau_ColButtom, Nded_ColButtom, Ntau_ColButtom, ht_ColButtom, yLO_ColButtom, yHI_ColButtom);\n end\n if rem(k,model_sampling_frequency/controller_sampling_frequency(25))==0 & k~=0\n [MVs(25),xi_ColButtom,flag_ColButtom]=controller(SP_ColButtom, yyy_ColButtom(Ntau_ColButtom), MVs(25), xi_ColButtom, mode_ColButtom, K_ColButtom, Ti_ColButtom, hc_ColButtom,...\n yLO_ColButtom, yHI_ColButtom, uLO_ColButtom, uHI_ColButtom, act_ColButtom, Ponly_ColButtom, 0, 0, 0, 0);\n end\n\nend\ntoc\n%plot graphics\nmy_label=[' %O2 ';' Pres ';' HAc-L ';' Vap-L ';' Vap-P ';' Pre-T ';' RCT-T ';' Sep-L ';' Sep-T ';' Sep-V ';' Com-T ';' Abs-L ';' Cir-F ';' Cir-T ';' Scr-F ';' Scr-T ';' %CO2 ';' %C2H6 ';' FEHE-T ';' %H2O ';' Col-T ';' Org-L ';' Aqu-L ';' Col-L ';' Vap-In ';' Dect-T ';'%VAc E-3'];\nMV_label=[' F-O2 ';'F-C2H4';' F-HAc';' Q-Vap';' F-Vap';'Q-Heat';'ShellT';'F-SepL';' T-Sep';'F-SepV';'Q-Comp';'F-AbsL';'F-Circ';'Q-Circ';'F-Scru';'Q-Scru';' F-CO2';' Purge';'bypass';'Reflux';'Q-Rebo';'F-Orga';'F-Aque';' F-Bot';'Q_Cond';'F-Tank'];\nsetpoint=[SP_O2;SP_C2H4;SP_HAc;SP_LevelVap;SP_PresVap;150;SP_TRCT;SP_LevelSep;SP_TempSep;16.1026;80;SP_LevelAbs;15.1198;25;0.756;25;SP_CO2;SP_C2H6;SP_FEHE;SP_H2OCol;SP_TempCol;0.5;0.5;SP_ColButtom;45.845;2.1924];\nwarning off\nif selected_ID==1\n McAvoy_Plot_1(y_history,u_history,setpoint,my_label,MV_label,storage_sampling_frequency);\nelseif selected_ID==2\n McAvoy_Plot_2(y_history,u_history,setpoint,my_label,MV_label,storage_sampling_frequency);\nelseif selected_ID==3\n McAvoy_Plot_3(y_history,u_history,setpoint,my_label,MV_label,storage_sampling_frequency);\nelseif selected_ID==4\n McAvoy_Plot_4(y_history,u_history,setpoint,my_label,MV_label,storage_sampling_frequency); \nelse\n Transient_Plot(y_history,u_history,setpoint,my_label,MV_label,storage_sampling_frequency); \nend\nreturn\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/4110-vinyl-acetate-process-model/test_VAcPlant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.026355349978307813, "lm_q1q2_score": 0.012252644009801028}} {"text": "function [bbci_cls, data_adapt]= bbci_adaptation_pcovmean(bbci_cls, data_adapt, marker, varargin)\n%BBCI_ADAPTATIOIN_PCOVMEAN - Supervised adapt class means and pooled covariance matrix of an LDA classifier\n%\n%Technique by Carmen Vidaurre, see\n% Viduarre C et al, J Neural Eng, 2011\n% http://dx.doi.org/10.1088/1741-2560/8/2/025009\n%\n%Synopsis:\n% [BBCI_CLS, DATA_ADAPT]= ...\n% bbci_adaptation_pcovmean(BBCI_CLS, DATA_ADAPT, 'init', PARAMs, ...)\n% [BBCI_CLS, DATA_ADAPT]= ...\n% bbci_adaptation_pcovmean(BBCI_CLS, DATA_ADAPT, MARKER, FEATURE)\n%\n%This function is called internally by bbci_apply_adaptation.\n%\n%The selectable parameters are\n% 'UC_mean' - [DOUBLE, default 0.05] Update coefficient for supervised\n% adaptation of the class means.\n% 'UC_pcov' - [DOUBLE, default 0.03] Update coefficient for unsupervised\n% adaptation of the pooled covariance matrix (inverse of the\n% extended ..., to be exact).\n% 'ival' - [1x2 DOUBLE] Time interval relative to the start marker, during\n% which features are averaged and used for adaptation; \n% no default - needs to be set.\n% Note: When choosing the start of the adaptation interval,\n% you have to take into account bbci.feature.ival (meaning\n% that feature are based on retrospective signals).\n% 'mrk_start' - {1xnClasses CELL} defines the markers that trigger the\n% adaptation for each class; no default - needs to be set.\n% 'mrk_end' - [1 nMarkers INT, default []] specifies markers that indicate\n% the end of a trial. Gathering feature information for the\n% adaptation of one trial ends, when one of those end-markers\n% is received AND the end of the adaptation interval 'ival'\n% (see above) is reached. If 'mrk_end' is empty, the first part\n% of the condition is ignored, i.e., only 'ival' is taken into\n% account.\n% 'scaling' - [BOOL, default true] Defines whether the updated classifier\n% should be (re-) scaled.\n% 'log_mean_limit' - [INT, default 100].\n\n% 01-2012 Benjamin Blankertz\n% 04-2011 Claudia Sannelli\n\n\nif ischar(marker) && strcmp(marker, 'init'),\n props= {'UC_mean' 0.05 '!DOUBLE[1]'\n 'UC_pcov' 0.03 '!DOUBLE[1]'\n 'ival' [] '!DOUBLE[2]'\n 'scaling' 1 '!BOOL'\n 'mrk_start' {} 'CELL'\n 'mrk_end' [] 'INT'\n 'log_mean_limit' 100 '!INT'\n 'tag' '' 'CHAR'\n };\n opt= opt_proplistToStruct(varargin{:});\n opt= opt_setDefaults(opt, props, 2);\n data_adapt.opt= opt;\n data_adapt.feature= zeros(size(bbci_cls.C.w));\n data_adapt.trial_start= NaN;\n data_adapt.lastcheck= -inf;\n bbci_log_write(data_adapt.log.fid, ...\n '# %s started with bias=%g and options %s.', ...\n data_adapt.opt.tag, bbci_cls.C.b, util_toString(opt));\n return;\nelse\n feature= varargin{1};\nend\n\ntime= marker.current_time;\ncheck_ival= [data_adapt.lastcheck time];\nevents= bbci_apply_queryMarker(marker, check_ival);\ndata_adapt.lastcheck= time;\n\nif ~isempty(events) && isnan(data_adapt.trial_start),\n data_adapt.clidx= 0;\n for k= 1:length(data_adapt.opt.mrk_start),\n marker_idx= find(ismember([events.desc], data_adapt.opt.mrk_start{k},'legacy'));\n if ~isempty(marker_idx),\n data_adapt.clidx= k;\n break;\n end\n end\n if data_adapt.clidx>0,\n data_adapt.trial_start= events(marker_idx(1)).time;\n data_adapt.end_marker_received= isempty(data_adapt.opt.mrk_end);\n data_adapt.counter= 0;\n bbci_log_write(data_adapt.log.fid, ...\n ['# %s at ' data_adapt.log.time_fmt ...\n ' trial started with marker %d -> class %d.'], ...\n data_adapt.opt.tag, data_adapt.trial_start/1000, ...\n events(marker_idx(1)).desc, data_adapt.clidx);\n end\nend\n\nif isnan(data_adapt.trial_start),\n return;\nend\n\n% within the adaptation interval, add up the features and count them\nadapt_ival= data_adapt.trial_start + data_adapt.opt.ival;\nif time >= adapt_ival(1) && time <= adapt_ival(2),\n data_adapt.feature= data_adapt.feature + feature.x(:);\n data_adapt.counter= data_adapt.counter + 1;\nend\n\nif ~isempty(events) && any(ismember([events.desc], data_adapt.opt.mrk_end,'legacy'));\n data_adapt.end_marker_received= 1;\nend\nif data_adapt.end_marker_received && time >= adapt_ival(2),\n if data_adapt.counter==0,\n return;\n end\n % handy definitions\n UCm= data_adapt.opt.UC_mean;\n UCp= data_adapt.opt.UC_pcov;\n feat= data_adapt.feature/data_adapt.counter;\n % adapt class means (supervised)\n bbci_cls.C.mean(:,data_adapt.clidx)= UCm * feat + ...\n (1 - UCm) * bbci_cls.C.mean(:,data_adapt.clidx);\n % adapt (inverse of extended) pooled covariance matrix (unsupervised)\n extfeat= [1; feat];\n v= bbci_cls.C.extinvcov*extfeat;\n bbci_cls.C.extinvcov= (1/(1 - UCp)) * ...\n (bbci_cls.C.extinvcov - UCp/(1 - UCp + UCp * extfeat' * v) * v*v');\n bbci_cls.C.extinvcov= 0.5 * (bbci_cls.C.extinvcov + bbci_cls.C.extinvcov');\n % recalculate classifier\n diff_mean= diff(bbci_cls.C.mean, 1, 2);\n bbci_cls.C.w= bbci_cls.C.extinvcov(2:end, 2:end) * diff_mean;\n \n % rescale projection vector\n if data_adapt.opt.scaling,\n bbci_cls.C.w= bbci_cls.C.w/(bbci_cls.C.w' * diff_mean)*2;\n end\n bbci_cls.C.b= -bbci_cls.C.w' * mean(bbci_cls.C.mean, 2);\n if numel(bbci_cls.C.mean) < data_adapt.opt.log_mean_limit,\n bbci_log_write(data_adapt.log.fid, ...\n ['# %s at ' data_adapt.log.time_fmt ...\n ' bias adapted to %g, mean adapted to %s' ...\n ' with %d features.'], ...\n data_adapt.opt.tag, marker.current_time/1000, ...\n bbci_cls.C.b, util_toString(bbci_cls.C.mean), ...\n data_adapt.counter);\n else\n bbci_log_write(data_adapt.log.fid, ...\n ['# %s at ' data_adapt.log.time_fmt ...\n ' bias adapted to %g with %d features.'], ...\n data_adapt.opt.tag, marker.current_time/1000, ...\n bbci_cls.C.b, data_adapt.counter);\n end\n data_adapt.feature(:)= 0;\n data_adapt.trial_start= NaN;\nend\n", "meta": {"author": "bbci", "repo": "bbci_public", "sha": "2e6fe9481537dcfee702e74544191dcf737f02ce", "save_path": "github-repos/MATLAB/bbci-bbci_public", "path": "github-repos/MATLAB/bbci-bbci_public/bbci_public-2e6fe9481537dcfee702e74544191dcf737f02ce/online/adaptation/bbci_adaptation_pcovmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.027169230157193653, "lm_q1q2_score": 0.011999915145777935}} {"text": "function exact = p00_exact ( problem )\n\n%*****************************************************************************80\n%\n%% P00_EXACT returns the exact integral for any problem.\n%\n% Discussion:\n%\n% This routine provides a \"generic\" interface to the exact integral\n% routines for the various problems, and allows a problem to be called\n% by index (PROBLEM) rather than by name.\n%\n% In most cases, the \"exact\" value of the integral is not given;\n% instead a \"respectable\" approximation is available.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer PROBLEM, the index of the problem.\n%\n% Output, real EXACT, the exact value of the integral.\n%\n if ( problem == 1 )\n exact = p01_exact ( );\n elseif ( problem == 2 )\n exact = p02_exact ( );\n elseif ( problem == 3 )\n exact = p03_exact ( );\n elseif ( problem == 4 )\n exact = p04_exact ( );\n elseif ( problem == 5 )\n exact = p05_exact ( );\n elseif ( problem == 6 )\n exact = p06_exact ( );\n elseif ( problem == 7 )\n exact = p07_exact ( );\n elseif ( problem == 8 )\n exact = p08_exact ( );\n elseif ( problem == 9 )\n exact = p09_exact ( );\n elseif ( problem == 10 )\n exact = p10_exact ( );\n elseif ( problem == 11 )\n exact = p11_exact ( );\n elseif ( problem == 12 )\n exact = p12_exact ( );\n elseif ( problem == 13 )\n exact = p13_exact ( );\n elseif ( problem == 14 )\n exact = p14_exact ( );\n elseif ( problem == 15 )\n exact = p15_exact ( );\n elseif ( problem == 16 )\n exact = p16_exact ( );\n elseif ( problem == 17 )\n exact = p17_exact ( );\n elseif ( problem == 18 )\n exact = p18_exact ( );\n elseif ( problem == 19 )\n exact = p19_exact ( );\n elseif ( problem == 20 )\n exact = p20_exact ( );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'P00_EXACT - Fatal error!\\n' );\n fprintf ( 1, ' Illegal problem number = %d\\n', problem );\n error ( 'P00_EXACT - Fatal error!' );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laguerre_test_int/p00_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.04468086741043219, "lm_q1q2_score": 0.011879770165595903}} {"text": "function varargout = KUKA_GUI(varargin)\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @KUKA_GUI_OpeningFcn, ...\n 'gui_OutputFcn', @KUKA_GUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% %%\n%%% Written by Rohit Mishra %%\n%%% A.C. Patil College of Engg. %%\n%%% March 2013 %%\n%%% Simulation of six axis kuka kr6. %%\n%%% %%\n%%% The purpose of this program is to simulate a six axis kuka kr6 %%\t\t\n%%% robot located in the DRHR DEPT. at BARC MUMBAI . This %%\n%%% program simulates Forward Kinematics of this robot. %%\n%%% To operate this program: %% \n%%% 1) Make sure that KUKA.WRL, KUKA_GUI.fig, KUKA_GUI.m %%\n%%% are in the appropriate path. %% \n%%% 2) Execute KUKA_GUI.m %%\n%%% 4) Have fun! %%\n%%% If you have question about this program email Rohit Mishra %%\n%%% . Rohit Mishra is Final Year Student%%\n%%% from Mumbai University(ACPCE, TRONIX 2013)has developed this %%\n%%% project with the help of his friends Tejas Mahadik, Kaushik %%\n%%% Natrajan and Siddhesh Chavan . %%\n%%% We are thankful to our project guide and HOD Dr. V.N. Pawar for %%\n%%% his unwavering support and guidance in helping us with this %%\n%%% project and also to Mrs. Varsha Shirwalkar at Barc, Mumbai. %%\n%%% %%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n \n\n\nfunction KUKA_GUI_OpeningFcn(hObject, eventdata, handles, varargin)\nhandles.output = hObject;\nguidata(hObject, handles);\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nview(KUKA)\n\n radian=0\n KUKA.shoulder.rotation = [0, 1, 0, radian];\n \n KUKA.elbow.rotation = [0, 0, 1, radian];\n\n KUKA.pitch.rotation = [0, 0, 1, radian];\n \n KUKA.roll.rotation = [1, 0, 0, radian];\n \n KUKA.yaw.rotation = [0, 0, 1, radian];\n \n KUKA.drill.rotation = [1, 0, 0, radian];\n \n\n% --- Executes on slider movement.\nfunction slider1_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT1=get(handles.slider1,'value');\nset(handles.edit57,'String',num2str(T1));\nguidata(hObject, handles);\n radian=T1*pi/180;\n q1=radian;\n KUKA.shoulder.rotation = [0, 1, 0, radian];\n \n% --- Executes on slider movement.\nfunction slider2_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT2=get(handles.slider2,'value');\nset(handles.edit58,'String',num2str(T2));\nguidata(hObject, handles);\n radian=T2*pi/180;\n q2=radian;\n KUKA.elbow.rotation = [0, 0, 1, radian];\n\n\n% --- Executes on slider movement.\nfunction slider3_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT3=get(handles.slider3,'value');\nset(handles.edit59,'String',num2str(T3));\nguidata(hObject, handles);\n radian=T3*pi/180;\n q3=radian;\n KUKA.pitch.rotation = [0, 0, 1, radian];\n\n\n\n% --- Executes on slider movement.\nfunction slider4_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT4=-get(handles.slider4,'value');\nset(handles.edit60,'String',num2str(T4));\nguidata(hObject, handles);\n radian=T4*pi/180;\n q4=radian;\n KUKA.roll.rotation = [1, 0, 0, radian];\n\n\n% --- Executes on slider movement.\nfunction slider5_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT5=-get(handles.slider5,'value');\n set(handles.edit61,'String',num2str(T5));\n guidata(hObject, handles);\n radian=T5*pi/180;\n q5=radian;\n KUKA.yaw.rotation = [0, 0, 1, radian];\n \n \n % --- Executes on slider movement.\nfunction slider6_Callback(hObject, eventdata, handles)\nKUKA = vrworld('KUKA.wrl');\nopen(KUKA)\nT6=-get(handles.slider6,'value');\nset(handles.edit62,'String',num2str(T6));\nguidata(hObject, handles);\n radian=T6*pi/180;\n q6=radian;\n KUKA.drill.rotation = [1, 0, 0, radian];\n\n\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n\n\n% % % GIVEN JOINT VARIABLES\n\nd=[335 0 0 -295 0 -80];\na=[75 270 90 0 0 0];\n \n% % TRANSFORMATION MATRIX 1.\nq1=get(handles.slider1,'Value');\nT1=[ cos(q1) 0 -sin(q1) a(1)*cos(q1)\n sin(q1) 0 -cos(q1) a(1)*sin(q1) \n 0 -1 0 d(1)\n 0 0 0 1 ];\n\n% % TRANSFORMATION MATRIX 2. \nq2=get(handles.slider2,'Value');\nT2=[ cos(q2) -sin(q2) 0 a(2)*cos(q2)\n sin(q2) cos(q2) 0 a(2)*sin(q2)\n 0 0 1 0\n 0 0 0 1 ];\n \n\n% % TRANSFORMATION MATRIX 3. \nq3=get(handles.slider3,'Value');\nT3=[ cos(q3) 0 sin(q3) a(3)*cos(q3)\n sin(q3) 0 -cos(q3) a(3)*sin(q3)\n 0 0 0 0\n 0 0 0 1 ];\n% % TRANSFORMATION MATRIX 4. \nq4=get(handles.slider4,'Value');\nT4=[ cos(q4) 0 -sin(q4) 0\n sin(q4) 0 cos(q4) 0\n 0 -1 0 d(4)\n 0 0 0 1 ];\n \n\n% % TRANSFORMATION MATRIX 5.\nq5=get(handles.slider5,'Value');\nT5=[ cos(q5) 0 sin(q5) 0 \n sin(q5) 0 -cos(q5) 0\n 0 1 0 0\n 0 0 0 1 ];\n \n\n% % TRANSFORMATION MATRIX 6. \nq6=get(handles.slider6,'Value');\nT6=[ cos(q6) -sin(q6) 0 0\n sin(q6) cos(q6) 0 0\n 0 0 1 0\n 0 0 0 1 ];\n \n \n \nA=T1*T2*T3*T4*T5*T6;\n \nset(handles.edit42,'String',num2str(A(13)));\nset(handles.edit43,'String',num2str(A(14)));\nset(handles.edit44,'String',num2str(A(15)));\nset(handles.edit48,'String',num2str(A(1)));\nset(handles.edit49,'String',num2str(A(5)));\nset(handles.edit50,'String',num2str(A(9)));\nset(handles.edit51,'String',num2str(A(2)));\nset(handles.edit52,'String',num2str(A(6)));\nset(handles.edit53,'String',num2str(A(10)));\nset(handles.edit54,'String',num2str(A(3)));\nset(handles.edit55,'String',num2str(A(7)));\nset(handles.edit56,'String',num2str(A(11)));\nguidata(hObject, handles);\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/41451-modelling-and-simulation-of-kuka-kr6-robot/kuka kr6 robot/KUKA_GUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.032589744883475005, "lm_q1q2_score": 0.011829073359292059}} {"text": "function [lrp] = ft_lateralizedpotential(cfg, avgL, avgR)\n\n% FT_LATERALIZEDPOTENTIAL computes lateralized potentials such as the\n% lateralized readiness potential (LRP)\n%\n% Use as\n% [lrp] = ft_lateralizedpotential(cfg, avgL, avgR)\n%\n% where the input datasets should come from FT_TIMELOCKANALYSIS\n% and the configuration should contain\n% cfg.channelcmb = Nx2 cell-array\n%\n% An example channelcombination containing the homologous channels\n% in the 10-20 standard system is\n% cfg.channelcmb = {'Fp1' 'Fp2'\n% 'F7' 'F8'\n% 'F3' 'F4'\n% 'T7' 'T8'\n% 'C3' 'C4'\n% 'P7' 'P8'\n% 'P3' 'P4'\n% 'O1' 'O2'}\n%\n% The lateralized potential is computed on combinations of channels and\n% not on indivudual channels. However, if you want to make a topographic\n% plot with e.g. FT_MULTIPLOTER, you can replace the output lrp.label\n% with lrp.plotlabel.\n%\n% The concept for the LRP was introduced approximately simultaneously in the\n% following two papers\n% - M. G. H. Coles. Modern mind-brain reading - psychophysiology,\n% physiology, and cognition. Psychophysiology, 26(3):251-269, 1988.\n% - R. de Jong, M. Wierda, G. Mulder, and L. J. Mulder. Use of\n% partial stimulus information in response processing. J Exp Psychol\n% Hum Percept Perform, 14:682-692, 1988.\n% and it is discussed in detail on a technical level in\n% - R. Oostenveld, D.F. Stegeman, P. Praamstra and A. van Oosterom.\n% Brain symmetry and topographic analysis of lateralized event-related\n% potentials. Clin Neurophysiol. 114(7):1194-202, 2003.\n%\n% To facilitate data-handling and distributed computing you can use\n% cfg.inputfile = ...\n% cfg.outputfile = ...\n% If you specify one of these (or both) the input data will be read from a *.mat\n% file on disk and/or the output data will be written to a *.mat file. These mat\n% files should contain only a single variable, corresponding with the\n% input/output structure.\n%\n% See also FT_TIMELOCKANALYSIS, FT_MULTIPLOTER\n\n% Copyright (C) 2004, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\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 avgL avgR\nft_preamble provenance avgL avgR\n\n% the ft_abort variable is set to true or false in ft_preamble_init\nif ft_abort\n return\nend\n\n% check if the input data is valid for this function\navgL = ft_checkdata(avgL, 'datatype', 'timelock');\navgR = ft_checkdata(avgR, 'datatype', 'timelock');\n\n% check if the input cfg is valid for this function\ncfg = ft_checkconfig(cfg, 'forbidden', {'channels'}); % prevent accidental typos, see issue 1729\n\n% set the defaults\nif ~isfield(cfg, 'channelcmb')\n cfg.channelcmb = {\n 'Fp1' 'Fp2'\n 'F7' 'F8'\n 'F3' 'F4'\n 'T7' 'T8'\n 'C3' 'C4'\n 'P7' 'P8'\n 'P3' 'P4'\n 'O1' 'O2'\n };\nend\n\nif ~isequal(avgL.time, avgR.time)\n ft_error('the time axes are not the same');\nend\n\n% start with an empty output structure\nlrp.label = {};\nlrp.plotlabel = {};\nlrp.avg = [];\nlrp.time = avgL.time;\n\n% add timelock signature\nif isfield(avgL, 'dimord') && isfield(avgR, 'dimord')\n if ~strcmp(avgL.dimord, avgR.dimord)\n ft_error('The input data are of different dimord types');\n else\n lrp.dimord = avgL.dimord;\n end\nelse\n ft_error('''dimord'' not found. The function expects timelock data');\nend\n\n% compute the lateralized potentials\nNchan = size(cfg.channelcmb,1);\nfor i=1:Nchan\n % here the channel names \"C3\" and \"C4\" are used to clarify the\n % computation of the lateralized potential on all channel pairs\n C3R = strcmp(cfg.channelcmb{i,1}, avgR.label);\n C4R = strcmp(cfg.channelcmb{i,2}, avgR.label);\n C3L = strcmp(cfg.channelcmb{i,1}, avgL.label);\n C4L = strcmp(cfg.channelcmb{i,2}, avgL.label);\n if any(C3R) && any(C4R) && any(C3L) && any(C4L)\n lrp.label{end+1} = sprintf('%s/%s', cfg.channelcmb{i,1}, cfg.channelcmb{i,2});\n lrp.plotlabel{end+1} = cfg.channelcmb{i,1};\n erpC3L = avgL.avg(C3L,:);\n erpC4L = avgL.avg(C4L,:);\n erpC3R = avgR.avg(C3R,:);\n erpC4R = avgR.avg(C4R,:);\n lrp.avg(end+1,:) = 1/2 * ((erpC3R - erpC4R) + (erpC4L - erpC3L));\n end\nend\n\n% do the general cleanup and bookkeeping at the end of the function\nft_postamble debug\nft_postamble previous avgL avgR\nft_postamble provenance lrp\nft_postamble history lrp\nft_postamble savevar lrp\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/ft_lateralizedpotential.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.04336579984571784, "lm_q1q2_score": 0.011796562235864626}} {"text": "function [s,error] = openDEeph( s, denum, ineph, dontSave )\n% open a binary JPL planetary ephemeris file and sets initial values\n% short int ephem_open (char *ephem_name,\n% double *jd_begin, double *jd_end,\n% short int *de_number)\n%\n% ------------------------------------------------------------------------\n%\n% PURPOSE:\n% This function opens a JPL planetary ephemeris file and\n% sets initial values. This function must be called\n% prior to calls to the other JPL ephemeris functions.\n%\n% REFERENCES:\n% Standish, E.M. and Newhall, X X (1988). \"The JPL Export\n% Planetary Ephemeris\"; JPL document dated 17 June 1988.\n%\n% INPUT\n% ARGUMENTS:\n% *ephem_name (char)\n% Name of the direct-access ephemeris file.\n%\n% OUTPUT\n% ARGUMENTS:\n% *jd_begin (double)\n% Beginning Julian date of the ephemeris file.\n% *jd_end (double)\n% Ending Julian date of the ephemeris file.\n% *de_number (short int)\n% DE number of the ephemeris file opened.\n%\n% RETURNED\n% VALUE:\n% (short int)\n% 0 ...file exists and is opened correctly.\n% 1 ...file does not exist/not found.\n% 2-10...error reading from file header.\n% 11 ...unable to set record length; ephemeris (DE number)\n% not in look-up table.\n%\n% GLOBALS\n% USED:\n% SS eph_manager.h\n% JPLAU eph_manager.h\n% PC eph_manager.h\n% VC eph_manager.h\n% TWOT eph_manager.h\n% EM_RATIO eph_manager.h\n% BUFFER eph_manager.h\n% IPT eph_manager.h\n% LPT eph_manager.h\n% NRL eph_manager.h\n% KM eph_manager.h\n% NP eph_manager.h\n% NV eph_manager.h\n% RECORD_LENGTH eph_manager.h\n% EPHFILE eph_manager.h\n%\n% FUNCTIONS\n% CALLED:\n% fclose stdio.h\n% free stdlib.h\n% fopen stdio.h\n% fread stdio.h\n% calloc stdlib.h\n%\n% VER./DATE/\n% PROGRAMMER:\n% V1.0/06-90/JAB (USNO/NA)\n% V1.1/06-92/JAB (USNO/AA): Restructure and add initializations.\n% V1.2/07-98/WTH (USNO/AA): Modified to open files for different\n% ephemeris types. (200,403,404,405,406)\n% V1.3/11-07/WKP (USNO/AA): Updated prolog.\n% V1.4/09-10/WKP (USNO/AA): Changed ncon and denum variables and\n% sizeof ipt array to type 'int' for\n% 64-bit system compatibility.\n% V1.5/09-10/WTH (USNO/AA): Added support for DE421, default case\n% for switch, close file on error.\n% V1.6/10-10/WKP (USNO/AA): Renamed function to lowercase to\n% comply with coding standards.\n%\n% NOTES:\n% KM...flag defining physical units of the output states.\n% = 1, km and km/sec\n% = 0, AU and AU/day\n% Default value is 0 (KM determines time unit for nutations.\n% Angle unit is always radians.)\n%\n% ------------------------------------------------------------------------\n persistent m;\n if isempty(m)\n m = containers.Map('KeyType','char','ValueType','any');\n end\n if nargin < 4\n dontSave = false;\n end\n s.de_number = 0;\n s.jd_begin = 0.0;\n s.jd_end = 0.0;\n if isnumeric(denum)\n denum = sprintf('%d',denum);\n end\n error = 0;\n if isempty(ineph)\n error = 1;\n return;\n elseif exist(ineph, 'file') ~= 2\n inasc = ineph;\n inasc(1:3) = 'asc';\n Ephem.asc2eph(denum,inasc,ineph);\n end\n if exist(ineph, 'file') == 2\n % found locally\n if m.isKey(ineph)\n st = m(ineph);\n else\n EPHFILE = fopen (ineph,'rb');\n if EPHFILE ~= -1\n for i=1:3\n [st.ttl{i},count] = fread (EPHFILE, Ephem.TTLsize, '*char');\n if count ~= Ephem.TTLsize\n error = 1;\n fprintf(2,'openDEeph: Error TTL retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,Ephem.TTLsize);\n end\n st.ttl{i} = strcat(transpose(st.ttl{i}));\n end\n % pos 252\n for i=1:Ephem.OLDCONMAX\n [st.CNAM{i},count] = fread (EPHFILE, Ephem.CNAMsize, '*char');\n if count ~= Ephem.CNAMsize\n error = 1;\n fprintf(2,'openDEeph: Error CNAM retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,Ephem.CNAMsize);\n end\n st.CNAM{i} = strcat(transpose(st.CNAM{i}));\n end\n % pos 2652\n [st.SS,count] = fread (EPHFILE, 3, 'double');\n if count ~= 3\n error = 1;\n fprintf(2,'openDEeph: Error SS retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,3);\n end\n [st.NCON,count] = fread (EPHFILE, 1, 'int32');\n if count ~= 1\n error = 1;\n fprintf(2,'openDEeph: Error NCON retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,1);\n end\n [st.JPLAU,count] = fread (EPHFILE, 1, 'double');\n if count ~= 1\n error = 1;\n fprintf(2,'openDEeph: Error JPLAU retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,1);\n end\n [st.EM_RATIO,count] = fread (EPHFILE, 1, 'double');\n if count ~= 1\n error = 1;\n fprintf(2,'openDEeph: Error EM_RATIO retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,1);\n end\n % pos 2652+8*3+4+8+8\n for i=1:12\n for j=1:3\n [st.IPT(j,i),count] = fread (EPHFILE, 1, 'int32');\n if count ~= 1\n error = 1;\n fprintf(2,'openDEeph: Error IPT retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,1);\n end\n end\n end\n % pos 2652+8*3+4+8+8+12*3*4\n [st.de_number,count] = fread (EPHFILE, 1, 'int32');\n st.de_number = sprintf('%d',st.de_number);\n if count ~= 1\n error = 1;\n fprintf(2,'openDEeph: Error de_number retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,1);\n end\n % pos 2652+8*3+4+8+8+12*3*4+4\n if strcmp(st.de_number,denum(1:min(length(st.de_number),length(denum)))) == false\n if s.output > 0\n fprintf(s.output,'openDEeph: Warning DE# retrieved %s from \"%s\", expected %s\\n',...\n st.de_number,ineph,denum);\n end\n end\n [LPT,count] = fread (EPHFILE, 3, 'int32');\n if count ~= 3\n error = 1;\n fprintf(2,'openDEeph: Error LPT retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,3);\n end\n % pos 2652+8*3+4+8+8+12*3*4+4+3*4\n for i=Ephem.OLDCONMAX+1:st.NCON\n [st.CNAM{i},count] = fread (EPHFILE, Ephem.CNAMsize, '*char');\n if count ~= Ephem.CNAMsize\n error = 1;\n fprintf(2,'openDEeph: Error CNAM retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,Ephem.CNAMsize);\n end\n st.CNAM{i} = strcat(transpose(st.CNAM{i}));\n end\n [RPT,count] = fread (EPHFILE, 3, 'int32');\n if count ~= 3\n error = 1;\n fprintf(2,'openDEeph: Error RPT retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,3);\n end\n [TPT,count] = fread (EPHFILE, 3, 'int32');\n if count ~= 3\n error = 1;\n fprintf(2,'openDEeph: Error TPT retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,3);\n end\n for i=1:3\n st.IPT(i,13) = LPT(i);\n st.IPT(i,14) = RPT(i);\n st.IPT(i,15) = TPT(i);\n end\n st.NCOEFF = Ephem.numCoeff( st.IPT );\n st.RECORD_LENGTH = 8*st.NCOEFF;\n status = fseek(EPHFILE,(2-1)*st.RECORD_LENGTH,'bof');\n if status == -1\n fprintf(2,'openDEeph seek error at %d\\n',2);\n end\n [st.CVAL,count] = fread (EPHFILE, st.NCON, 'double');\n if count ~= st.NCON\n error = 1;\n fprintf(2,'openDEeph: Error CVAL retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,st.NCON);\n end\n for i=1:st.NCON\n cnm = deblank(st.CNAM{i});\n indx = strfind(cnm,'.');\n for j=1:length(indx)\n cnm(indx(j)) = '_';\n end\n if ~isempty(cnm)\n st.(cnm) = st.CVAL(i);\n else\n st.('blank') = st.CVAL(i);\n end\n end\n st.masses(Ephem.Mercury) = st.GM1;\n st.masses(Ephem.Venus) = st.GM2;\n st.masses(Ephem.Mars) = st.GM4;\n st.masses(Ephem.Jupiter) = st.GM5;\n st.masses(Ephem.Saturn) = st.GM6;\n st.masses(Ephem.Uranus) = st.GM7;\n st.masses(Ephem.Neptune) = st.GM8;\n st.masses(Ephem.Pluto) = st.GM9;\n st.masses(Ephem.Sun) = st.GMS;\n st.masses(Ephem.EarthMoonBarycenter) = st.GMB;\n st.masses(Ephem.Moon) = st.GMB/(1+s.EM_RATIO);\n st.masses(Ephem.Earth) = st.GMB*s.EM_RATIO/(1+s.EM_RATIO);\n mm = 0;\n for i=Ephem.Mercury:Ephem.Sun\n mm = mm + st.masses(i);\n end\n st.masses(Ephem.SolarSystemBarycenter) = mm;\n\n pos = 1;\n status = fseek(EPHFILE,(3-1)*st.RECORD_LENGTH,'bof');\n if status == -1\n if s.output > 0\n fprintf(s.output,'openDEeph: Bad fseek of \"%s\"\\n',ineph);\n end\n fclose (EPHFILE);\n error = 9;\n return;\n end\n st.scan = zeros(1,0);\n for NROUT = 3:281474976710655\n [sc,count] = fread (EPHFILE,st.NCOEFF,'double');\n if isempty(sc) || count == 0 % expected end\n break;\n end\n if st.NCOEFF ~= count\n fprintf(2,'openDEeph: Error COEFF retrieved %d from \"%s\", expected %d\\n',...\n count,ineph,st.NCOEFF);\n %break;\n else\n for K=1:st.NCOEFF\n st.scan(pos) = sc(K);\n pos = pos + 1;\n end\n end\n end\n fclose (EPHFILE);\n if isempty(st.scan)\n if s.output > 0\n fprintf(s.output,'openDEeph: Bad textscan of \"%s\"\\n',ineph);\n end\n error = 9;\n return;\n end\n if dontSave == false\n m(ineph) = st;\n end\n else\n if s.output > 0\n fprintf(s.output,'openDEeph: Could not open \"%s\"\\n',ineph);\n end\n error = 10;\n return;\n end\n end\n else\n if s.output > 0\n fprintf(2,'openDEeph: Bad file access for \"%s\"\\n',ineph);\n end\n error = 10;\n return;\n end\n\n s.scan = st.scan;\n s.SS = st.SS;\n s.de_number = denum;\n s.RECORD_LENGTH = st.RECORD_LENGTH;\n s.IPT = st.IPT;\n s.JPLAU = st.JPLAU;\n s.EM_RATIO = st.EM_RATIO;\n for i=Ephem.Mercury:Ephem.EarthMoonBarycenter\n s.masses(i) = st.masses(i);\n end\n\n s.jd_begin = s.SS(1);\n s.jd_end = s.SS(2);\n s.jd_inc = s.SS(3);\n s.numRecs = 1 + (s.jd_end-s.jd_begin)/s.jd_inc;\n if mod(s.numRecs,1.0) ~= 0\n if s.output > 0\n fprintf(s.output,'openDEeph: DE%s Bad jd_inc (%g) numRecs (%g) should be integer\\n',...\n denum,s.indexInc,s.numRecs);\n end\n s.jd_begin = 0.0;\n s.jd_end = 0.0;\n s.jd_inc = 0.0;\n error = 12;\n return;\n end\n s.indexInc = s.RECORD_LENGTH / 8;\n s.indexOffset = -1;\nend\n", "meta": {"author": "goGPS-Project", "repo": "goGPS_MATLAB", "sha": "30644df61d2459e3347ac5f3e31b71d9f69f4b01", "save_path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB", "path": "github-repos/MATLAB/goGPS-Project-goGPS_MATLAB/goGPS_MATLAB-30644df61d2459e3347ac5f3e31b71d9f69f4b01/source/utility/sun_moon/Ephem/openDEeph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.02931223000938591, "lm_q1q2_score": 0.011609641189220412}} {"text": "function [resample] = resampledesign(cfg, design)\n\n% RESAMPLEDESIGN returns a resampling matrix, in which each row can be\n% used to resample either the original design matrix or the original data.\n% The random resampling is done given user-specified constraints on the\n% experimental design, e.g. to swap within paired observations but not\n% between pairs.\n%\n% Use as\n% [resample] = randomizedesign(cfg, design)\n% where the configuration can contain\n% cfg.resampling = 'permutation' or 'bootstrap'\n% cfg.numrandomization = number (e.g. 300), can be 'all' in case of two conditions\n% cfg.ivar = number or list with indices, independent variable(s)\n% cfg.uvar = number or list with indices, unit variable(s)\n% cfg.wvar = number or list with indices, within-cell variable(s)\n% cfg.cvar = number or list with indices, control variable(s)\n%\n% The \"Independent variable\" codes the condition number. Since the data is\n% assumed to be independent from the condition number any reshuffeling of\n% the condition number is allowed and ivar does NOT affect the resampling\n% outcome.\n%\n% The \"Unit of observation variable\" corresponds to the subject number (in a\n% within-subject manipulation) or the trial number (in a within-trial\n% manipulation). It is best understood by considering that it corresponds\n% to the \"pairing\" of the data in a paired T-test or repeared measures\n% ANOVA. The uvar affects the resampling outcome in the way that only\n% resamplings within one unit of observation are returned (e.g. swap\n% conditions within a subject, not over subjects).\n%\n% The \"Within-cell variable\" corresponds to the grouping of the data in\n% cells, where the multiple observations in a groups should not be broken\n% apart. This for example applies to multiple tapers in a spectral estimate\n% of a single trial of data (the \"rpttap\" dimension), where different\n% tapers should not be shuffled separately. Another example is a blocked\n% fMRI design, with a different condition in each block and multiple\n% repetitions of the same condition within a block. Assuming that there is\n% a slow HRF that convolutes the trials within a block, you can shuffle the\n% blocks but not the individual trials in a block.\n%\n% The \"Control variable\" can be seen as the opposite from the within-cell\n% variable: it allows you to specify blocks in which the resampling should\n% be done, at the same time controlling that repetitions are not shuffled\n% between different control blocks.\n%\n% See also FT_STATISTICS_MONTECARLO\n\n% Copyright (C) 2005-2020, Robert Oostenveld\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nft_checkopt(cfg, 'ivar', {'numericscalar', 'numericvector', 'empty'});\nft_checkopt(cfg, 'uvar', {'numericscalar', 'numericvector', 'empty'});\nft_checkopt(cfg, 'wvar', {'numericscalar', 'numericvector', 'empty'});\nft_checkopt(cfg, 'cvar', {'numericscalar', 'numericvector', 'empty'});\nft_checkopt(cfg, 'numrandomization', {'numericscalar', 'char'});\nft_checkopt(cfg, 'resampling', {'char'});\n\ncfg.ivar = ft_getopt(cfg, 'ivar'); % the default is empty\ncfg.uvar = ft_getopt(cfg, 'uvar'); % the default is empty\ncfg.wvar = ft_getopt(cfg, 'wvar'); % the default is empty\ncfg.cvar = ft_getopt(cfg, 'cvar'); % the default is empty\n\n% the default is 'no', consistent with the situation prior to 14 Sept 2011\n% FIXME this needs finalization\nefficient = ft_getopt(cfg, 'efficient', 'no');\n\n% if size(design,1)>size(design,2)\n% % this function wants the replications in the column direction\n% % the matrix seems to be transposed\n% design = transpose(design);\n% end\n\nNvar = size(design,1); % number of factors or regressors\nNrepl = size(design,2); % number of replications\n\nif ~isempty(intersect(cfg.ivar, cfg.uvar)), ft_warning('there is an intersection between cfg.ivar and cfg.uvar'); end\nif ~isempty(intersect(cfg.ivar, cfg.wvar)), ft_warning('there is an intersection between cfg.ivar and cfg.wvar'); end\nif ~isempty(intersect(cfg.ivar, cfg.cvar)), ft_warning('there is an intersection between cfg.ivar and cfg.cvar'); end\nif ~isempty(intersect(cfg.uvar, cfg.wvar)), ft_warning('there is an intersection between cfg.uvar and cfg.wvar'); end\nif ~isempty(intersect(cfg.uvar, cfg.cvar)), ft_warning('there is an intersection between cfg.uvar and cfg.cvar'); end\nif ~isempty(intersect(cfg.wvar, cfg.cvar)), ft_warning('there is an intersection between cfg.wvar and cfg.cvar'); end\n\nfprintf('total number of measurements = %d\\n', Nrepl);\nfprintf('total number of variables = %d\\n', Nvar);\nfprintf('number of independent variables = %d\\n', length(cfg.ivar));\nfprintf('number of unit variables = %d\\n', length(cfg.uvar));\nfprintf('number of within-cell variables = %d\\n', length(cfg.wvar));\nfprintf('number of control variables = %d\\n', length(cfg.cvar));\nfprintf('using a %s resampling approach\\n', cfg.resampling);\n\nif ~isempty(cfg.cvar)\n % the different levels of the control variable indicate the blocks in which the resampling can be done\n % the replications should not be resampled over the blocks\n blocklevel = unique(design(cfg.cvar,:)', 'rows')';\n for i=1:size(blocklevel,2)\n blocksel{i} = find(all(design(cfg.cvar,:)==repmat(blocklevel(:,i), 1, Nrepl), 1));\n blocklen(i) = length(blocksel{i});\n end\n for i=1:size(blocklevel,2)\n fprintf('------------------------------------------------------------\\n');\n if length(cfg.cvar)>1\n fprintf('resampling the subset where the control variable level is [%s]\\n', num2str(blocklevel(:,i)));\n else\n fprintf('resampling the subset where the control variable level is %s\\n', num2str(blocklevel(:,i)));\n end\n % use recursion to resample the replications within each block\n tmpcfg = cfg;\n tmpcfg.cvar = [];\n blockres{i} = blocksel{i}(resampledesign(tmpcfg, design(:, blocksel{i})));\n end\n % concatenate the blocks and return the result\n resample = cat(2, blockres{:});\n return\nend\n\nif isnumeric(cfg.numrandomization) && cfg.numrandomization==0\n % no randomizations are requested, return an empty shuffling matrix\n resample = zeros(0,Nrepl);\n return;\nend\n\nif ~isempty(cfg.wvar)\n % keep the elements within a cell together, e.g. multiple tapers in a trial\n % this is realized by replacing the design matrix temporarily with a smaller version\n blkmeas = unique(design(cfg.wvar,:)', 'rows')';\n for i=1:size(blkmeas,2)\n blksel{i} = find(all(design(cfg.wvar,:)==repmat(blkmeas(:,i), 1, Nrepl), 1));\n blklen(i) = length(blksel{i});\n end\n if any(blklen~=blklen(1))\n ft_error('the number of repetitions per block should be constant');\n end\n for i=1:size(blkmeas,2)\n if any(diff(design(:, blksel{i}), 1, 2)~=0)\n ft_error('the design matrix variables should be constant within a block');\n end\n end\n orig_design = design;\n orig_Nrepl = Nrepl;\n % replace the design matrix by a blocked version\n design = zeros(size(design,1), size(blkmeas,2));\n Nrepl = size(blkmeas,2);\n for i=1:size(blkmeas,2)\n design(:,i) = orig_design(:, blksel{i}(1));\n end\nend\n\n% do some validity checks\nif Nvar==1 && ~isempty(cfg.uvar)\n ft_error('A within-units shuffling requires a at least one unit variable and at least one independent variable');\nend\n\nif isempty(cfg.uvar) && strcmp(cfg.resampling, 'permutation')\n % reshuffle the colums of the design matrix\n if ischar(cfg.numrandomization) && strcmp(cfg.numrandomization, 'all')\n % systematically shuffle the columns in the design matrix\n Nperm = prod(1:Nrepl);\n fprintf('creating all possible permutations (%d)\\n', Nperm);\n resample = perms(1:Nrepl);\n elseif ~ischar(cfg.numrandomization)\n % randomly shuffle the columns in the design matrix the specified number of times\n resample = zeros(cfg.numrandomization, Nrepl);\n for i=1:cfg.numrandomization\n resample(i,:) = randperm(Nrepl);\n end\n end\n \nelseif isempty(cfg.uvar) && strcmp(cfg.resampling, 'bootstrap')\n % randomly draw with replacement, keeping the number of elements the same in each class\n % only the test under the null-hypothesis (h0) is explicitely implemented here\n % but the h1 test can be achieved using a control variable\n resample = zeros(cfg.numrandomization, Nrepl);\n for i=1:cfg.numrandomization\n resample(i,:) = randsample(1:Nrepl, Nrepl, true);\n end\n \nelseif ~isempty(cfg.uvar) && strcmp(cfg.resampling, 'permutation')\n % reshuffle the colums of the design matrix, keep the rows of the design matrix with the unit variable intact\n unitlevel = unique(design(cfg.uvar,:)', 'rows')';\n for i=1:size(unitlevel,2)\n unitsel{i} = find(all(design(cfg.uvar,:)==repmat(unitlevel(:,i), 1, Nrepl), 1));\n unitlen(i) = length(unitsel{i});\n end\n if length(cfg.uvar)==1\n fprintf('repeated measurement in variable %d over %d levels\\n', cfg.uvar, length(unitlevel));\n fprintf('number of repeated measurements in each level is '); fprintf('%d ', unitlen); fprintf('\\n');\n else\n fprintf('repeated measurement in mutiple variables over %d levels\\n', length(unitlevel));\n fprintf('number of repeated measurements in each level is '); fprintf('%d ', unitlen); fprintf('\\n');\n end\n fprintf('the maximum number of unique permutations is %d\\n', prod(unitlen));\n \n if ischar(cfg.numrandomization) && strcmp(cfg.numrandomization, 'all')\n % create all possible permutations by systematic assignment\n if any(unitlen~=2)\n % it would be possible to also implement it for other cases\n % but so far ther has not been a concrete need for it\n ft_error('cfg.numrandomization=''all'' is only supported for two repeated measurements');\n end\n Nperm = 2^(length(unitlevel));\n resample = zeros(Nperm, Nrepl);\n for i=1:Nperm\n flip = dec2bin( i-1, length(unitlevel));\n for j=1:length(unitlevel)\n if strcmp('0', flip(j))\n resample(i, unitsel{j}(1)) = unitsel{j}(1);\n resample(i, unitsel{j}(2)) = unitsel{j}(2);\n elseif strcmp('1', flip(j))\n resample(i, unitsel{j}(1)) = unitsel{j}(2);\n resample(i, unitsel{j}(2)) = unitsel{j}(1);\n end\n end\n end\n fprintf('generated all %d possible permutations\\n', 2^(length(unitlevel)));\n \n elseif ~ischar(cfg.numrandomization)\n % see https://github.com/fieldtrip/fieldtrip/issues/1313\n if cfg.numrandomization > prod(unitlen)\n ft_warning('the number of randomizations (%d) is larger than the maximum number of unique permutations (%d), better use cfg.numrandomization=''all''', cfg.numrandomization, prod(unitlen))\n elseif cfg.numrandomization/prod(unitlen) > 0.5\n ft_warning('the number of randomizations (%d) is close to the maximum number of unique permutations (%d), better use cfg.numrandomization=''all''', cfg.numrandomization, prod(unitlen))\n end\n \n % create the desired number of permutations by random shuffling\n resample = zeros(cfg.numrandomization, Nrepl);\n for i=1:cfg.numrandomization\n for j=1:length(unitlevel)\n resample(i, unitsel{j}) = unitsel{j}(randperm(length(unitsel{j})));\n end\n end\n fprintf('generated %d random permutations\\n', cfg.numrandomization);\n end\n \nelseif length(cfg.uvar)==1 && strcmp(cfg.resampling, 'bootstrap') && isempty(cfg.cvar)\n % randomly draw with replacement, keeping the number of elements the same in each class\n % only the test under the null-hypothesis (h0) is explicitely implemented here\n % but the h1 test can be achieved using a control variable\n \n % FIXME allow for length(cfg.uvar)>1, does it make sense in the first place\n % bootstrap the units of observation\n units = design(cfg.uvar,:);\n for k = 1:length(unique(units))\n sel = find(units==k);\n indx(:,k) = sel;\n Nrep(k) = length(sel);\n end\n resample = zeros(cfg.numrandomization, Nrepl);\n \n %sanity check on number of repetitions\n if any(Nrep~=Nrep(1)), ft_error('all units of observation should have an equal number of repetitions'); end\n \n if max(units(:))<20\n ft_warning('fewer than 20 units warrants explicit checking of double occurrences of ''bootstraps''');\n checkunique = 1;\n else\n checkunique = 0;\n end\n \n if ~checkunique\n for i=1:cfg.numrandomization\n tmp = randsample(1:Nrepl/Nrep(1), Nrepl/Nrep(1), true);\n for k=1:size(indx,1)\n resample(i,indx(k,:)) = indx(k,tmp);\n end\n end\n else\n tmp = zeros(cfg.numrandomization*10, Nrepl/Nrep(1));\n for i=1:cfg.numrandomization*10\n tmp(i,:) = sort(randsample(1:Nrepl/Nrep(1), Nrepl/Nrep(1), true));\n end\n \n tmp = unique(tmp, 'rows');\n fprintf('found %d unique rows in bootstrap matrix of %d bootstraps', size(tmp,1), cfg.numrandomization*10);\n \n if size(tmp,1)0\n ft_error('this is not yet supported in combination with a unit of observation (uvar)');\n end\n \n original = zeros(size(resample,1), numel(cfg.ivar)*size(resample,2));\n for i=1:size(resample,1)\n for j=1:numel(cfg.ivar)\n sel = (1:Nrepl) + (j-1)*Nrepl;\n original(i,sel) = design(cfg.ivar(j), resample(i,:));\n end\n end\n \n [reduced, indx1, indx2] = unique(original, 'rows');\n % this returns the reduced condition sequences, where\n % indx1 contains for the reduced row number the original (last) row number\n % indx2 contains for the original condition sequences the reduced row number\n frequency = zeros(size(reduced,1),1);\n for i=1:size(reduced,1)\n frequency(i) = sum(indx2==i);\n end\n \n if all(frequency==frequency(1))\n % the relative frequency of the reduced condition sequences is the same\n % as the relative frequency of the original condition sequences, which\n % means that the reduced set of permutations is appropriate\n fprintf('using the reduced set of permutations (%d) instead of the original permutations (%d)\\n', size(reduced,1), size(resample,1));\n resample = resample(indx1,:);\n else\n % don't use the reduced set of permutations\n fprintf('the reduced set has different relative frequencies of the conditions, retaining the original permutations\\n')\n end\nend % if efficient\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/private/resampledesign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.028436035514937046, "lm_q1q2_score": 0.011475841385470515}} {"text": "%%*****************************************************************************\n%% HSDsqlpcheckconvg: check convergence.\n%%\n%% ZpATynorm, AX, normX, normZ are with respect to the\n%% original variables, not the HSD variables.\n%%\n%% SDPT3: version 3.1\n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last Modified: 16 Sep 2004\n%%*****************************************************************************\n\nfunction [param,breakyes,use_olditer,msg] = HSDsqlpcheckconvg(param,runhist)\n\ntermcode = param.termcode;\niter = param.iter;\nobj = param.obj;\nrelgap = param.relgap;\ngap = param.gap;\nprim_infeas = param.prim_infeas;\ndual_infeas = param.dual_infeas;\nmu = param.mu;\nprim_infeas_bad = param.prim_infeas_bad;\ndual_infeas_bad = param.dual_infeas_bad;\nprintlevel = param.printlevel;\nstoplevel = param.stoplevel;\ninftol = param.inftol;\ngaptol = param.gaptol;\nkap = param.kap;\ntau = param.tau;\ntheta = param.theta;\nbreakyes = 0;\nuse_olditer = 0;\nmsg = [];\ninfeas = max(prim_infeas,dual_infeas);\nprim_infeas_min = min(param.prim_infeas_min, max(prim_infeas,1e-10));\ndual_infeas_min = min(param.dual_infeas_min, max(dual_infeas,1e-10));\n%%\nerr = max(infeas,relgap);\nif (obj(2) > 0); homRd = param.ZpATynorm/obj(2); else homRd = inf; end\nif (obj(1) < 0); homrp = norm(param.AX)/(-obj(1)); else homrp = inf; end\nif (param.normX > 1e15*param.normX0 || param.normZ > 1e15*param.normZ0)\n termcode = 3;\n breakyes = 1;\nend\nif (homRd < min(1e-6,1e-2*sqrt(err*inftol)) && tau < 1e-4 ...\n && prim_infeas > 0.5*runhist.pinfeas(iter)) ...\n || (homRd < 10*tau && tau < 1e-7)\n termcode = 1;\n breakyes = 1;\nend\nif (homrp < min(1e-6,1e-2*sqrt(err*inftol)) && tau < 1e-4 ...\n && dual_infeas > 0.5*runhist.dinfeas(iter)) ...\n || (homrp < 10*tau && tau < 1e-7)\n termcode = 2;\n breakyes = 1;\nend\nif (err < gaptol)\n msg = sprintf('Stop: max(relative gap,infeasibilities) < %3.2e',gaptol);\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = 0;\n breakyes = 1;\nend\nmin_prim_infeas = min(runhist.pinfeas(1:iter));\nprim_infeas_bad = prim_infeas_bad + (prim_infeas > ...\n max(1e-10,5*min_prim_infeas) && (min_prim_infeas < 1e-2));\nif (mu < 1e-6)\n idx = max(1,iter-1): iter;\nelseif (mu < 1e-3);\n idx = max(1,iter-2): iter;\nelse\n idx = max(1,iter-3): iter;\nend\nidx2 = max(1,iter-4): iter;\ngap_ratio2 = runhist.gap(idx2+1)./runhist.gap(idx2);\ngap_slowrate = min(0.8,max(0.6,2*mean(gap_ratio2)));\ngap_ratio = runhist.gap(idx+1)./runhist.gap(idx);\npstep = runhist.step(iter+1);\nif (infeas < 1e-4 || prim_infeas_bad) && (relgap < 1e-3) ...\n && (iter > 5) && (prim_infeas > (1-pstep/2)*runhist.pinfeas(iter))\n gap_slow = all(gap_ratio > gap_slowrate) && (relgap < 1e-3);\n min_pinfeas = min(runhist.pinfeas);\n if (relgap < 0.1*infeas) ...\n && ((runhist.step(iter+1) < 0.5) || (min_pinfeas < min(1e-6,0.1*prim_infeas))) ...\n && (dual_infeas > 0.9*runhist.dinfeas(iter) || (dual_infeas < 1e-2*gaptol))\n msg = 'Stop: relative gap < infeasibility';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -1;\n breakyes = 1;\n elseif (gap_slow) && (infeas > 0.9*runhist.infeas(iter)) ...\n && (theta < 1e-8)\n msg = 'Stop: progress is too slow';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\n end\nelseif (prim_infeas_bad) && (iter >50) && all(gap_ratio > gap_slowrate)\n msg = 'Stop: progress is bad';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\nelseif (infeas < 1e-8) && (gap > 1.2*mean(runhist.gap(idx)))\n msg = 'Stop: progress is bad*';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\nend\nif (err < 1e-3) && (iter > 10) ...\n && (runhist.pinfeas(iter+1) > 0.9*runhist.pinfeas(max(1,iter-5))) ...\n && (runhist.dinfeas(iter+1) > 0.9*runhist.dinfeas(max(1,iter-5))) ...\n && (runhist.relgap(iter+1) > 0.1*runhist.relgap(max(1,iter-5)));\n msg = 'Stop: progress is bad**';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\nend\nif (infeas > 100*max(1e-12,min(runhist.infeas)) && relgap < 1e-4)\n msg = 'Stop: infeas has deteriorated too much';\n if (printlevel); fprintf('\\n %s, %3.1e',msg,infeas); end\n use_olditer = 1;\n termcode = -7;\n breakyes = 1;\nend\nif (min(runhist.infeas) < 1e-4 || prim_infeas_bad) ...\n && (max(runhist.infeas) > 1e-4) && (iter > 5)\n relgap2 = abs(diff(obj))/(1+mean(abs(obj)));\n if (relgap2 < 1e-3);\n step_short = all(runhist.step(iter:iter+1) < 0.1) ;\n elseif (relgap2 < 1)\n idx = max(1,iter-3): iter+1;\n step_short = all(runhist.step(idx) < 0.05);\n else\n step_short = 0;\n end\n if (step_short)\n msg = 'Stop: steps too short consecutively';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\n end\nend\nif (iter > 3 && iter < 20) && (max(runhist.step(max(1,iter-3):iter+1)) < 1e-3) ...\n && (infeas > 1) && (min(homrp,homRd) > 1000*inftol)\n if (stoplevel >= 2)\n msg = 'Stop: steps too short consecutively';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = -5;\n breakyes = 1;\n end\nend\nif (pstep < 1e-4) && (err > 1.1*max(runhist.relgap(iter),runhist.infeas(iter)))\n msg = 'Stop: steps are too short';\n if (printlevel); fprintf('\\n %s',msg); end\n use_olditer = 1;\n termcode = -5;\n breakyes = 1;\nend\nif (iter == param.maxit)\n termcode = -6;\n msg = 'Stop: maximum number of iterations reached';\n if (printlevel); fprintf('\\n %s',msg); end\nend\nif (infeas < 1e-8 && relgap < 1e-10 && kap < 1e-13 && theta < 1e-15)\n msg = 'Stop: obtained accurate solution';\n if (printlevel); fprintf('\\n %s',msg); end\n termcode = 0;\n breakyes = 1;\nend\nparam.prim_infeas_bad = prim_infeas_bad;\nparam.prim_infeas_min = prim_infeas_min;\nparam.dual_infeas_bad = dual_infeas_bad;\nparam.dual_infeas_min = dual_infeas_min;\nparam.termcode = termcode;\n%%*****************************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/HSDSolver/HSDsqlpcheckconvg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228964, "lm_q2_score": 0.024798157537946047, "lm_q1q2_score": 0.011432367088298425}} {"text": "function [estimate] = ft_inverse_dics(sourcemodel, sens, headmodel, dat, C, varargin)\n\n% FT_INVERSE_DICS scans on pre-defined dipole locations with a single dipole\n% and returns the beamformer spatial filter output for a dipole on every\n% location.\n%\n% Use as\n% [estimate] = ft_inverse_dics(sourcemodel, sens, headmodel, dat, cov, ...)\n% where\n% sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL\n% sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS\n% headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL\n% dat is the data matrix with the ERP or ERF\n% cov is the data covariance or cross-spectral density matrix\n% and\n% estimate contains the estimated source parameters\n%\n% Additional input arguments should be specified as key-value pairs and can include\n% 'Pr' = power of the external reference channel\n% 'Cr' = cross spectral density between all data channels and the external reference channel\n% 'refdip' = location of dipole with which coherence is computed\n% 'powmethod' = can be 'trace' or 'lambda1'\n% 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text')\n% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'\n% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'\n% 'realfilter' = construct a real-valued filter, can be 'yes' or 'no'\n% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'\n% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'\n% 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no'\n% 'weightnorm' = normalize the beamformer weights, can be 'no', 'unitnoisegain' or 'nai'\n%\n% These options influence the forward computation of the leadfield\n% 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG)\n% 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes')\n% 'normalize' = 'no', 'yes' or 'column' (default = 'no')\n% 'normalizeparam' = parameter for depth normalization (default = 0.5)\n% 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1)\n%\n% These options influence the mathematical inversion of the cross-spectral density matrix\n% 'lambda' = regularisation parameter\n% 'kappa' = parameter for covariance matrix inversion\n% 'tol' = parameter for covariance matrix inversion\n%\n% If the dipole definition only specifies the dipole location, a rotating\n% dipole (regional source) is assumed on each location. If a dipole moment\n% is specified, its orientation will be used and only the strength will\n% be fitted to the data.\n%\n% See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL\n\n% Copyright (C) 2003-2020, Robert Oostenveld and Jan-Mathijs Schoffelen\n%\n% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org\n% for the documentation and details.\n%\n% FieldTrip is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% FieldTrip is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with FieldTrip. If not, see .\n%\n% $Id$\n\nif mod(nargin-5,2)\n % the first 5 arguments are fixed, the other arguments should come in pairs\n ft_error('invalid number of optional arguments');\nend\n\n% get the optional input arguments, or use defaults\nPr = ft_getopt(varargin, 'Pr');\nCr = ft_getopt(varargin, 'Cr');\nrefdip = ft_getopt(varargin, 'refdip');\npowmethod = ft_getopt(varargin, 'powmethod'); % the default for this is set below\nrealfilter = ft_getopt(varargin, 'realfilter'); % the default for this is set below\nsubspace = ft_getopt(varargin, 'subspace');\nfeedback = ft_getopt(varargin, 'feedback', 'text');\nkeepcsd = ft_getopt(varargin, 'keepcsd', 'no');\nkeepfilter = ft_getopt(varargin, 'keepfilter', 'no');\nkeepleadfield = ft_getopt(varargin, 'keepleadfield', 'no');\nprojectnoise = ft_getopt(varargin, 'projectnoise', 'yes');\nfixedori = ft_getopt(varargin, 'fixedori', 'no');\nweightnorm = ft_getopt(varargin, 'weightnorm', 'no');\n\n% construct the low-level options for the covariance matrix inversion as key-value pairs, these are passed to FT_INV\ninvopt = {};\ninvopt = ft_setopt(invopt, 'lambda', ft_getopt(varargin, 'lambda', 0));\ninvopt = ft_setopt(invopt, 'kappa', ft_getopt(varargin, 'kappa'));\ninvopt = ft_setopt(invopt, 'tolerance', ft_getopt(varargin, 'tol'));\ninvopt = ft_setopt(invopt, 'method', ft_getopt(varargin, 'invmethod'));\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(varargin, 'reducerank'));\nleadfieldopt = ft_setopt(leadfieldopt, 'backproject', ft_getopt(varargin, 'backproject'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalize', ft_getopt(varargin, 'normalize'));\nleadfieldopt = ft_setopt(leadfieldopt, 'normalizeparam', ft_getopt(varargin, 'normalizeparam'));\nleadfieldopt = ft_setopt(leadfieldopt, 'weight', ft_getopt(varargin, 'weight'));\n\n% convert the yes/no arguments to the corresponding logical values\nkeepfilter = istrue(keepfilter);\nkeepleadfield = istrue(keepleadfield);\nkeepcsd = istrue(keepcsd);\nprojectnoise = istrue(projectnoise);\nfixedori = istrue(fixedori);\n\n% FIXME besides regular/complex lambda1, also implement a real version\n\n% default is to use the largest singular value of the csd matrix, see Gross 2001\nif isempty(powmethod)\n powmethod = 'lambda1';\nend\n\n% default is to be consistent with the original description of DICS in Gross 2001\nif isempty(realfilter)\n realfilter = 'no';\nend\n\n% use these two logical flags instead of doing the string comparisons each time again\npowtrace = strcmp(powmethod, 'trace');\npowlambda1 = strcmp(powmethod, 'lambda1');\n\nif ~isempty(Cr)\n % ensure that the cross-spectral density with the reference signal is a column matrix\n Cr = Cr(:);\nend\n\nif isfield(sourcemodel, 'mom') && fixedori\n ft_error('you cannot specify a dipole orientation and fixedori simultaneously');\nend\n\n% flags to avoid calling isfield repeatedly in the loop over grid positions (saves a lot of time)\nhasmom = isfield(sourcemodel, 'mom');\nhasleadfield = isfield(sourcemodel, 'leadfield');\nhasfilter = isfield(sourcemodel, 'filter');\nhassubspace = isfield(sourcemodel, 'subspace');\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% find the dipole positions that are inside/outside the brain\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ~isfield(sourcemodel, 'inside')\n if hasfilter\n sourcemodel.inside = ~cellfun(@isempty, sourcemodel.filter);\n elseif hasleadfield\n sourcemodel.inside = ~cellfun(@isempty, sourcemodel.leadfield);\n else\n sourcemodel.inside = ft_inside_headmodel(sourcemodel.pos, headmodel);\n end\nend\n\n% convert to logical representation\nsourcemodel = fixinside(sourcemodel);\n\nif hasfilter && (fixedori || ~isequal(weightnorm, 'no'))\n ft_warning('with precomputed spatial filters a fixed orientation constraint or weight normalisation options are not applied');\nend\n\n% keep the original details on inside and outside positions\noriginside = sourcemodel.inside;\norigpos = sourcemodel.pos;\n\n% select only the dipole positions inside the brain for scanning\nsourcemodel.pos = sourcemodel.pos(originside,:);\nsourcemodel.inside = true(size(sourcemodel.pos,1),1);\n\nif hasmom\n sourcemodel.mom = sourcemodel.mom(:,originside);\nend\n\nif hasfilter\n ft_info('using precomputed filters\\n');\n sourcemodel.filter = sourcemodel.filter(originside);\nelseif hasleadfield\n ft_info('using precomputed leadfields\\n');\n sourcemodel.leadfield = sourcemodel.leadfield(originside);\nelse\n ft_info('computing forward model on the fly\\n');\nend\n\nif hassubspace\n ft_info('using subspace projection\\n');\n sourcemodel.subspace = sourcemodel.subspace(originside);\nend\n\n% dics has the following sub-methods, which depend on the function input arguments\n% power only, cortico-muscular coherence and cortico-cortical coherence\nif ~isempty(Cr) && ~isempty(Pr) && isempty(refdip)\n % compute cortico-muscular coherence, using reference cross spectral density\n submethod = 'dics_refchan';\nelseif isempty(Cr) && isempty(Pr) && ~isempty(refdip)\n % compute cortico-cortical coherence with a dipole at the reference position\n submethod = 'dics_refdip';\n % check for forbidden options in combination with this submethod\n if hassubspace || ~isempty(subspace)\n ft_error('subspace projections are not supported for beaming cortico-cortical coherence');\n end\n if fixedori\n ft_error('fixed orientations are not supported for beaming cortico-cortical coherence');\n end\nelseif isempty(Cr) && isempty(Pr) && isempty(refdip)\n % only compute power of a dipole at the grid positions\n submethod = 'dics_power';\nelse\n ft_error('invalid combination of input arguments for dics');\nend\n\n% it is difficult to give a quantitative estimate of lambda, therefore also\n% support relative (percentage) measure that can be specified as string (e.g. '10%')\n% the converted value needs to be passed on to ft_inv\nlambda = ft_getopt(invopt, 'lambda');\nif ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'\n ratio = sscanf(lambda, '%f%%');\n ratio = ratio/100;\n lambda = ratio * trace(C)/size(C,1);\n if ~hassubspace\n invopt = ft_setopt(invopt, 'lambda', lambda);\n end\nend\n\nif projectnoise || strcmp(weightnorm, 'nai')\n % estimate the noise level in the covariance matrix by the smallest (non-zero) singular value\n % always needed for the NAI weight normalization case\n noise = svd(C);\n noise = noise(rank(C));\n % estimated noise floor is equal to or higher than lambda\n noise = max(noise, lambda);\nend\n\n% the inverse of the cross-spectral density matrix only has to be computed once for all dipoles\nif hassubspace\n ft_notice('using source-specific subspace projection\\n');\n % remember the original data prior to the voxel dependent subspace projection\n dat_pre_subspace = dat;\n C_pre_subspace = C;\n if strcmp(submethod, 'dics_refchan')\n Cr_pre_subspace = Cr;\n Pr_pre_subspace = Pr;\n end\nelseif ~isempty(subspace)\n ft_notice('using data-specific subspace projection\\n');\n % TODO implement an \"eigenspace beamformer\" as described in Sekihara et al. 2002 in HBM\n if numel(subspace)==1\n % interpret this as a truncation of the eigenvalue-spectrum\n % if <1 it is a fraction of the largest eigenvalue\n % if >=1 it is the number of largest eigenvalues\n dat_pre_subspace = dat;\n C_pre_subspace = C;\n [u, s, v] = svd(real(C));\n if subspace<1\n subspace = find(diag(s)./s(1,1) > subspace, 1, 'last');\n end\n \n C = s(1:subspace,1:subspace);\n % this is equivalent to subspace*C*subspace' but behaves well numerically\n % by construction.\n invC = diag(1./diag(C + lambda * eye(size(C))));\n subspace = u(:,1:subspace)';\n if ~isempty(dat), dat = subspace*dat; end\n \n if strcmp(submethod, 'dics_refchan')\n Cr = subspace*Cr;\n end\n \n else\n C_pre_subspace = C;\n C = subspace*C*subspace';\n % here the subspace can be different from the singular vectors of C, so we\n % have to do the sandwiching as opposed to line 256\n if strcmp(realfilter, 'yes')\n invC = ft_inv(real(C), invopt{:});\n else\n invC = ft_inv(C, invopt{:});\n end\n \n if strcmp(submethod, 'dics_refchan')\n Cr = subspace*Cr;\n end\n end\nelse\n if strcmp(realfilter, 'yes')\n % the filter is computed using only the leadfield and the inverse covariance or CSD matrix\n % therefore using the real-valued part of the CSD matrix here ensures a real-valued filter\n invC = ft_inv(real(C), invopt{:});\n else\n invC = ft_inv(C, invopt{:});\n end\nend\n\nif ~hassubspace\n % compute the square of invC, which might be needed for unitnoisegain or NAI constraint\n invC_squared = invC^2;\nend\n\nif strcmp(submethod, 'dics_refdip')\n % handle the reference dipole, this needs to be done only once, since in this implementation\n % no fancy pairwise dipole source model is assumed\n if isstruct(refdip) && isfield(refdip, 'filter') % check if precomputed filter is present\n assert(iscell(refdip.filter) && numel(refdip.filter)==1);\n filt1 = refdip.filter{1};\n else\n if ~isstruct(refdip)\n % this is very old behavior: refdip is assumed to be a 1x3 position vector\n refpos = refdip; clear refdip;\n refdip.pos = refpos;\n end\n % now refdip is always a struct\n if isfield(refdip, 'leadfield') % check if precomputed leadfield is present\n assert(iscell(refdip.leadfield) && numel(refdip.leadfield)==1);\n lf1 = refdip.leadfield{1};\n elseif isfield(refdip, 'pos')\n assert(isnumeric(refdip.pos) && numel(refdip.pos)==3);\n lf1 = ft_compute_leadfield(refdip.pos, sens, headmodel, leadfieldopt{:});\n end\n if isfield(refdip, 'mom') % check for fixed orientation\n lf1 = lf1 * refdip.mom(:);\n end\n \n % construct the spatial filter\n switch weightnorm\n case 'nai'\n % Van Veen's Neural Activity Index\n ft_error('vector version of nai weight normalization is not implemented');\n case 'unitnoisegain'\n % filt*filt' = I\n % Unit-noise gain minimum variance (aka Borgiotti-Kaplan) beamformer\n denom = pinv(lf1' * invC * lf1);\n gamma = denom * (lf1' * invC_squared * lf1) * denom;\n \n % compute the spatial filter, as per eqn. 4.85\n filt1 = diag(1./sqrt(diag(gamma))) * denom * lf1' * invC;\n case 'arraygain'\n % filt*lf = ||lf||, applies to scalar leadfield, and to one of the possibilities of the vector version, eqn. 4.75\n lfn = lf1./norm(lf1);\n filt1 = pinv(lfn' * invC * lfn) * lfn' * invC; % S&N eqn. 4.09 (scalar version), and eqn. 4.75 (vector version)\n case {'unitgain' 'no'}\n % this is the 'standard' unit gain constraint spatial filter: filt*lf=I, applies both to vector and scalar leadfields\n filt1 = pinv(lf1' * invC * lf1) * lf1' * invC; % Gross eqn. 3 & van Veen eqn. 23, use PINV/SVD to cover rank deficient leadfield\n otherwise\n ft_error('unsupported option for weightnorm');\n end\n end\n \n % compute the power of the reference dipole location\n if powlambda1\n Pr = lambda1(filt1 * C * ctranspose(filt1)); % compute the power at the first dipole location, Gross eqn. 8\n elseif powtrace\n Pr = real(trace(filt1 * C * ctranspose(filt1))); % compute the power at the first dipole location\n end\nend % if dics_refdip\n\n% start the scanning with the proper metric\nft_progress('init', feedback, 'scanning grid');\nfor i=1:size(sourcemodel.pos,1)\n ft_progress(i/size(sourcemodel.pos,1), 'scanning grid %d/%d\\n', i, size(sourcemodel.pos,1));\n\n if hasfilter\n % precomputed filter is provided, the leadfield is not needed\n filt = sourcemodel.filter{i};\n\n else\n if hasleadfield && hasmom && size(sourcemodel.mom, 1)==size(sourcemodel.leadfield{i}, 2)\n % reuse the leadfield that was previously computed and project\n lf = sourcemodel.leadfield{i} * sourcemodel.mom(:,i);\n elseif hasleadfield && hasmom\n % reuse the leadfield that was previously computed but don't project\n lf = sourcemodel.leadfield{i};\n elseif hasleadfield && ~hasmom\n % reuse the leadfield that was previously computed\n lf = sourcemodel.leadfield{i};\n elseif ~hasleadfield && hasmom\n % compute the leadfield for a fixed dipole orientation\n lf = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:}) * sourcemodel.mom(:,i);\n else\n % compute the leadfield\n lf = ft_compute_leadfield(sourcemodel.pos(i,:), sens, headmodel, leadfieldopt{:});\n end\n \n if hassubspace\n % do subspace projection of the forward model\n lforig = lf;\n lf = sourcemodel.subspace{i} * lf;\n % the cross-spectral density becomes voxel dependent due to the projection\n C = sourcemodel.subspace{i} * C_pre_subspace * sourcemodel.subspace{i}';\n if strcmp(realfilter, 'yes')\n invC = ft_inv(sourcemodel.subspace{i} * real(C_pre_subspace) * sourcemodel.subspace{i}', invopt{:});\n else\n invC = ft_inv(sourcemodel.subspace{i} * C_pre_subspace * sourcemodel.subspace{i}', invopt{:});\n end\n elseif ~isempty(subspace)\n % do subspace projection of the forward model only\n lforig = lf;\n lf = subspace * lf;\n \n % according to Kensuke's paper, the eigenspace bf boils down to projecting\n % the 'traditional' filter onto the subspace spanned by the first k eigenvectors\n % [u,s,v] = svd(C); filt = ESES*filt; ESES = u(:,1:k)*u(:,1:k)';\n % however, even though it seems that the shape of the filter is identical to\n % the shape it is obtained with the following code, the w*lf=I does not hold.\n end\n \n if fixedori\n switch(weightnorm)\n case {'unitnoisegain','nai'}\n % optimal orientation calculation for unit-noise gain beamformer,\n % (also applies nai weightnorm constraint), based on equation 4.47 from Sekihara & Nagarajan (2008)\n % the following is a reformulation of the generalized eigenproblem\n [v, d] = eig(pinv(lf' * invC_squared *lf)*(lf' * invC *lf));\n [d, iv] = sort(diag(d), 'descend');\n unitnoiseori = v(:,iv(1));\n lf = lf * unitnoiseori;\n estimate.ori{i} = unitnoiseori;\n estimate.eta(i) = d(1)./d(2); % ratio between largest and second largest eigenvalues\n if hassubspace, lforig = lforig * unitnoiseori; end\n \n case 'arraygain'\n % optimal orientation calculation for array-gain beamformer, Sekihara & Nagarajan eqn. 4.44\n [v, d] = eig(pinv(lf' * invC *lf)*(lf' * lf));\n [d, iv] = sort(diag(d), 'descend');\n arraygainori = v(:,iv(1));\n lf = lf * arraygainori;\n estimate.ori{i} = arraygainori;\n estimate.eta(i) = d(1)./d(2); % ratio between largest and second largest eigenvalues\n if hassubspace, lforig = lforig * arraygainori; end\n \n otherwise\n % compute the leadfield for the optimal dipole orientation that maximizes spatial filter output\n % subsequently the leadfield for only that dipole orientation will be used for the final filter computation\n % filt = pinv(lf' * invC * lf) * lf' * invC;\n % [u, s, v] = svd(real(filt * C * ctranspose(filt)));\n % in this step the filter computation is not necessary, use the quick way to compute the voxel level covariance (cf. van Veen 1997)\n [u, s, v] = svd(real(pinv(lf' * invC *lf)));\n maxpowori = u(:,1);\n lf = lf * maxpowori;\n estimate.ori{i} = maxpowori;\n estimate.eta(i) = s(1,1)./s(2,2); % ratio between the first and second singular values\n if hassubspace, lforig = lforig * maxpowori; end\n end\n end\n \n % construct the spatial filter\n switch weightnorm\n case 'nai'\n % Van Veen's Neural Activity Index\n % below equation is equivalent to following:\n % filt = pinv(lf' * invC * lf) * lf' * invC;\n % filt = filt/sqrt(noise*filt*filt');\n % the scaling term in the denominator is sqrt of projected noise, as per eqn. 2.67 of Sekihara & Nagarajan 2008 (S&N)\n if fixedori\n filt = pinv(sqrt(noise * lf' * invC_squared * lf)) * lf' *invC; % based on S&N eqn. 4.08\n else\n ft_error('vector version of nai weight normalization is not implemented');\n end\n case 'unitnoisegain'\n % filt*filt' = I\n % Unit-noise gain minimum variance (aka Borgiotti-Kaplan) beamformer\n % below equation is equivalent to following:\n % filt = pinv(lf' * invC * lf) * lf' * invC;\n % filt = filt/sqrt(filt*filt');\n if fixedori\n filt = pinv(sqrt(lf' * invC_squared * lf)) * lf' *invC; % S&N eqn. 4.15\n else\n % compute the matrix that is used for scaling of the filter's rows, as per eqn. 4.83\n denom = pinv(lf' * invC * lf);\n gamma = denom * (lf' * invC_squared * lf) * denom;\n \n % compute the spatial filter, as per eqn. 4.85\n filt = diag(1./sqrt(diag(gamma))) * denom * lf' * invC;\n end\n case 'arraygain'\n % filt*lf = ||lf||, applies to scalar leadfield, and to one of the possibilities of the vector version, eqn. 4.75\n lfn = lf./norm(lf);\n filt = pinv(lfn' * invC * lfn) * lfn' * invC; % S&N eqn. 4.09 (scalar version), and eqn. 4.75 (vector version)\n \n case {'unitgain' 'no'}\n % this is the 'standard' unit gain constraint spatial filter: filt*lf=I, applies both to vector and scalar leadfields\n filt = pinv(lf' * invC * lf) * lf' * invC; % Gross eqn. 3 & van Veen eqn. 23, use PINV/SVD to cover rank deficient leadfield\n \n otherwise\n end\n end\n \n cfilt = filt * C * ctranspose(filt); % Gross eqn. 4 and 5\n if powlambda1\n if size(cfilt,1) == 1\n % only 1 orientation, no need to do svd\n estimate.pow(i,1) = real(cfilt);\n else\n estimate.pow(i,1) = lambda1(cfilt); % compute the power at the dipole location, Gross eqn. 8\n end\n elseif powtrace\n estimate.pow(i,1) = real(trace(cfilt)); % compute the power at the dipole location\n end\n \n if strcmp(submethod, 'dics_refchan')\n % compute the cross-spectrum between the dipole and the reference channel\n cfilt = filt*Cr; % Gross eqn. 6, replaces cfilt computed above\n if powlambda1\n coh = lambda1(cfilt)^2 / (estimate.pow(i,1) * Pr); % Gross eqn. 9\n elseif powtrace\n coh = norm(cfilt)^2 / (estimate.pow(i,1) * Pr);\n end\n estimate.coh(i,1) = coh;\n elseif strcmp(submethod, 'dics_refdip')\n % compute the cross-spectrum between the reference dipole and the dipole\n cfilt = filt1 * C * ctranspose(filt); % Gross eqn. 6, replaces cfilt computed above\n if powlambda1\n coh = lambda1(cfilt)^2 / (estimate.pow(i,1) * Pr); % Gross eqn. 9\n elseif powtrace\n coh = norm(cfilt)^2 / (estimate.pow(i,1) * Pr);\n end\n estimate.coh(i,1) = coh;\n end\n \n if keepcsd\n % keep the dipole's csd or the dipole-ref cross-spectrum in the output\n estimate.csd{i,1} = cfilt;\n end\n \n if projectnoise\n if powlambda1\n estimate.noise(i,1) = noise * lambda1(filt * ctranspose(filt));\n elseif powtrace\n estimate.noise(i,1) = noise * real(trace(filt * ctranspose(filt)));\n end\n if keepcsd\n estimate.noisecsd{i,1} = noise * filt * ctranspose(filt);\n end\n end\n \n if keepfilter\n if hassubspace\n estimate.filter{i,1} = filt*sourcemodel.subspace{i};\n elseif ~isempty(subspace)\n estimate.filter{i,1} = filt*subspace; % FIXME should this be subspace, or pinv(subspace)?\n else\n estimate.filter{i,1} = filt;\n end\n end\n \n if keepleadfield\n if ~isempty(subspace)\n estimate.leadfield{i,1} = lforig;\n else\n estimate.leadfield{i,1} = lf;\n end\n end\n \nend % for each dipole position\nft_progress('close');\n\n% reassign the estimated values over the inside and outside grid positions\nestimate.inside = originside;\nestimate.pos = origpos;\n\nfnames_cell = {'leadfield' 'filter' 'ori' 'csd' 'noisecsd' 'subspace'};\nfor k = 1:numel(fnames_cell)\n if isfield(estimate, fnames_cell{k})\n estimate.(fnames_cell{k})( originside) = estimate.(fnames_cell{k});\n estimate.(fnames_cell{k})(~originside) = {[]};\n end\nend\n\nfnames_scalar = {'pow' 'noise' 'eta' 'coh'};\nfor k = 1:numel(fnames_scalar)\n if isfield(estimate, fnames_scalar{k})\n estimate.(fnames_scalar{k})( originside) = estimate.(fnames_scalar{k});\n estimate.(fnames_scalar{k})(~originside) = nan;\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to obtain the largest singular value\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [s, ori] = lambda1(x)\n% determine the largest singular value, which corresponds to the power along the dominant direction\n[u, s, v] = svd(x);\ns = s(1);\nori = u(:,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper function to compute the pseudo inverse. This is the same as the\n% standard MATLAB function, except that the default tolerance is twice as\n% high.\n% Copyright 1984-2004 The MathWorks, Inc.\n% $Revision$ $Date: 2009/06/17 13:40:37 $\n% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction X = pinv(A,varargin)\n[m,n] = size(A);\nif n > m\n X = pinv(A',varargin{:})';\nelse\n [U,S,V] = svd(A,0);\n if m > 1, s = diag(S);\n elseif m == 1, s = S(1);\n else s = 0;\n end\n if nargin == 2\n tol = varargin{1};\n else\n tol = 10 * max(m,n) * max(s) * eps;\n end\n r = sum(s > tol);\n if (r == 0)\n X = zeros(size(A'),class(A));\n else\n s = diag(ones(r,1)./s(1:r));\n X = V(:,1:r)*s*U(:,1:r)';\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/inverse/ft_inverse_dics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.02368947237636893, "lm_q1q2_score": 0.011382286371050154}} {"text": "%tRNA Aminoacylation\n%\n% @wholeCellModelID Process_tRNAAminoacylation\n% @name tRNA Aminoacylation\n% @description\n% Biology\n% ===============\n% In biological systems tRNAs serve as mediators between the ribosome and\n% the amino acids which forms peptide polymers. In this process we\n% simulate the conjugation of amino acids to the tRNAs which deliver them\n% to the ribosome. Additionally we simulate the aminoacylation of the\n% tmRNA which similarly delivers the amino acid alanine to stalled\n% ribosomes.\n%\n% Knowledge Base\n% ===============\n% As of 8/11/2010 the M. genitalium knowledge base contains 39 tRNA\n% aminoacylation reactions involving\n% - 37 aminoacylation reactions, each assuming a cost of 1 ATP per\n% aminoacylation\n% - 2 transfer reactions\n% - 36 tRNAs and 1 tmRNA\n% - 21 enzymes\n% - 20 amino acid substrates and 10 additional substrates\n%\n% The reaction kinetics stored in the knowledge base were compiled\n% several sources including SABIO-RK [PUB_0100].\n%\n% Note: Unlike knowledge base representation, for transfer reactions\n% reactionStoichiometryMatrix doesn't include the already conjugated\n% amino acid on the left-hand-side or the the ultimate conjugated amino\n% acid on the right-hand-side.\n%\n% Representation\n% ===============\n% substrates represents the counts of free metabolites available for tRNA\n% aminoacylation. enzymes represents the counts of proteins available to\n% catalyze tRNA aminoacylation reactions. freeRNAs and aminoacylatedRNAs\n% represent the counts of free, unaminoacylated and aminocylated RNAs. We do\n% not represent intermediate states in the aminoacylation of tRNAs. The\n% molecular weights of the unaminoacylated and aminocylated tRNAs are computed\n% by the knowledge base RNA classes.\n%\n% reactionStoichiometryMatrix, reactionModificationMatrix,\n% reactionCatalysisMatrix, and enzymeBounds represent the tRNA aminoacylation\n% reactions. reactionStoichiometryMatrix represents the free metabolites\n% required for each reaction. reactionModificationMatrix represents the tRNA\n% aminoacylated by each reaction. reactionCatalysis represents the enzyme\n% required to aminoacylate each tRNA. enzymeBounds represents the kcat of the\n% catalyzing enzyme of each reaction. Note: reactionStoichiometryMatrix here\n% is slightly modified from that computed by the super class: amino acids\n% conjugated to tRNAs before and after transfer reactions have been removed\n% from the left- and righ-hand-side of reactionStoichiometryMatrix.\n%\n% Initialization\n% ===============\n% tRNAs are all initialized to the aminoacylated state.\n%\n% Simulation\n% ===============\n% Uses greedy algorithm to simulate tRNA aminacylation (complexation of\n% tRNAs with the specific amino acids that aminoacylate them).\n% 1. Deterministically activate tRNAs up to the minimum of free tRNAs and\n% amino acids, proportional to free tRNAs\n% 2. Stoichastically activate residual tRNAs using residual amino acids\n% with probabilities proportional to remaining free tRNAs\n%\n% While(true)\n% 1. Calculate numbers of protein monomers that can be modified based on\n% substrate, enzyme, and unmodified protein monomer availability and\n% kinetics.\n% 2. Randomly select protein monomer to modify weighted by limits\n% calculated in step (1).\n% 3. Update substrates, enzymes, unmodified protein monomers\n% 4. Repeat until insufficient resources to further modify protein\n% monomers\n% End\n%\n% Author: Markus Covert, mcovert@stanford.edu\n% Author: Jayodita Sanghvi, jayodita@stanfod.edu\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 8/11/2010\n\nclassdef tRNAAminoacylation < edu.stanford.covert.cell.sim.ReactionProcess\n %property annotations\n properties (Constant)\n optionNames__ = {}; %names of option properties\n\t\tfixedConstantNames__ = { %names of fixed constant properties\n\t\t\t'monomerTRNACounts';\n\t\t\t};\n fittedConstantNames__ = {}; %names of fitted constant properties\n localStateNames__ = { %names of simulation state properties redundant with timecourses in this or other processes or the simulation\n 'freeRNAs';\n 'aminoacylatedRNAs'};\n end\n\n %IDs, names, and local indices\n properties\n substrateIndexs_aminoAcids %indices within substrates of amino acids\n substrateIndexs_glutamate %index within substrates of glutamate\n substrateIndexs_glutamine %index within substrates of glutamine\n substrateIndexs_methionine %index within substrates of methionine\n substrateIndexs_fmethionine %index within substrates of formylmethionine\n substrateIndexs_atp %index within substrates of ATP\n substrateIndexs_amp %index within substrates of AMP\n substrateIndexs_adp %index within substrates of ADP\n substrateIndexs_diphosphate %index within substrates of diphosphate\n substrateIndexs_phosphate %index within substrates of inorganic phosphate\n substrateIndexs_water %index within substrates of water\n substrateIndexs_hydrogen %index within substrates of hydrogen\n substrateIndexs_fthf10 %index within substrates of 10-forymltetrahydrofolate\n substrateIndexs_thf %index within substrates of tetrahydrofolate\n\n enzymeIndexs_tRNASynthetases %indices within enzymes of tRNA synthetases\n enzymeIndexs_tRNATransferases %indices within enzymes of tRNA transferases\n enzymeIndexs_tRNAGlutamylSynthetase %index within enzymes of tRNA glutamyl synthetase\n enzymeIndexs_tRNAMethionylSynthetase %index within enzymes of tRNA methionyl synthetase\n enzymeIndexs_tRNAGlutamylAmidotransferase %index within enzymes of tRNA glutamyl amidotransferase\n enzymeIndexs_tRNAMethionylFormyltransferase %index within enzymes of tRNA methionyl formyltransferase\n enzymeIndexs_tRNAs %index within enzymes of tRNAs\n enzymeIndexs_tmRNA %index within enzymes of tmRNA\n\n reactionIndexs_aminoacylation %indices within reactions of tRNA aminoacylation reactions\n reactionIndexs_transfer %indices within reactions of tRNA transfer reactions\n reactionIndexs_glutamylamidotransfer %index within reactions of tRNA glutamylamidotransfer reaction\n reactionIndexs_methionylformyltransfer %index within reactions of tRNA methionylformyltransfer reaction\n\n compartmentWholeCellModelIDs %whole cell model ids of compartments\n compartmentIndexs_cytosol %index within compartments of cytosol\n\n freeRNAWholeCellModelIDs %whole cell model ids of free RNAs\n aminoacylatedRNAWholeCellModelIDs %whole cell model ids of aminoacylated RNAs\n\n aminoacylatedRNAGlobalIndexs %indices of aminoacylated RNAs within simulation.matureRNAIndexs\n aminoacylatedRNAtRNAIndexs %indices of aminoacylated tRNAs within aminoacylatedRNAGlobalIndexs\n \n speciesIndexs_enzymes %indexs of enzyme species within speciesReactantByproductMatrix, speciesReactantMatrix\n end\n\n %fixed biological constants\n properties\n monomerTRNACounts %numbers of each tRNA species required to translate each protein monomer species \n \n speciesReactantByproductMatrix %stoichiometry of susbtrates, enzymes, RNA in modifications necessary to mature each modifying RNA: [RNA modifications] X [subtrates; enzymes; free RNAs]\n speciesReactantMatrix %reactant stoichiometry of susbtrates, enzymes, RNA in modifications necessary to mature each modifying RNA: [RNA modifications] X [subtrates; enzymes; free RNAs]\n end\n\n %global state (stored locally for convenience)\n properties\n freeRNAs %counts of free RNAs\n aminoacylatedRNAs %counts of aminoacylated RNAs\n end\n \n %dependent global state (implemented as dependent property for\n %convenience)\n properties (Dependent)\n tRNASynthetases %counts of tRNA synthetases\n tRNATransferases %counts of tRNA transferases\n end\n\n %constructor\n methods\n function this = tRNAAminoacylation(wholeCellModelID, name)\n this = this@edu.stanford.covert.cell.sim.ReactionProcess(wholeCellModelID, name);\n end\n end\n\n %communication between process/simulation\n methods\n %initialize constants\n function initializeConstants(this, knowledgeBase, simulation, varargin)\n %import classes\n import edu.stanford.covert.util.ComputationUtil;\n\n %call super class method to get knowledge base reactions\n this.initializeConstants@edu.stanford.covert.cell.sim.ReactionProcess(knowledgeBase, simulation, varargin{:});\n\n %compartments\n this.compartmentWholeCellModelIDs = this.compartment.wholeCellModelIDs(this.compartment.cytosolIndexs);\n this.compartmentIndexs_cytosol = 1;\n\n %create representation for GLN which super class leaves off\n %because it cancels out in the knowledge base\n this.substrateWholeCellModelIDs = [this.substrateWholeCellModelIDs; 'GLN'];\n this.reactionStoichiometryMatrix = [this.reactionStoichiometryMatrix; zeros(1, size(this.reactionStoichiometryMatrix, 2))];\n this.reactionCoenzymeMatrix = [this.reactionCoenzymeMatrix zeros(size(this.reactionCoenzymeMatrix, 1), 1)];\n\n %substrate indices\n this.substrateIndexs_aminoAcids = this.substrateIndexs({'ALA'; 'ARG'; 'ASN'; 'ASP'; 'CYS'; 'GLN'; 'GLU'; 'GLY'; 'HIS'; 'ILE'; 'LEU'; 'LYS'; 'MET'; 'PHE'; 'PRO'; 'SER'; 'THR'; 'TRP'; 'TYR'; 'VAL'});\n this.substrateIndexs_glutamate = this.substrateIndexs({'GLU'});\n this.substrateIndexs_glutamine = this.substrateIndexs({'GLN'});\n this.substrateIndexs_methionine = this.substrateIndexs({'MET'});\n this.substrateIndexs_fmethionine = this.substrateIndexs({'FMET'});\n this.substrateIndexs_atp = this.substrateIndexs({'ATP'});\n this.substrateIndexs_amp = this.substrateIndexs({'AMP'});\n this.substrateIndexs_adp = this.substrateIndexs({'ADP'});\n this.substrateIndexs_diphosphate = this.substrateIndexs({'PPI'});\n this.substrateIndexs_phosphate = this.substrateIndexs({'PI'});\n this.substrateIndexs_water = this.substrateIndexs({'H2O'});\n this.substrateIndexs_hydrogen = this.substrateIndexs({'H'});\n this.substrateIndexs_fthf10 = this.substrateIndexs({'FTHF10'});\n this.substrateIndexs_thf = this.substrateIndexs({'THF'});\n\n %include tRNAs as enzymes\n this.enzymeWholeCellModelIDs = [\n this.enzymeWholeCellModelIDs;\n this.rna.wholeCellModelIDs(this.rna.matureIndexs(this.rna.matureTRNAIndexs));\n 'MG_0004'];\n\n %enzyme indices\n this.enzymeIndexs_tRNASynthetases = this.enzymeIndexs({\n 'MG_292_TETRAMER'; %alanyl-tRNA synthetase\n 'MG_378_MONOMER'; %arginyl-tRNA synthetase\n 'MG_036_DIMER'; %aspartyl-tRNA synthetase\n 'MG_113_DIMER'; %asparaginyl-tRNA synthetase\n 'MG_253_MONOMER'; %cysteinyl-tRNA synthetase\n 'MG_462_MONOMER'; %glutamyl-tRNA synthetase\n 'MG_251_DIMER'; %glycyl-tRNA synthetase\n 'MG_035_DIMER'; %histidyl-tRNA synthetase\n 'MG_345_MONOMER'; %isoleucyl-tRNA synthetase\n 'MG_266_MONOMER'; %leucyl-tRNA synthetase\n 'MG_136_DIMER'; %lysyl-tRNA synthetase\n 'MG_021_DIMER'; %methionyl-tRNA synthetase\n 'MG_194_195_TETRAMER'; %phenylalanyl-tRNA synthetase\n 'MG_283_DIMER'; %prolyl-tRNA synthetase\n 'MG_005_DIMER'; %seryl-tRNA synthetase\n 'MG_375_DIMER'; %threonyl-tRNA synthetase\n 'MG_126_DIMER'; %tryptophanyl-tRNA synthetase\n 'MG_455_DIMER'; %tyrosyl-tRNA synthetase\n 'MG_334_MONOMER'}); %valyl-tRNA synthetase\n this.enzymeIndexs_tRNATransferases = this.enzymeIndexs({\n 'MG_098_099_100_TRIMER'; %glutamyl-tRNA(Gln) and/or aspartyl-tRNA(Asn) amidotransferase\n 'MG_365_MONOMER'}); %methionyl-tRNA formyltransferase\n this.enzymeIndexs_tRNAGlutamylSynthetase = this.enzymeIndexs({'MG_462_MONOMER'}); %glutamyl-tRNA synthetase\n this.enzymeIndexs_tRNAMethionylSynthetase = this.enzymeIndexs({'MG_021_DIMER'}); %methionyl-tRNA synthetase\n this.enzymeIndexs_tRNAGlutamylAmidotransferase = this.enzymeIndexs({'MG_098_099_100_TRIMER'}); %glutamyl-tRNA(Gln) and/or aspartyl-tRNA(Asn) amidotransferase\n this.enzymeIndexs_tRNAMethionylFormyltransferase = this.enzymeIndexs({'MG_365_MONOMER'}); %methionyl-tRNA formyltransferase\n this.enzymeIndexs_tRNAs = this.enzymeIndexs(this.rna.wholeCellModelIDs(this.rna.matureIndexs(this.rna.matureTRNAIndexs)));\n this.enzymeIndexs_tmRNA = this.enzymeIndexs({'MG_0004'});\n\n %RNAs\n this.reactionModificationMatrix(isnan(this.reactionModificationMatrix)) = 1;\n\n aaGenes = any(this.reactionModificationMatrix, 1)';\n aaRNAs = ComputationUtil.invertCompositionMatrix(this.rna.matureRNAGeneComposition) * aaGenes;\n this.aminoacylatedRNAGlobalIndexs = find(aaRNAs);\n this.aminoacylatedRNAtRNAIndexs = intersect(this.aminoacylatedRNAGlobalIndexs, this.rna.matureTRNAIndexs);\n\n this.freeRNAWholeCellModelIDs = this.rna.wholeCellModelIDs(this.rna.matureIndexs(this.aminoacylatedRNAGlobalIndexs));\n this.aminoacylatedRNAWholeCellModelIDs = this.rna.wholeCellModelIDs(this.rna.aminoacylatedIndexs(this.aminoacylatedRNAGlobalIndexs));\n\n this.reactionModificationMatrix = this.reactionModificationMatrix(:, aaGenes);\n\n %reaction indices\n this.reactionIndexs_aminoacylation = find(strcmp(this.reactionTypes, 'aminoacylation'));\n this.reactionIndexs_transfer = find(strcmp(this.reactionTypes, 'transfer'));\n this.reactionIndexs_glutamylamidotransfer = this.reactionIndexs({'MG502_Amidotransferase'});\n this.reactionIndexs_methionylformyltransfer = this.reactionIndexs({'MG488_Formyltransferase'});\n\n %for transfer reactions unlike knowledge base representation,\n %formulate reactionStoichiometryMatrix so that left-hand-side\n %doesn't include the already conjugated amino acid, and the\n %right-hand-side doesn't include the ultimate conjugated amino\n %acid\n this.reactionStoichiometryMatrix(this.substrateIndexs_glutamine, this.reactionIndexs_glutamylamidotransfer) = -1;\n this.reactionStoichiometryMatrix(this.substrateIndexs_glutamate, this.reactionIndexs_glutamylamidotransfer) = 1;\n this.reactionStoichiometryMatrix(this.substrateIndexs_methionine, this.reactionIndexs_methionylformyltransfer) = 0;\n this.reactionStoichiometryMatrix(this.substrateIndexs_fmethionine, this.reactionIndexs_methionylformyltransfer) = 0;\n\n %re-run super class method to update substrate and enzyme\n %mappings to include GLN, the tRNAs, and the tmRNA\n this.initializeConstants@edu.stanford.covert.cell.sim.Process(knowledgeBase, simulation, varargin{:});\n \n this.initializeSpeciesNetwork();\n\n %protein monomers -- needed for fitting\n this.monomerTRNACounts = knowledgeBase.proteinMonomerTRNACounts;\n end\n \n %initialize reaction stoichiomety to be used in evolveState:\n % [tRNA aminoacylations and transfers] X [subtrates; enzymes; free tRNAs]\n function initializeSpeciesNetwork(this)\n % formulate network: [tRNA aminoacylations and transfers] X [subtrates; enzymes; free tRNAs]\n numMetabolites = size(this.reactionStoichiometryMatrix, 1);\n numEnzymes = size(this.reactionCatalysisMatrix, 2);\n numRNAs = size(this.reactionModificationMatrix, 2);\n \n this.speciesReactantByproductMatrix = [this.reactionModificationMatrix' * [ ...\n -this.reactionStoichiometryMatrix' ...\n this.reactionCatalysisMatrix ./ repmat(this.enzymeBounds(:, 2) * this.stepSizeSec, 1, numEnzymes)] ...\n eye(numRNAs)];\n this.speciesReactantMatrix = [this.reactionModificationMatrix' * max(0, [ ...\n -this.reactionStoichiometryMatrix' ...\n this.reactionCatalysisMatrix ./ repmat(this.enzymeBounds(:, 2) * this.stepSizeSec, 1, numEnzymes)]) ...\n eye(numRNAs)];\n \n this.speciesIndexs_enzymes = (1:numEnzymes)' + numMetabolites;\n end\n\n %retrieve state from simulation\n function copyFromState(this)\n this.copyFromState@edu.stanford.covert.cell.sim.ReactionProcess();\n\n this.freeRNAs = this.rna.counts(this.rna.matureIndexs( this.aminoacylatedRNAGlobalIndexs), this.compartment.cytosolIndexs, :);\n this.aminoacylatedRNAs = this.rna.counts(this.rna.aminoacylatedIndexs(this.aminoacylatedRNAGlobalIndexs), this.compartment.cytosolIndexs, :);\n end\n\n %send state to simulation\n function copyToState(this)\n this.copyToState@edu.stanford.covert.cell.sim.ReactionProcess();\n\n this.rna.counts(this.rna.matureIndexs( this.aminoacylatedRNAGlobalIndexs), this.compartment.cytosolIndexs, :) = this.freeRNAs;\n this.rna.counts(this.rna.aminoacylatedIndexs(this.aminoacylatedRNAGlobalIndexs), this.compartment.cytosolIndexs, :) = this.aminoacylatedRNAs;\n end\n end\n\n %allocate memory for state\n methods\n function allocateMemoryForState(this, numTimePoints)\n this.allocateMemoryForState@edu.stanford.covert.cell.sim.ReactionProcess(numTimePoints);\n\n this.freeRNAs = zeros(length(this.aminoacylatedRNAGlobalIndexs), 1, numTimePoints);\n this.aminoacylatedRNAs = zeros(length(this.aminoacylatedRNAGlobalIndexs), 1, numTimePoints);\n end\n end\n\n %model\n methods\n %Calculate\n %- contribution to FBA objective\n %- minimum expression consistent with cell cycle length\n function [bmProd, byProd, minEnzExp, maxEnzExp] = calcResourceRequirements_LifeCycle(this, ~, states)\n %% substrate and byproducts\n %aminoacylations of each t(m)RNA\n [~, idxs] = ismember(this.aminoacylatedRNAtRNAIndexs, this.aminoacylatedRNAGlobalIndexs);\n aminoacylations = zeros(size(this.aminoacylatedRNAGlobalIndexs));\n aminoacylations(idxs) = aminoacylations(idxs) + ...\n this.monomerTRNACounts' * states.monomerProductions;\n \n %t(m)RNA aminoacylation reactions\n reactions = this.reactionModificationMatrix * aminoacylations;\n \n %metabolic load of t(m)RNA aminoacylation reactions\n bmProd = max(0, -this.reactionStoichiometryMatrix) * reactions;\n byProd = max(0, this.reactionStoichiometryMatrix) * reactions;\n \n %% enzymes\n %initialize\n minEnzExp = zeros(size(this.enzymeWholeCellModelIDs));\n maxEnzExp = Inf(size(this.enzymeWholeCellModelIDs));\n \n %tRNAs\n minEnzExp(this.enzymeIndexs_tRNAs) = 1.95 * this.monomerTRNACounts' * states.monomerProductions0;\n \n %tmRNA\n minEnzExp(this.enzymeIndexs_tmRNA) = 0;\n\n %tRNA synthetases, transferases\n [~, idxs] = ismember(this.aminoacylatedRNAtRNAIndexs, this.aminoacylatedRNAGlobalIndexs);\n aminoacylations = states.rnaProductions0(this.aminoacylatedRNAGlobalIndexs);\n aminoacylations(idxs) = max(aminoacylations(idxs), minEnzExp(this.enzymeIndexs_tRNAs));\n aminoacylations(setdiff(1:end,idxs)) = max(aminoacylations(setdiff(1:end,idxs)), minEnzExp(this.enzymeIndexs_tmRNA)); \n \n minEnzExp(setdiff(1:end, [this.enzymeIndexs_tRNAs; this.enzymeIndexs_tmRNA])) = ...\n + minEnzExp(setdiff(1:end, [this.enzymeIndexs_tRNAs; this.enzymeIndexs_tmRNA])) ...\n + 3 * this.reactionCatalysisMatrix' * ((this.reactionModificationMatrix * aminoacylations) ./ this.enzymeBounds(:, 2));\n end\n\n %initialization: RNAs initialized to mature state by simulation\n %initializeState method. This class initializes RNAs to\n %aminoacylated state.\n function initializeState(this)\n totalRNAs = this.aminoacylatedRNAs + this.freeRNAs;\n this.aminoacylatedRNAs = ceil(2 / 3 * totalRNAs);\n this.freeRNAs = totalRNAs - this.aminoacylatedRNAs;\n end\n\n %resource requirements\n function result = calcResourceRequirements_Current(this)\n result = max(0, -this.reactionStoichiometryMatrix) * min(...\n this.reactionModificationMatrix * (this.freeRNAs + this.aminoacylatedRNAs + 1), ...\n this.reactionCatalysisMatrix * this.enzymes(1:numel(this.speciesIndexs_enzymes)) * this.stepSizeSec);\n end\n \n %simulation\n function evolveState(this)\n %terminate early if no free RNAs\n if ~any(this.freeRNAs)\n return;\n end\n \n numRNAs = numel(this.freeRNAs);\n \n species = [\n this.substrates;\n this.enzymes(1:numel(this.speciesIndexs_enzymes));\n this.freeRNAs]';\n \n reactionFluxes = zeros(size(this.speciesReactantByproductMatrix, 1), 1);\n anyFlux = false;\n \n limits = species(ones(numRNAs, 1), :) ./ this.speciesReactantMatrix;\n limits(:, this.substrateIndexs_water) = NaN;\n limits(:, this.substrateIndexs_hydrogen) = NaN;\n reactionLimits = min(limits, [], 2)';\n reactionLimits(isinf(reactionLimits) | isnan(reactionLimits) | reactionLimits < 0) = 0;\n isReactionInactive = reactionLimits <= 0;\n \n while true\n %compute maximum number of each species that can be modified\n limits = species(ones(numRNAs, 1), :) ./ max(0, this.speciesReactantByproductMatrix); \n limits(:, this.substrateIndexs_water) = NaN;\n limits(:, this.substrateIndexs_hydrogen) = NaN;\n reactionLimits = min(...\n this.randStream.stochasticRound(min(limits(:, this.speciesIndexs_enzymes), [], 2)), ...\n min(limits(:, [1:this.speciesIndexs_enzymes(1)-1 this.speciesIndexs_enzymes(end)+1:end]), [], 2))';\n reactionLimits(isReactionInactive | isinf(reactionLimits) | isnan(reactionLimits) | reactionLimits < 1) = 0;\n \n %stop if no more tRNA can be aminoacylated\n if ~any(reactionLimits)\n break;\n end\n anyFlux = true;\n \n edges = min([0 cumsum(reactionLimits(:)' / sum(reactionLimits))], 1);\n nRxns = min(reactionLimits(reactionLimits > 0));\n if nRxns <= 1\n %pick substrate, reaction, enzymes\n [~, selectedReaction] = histc(rand(this.randStream, 1, 1), edges);\n reactionFluxes(selectedReaction) = ...\n + reactionFluxes(selectedReaction) ...\n + 1;\n \n %decrement metabolites, enzymes, unmodified substrates; increment modified substrates\n species = species - this.speciesReactantByproductMatrix(selectedReaction, :);\n else\n %pick substrate, reaction, enzymes\n edges(end) = 1.1;\n selectedReactions = histc(rand(this.randStream, nRxns, 1), edges);\n selectedReactions = selectedReactions(1:end-1);\n selectedReactions = selectedReactions(:);\n reactionFluxes = ...\n + reactionFluxes ...\n + selectedReactions;\n \n %decrement metabolites, enzymes, unmodified substrates; increment modified substrates\n species = species - selectedReactions' * this.speciesReactantByproductMatrix;\n end\n end\n \n %stop if no reaction can proceed\n if ~anyFlux\n return;\n end\n \n % update substrates\n this.substrates = this.substrates + ...\n this.reactionStoichiometryMatrix * this.reactionModificationMatrix * reactionFluxes;\n \n % update RNAs\n this.freeRNAs = this.freeRNAs - reactionFluxes;\n this.aminoacylatedRNAs = this.aminoacylatedRNAs + reactionFluxes;\n end\n end\n\n %get methods of dependent global state\n methods\n function value = get.tRNASynthetases(this)\n value = this.enzymes(this.enzymeIndexs_tRNASynthetases,:,:);\n end\n\n function value = get.tRNATransferases(this)\n value = this.enzymes(this.enzymeIndexs_tRNATransferases,:,:);\n end\n end\n\n %get methods of dependent local state\n methods\n function value = getDryWeight(this)\n if size(this.freeRNAs, 3) == 1\n value = this.getDryWeight@edu.stanford.covert.cell.sim.ReactionProcess() + (...\n this.rna.molecularWeights(this.rna.matureIndexs(this.aminoacylatedRNAGlobalIndexs))' * this.freeRNAs + ...\n this.rna.molecularWeights(this.rna.aminoacylatedIndexs(this.aminoacylatedRNAGlobalIndexs))' * this.aminoacylatedRNAs) ...\n / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n else\n value = this.getDryWeight@edu.stanford.covert.cell.sim.ReactionProcess() + (...\n permute(this.rna.molecularWeights(this.rna.matureIndexs(this.aminoacylatedRNAGlobalIndexs))' * permute(this.freeRNAs, [1 3 2]),[1 3 2]) + ...\n permute(this.rna.molecularWeights(this.rna.aminoacylatedIndexs(this.aminoacylatedRNAGlobalIndexs))' * permute(this.aminoacylatedRNAs,[1 3 2]),[1 3 2])) ...\n / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n end\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+process/tRNAAminoacylation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.03161876715458074, "lm_q1q2_score": 0.011362651229522219}} {"text": "function [modelJoint] = createMultipleSpeciesModel(models, varargin)\n% Based on the implementation from *Klitgord and Segre 2010, PMID 21124952*.\n% The present implementation has been used in *PMID 23022739*, *PMID 25841013*,\n% *PMID 25901891*, *PMID 27893703*.\n%\n% Joins one or more COBRA models with or without another COBRA model\n% representing the host. The created setup when a host is entered is\n% depicted schematically in Figures 1 and 2 in *PMID 27893703*.\n%\n% Creates a common space u (lumen) through which all cells can feed and exchange metabolites,\n% and separate extracellular spaces for all joined models.\n% If a host model is entered, a separate compartment `b` (body fluids) which has no\n% connection to extracellular space is created for the host. Metabolites can be transported from\n% the lumen to `e`, from `e` to the cytosol and from the cytosol to `b`,\n% but not from body fluids to the lumen.\n%\n% USAGE:\n%\n% [modelJoint] = createMultipleSpeciesModel(models, varargin)\n%\n% INPUTS:\n% models: cell array of COBRA models(at least one).\n% Format\n%\n% * models{1,1} = model 1\n% * models{2,1} = model 2...\n%\n% OPTIONAL INPUTS:\n% nameTagsModels: cell array of tags for reaction/metabolite abbreviation\n% corresponding to each model.\n% Format\n% * nameTagsModels{1,1} = 'name tag 1'\n% * nameTagsModels{2,1} = 'name tag 2'...\n% modelHost: COBRA model for host\n% nameTagHost: string of tag for reaction/metabolite abbreviation of host model\n% mergeGenesFlag: If true, the gene associations in both models are\n% included in the joined model. If false, empty fields are created\n% instead (default:false). Note: merging genes is time-consuming\n% and may crash certain models.\n% remCyclesFlag: If true, the function will attempt to remove futile\n% cycles that appear after merging the models (default: false).\n%\n% OUTPUT:\n% modelJoint: model structure for joint model\n%\n% .. Authors:\n% - Ines Thiele and Almut Heinken, 2011-2018\n% - Almut Heinken, 07.02.2018-included option whether or not genes are\n% merged\n% - Almut Heinken, 21.02.2018-fixed compatibility issue with reconstructions\n% from BIGG Models database that have _e instead of [e] as compartment IDs\n% - Almut Heinken, 06.03.2018-changed to parameter-input pairs\n% - Laurent Heirendt, 16/3/2018 - backward compatibility\n% - Almut Heinken, 15.01.2019-fixed compatibility issue with reconstructions\n% from KBase database that have [e0] instead of [e] as compartment IDs\n% - Almut Heinken, 01/2020-remove futile cycles in multi-species\n% AGORA models\n% - Almut Heinken, 07/2022-made futile cycles removal optional\n%\n% NOTE:\n% This function assumes, that exchange reactions are identified by\n% containing 'EX' in the reaction name and that no other reactions do have this property!\n\noldOptionalOrder = {'nameTagsModels', 'modelHost', 'nameTagHost', 'mergeGenesFlag'};\n\n% ensure backward compatibility\nif numel(varargin) > 0 && ~ischar(varargin{1})\n tempargin = cell(0);\n for i = 1:numel(varargin)\n if ~isempty(varargin{i})\n tempargin{end + 1} = oldOptionalOrder{i};\n tempargin{end + 1} = varargin{i};\n end\n end\n varargin = tempargin;\nend\n\n% Define default input parameters if not specified\nparser = inputParser();\nparser.addRequired('models', @iscell);\nparser.addParameter('nameTagsModels', {}, @iscell);\nparser.addParameter('modelHost', {}, @isstruct);\nparser.addParameter('nameTagHost', '', @(x) ischar(x) || iscell(x))\nparser.addParameter('mergeGenesFlag', false, @(x) isnumeric(x) || islogical(x))\nparser.addParameter('remCyclesFlag', false, @(x) isnumeric(x) || islogical(x))\n\nparser.parse(models, varargin{:});\n\nmodels = parser.Results.models;\nnameTagsModels = parser.Results.nameTagsModels;\nmodelHost = parser.Results.modelHost;\nnameTagHost = parser.Results.nameTagHost;\nmergeGenesFlag = parser.Results.mergeGenesFlag;\nremCyclesFlag = parser.Results.remCyclesFlag;\n\nif isempty(models)\n error('Please enter at least one model!')\nend\n% prepare the model structures and assign name tags for each model structure if not provided\nmodelNumber = size(models, 1);\n\nif isempty(nameTagsModels)\n % assign default name tags for microbes\n for i = 1:modelNumber\n nameTagsModels{i, 1} = strcat('model', num2str(i), '_');\n end\nelse\n if size(nameTagsModels, 1) ~= modelNumber\n error('Number of name tags and joint models needs to be identical!')\n end\nend\n\nif isempty(nameTagHost)\n % assign default name tag for host\n nameTagHost = 'Host_';\nend\n\n%% ensure compatibility with reconstructions from BIGG Models database\nfor i = 1:modelNumber\n model = models{i, 1};\n metIndices =~cellfun(@isempty, regexp(model.mets, '_e$'));\n model.mets(metIndices) = strrep(model.mets(metIndices), '_e', '[e]');\n models{i, 1} = model;\nend\nif ~isempty(modelHost)\nmetIndices =~cellfun(@isempty, regexp(modelHost.mets, '_e$'));\nmodelHost.mets(metIndices) = strrep(modelHost.mets(metIndices), '_e', '[e]');\nend\n\n%% Ensure compatibility with reconstructions from KBase database\nfor i = 1:modelNumber\n model = models{i, 1};\n metIndices =~cellfun(@isempty, regexp(model.mets, '\\[e0\\]$'));\n model.mets(metIndices) = strrep(model.mets(metIndices), '[e0]', '[e]');\n % need workaround for biomass metabolite, otherwise the resulting joint\n % model will be unable to carry biomass flux\n if ~isempty(find(ismember(model.mets, 'cpd11416[c0]')))\n model = addDemandReaction(model, 'cpd11416[c0]');\n end\n models{i, 1} = model;\nend\nif ~isempty(modelHost)\nmetIndices =~cellfun(@isempty, regexp(modelHost.mets, '\\[e0\\]$'));\nmodelHost.mets(metIndices) = strrep(modelHost.mets(metIndices), '[e0]', '[e]');\nend\n%% Remove futile cycles that may appear after joining (optional)\n\nif remCyclesFlag\n database = loadVMHDatabase;\n\n unionRxns={};\n for i = 1:modelNumber\n model=models{i, 1};\n unionRxns=vertcat(unionRxns,model.rxns);\n end\n unionRxns=unique(unionRxns);\n for i = 1:modelNumber\n model=models{i, 1};\n biomassReaction=model.rxns(find(strncmp(model.rxns, 'bio', 3)));\n model = removeFutileCycles(model, biomassReaction, database,unionRxns);\n models{i, 1} = model;\n end\nend\n%% define some variables\neTag = 'u';\nexTag = 'e';\n% find exchange reactions for models, but leaves demand and sink reactions\n% do this for all models to be added, remove exchange reactions from host while leaving demand and sink reactions\n% First, find the minimal number of fields common to all models.\npresentinallModels = fieldnames(models{1});\nmissingFields = {};\nfor i = 2:modelNumber\n cfields = fieldnames(models{i});\n missingFields = union(missingFields, setxor(cfields, presentinallModels));\n presentinallModels = intersect(presentinallModels, cfields);\nend\nfprintf('The following fields are missing in several models, they will not be merged:\\n');\ndisp(missingFields);\nmodels = restrictModelsToFields(models, presentinallModels);\n\nmodelStorage = cell(modelNumber, 1);\nfor i = 1:modelNumber\n % a new model each turn\n model = models{i, 1};\n % find exchange reactions and external metabolites\n exmod = model.rxns(strmatch('EX', model.rxns));\n % remove all previously defined exchange reactions\n model = removeRxns(model, exmod);\n % make sure the exchange reactions and changed model are saved under correct name\n modelStorage{i, 1} = model;\nend\n\nif ~isempty(modelHost)\n %% with a host\n exmod = modelHost.rxns(strmatch('EX', modelHost.rxns));\n\n % modelHost = removeRxns(modelHost,ExRH);\n % ExRH = modelHost.rxns(selExcH);\n % ExRH(strmatch('sink',modelHost.rxns(selExcH)))=[];\n % ExRH(strmatch('DM',modelHost.rxns(selExcH)))=[];\n\n % create a new extracellular space for host\n % find all metabolites in e\n relMetIndex = cellfun(@(x) ~isempty(strfind(x, '[e]')), modelHost.mets);\n relMets = modelHost.mets(relMetIndex);\n relRxns = findRxnsFromMets(modelHost, relMets); % These are all reactions which are relevant\n rxnIndices = ismember(modelHost.rxns, relRxns);\n Stoich = modelHost.S(:, rxnIndices);\n changedMets = regexprep(modelHost.mets, '\\[e\\]', '\\[b\\]');\n modelHost = addMultipleMetabolites(modelHost, setdiff(changedMets, modelHost.mets));\n modelHost = addMultipleReactions(modelHost, strcat(modelHost.rxns(rxnIndices), 'b'), changedMets, Stoich, 'lb', modelHost.lb(rxnIndices), ...\n 'ub', modelHost.ub(rxnIndices), 'c', modelHost.c(rxnIndices), 'subSystems', repmat({'Host Exchange'}, numel(relRxns), 1));\n\n % remove exchange reactions from host while leaving demand and sink reactions\n modelHost = removeRxns(modelHost, exmod);\n\n %% create intercellular space\n % will need to find all extracellular metabolites and duplicate reactions\n % if a host model was input, create the shared compartment for the microbes\n model = modelStorage{1, 1};\n nameTag = nameTagsModels{1, 1};\n [modelJoint, MexGJoint] = createInterSpace(model, nameTag, eTag, exTag);\n\n % if more than one microbe was input\n if modelNumber > 1\n for i = 1:modelNumber\n model = modelStorage{i, 1};\n nameTag = nameTagsModels{i, 1};\n [model, MexG] = createInterSpace(model, nameTag, eTag, exTag);\n % make sure the changed model is saved under correct name\n modelStorage{i, 1} = model;\n MexGJoint = union(MexG, MexGJoint);\n end\n end\n\n [modelHost,MexGHost] = createInterSpace(modelHost, nameTagHost, eTag, exTag);\n MexGJoint = union(MexGJoint, MexGHost);\n\n %% merge the models\n % if more than one microbe was input\n if modelNumber > 1\n for i = 2:modelNumber\n model = modelStorage{i, 1};\n [modelJoint] = mergeTwoModels(modelJoint, model, 1, mergeGenesFlag);\n end\n end\n [modelJoint] = mergeTwoModels(modelJoint,modelHost, 1, mergeGenesFlag);\n\n modelJoint = addExchangeRxn(modelJoint, unique(MexGJoint));\n\nelse\n %% without a host\n % create the shared compartment for the microbes\n model = modelStorage{1, 1};\n nameTag = nameTagsModels{1, 1};\n [modelJoint, MexGJoint] = createInterSpace(model, nameTag, eTag, exTag);\n if modelNumber > 1\n for i = 2:modelNumber\n model = modelStorage{i, 1};\n nameTag = nameTagsModels{i, 1};\n [model, MexG] = createInterSpace(model, nameTag, eTag, exTag);\n modelStorage{i, 1}=model;\n MexGJoint = union(MexG, MexGJoint);\n end\n end\n\n if modelNumber > 1\n for i = 2:modelNumber\n model = modelStorage{i, 1};\n [modelJoint] = mergeTwoModels(modelJoint, model, 1, mergeGenesFlag);\n end\n end\n\n modelJoint = addExchangeRxn(modelJoint, unique(MexGJoint));\nend\nend\n\n%%\nfunction [modelNew,MexG] = createInterSpace(model, nameTag, eTag, exTag)\n% create intercellular space\n% will need to find all extracellular metabolites and duplicate reactions using them\nmodelNew = model;\n% add name tag to all metabolites and reactions in model\nmodelNew.mets = strcat(nameTag, model.mets);\nmodelNew.rxns = strcat(nameTag, model.rxns);\n% Get the relevant metabolites\nrelMetsIndex = cellfun(@(x) ~isempty(strfind(x,'biomass[c]')) || ~isempty(strfind(x,['[', exTag, ']'])),modelNew.mets);\nrelMets = modelNew.mets(relMetsIndex);\n% Define the names of the interspace metabolites\nMexG = regexprep(strrep(relMets,nameTag,''),strcat('\\[', exTag, '\\]'), strcat('\\[', eTag, '\\]'));\nvarinput = {};\n% Add metNames and metFormulas, if present in the original model\nif isfield(modelNew,'metNames')\n varinput{end+1} = 'metNames';\n varinput{end+1} = modelNew.metNames(relMetsIndex);\nend\nif isfield(modelNew,'metFormulas')\n varinput{end+1} = 'metFormulas';\n varinput{end+1} = modelNew.metFormulas(relMetsIndex);\nend\n% Add all new Metabolites\nmodelNew = addMultipleMetabolites(modelNew, MexG, varinput{:});\n\nnExchange = numel(relMets);\n% Set the exchanger Stoichiometries (met[e] -> met[u])\nstoich = [-speye(nExchange);speye(nExchange)];\n% Set the names of the exchangers\nrxnNames = strcat(nameTag, 'IEX_', MexG, 'tr');\n% Set the bounds\nlbs = repmat(-1000,nExchange,1);\nubs = repmat(1000,nExchange,1);\n% Set the subSystem\nsubSystems = repmat({'Transport, intercellular'},nExchange,1);\n% Add all Reactions in one go.\nmodelNew = addMultipleReactions(modelNew,rxnNames,[relMets;MexG],stoich,'lb',lbs,'ub',ubs,'subSystems',subSystems);\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/multiSpecies/microbiomeModelingToolbox/pairwiseInteractionModeling/createMultipleSpeciesModel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.027169232618778332, "lm_q1q2_score": 0.011272483254715053}} {"text": "function model = setCommonZeroStandardGibbsEnergyOfFormation(model, adjustedMetList)\n% Sets all Alberty's cofactor metabolites to have a common thermodynamic baseline.\n%\n% Sets all the exceptional metabolites to have a common baseline.\n% i.e. Standard transformed Gibbs energies of reactants with the baseline adjusted\n% for certain paired cofactors e.g. `fad` & `fadh2`, such that the\n% difference between the two is the same as in Albertys data but\n% the absolute values are consistent with the group contribution data\n%\n% USAGE:\n%\n% model = setCommonZeroStandardGibbsEnergyOfFormation(model, adjustedMetList)\n%\n% INPUT:\n% model: Thermodynamic model:\n%\n% * .met(m).dGft0 - standard transformed Gibbs energy of formation(kJ/mol)\n% * .met(m).dGft0Keq - standard transformed Gibbs energy of formation(kJ/mol)\n% * .met(m).dGft0Source - origin of data, `Keq` or `groupContFileName.txt`\n% * .met(m).dGft0GroupCont - group. cont. estimate of standard transformed Gibbs energy of formation(kJ/mol)\n%\n% OPTIONAL INPUT:\n% adjustedMetList:\n% OUTPUT:\n% model: structure with field:\n%\n% * .met(m).dGft0 - Standard transformed Gibbs energies of reactants\n% with the baseline adjusted for certain paired\n% cofactors e.g. `fad` & `fadh2`, such that the\n% difference between the two is the same as in\n% Albertys data but the absolute values are\n% consistent with the group contribution data\n%\n% .. Author: - Ronan M.T. Fleming\n%\n% .. Here is the list of cofactors in iAF1260 that have thermodynamic\n% properties backcalculated from Equilibrium values by Alberty\n% The compartments here are important since the same reactant in different\n% compartments may have different properties.\n\nif ~exist('adjustedMetList','var')\n%This list of cofactors contains metabolites with own baselines reported\n%by Alberty in his 2006 book, plus some metabolites that appear on the\n%other side of a reaction from Alberty's set. It is important to keep an\n%eye on the latter as they must all be on a common baseline when the\n%adjustment is done.\nadjustedMetList={'coa','aacoa','accoa','ppcoa','mmcoa_R','mmcoa-R',...\n 'succoa','gthrd','gthox','q8h2','q8','fmn','fmnh2','nad',...\n 'nadh','nmn','fad','fadh2','nadp','nadph','malcoa'};\nend\n\nnumChar=1;\n[allMetCompartments,uniqueCompartments]=getCompartment(model.mets,numChar);\n\nfor p=1:length(uniqueCompartments)\n\n n=1;\n leftAll{n}=['fad' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['fadh2' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['q8' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['q8h2' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['nad' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['nadh' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['nad' '[' uniqueCompartments{p} ']']; % it is essential that the nad nmn pair are in this position\n rightAll{n}=['nmn' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['nadp' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['nadph' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['gthox' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['gthrd' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['fmn' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['fmnh2' '[' uniqueCompartments{p} ']'];\n n=n+1;\n %here is the list of cofactors in E. coli which are covered by Albertys data\n %see:\n %Standard transformed Gibbs energies of coenzyme A derivatives as\n %functions of pH and ionic strength\n %R.A. Alberty / Biophysical Chemistry 104 (2003) 327�334\n coAset={['coa[' uniqueCompartments{p} ']'],...\n ['aacoa[' uniqueCompartments{p} ']'],...\n ['accoa[' uniqueCompartments{p} ']'],...\n ['mmcoa-R[' uniqueCompartments{p} ']'],...\n ['mmcoa-S[' uniqueCompartments{p} ']'],...\n ['ppcoa[' uniqueCompartments{p} ']'],...\n ['succoa[' uniqueCompartments{p} ']'],...\n ['malcoa[' uniqueCompartments{p} ']']};\n leftAll{n}=[];n=n+1;\n leftAll{n}=['ppcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['succoa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['ppcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['mmcoa-S' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['ppcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=[];n=n+1;\n leftAll{n}=['succoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['succoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['mmcoa-R' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['malcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['malcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['accoa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=[];n=n+1;\n leftAll{n}=['dpcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['dpcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['2tpr3dpcoa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['dpcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['pan4p' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=[];n=n+1;\n leftAll{n}=['sbzcoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['aacoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n % Note this reaction that contains three cofactors:\n % KAT1, 3-ketoacyl-CoA thiolase [c] : aacoa + coa --> (2) accoa\n leftAll{n}=['accoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['coa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n leftAll{n}=['accoa' '[' uniqueCompartments{p} ']'];\n rightAll{n}=['aacoa' '[' uniqueCompartments{p} ']'];\n n=n+1;\n %check 'mmcoa-R'\n % methylmalonyl-CoA epimerase\n % equation:\t[c] : mmcoa-R <==> mmcoa-S\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n [nMet,nRxn]=size(model.S);\n\n exceptionMetBool=false(nMet,1);\n for m=1:nMet\n abbr=model.mets{m};\n abbr=abbr(1:end-3);\n if any(strcmp(abbr,adjustedMetList))\n exceptionMetBool(m)=1;\n end\n end\n fprintf('\\n%s\\n%s\\n','Setting certain Alberty reactants to have a common thermodynamic',...\n 'baseline so that this data can be incorporated with group contribution data.')\n fprintf('%s\\n','Before baseline edit of Cofactors:')\n fprintf('%s\\n','Metabolite properties:')\n %print out exceptional metabolite data before edit to baseline\n fprintf('%10s\\t%20s\\t%s\\t\\t%s\\t\\t%s\\n','abbr','albertyAbbr','dGft0Keq','dGft0gc','dGft0');\n for m=1:nMet\n if exceptionMetBool(m)\n fprintf('%10s\\t%20s\\t%8.4g\\t\\t%8.4g\\t\\t%8.4g\\n',model.mets{m},model.met(m).albertyAbbreviation,model.met(m).dGft0Keq,model.met(m).dGft0GroupCont,model.met(m).dGft0);\n end\n end\n fprintf('\\n\\n')\n\n fprintf('\\n\\n');\n fprintf('%s\\n','Differences between pairs of cofactors (cytoplasm only):')\n fprintf('%22s%10s%10s%10s%10s%10s%16s%16s\\n','left-right','#RxnLeft','#RxnRight','#Both','#LNotR','#RNotL','dGtr0Keq','dGrt0');\n for x=1:length(leftAll)\n abbrL=leftAll{x};\n abbrL=[abbrL(1:end-3) '[c]'];\n abbrR=rightAll{x};\n abbrR=[abbrR(1:end-3) '[c]'];\n\n nCoFcLRxn=length(find(model.S(strcmp(model.mets,abbrL),:)~=0));\n nCoFcRRxn=length(find(model.S(strcmp(model.mets,abbrR),:)~=0));\n nCoFc2Rxn=length(intersect(find(model.S(strcmp(model.mets,abbrL),:)~=0),find(model.S(strcmp(model.mets,abbrR),:)~=0)));\n nCoLeftOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrL),:)~=0),find(model.S(strcmp(model.mets,abbrR),:)~=0)));\n nCoRightOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrR),:)~=0),find(model.S(strcmp(model.mets,abbrL),:)~=0)));\n\n %nothing to print out if no match\n if any(strcmp(model.mets,abbrL)) && any(strcmp(model.mets,abbrR))\n fprintf('%22s%10i%10i%10i%10i%10i\\t%8.4g\\t%8.4g\\n',[abbrL '-' abbrR],nCoFcLRxn,nCoFcRRxn,nCoFc2Rxn,nCoLeftOnly,nCoRightOnly,...\n model.met(strcmp(model.mets,abbrL)).dGft0Keq-model.met(strcmp(model.mets,abbrR)).dGft0Keq,...\n model.met(strcmp(model.mets,abbrL)).dGft0-model.met(strcmp(model.mets,abbrR)).dGft0);\n end\n end\n\n% fprintf('%s\\n','Differences between pairs of cofactors:')\n% fprintf('%20s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n','left-right','#RxnLeft','#RxnRight','#Both','#LNotR','#RNotL','dGt0Keq','dGt0gc');\n% xx=0;\n% for x=1:length(leftAll)\n% if isempty(leftAll{x})\n% % fprintf('\\n');\n% else\n% nCoFcLRxn=length(find(model.S(strcmp(model.mets,leftAll{x}),:)~=0));\n% nCoFcRRxn=length(find(model.S(strcmp(model.mets,rightAll{x}),:)~=0));\n% nCoFc2Rxn=length(intersect(find(model.S(strcmp(model.mets,leftAll{x}),:)~=0),find(model.S(strcmp(model.mets,rightAll{x}),:)~=0)));\n% nCoLeftOnly=length(setdiff(find(model.S(strcmp(model.mets,leftAll{x}),:)~=0),find(model.S(strcmp(model.mets,rightAll{x}),:)~=0)));\n% nCoRightOnly=length(setdiff(find(model.S(strcmp(model.mets,rightAll{x}),:)~=0),find(model.S(strcmp(model.mets,leftAll{x}),:)~=0)));\n%\n% %nothing to print out if no match\n% if any(strcmp(model.mets,leftAll{x})) && any(strcmp(model.mets,rightAll{x}))\n% fprintf('%20s\\t\\t%i\\t\\t\\t%i\\t\\t%i\\t\\t%i\\t\\t%i\\t\\t%8.4g\\t\\t%8.4g\\n',[leftAll{x} '-' rightAll{x}],nCoFcLRxn,nCoFcRRxn,nCoFc2Rxn,nCoLeftOnly,nCoRightOnly,...\n% model.met(strcmp(model.mets,leftAll{x})).dGft0Keq-model.met(strcmp(model.mets,rightAll{x})).dGft0Keq,...\n% model.met(strcmp(model.mets,leftAll{x})).dGft0GroupCont-model.met(strcmp(model.mets,rightAll{x})).dGft0GroupCont);\n% end\n% a=1;\n% end\n% end\n\n %edit the baseline of a cofactor that is not always used in a pair\n %with another cofactor\n coaSorted=0;\n x=1;\n while x<=length(leftAll)\n abbrL=leftAll{x};\n abbrR=rightAll{x};\n\n pause(eps)\n if strcmp('coa[c]',abbrR)\n pause(eps)\n end\n %check that both left and right cofactors are always used in the network\n %together because there is no need to change if they are always used\n %together on different sides of the reaction\n if any(strcmp(abbrL,model.mets)) && any(strcmp(abbrR,model.mets))\n %check if coa is involved since coa is a special case that is not a\n %simple cofactor pair\n if ~(any(strcmp(abbrL,coAset) | any(strcmp(abbrR,coAset))))\n nCoLeftOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrL),:)~=0),find(model.S(strcmp(model.mets,abbrR),:)~=0)));\n nCoRightOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrR),:)~=0),find(model.S(strcmp(model.mets,abbrL),:)~=0)));\n %identify which one in each cofactor pair is synthesised/used in\n %another reaction, besides just being used in reactions with its\n %paired cofactor\n if nCoLeftOnly==0 && nCoRightOnly~=0\n %calculate the difference between the group contribution\n %estimate and Albertys value\n baseLineChange=model.met(strcmp(model.mets,abbrR)).dGft0GroupCont-model.met(strcmp(model.mets,abbrR)).dGft0Keq;\n for m=1:nMet\n abbr=model.mets{m};\n if any(strcmp(model.mets{m},{abbrL,abbrR}))\n %only change if we are using Albertys data\n if strcmp(model.met(m).dGft0Source,'Keq')\n model.met(m).dGft0=model.met(m).dGft0+baseLineChange;\n end\n end\n end\n end\n\n if nCoLeftOnly~=0 && nCoRightOnly==0\n %calculate the difference between the group contribution\n %estimate and Albertys value for the left cofactor\n baseLineChange=model.met(strcmp(model.mets,abbrL)).dGft0GroupCont-model.met(strcmp(model.mets,abbrL)).dGft0Keq;\n for m=1:nMet\n if any(strcmp(model.mets{m},{abbrL,abbrR})) % change baseline for both cofactors\n %only change if we are using Albertys data\n if strcmp(model.met(m).dGft0Source,'Keq')\n model.met(m).dGft0=model.met(m).dGft0+baseLineChange;\n end\n end\n end\n if strcmp(abbrL,['nad' '[' uniqueCompartments{p} ']']) && strcmp(abbrR,['nadh' '[' uniqueCompartments{p} ']']) && any(strcmp(model.mets,['nmn' '[' uniqueCompartments{p} ']'] ))\n fprintf('%s\\n',['Assuming Albertys value for nmn is set to nad baseline']);\n for m=1:nMet\n if any(strcmp(model.mets{m},['nmn' '[' uniqueCompartments{p} ']']))\n %only change if we are using Albertys data\n if strcmp(model.met(m).dGft0Source,'Keq')\n model.met(m).dGft0=model.met(m).dGft0+baseLineChange;\n end\n end\n end\n %ensure that nad baseline is not changed twice due to nad also\n %appearing as a cofactor with nmn\n %skip the next pair as it is nad[c] & nmn[c]\n x=x+1;\n end\n end\n\n else\n %for the cofactors associated with coa by Alberty, then set coA to\n %have the same baseline as the group contribution data\n if coaSorted==0\n pause(eps)\n for s=1:length(coAset)\n %Changed to make suitable for multiple compartments May 24th 2011\n baseLineChange=model.met(strcmp(model.mets,['coa[' uniqueCompartments{p} ']'])).dGft0GroupCont-model.met(strcmp(model.mets,['coa[' uniqueCompartments{p} ']'])).dGft0Keq;\n for m=1:nMet\n if strcmp(coAset{s},model.mets{m})\n %only change if we are using Albertys data\n if strcmp(model.met(m).dGft0Source,'Keq')\n model.met(m).dGft0=model.met(m).dGft0+baseLineChange;\n end\n end\n end\n end\n coaSorted=1;\n end\n end\n end\n x=x+1;\n end\n %compartment by compartment\n coASorted=0;\nend\n\nfprintf('\\n\\n')\nfprintf('%s\\n','After baseline edit of Cofactors:')\nfprintf('%s\\n','Metabolite properties:')\nfprintf('%10s\\t%30s\\t%s\\t%s\\t%s\\n','abbr','albertyAbbr','dGft0Keq',' dGft0gc',' dGft0');\n%print out the new changes\nfor m=1:nMet\n if strcmp('nad[c]',model.mets{m})\n pause(eps)\n end\n if exceptionMetBool(m)\n fprintf('%10s\\t%30s\\t%8.4g\\t%8.4g\\t%8.4g\\n',model.mets{m},model.met(m).albertyAbbreviation,model.met(m).dGft0Keq,model.met(m).dGft0GroupCont,model.met(m).dGft0);\n end\nend\n\nfprintf('\\n\\n');\nfprintf('%s\\n','Differences between pairs of cofactors, after baseline edit (cytoplasm only):')\nfprintf('%22s%10s%10s%10s%10s%10s%16s%16s\\n','left-right','#RxnLeft','#RxnRight','#Both','#LNotR','#RNotL','dGtr0Keq','dGrt0');\nfor x=1:length(leftAll)\n abbrL=leftAll{x};\n abbrL=[abbrL(1:end-3) '[c]'];\n abbrR=rightAll{x};\n abbrR=[abbrR(1:end-3) '[c]'];\n\n nCoFcLRxn=length(find(model.S(strcmp(model.mets,abbrL),:)~=0));\n nCoFcRRxn=length(find(model.S(strcmp(model.mets,abbrR),:)~=0));\n nCoFc2Rxn=length(intersect(find(model.S(strcmp(model.mets,abbrL),:)~=0),find(model.S(strcmp(model.mets,abbrR),:)~=0)));\n nCoLeftOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrL),:)~=0),find(model.S(strcmp(model.mets,abbrR),:)~=0)));\n nCoRightOnly=length(setdiff(find(model.S(strcmp(model.mets,abbrR),:)~=0),find(model.S(strcmp(model.mets,abbrL),:)~=0)));\n\n %nothing to print out if no match\n if any(strcmp(model.mets,abbrL)) && any(strcmp(model.mets,abbrR))\n fprintf('%22s%10i%10i%10i%10i%10i\\t%8.4g\\t%8.4g\\n',[abbrL '-' abbrR],nCoFcLRxn,nCoFcRRxn,nCoFc2Rxn,nCoLeftOnly,nCoRightOnly,...\n model.met(strcmp(model.mets,abbrL)).dGft0Keq-model.met(strcmp(model.mets,abbrR)).dGft0Keq,...\n model.met(strcmp(model.mets,abbrL)).dGft0-model.met(strcmp(model.mets,abbrR)).dGft0);\n end\nend\n\n\n%OLD CODE -may still be usefull for looking at nullspace of internal\n%reactions that are also involve cofactors\n% if ~exist('exceptions','var')\n% exceptions={'coa','aacoa','accoa','ppcoa','mmcoa_R','mmcoa-R',...\n% 'succoa','gthrd','gthox','q8h2','q8','fmn','fmnh2','nad',...\n% 'nadh','fad','fadh2','nadp','nadph','malcoa'};\n% end\n%\n%\n% [nMet,nRxn]=size(model.S);\n%\n% if ~isfield(model,'biomassRxnAbbr')\n% if ~exist('biomassRxnAbbr')\n% fprintf('\\n%s\\n','...checkObjective');\n% objectiveAbbr=checkObjective(model);\n% fprintf('%s\\n',['Asumming objective is ' objectiveAbbr]);\n% model.biomassRxnAbbr=objectiveAbbr;\n% else\n% model.biomassRxnAbbr=biomassRxnAbbr;\n% end\n% end\n%\n% %finds the reactions in the model which export/import from the model\n% %boundary\n% %e.g. Exchange reactions\n% % Demand reactions\n% % Sink reactions\n% model=findSExRxnInd(model);\n% %OUTPUT\n% % model.SIntRxnInd indices of internal reactions\n% % model.SExRxnInd indices of boundary reactions\n% intRxnBool=false(1,nRxn);\n% intRxnBool(model.SIntRxnInd)=1;\n%\n\n%\n% %extract subnetwork\n% modelE=model;\n% %reactions\n% exceptionRxnBool=logical(sign(sum(abs(model.S(exceptionMetBool,:)),1)));\n% %only keep internal reactions involving exceptional metabolites\n% modelE.S=modelE.S(:,exceptionRxnBool & intRxnBool);\n% modelE.rxns=modelE.rxns(exceptionRxnBool & intRxnBool);\n% modelE.lb=modelE.lb(exceptionRxnBool & intRxnBool);\n% modelE.ub=modelE.ub(exceptionRxnBool & intRxnBool);\n% %metabolites\n% keepMetBool=false(nMet,1);\n% for m=1:nMet\n% if nnz(modelE.S(m,:))~=0\n% keepMetBool(m,1)=1;\n% end\n% end\n% modelE.S=modelE.S(keepMetBool,:);\n% modelE.mets=modelE.mets(keepMetBool);\n%\n% exceptionMetBool=false(nMet,1);\n% for m=1:nMet\n% abbr=model.mets{m};\n% if any(strcmp(abbr(end-2:end),'[c]'))\n% abbr=abbr(1:end-3);\n% if any(strcmp(abbr,exceptions))\n% exceptionMetBool(m)=1;\n% end\n% end\n% end\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/thermo/reactantContribution/setCommonZeroStandardGibbsEnergyOfFormation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.024798162402778087, "lm_q1q2_score": 0.01124006128436147}} {"text": "function Model = buildRxnEquations(Model)\n% Takes a COBRA model and creates reaction equations based\n% on the metabolites list, `S` matrix and bound information. Returns the\n% model with the additinal field `rxnEquations`. Is called by `cleanTmodel`, `compareCbModels`, `readCbTmodel`, `verifyModel`, `addSEEDInfo`.\n%\n% USAGE:\n%\n% Model = buildRxnEquations(Model)\n%\n% INPUTS:\n% Model: COBRA format model or `Tmodel`\n%\n% OUTPUTS:\n% Model: Model with corrected `rxnEquations` field.\n%\n% Please cite:\n% `Sauls, J. T., & Buescher, J. M. (2014). Assimilating genome-scale\n% metabolic reconstructions with modelBorgifier. Bioinformatics\n% (Oxford, England), 30(7), 1036?8`. http://doi.org/10.1093/bioinformatics/btt747\n%\n% ..\n% Edit the above text to modify the response to help addMetInfo\n% Last Modified by GUIDE v2.5 06-Dec-2013 14:19:28\n% This file is published under Creative Commons BY-NC-SA.\n%\n% Correspondance:\n% johntsauls@gmail.com\n%\n% Developed at:\n% BRAIN Aktiengesellschaft\n% Microbial Production Technologies Unit\n% Quantitative Biology and Sequencing Platform\n% Darmstaeter Str. 34-36\n% 64673 Zwingenberg, Germany\n% www.brain-biotech.de\n\nif isstruct(Model.lb) % If the function is fed Tmodel, use reaction bounds from first model.\n modelNames = fieldnames(Model.Models) ;\n firstModel = modelNames{1} ;\n lb = Model.lb.(firstModel) ;\n ub = Model.ub.(firstModel) ;\nelse\n lb = Model.lb ;\n ub = Model.ub ;\nend\n\n%% Make the equations.\nfor iRxn = 1:length(Model.rxns)\n rxnCode = [] ;\n\n educts = find(Model.S(:,iRxn) < 0) ;\n products = find(Model.S(:,iRxn) > 0) ;\n if lb(iRxn) < 0 && ub(iRxn) > 0\n arrow = '<==>' ;\n elseif lb(iRxn) >= 0 && ub(iRxn) > 0\n arrow = '-->' ;\n elseif lb(iRxn) < 0 && ub(iRxn) <= 0\n arrow = '<--' ;\n elseif lb(iRxn) == 0 && ub(iRxn) == 0\n arrow = '|||' ;\n else\n disp(['Do not understand directionality of ' Model.rxns{iRxn}])\n end\n\n if ~isempty(educts)\n for ie = 1:length(educts)\n if Model.S(educts(ie), iRxn) ~= -1\n rxnCode = [rxnCode '(' num2str(-Model.S(educts(ie),iRxn)) ...\n ') ' Model.mets{educts(ie)} ] ;\n else\n rxnCode = [rxnCode Model.mets{educts(ie)}] ;\n end\n rxnCode = [rxnCode ' + '] ;\n end\n % Note how just 2 positions are substracted from the end, leaving a\n % space.\n rxnCode = [rxnCode(1:end - 2) arrow] ;\n end\n if ~isempty(products)\n rxnCode = [rxnCode ' '] ;\n for ip = 1:length(products)\n if Model.S(products(ip), iRxn) ~= 1\n rxnCode = [rxnCode '(' num2str(Model.S(products(ip), iRxn))...\n ') ' Model.mets{products(ip)}] ;\n else\n rxnCode = [rxnCode Model.mets{products(ip)}] ;\n end\n rxnCode = [rxnCode ' + '] ;\n end\n rxnCode = rxnCode(1:end - 3) ;\n end\n\n Model.rxnEquations{iRxn, 1} = rxnCode ;\n clear educts ; clear products; clear ie ; clear ip ; clear rxcode ;\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/comparison/modelBorgifier/buildRxnEquations.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.03514484842196812, "lm_q1q2_score": 0.011037259251840422}} {"text": "function result = parseBC(N, BC, type)\n%PARSEBC Parse boundary conditions for CHEBOP object.\n% This method is not intended for end users. For information about boundary\n% conditions in CHEBOPs, see CHEBOP.\n%\n% This method is invoked by the set methods for LBC, RBC, and BC. The types\n% and meanings of the allowed input are described in the documentation for\n% CHEBOP. The result is either empty or a function handle that represents the\n% given condition as needed internally.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers. \n% See http://www.chebfun.org/ for Chebfun information.\n\nnumIn = nargin(N);\n\nif ( isempty(BC) )\n result = [];\n \nelseif ( isnumeric(BC) )\n % We reach here if we get assigned BCs like N.lbc = [1; 3].\n % * In the scalar case, this means setting up conditions so that the\n % solution equals the first entry of the vector at the endpoint, its\n % derivative the second entry etc. In the example above, for a\n % second order problem on [0,1], this amounts to\n % u(0) = 1, u'(0) = 3.\n % * In the system case, this means that the value of the first unknown \n % function equals the first entry of the vector, the second unknown\n % function the second entry of the vector, etc. In the example above,\n % for a coupled system on [0,1], this amounts to \n % u(0) = 1, v(0) = 3.\n % Higher order coupled systems are not supported, as that would require\n % inspecting the diffOrder of the linearized chebop, a (relatively)\n % computionally expensive operation. That information only becomes\n % available for free once we've called \\ for starting to solve the\n % problem.\n result = @(varargin) setupNumericalConditions(BC, varargin);\n \nelseif ( isa(BC, 'function_handle') )\n % If we are dealing with a scalar problem where the independent variable is\n % not specified in the function handle arguments, allow also passing an\n % input function handle that takes one argument. Otherwise, we request that\n % the number of input to the BC function handle is one less than the number\n % of arguments to the OP part. A special case is when BCs are specified as a\n % vector, this leads to nargin(BC) = -1 (since we assigned the boundary\n % conditions as an anonymous function with a varargin argument), if this is\n % the case and the number of inputs for the BC don't match the operator, a\n % meaningful error will be thrown later on.\n if ( (numIn == 0) || ( (numIn == 1) && (nargin(BC) == 1) ) || ...\n ( strcmp(type,'lrbc') && (nargin(BC) == (numIn - 1)) ) || ...\n ( strcmp(type,'lrbc') && (nargin(BC) == -1) ) || ...\n ( strcmp(type,'bc') && (nargin(BC) == numIn) ) || ...\n ( strcmp(type,'bc') && (nargin(BC) == numIn + 1) ) )\n % We've got an anonymous function we're happy with. Do we need to\n % vectorize it?\n if ( N.vectorize && ~strcmp(func2str(BC), vectorize(BC)) )\n result = N.vectorizeOp(BC);\n else\n result = BC;\n end\n else\n error('CHEBFUN:CHEBOP:parseBC:inputs', ...\n 'Number of inputs to BCs do not match operator.');\n end\n \nelseif ( strcmpi(BC, 'neumann') )\n % Homogeneous Neumann.\n if ( numIn <= 2 )\n result = @(u) diff(u);\n else\n error('CHEBFUN:CHEBOP:parseBC:neuman', ...\n 'Can only assign scalar BCs to scalar problems.');\n end\n \nelseif ( strcmpi(BC, 'dirichlet') )\n % Homogeneous Dirichlet. \n if ( numIn <= 2 )\n result = @(u) u;\n else\n error('CHEBFUN:CHEBOP:parseBC:dirichlet', ...\n 'Can only assign scalar BCs to scalar problems.');\n end\n \nelseif ( iscell(BC) ) && ( length(BC) == 2 ) && ( ischar(BC{2}) ) && ...\n ( isnumeric(BC{1}) )\n % A cell may have a numerical value followed by a keyword of 'dirichlet' or\n % 'neumann'.\n \n % This behavior is retained only for backward compatibility and only for\n % problems with one variable. \n warning('CHEBFUN:CHEBOP:parseBC:keywordbc',...\n ['Keyword/value specifications of boundary conditions are ', ...\n 'deprecated and may be removed in future versions of Chebfun.'])\n \n if ( strcmpi(BC{2}, 'neumann') && ( numIn <= 2 ) )\n result = @(u) diff(u) - BC{1};\n elseif ( strcmpi(BC{2}, 'dirichlet') && ( numIn <= 2 ) )\n result = @(u) u - BC{1};\n else\n error('CHEBFUN:CHEBOP:parseBC:cell', ...\n 'Unable to parse cell input to set BC.');\n end\n \nelse\n error('CHEBFUN:CHEBOP:parseBC:unknown', 'Unsupported format of BCs.')\n\nend\n\nend\n\nfunction out = setupNumericalConditions(BC, varargin)\n% SETUPNUMERICALCONDITIONS Return anonymous function for evaluating BCs.\n%\n% We need this function so that we can construct a function handle that allows\n% specifying boundary conditions with a vector. In the scalar case, we will be\n% subtracting the nth entry of the BC vector from the (n-1)st derivative of the\n% solution. In the system case, we will be subtracting the nth entry of the\n% vector from the nth unknown function at the endpoint:\n\nu = varargin{1};\n% Check if we're dealing with scalar or system case:\nif (length(u) == 1)\n % Scalar case, subtract entries of BC from U and its derivatives:\n u = u{1};\n % We must always have at least one condition\n out = u - BC(1);\n for bcCounter = 2:length(BC)\n % Add to the boundary conditions vector. It's tricky to initialize the\n % OUT argument to the correct dimensions, as we need to be able to\n % evaluate this both with CHEBFUNs, ADCHEBFUNs and TREEVARs, hence a\n % cheeky growth of the array.\n out = [out; diff(u, bcCounter-1) - BC(bcCounter)]; %#ok\n end\nelse\n assert(length(u) == length(BC), ...\n 'CHEBFUN:CHEBOP:parseBC:numberOfConditions', ...\n ['The number of initial/final conditions appears to be greater than' ...\n ' the number of variables in problem. Specifying boundary ' ...\n 'conditions as a vector for systems is only supported for first ' ...\n 'order systems.']);\n % We must always have at least one condition\n out = u{1} - BC(1);\n for bcCounter = 2:length(BC)\n % Add to the boundary conditions vector. Like above, it's tricky to\n % initialize the OUT argument to the correct dimensions, as we need to\n % be able to evaluate this both with CHEBFUNs, ADCHEBFUNs and TREEVARs.\n % So, allow ourselves to grow the array, by subtracting elements from\n % the BC vector from the solution components.\n out = [out; u{bcCounter} - BC(bcCounter)]; %#ok\n end\nend\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop/parseBC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.036220052093726696, "lm_q1q2_score": 0.010774376817463554}} {"text": "function [mpc, warns] = psse_convert(warns, data, verbose)\n%PSSE_CONVERT Converts data read from PSS/E RAW file to MATPOWER case.\n% [MPC, WARNINGS] = PSSE_CONVERT(WARNINGS, DATA)\n% [MPC, WARNINGS] = PSSE_CONVERT(WARNINGS, DATA, VERBOSE)\n%\n% Converts data read from a version RAW data file into a\n% MATPOWER case struct.\n%\n% Input:\n% WARNINGS : cell array of strings containing accumulated\n% warning messages\n% DATA : struct read by PSSE_READ (see PSSE_READ for details).\n% VERBOSE : 1 to display progress info, 0 (default) otherwise\n%\n% Output:\n% MPC : a MATPOWER case struct created from the PSS/E data\n% WARNINGS : cell array of strings containing updated accumulated\n% warning messages\n%\n% See also PSSE_READ.\n\n% MATPOWER\n% Copyright (c) 2014-2016, Power Systems Engineering Research Center (PSERC)\n% by Yujia Zhu, PSERC ASU\n% and Ray Zimmerman, PSERC Cornell\n% Based on mpraw2mp.m, written by: Yujia Zhu, Jan 2014, yzhu54@asu.edu.\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% define named indices into bus, gen, branch matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n\n%% options\nsort_buses = 1;\n\n%% defaults\nif nargin < 3\n verbose = 0;\nend\nhaveVlims = 0;\nVmin = 0.9;\nVmax = 1.1;\n\n%%----- case identification data -----\nbaseMVA = data.id.SBASE;\nrev = data.id.REV;\n\n%%----- bus data -----\nnumbus = data.bus.num;\n[nb, ncols] = size(numbus); %% number of buses, number of cols\nbus = zeros(nb, VMIN); %% initialize bus matrix\nif rev < 24\n bus_name_col = 10;\nelse\n bus_name_col = 2;\nend\nif sort_buses\n [numbus, i] = sortrows(numbus, 1);\n bus_name = data.bus.txt(i, bus_name_col);\nelse\n bus_name = data.bus.txt(:, bus_name_col);\nend\nif rev < 24 %% includes loads\n bus(:, [BUS_I BUS_TYPE PD QD GS BS BUS_AREA VM VA BASE_KV ZONE]) = ...\n numbus(:, [1:9 11:12]);\nelseif rev < 31 %% includes GL, BL\n bus(:, [BUS_I BASE_KV BUS_TYPE GS BS BUS_AREA ZONE VM VA]) = ...\n numbus(:, [1 3 4 5 6 7 8 9 10]);\nelse %% fixed shunts and loads are in their own tables\n bus(:, [BUS_I BASE_KV BUS_TYPE BUS_AREA ZONE VM VA]) = ...\n numbus(:, [1 3 4 5 6 8 9]);\n if ncols >= 11 && all(all(~isnan(numbus(:, [10 11]))))\n haveVlims = 1;\n bus(:, [VMAX VMIN]) = numbus(:, [10 11]);\n end\nend\nif ~haveVlims %% add default voltage magnitude limits if not provided\n warns{end+1} = sprintf('Using default voltage magnitude limits: VMIN = %g p.u., VMAX = %g p.u.', Vmin, Vmax);\n if verbose\n fprintf('WARNING: No bus voltage magnitude limits provided.\\n Using defaults: VMIN = %g p.u., VMAX = %g p.u.\\n', Vmin, Vmax);\n end\n bus(:, VMIN) = Vmin;\n bus(:, VMAX) = Vmax;\nend\n\n%% create map of external bus numbers to bus indices\ni2e = bus(:, BUS_I);\ne2i = sparse(i2e, ones(nb, 1), 1:nb, max(i2e), 1);\n\n%%----- load data -----\nif rev >= 24\n nld = size(data.load.num, 1);\n loadbus = e2i(data.load.num(:,1));\n %% PSS/E loads are divided into:\n %% 1. constant MVA, (I=1)\n %% 2. constant current (I=I)\n %% 3. constant reactance/resistance (I = I^2)\n %% NOTE: reactive power component of constant admittance load is negative\n %% quantity for inductive load and positive for capacitive load\n Pd = data.load.num(:,6) + data.load.num(:,8) .* bus(loadbus, VM) ...\n + data.load.num(:,10) .* bus(loadbus, VM).^2;\n Qd = data.load.num(:,7) + data.load.num(:,9) .* bus(loadbus, VM) ...\n - data.load.num(:,11) .* bus(loadbus, VM).^2;\n Cld = sparse(1:nld, loadbus, data.load.num(:,3), nld, nb); %% only in-service-loads\n bus(:, [PD QD]) = Cld' * [Pd Qd];\nend\n\n%%----- fixed shunt data -----\nif isfield(data, 'shunt') %% rev > 30\n nsh = size(data.shunt.num, 1);\n shuntbus = e2i(data.shunt.num(:,1));\n Csh = sparse(1:nsh, shuntbus, data.shunt.num(:,3), nsh, nb); %% only in-service shunts\n bus(:, [GS BS]) = Csh' * data.shunt.num(:, 4:5);\nend\n\n%%----- switched shunt data -----\nnswsh = size(data.swshunt.num, 1);\nswshuntbus = e2i(data.swshunt.num(:,1));\nCswsh = sparse(1:nswsh, swshuntbus, 1, nswsh, nb);\nif rev <= 27\n bus(:, BS) = bus(:, BS) + Cswsh' * data.swshunt.num(:, 6);\nelseif rev <= 29\n bus(:, BS) = bus(:, BS) + Cswsh' * data.swshunt.num(:, 7);\nelseif rev < 32\n bus(:, BS) = bus(:, BS) + Cswsh' * data.swshunt.num(:, 8);\nelse\n bus(:, BS) = bus(:, BS) + Cswsh' * data.swshunt.num(:, 10);\nend\n\n%%----- branch data -----\nnbr = size(data.branch.num, 1);\nbranch = zeros(nbr, ANGMAX);\nbranch(:, ANGMIN) = -360;\nbranch(:, ANGMAX) = 360;\nbranch(:, [F_BUS BR_R BR_X BR_B RATE_A RATE_B RATE_C]) = ...\n data.branch.num(:, [1 4 5 6 7 8 9]);\nbranch(:, T_BUS) = abs(data.branch.num(:, 2)); %% can be negative to indicate metered end\nif rev <= 27 %% includes transformer ratio, angle\n branch(:, BR_STATUS) = data.branch.num(:, 16);\n branch(~isnan(data.branch.num(:, 10)), TAP) = ...\n data.branch.num(~isnan(data.branch.num(:, 10)), 10);\n branch(~isnan(data.branch.num(:, 11)), SHIFT) = ...\n data.branch.num(~isnan(data.branch.num(:, 11)), 11);\nelse\n branch(:, BR_STATUS) = data.branch.num(:, 14);\nend\n%% integrate branch shunts (explicit shunts, not line-charging)\nibr = (1:nbr)';\nfbus = e2i(branch(:, F_BUS));\ntbus = e2i(branch(:, T_BUS));\nnzf = find(fbus); %% ignore branches with bad bus numbers\nnzt = find(tbus);\nif length(nzf) < nbr\n warns{end+1} = sprintf('%d branches have bad ''from'' bus numbers', nbr-length(nzf));\n if verbose\n fprintf('WARNING: %d branches have bad ''from'' bus numbers\\n', nbr-length(nzf));\n end\nend\nif length(nzt) < nbr\n warns{end+1} = sprintf('%d branches have bad ''to'' bus numbers', nbr-length(nzt));\n if verbose\n fprintf('WARNING: %d branches have bad ''to'' bus numbers\\n', nbr-length(nzt));\n end\nend\nCf = sparse(ibr(nzf), fbus(nzf), branch(nzf, BR_STATUS), nbr, nb); %% only in-service branches\nCt = sparse(ibr(nzt), tbus(nzt), branch(nzt, BR_STATUS), nbr, nb); %% only in-service branches\nif rev <= 27\n bus(:, [GS BS]) = bus(:, [GS BS]) + ...\n Cf' * data.branch.num(:, 12:13)*baseMVA + ...\n Ct' * data.branch.num(:, 14:15)*baseMVA;\nelse\n bus(:, [GS BS]) = bus(:, [GS BS]) + ...\n Cf' * data.branch.num(:, 10:11)*baseMVA + ...\n Ct' * data.branch.num(:, 12:13)*baseMVA;\nend\n\n%%----- generator data -----\nng = size(data.gen.num, 1);\ngenbus = e2i(data.gen.num(:,1));\ngen = zeros(ng, APF);\ngen(:, [GEN_BUS PG QG QMAX QMIN VG MBASE GEN_STATUS PMAX PMIN]) = ...\n data.gen.num(:, [1 3 4 5 6 7 9 15 17 18]);\n\n%%----- transformer data -----\nif rev > 27\n [transformer, bus, warns, bus_name] = psse_convert_xfmr(warns, data.trans2.num, data.trans3.num, verbose, baseMVA, bus, bus_name);\n branch = [branch; transformer];\nend\n\n%%----- two-terminal DC transmission line data -----\ndcline = psse_convert_hvdc(data.twodc.num, bus);\n\n%% assemble MPC\nmpc = struct( ...\n 'baseMVA', baseMVA, ...\n 'bus', bus, ...\n 'bus_name', {bus_name}, ...\n 'branch', branch, ...\n 'gen', gen ...\n);\nif ~isempty(dcline)\n mpc.dcline = dcline;\n mpc = toggle_dcline(mpc, 'on');\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/psse_convert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.025957354937269382, "lm_q1q2_score": 0.010475528063326195}} {"text": "%% initializeWecSim\n% Initialize WEC-Sim run, called from wecSim.m\n%\n%% Following Classes are required to be defined in the WEC-Sim input file:\n%%\n%% simu = simulationClass(); - To Create the Simulation Variable\n%%\n%% waves = waveClass(') = bodyClass('.h5'); - To initialize bodyClass:\n%%\n%% constraint() = constraintClass(''); - To initialize constraintClass\n%%\n%% pto() = ptoClass(''); - To initialize ptoClass\n%%\n%% mooring() = mooringClass(''); - To initialize mooringClass (only needed when mooring blocks are used)\n%%\n%%\n\n%% Start WEC-Sim log\n% Clear old input, plots, log file and start new log file.\ndiary off\nclear body waves simu output pto constraint ptoSim mooring values names InParam\ntry delete('*.log'); end\ndiary('simulation.log')\n\n\n%% Add 'temp' directory\n% Store root directory of this *.m file\nprojectRootDir = pwd;\nif exist('pctDir')\n projectRootDir = [projectRootDir filesep pctDir];\nend\n\n% Create 'temp' directory if it doesn't exist and add to 'temp' path\nwarning('off','MATLAB:MKDIR:DirectoryExists')\nif exist('pctDir')\n mkdir ([pctDir filesep 'temp'])\nelse\n if mkdir('temp') == 0\n mkdir 'temp'\n end\nend\naddpath(fullfile(projectRootDir,'temp'),'-end');\n\n% Save Simulink-generated helper files to 'temp' directory\nSimulink.fileGenControl('set',...\n 'CacheFolder',fullfile(projectRootDir,'temp'))\n\n\n%% Read input file\ntic\n\n% Set input parameters based on how the simulation is called\nif exist('runWecSimCML','var') && runWecSimCML==1\n % wecSim input from wecSimInputFile.m of case directory in the standard manner\n fprintf('\\nWEC-Sim Input From Standard wecSimInputFile.m Of Case Directory... \\n');\n bdclose('all');\n run('wecSimInputFile');\nelse\n % Get global reference frame parameters\n values = get_param([bdroot,'/Global Reference Frame'],'MaskValues'); % Cell array containing all Masked Parameter values\n names = get_param([bdroot,'/Global Reference Frame'],'MaskNames'); % Cell array containing all Masked Parameter names\n j = find(strcmp(names,'InputMethod')); \n if strcmp(values{j},'Input File')\n % wecSim input from input file selected in Simulink block\n fprintf('\\nWEC-Sim Input From File Selected In Simulink... \\n');\n i = find(strcmp(names,'InputFile'));\n run(values{i});\n elseif strcmp(values{j},'Custom Parameters')\n % wecSim input from custom parameters in Simulink block\n fprintf('\\nWEC-Sim Input From Custom Parameters In Simulink... \\n');\n inputFile = 'wecSimInputFile_simulinkCustomParameters';\n writeInputFromBlocks(inputFile);\n run(inputFile);\n end\nend\nclear values names i j;\n\n% Read Inputs for Multiple Conditions Run\ntry fprintf('wecSimMCR Case %g\\n',imcr); end\n\nif exist('mcr','var') == 1\n for n=1:length(mcr.cases(1,:))\n if strcmp(mcr.header{n},'LoadFile') % added this flag for system ID efforts!\n load(mcr.cases{imcr,n});\n elseif iscell(mcr.cases)\n eval([mcr.header{n} '= mcr.cases{imcr,n};']);\n else\n eval([mcr.header{n} '= mcr.cases(imcr,n);']);\n end\n end; clear n combine;\n try \n waves.spectrumFile = ['..' filesep pctDir filesep '..' filesep waves.spectrumFile];\n waves.elevationFile = ['..' filesep pctDir filesep '..' filesep waves.elevationFile];\n end\nend\n\n% Waves and Simu: check inputs\nwaves.checkInputs();\nsimu.checkInputs();\n\n% Constraints: count & set orientation\nif exist('constraint','var') == 1\n simu.numConstraints = length(constraint(1,:));\n for ii = 1:simu.numConstraints\n constraint(ii).setNumber(ii);\n constraint(ii).setOrientation();\n end; clear ii\nend\n\n% PTOs: count & set orientation & set pretension\nif exist('pto','var') == 1\n simu.numPtos = length(pto(1,:));\n for ii = 1:simu.numPtos\n pto(ii).setNumber(ii);\n pto(ii).setOrientation();\n pto(ii).setPretension();\n end; clear ii\nend\n\n% Mooring Configuration: count\nif exist('mooring','var') == 1\n simu.numMoorings = length(mooring(1,:));\n for ii = 1:simu.numMoorings\n mooring(ii).setLoc();\n mooring(ii).setNumber(ii);\n end; clear ii\nend\n\n% Bodies: count, check inputs, read hdf5 file, and check inputs\nnumHydroBodies = 0; \nnumNonHydroBodies = 0;\nnumDragBodies = 0; \nhydroBodLogic = zeros(length(body(1,:)),1);\nnonHydroBodLogic = zeros(length(body(1,:)),1);\ndragBodLogic = zeros(length(body(1,:)),1);\nfor ii = 1:length(body(1,:))\n body(ii).setNumber(ii);\n body(ii).checkInputs(simu.explorer);\n if body(ii).nonHydro==0\n if numNonHydroBodies > 0 || numDragBodies > 0\n error('All hydro bodies must be specified before any drag or non-hydro bodies.')\n end\n numHydroBodies = numHydroBodies + 1;\n hydroBodLogic(ii) = 1;\n elseif body(ii).nonHydro==1\n numNonHydroBodies = numNonHydroBodies + 1;\n nonHydroBodLogic(ii) = 1;\n elseif body(ii).nonHydro==2\n numDragBodies = numDragBodies + 1;\n dragBodLogic(ii) = 1;\n end\nend\nsimu.numHydroBodies = numHydroBodies; clear numHydroBodies\nsimu.numDragBodies = numDragBodies; clear numDragBodies\nfor ii = 1:simu.numHydroBodies\n body(ii).setDOF(simu.numHydroBodies,simu.b2b);\n\n % Determine if hydro data needs to be reloaded from h5 file, or if hydroData\n % was stored in memory from a previous run.\n if exist('totalNumOfWorkers','var') ==0 && exist('mcr','var') == 1 && simu.reloadH5Data == 0 && imcr > 1\n body(ii).loadHydroData(hydroData(ii));\n else\n % check for correct h5 file\n h5Info = dir(body(ii).h5File);\n h5Info.bytes;\n if h5Info.bytes < 1000\n error(['This is not the correct *.h5 file. Please install git-lfs to access the correct *.h5 file, or run \\hydroData\\bemio.m to generate a new *.h5 file'])\n end\n clearvars h5Info \n % Read hydro data from BEMIO and load into the bodyClass\n tmp_hydroData = readBEMIOH5(body(ii).h5File, body(ii).number, body(ii).meanDrift);\n body(ii).loadHydroData(tmp_hydroData);\n clear tmp_hydroData\n end\nend; clear ii\n\n% Cable Configuration: count, set Cg/Cb, PTO loc, L0 and initialize bodies\nif exist('cable','var')==1\n simu.numCables = length(cable(1,:));\n for ii = 1:simu.numCables\n cable(ii).setNumber(ii);\n cable(ii).setCg();\n cable(ii).setCb();\n cable(ii).setTransPTOLoc();\n cable(ii).setLength();\n cable(ii).dragForcePre(simu.rho);\n cable(ii).setVolume(simu.rho);\n cable(ii).setOrientation();\n cable(ii).linearDampingMatrix();\n end\nend\n\n% PTO-Sim: read input, count\nif exist('ptoSim','var') == 1\n simu.numPtoSim = length(ptoSim(1,:));\n for ii = 1:simu.numPtoSim\n ptoSim(ii).number = ii;\n end; clear ii\nend\n\n\ntoc\n\n%% Pre-processing start\ntic\nfprintf('\\nWEC-Sim Pre-processing ... \\n');\nif exist('pctDir')\n cd(pctDir); \nend\n\n%% HydroForce Pre-Processing: Wave Setup & HydroForcePre.\n% simulation setup\nsimu.setup();\n\n% wave setup\nif any(hydroBodLogic == 1)\n % When hydro bodies (and an .h5) are present, define the wave using those\n % parameters.\n waves.setup(body(1).hydroData.simulation_parameters.w, body(1).hydroData.simulation_parameters.waterDepth, simu.rampTime, simu.dt, simu.maxIt, simu.time, simu.gravity, simu.rho);\n % Check that direction and freq are within range of hydro data\n if min(waves.direction) < min(body(1).hydroData.simulation_parameters.direction) || max(waves.direction) > max(body(1).hydroData.simulation_parameters.direction)\n error('waves.direction outside of range of available hydro data')\n end\n if strcmp(waves.type,'elevationImport')~=1 && strcmp(waves.type,'noWave')~=1 && strcmp(waves.type,'noWaveCIC')~=1\n if min(waves.omega) < min(body(1).hydroData.simulation_parameters.w) || max(waves.omega) > max(body(1).hydroData.simulation_parameters.w)\n error('waves.omega outside of range of available hydro data')\n end\n end\nelse\n % When no hydro bodies (and no .h5) are present, define the wave using\n % input file parameters\n waves.setup([], [], simu.rampTime, simu.dt, simu.maxIt, simu.time, simu.gravity, simu.rho);\nend\n\n% Nonlinear hydro\nfor kk = 1:length(body(1,:))\n if (body(kk).nonlinearHydro > 0) || (simu.paraview.option == 1)\n body(kk).importBodyGeometry(simu.domainSize)\n end\nend; clear kk\n\n% hydroForcePre\nidx = find(hydroBodLogic==1);\nif ~isempty(idx)\n for kk = 1:length(idx)\n it = idx(kk);\n body(it).hydroForcePre(waves.omega,waves.direction,simu.cicTime,waves.bem.count,simu.dt,...\n simu.rho,simu.gravity,waves.type,waves.waveAmpTime,simu.stateSpace,simu.b2b);\n end; clear kk idx\nend\n\n% nonHydroPre\nidx = find(nonHydroBodLogic==1);\nif ~isempty(idx)\n for kk = 1:length(idx)\n it = idx(kk);\n body(it).nonHydroForcePre(simu.rho);\n end; clear kk idx\nend\n\n% dragBodyPre\nidx = find(dragBodLogic == 1);\nif ~isempty(idx)\n for kk = 1:length(idx)\n it = idx(kk);\n body(it).dragForcePre(simu.rho);\n end; clear kk idx\nend\n \n% Check cicEndTime\nif waves.typeNum~=0 && waves.typeNum~=10\n for iBod = 1:simu.numHydroBodies\n if simu.cicEndTime > max(body(iBod).hydroData.hydro_coeffs.radiation_damping.impulse_response_fun.t)\n error('simu.cicEndTime is larger than the length of the IRF');\n end\n end\nend\n\n% Check that the hydro data for each body is given for the same frequencies\nfor ii = 1:simu.numHydroBodies\n if length(body(1).hydroData.simulation_parameters.w) ~= length(body(ii).hydroData.simulation_parameters.w)\n error('BEM simulations for each body must have the same number of frequencies')\n else\n for jj = 1:length(body(1).hydroData.simulation_parameters.w)\n if body(1).hydroData.simulation_parameters.w(jj) ~= body(ii).hydroData.simulation_parameters.w(jj)\n error('BEM simulations must be run with the same frequencies.')\n end; clear jj;\n end\n end\nend; clear ii;\n\n% Check for elevationImport with nonlinearHydro\nfor ii = 1:simu.numHydroBodies\n if strcmp(waves.type,'elevationImport') && body(ii).nonlinearHydro == 1\n error(['Cannot run WEC-Sim with nonlinear hydro (body(ii).nonlinearHydro) and \"elevationImport\" wave type'])\n end\nend\n\n% Check for elevationImport with morisonElement\nfor ii = 1:simu.numHydroBodies\n if strcmp(waves.type,'elevationImport') && body(ii).morisonElement.option ~= 0\n error(['Cannot run WEC-Sim with Morison Element (body(ii).morisonElement.option>0) and \"elevationImport\" wave type'])\n end\nend\n\n% Check for morisonElement inputs for body(ii).morisonElement.option == 1 || body(ii).morisonElement.option == 2\nfor ii = 1:length(body(1,:))\n if body(ii).morisonElement.option == 1\n if body(ii).nonHydro ~=1\n [rgME,~] = size(body(ii).morisonElement.rgME);\n for jj = 1:rgME\n if true(isfinite(body(ii).morisonElement.z(jj,:))) == true\n warning(['\"body.morisonElement.z\" is not used for \"body.morisonElement.option = 1\". Check body ',num2str(ii),' element ',num2str(jj)])\n end\n if length(body(ii).morisonElement.cd(jj,:)) ~= 3 || length(body(ii).morisonElement.ca(jj,:)) ~= 3 || length(body(ii).morisonElement.area(jj,:)) ~= 3\n error(['cd, ca, and area coefficients for each elelement for \"body.morisonElement.option = 1\" must be of size [1x3] and all columns of data must be real and finite. Check body ',num2str(ii),' element ',num2str(jj),' coefficients'])\n end\n end; clear jj\n else\n if body(ii).morisonElement.option == 1 || body(ii).morisonElement.option == 2\n warning(['Morison elements are not available for non-hydro bodies. Please check body ',num2str(ii),' inputs.'])\n end\n end\n elseif body(ii).morisonElement.option == 2\n if body(ii).nonHydro ~=1\n [rgME,~] = size(body(ii).morisonElement.rgME);\n for jj = 1:rgME\n if body(ii).morisonElement.cd(jj,3) ~= 0 || body(ii).morisonElement.ca(jj,3) ~= 0 || body(ii).morisonElement.area(jj,3) ~= 0\n warning(['cd, ca, and area coefficients for \"body.morisonElement.option == 2\" must be of size [1x2], third column of data is not used. Check body ',num2str(ii),' element ',num2str(jj),' coefficients'])\n end\n end; clear jj\n else\n if body(ii).morisonElement.option ==1 || body(ii).morisonElement.option ==2\n warning(['Morison elements are not available for non-hydro bodies. Please check body ',num2str(ii),' inputs.'])\n end\n end\n end; clear ii\nend\n\n%% Set variant subsystems options\nfor ii=1:length(body(1,:))\n if body(ii).nonHydro==0\n % Nonlinear FK Force Variant Subsystem\n eval(['nonLinearHydro_' num2str(ii) ' = body(ii).nonlinearHydro;']);\n eval(['sv_b' num2str(ii) '_linearHydro = Simulink.Variant(''nonLinearHydro_', num2str(ii), '==0'');']);\n eval(['sv_b' num2str(ii) '_nonlinearHydro=Simulink.Variant(''nonLinearHydro_', num2str(ii), '>0'');']);\n % Nonlinear Wave Elevation Variant Subsystem\n eval(['sv_b' num2str(ii) '_meanFS=Simulink.Variant(''nonLinearHydro_', num2str(ii), '<2'');']);\n eval(['sv_b' num2str(ii) '_instFS=Simulink.Variant(''nonLinearHydro_', num2str(ii), '==2'');']);\n end\nend; clear ii;\n% Morison Element\nfor ii=1:length(body(1,:))\n if body(ii).nonHydro ~=1\n eval(['morisonElement_' num2str(ii) ' = body(ii).morisonElement.option;'])\n eval(['sv_b' num2str(ii) '_MEOff = Simulink.Variant(''morisonElement_' num2str(ii) '==0'');'])\n eval(['sv_b' num2str(ii) '_MEOn = Simulink.Variant(''morisonElement_' num2str(ii) '==1 || morisonElement_' num2str(ii) '==2'');']) \n end\nend; clear ii;\n% Radiation Damping\nif waves.typeNum==0 || waves.typeNum==10 %'noWave' & 'regular'\n radiation_option = 1;\nelseif simu.stateSpace == 1\n radiation_option = 3;\nelse\n radiation_option = 2;\nend\nsv_constantCoeff=Simulink.Variant('radiation_option==1');\nsv_convolution=Simulink.Variant('radiation_option==2');\nsv_stateSpace=Simulink.Variant('radiation_option==3');\n% Wave type\ntypeNum = waves.typeNum;\nsv_noWave=Simulink.Variant('typeNum<10');\n\n% Passive Yaw\nfor ii=1:length(body(1,:))\n eval(['yaw_' num2str(ii) ' = body(ii).yaw.option;'])\n eval(['sv_regularWaves_b' num2str(ii) '= Simulink.Variant(''typeNum>=10 && typeNum<20 && yaw_', num2str(ii), '==0'');']) \n eval(['sv_regularWavesYaw_b' num2str(ii) '= Simulink.Variant(''typeNum>=10 && typeNum<20 && yaw_' num2str(ii) '==1'');']) \n eval(['sv_irregularWaves_b' num2str(ii) '= Simulink.Variant(''typeNum>=20 && typeNum<30 && yaw_' num2str(ii) '==0'');']) \n eval(['sv_irregularWavesYaw_b' num2str(ii) '= Simulink.Variant(''typeNum>=20 && typeNum<30 && yaw_' num2str(ii) '==1'');']) \nend; clear ii\n\nsv_udfWaves=Simulink.Variant('typeNum>=30');\n% Body2Body\nB2B = simu.b2b;\nsv_noB2B=Simulink.Variant('B2B==0');\nsv_B2B=Simulink.Variant('B2B==1');\nnumBody=simu.numHydroBodies;\n% nonHydro\nfor ii=1:length(body(1,:))\n eval(['nhbody_' num2str(ii) ' = body(ii).nonHydro;'])\n eval(['sv_b' num2str(ii) '_hydroBody = Simulink.Variant(''nhbody_' num2str(ii) '==0'');'])\n eval(['sv_b' num2str(ii) '_nonHydroBody = Simulink.Variant(''nhbody_' num2str(ii) '==1'');'])\n eval(['sv_b' num2str(ii) '_dragBody = Simulink.Variant(''nhbody_' num2str(ii) '==2'');'])\nend; clear ii\n\n%Efficiency model for hydraulic motor PTO-Sim block\ntry\n for ii=1:length(ptoSim(1,:))\n eval(['EffModel_' num2str(ii) ' = ptoSim(ii).hydraulicMotor.effModel;']);\n eval(['sv_b' num2str(ii) '_AnalyticalEfficiency = Simulink.Variant(''EffModel_', num2str(ii), '==1'');']);\n eval(['sv_b' num2str(ii) '_TabulatedEfficiency = Simulink.Variant(''EffModel_', num2str(ii), '==2'');']);\n end; clear ii;\nend\n\n% Visualization Blocks\nif ~isempty(waves.marker.location) && typeNum < 30\n visON = 1;\nelse\n visON = 0;\nend \nsv_visualizationON = Simulink.Variant('visON==1');\nsv_visualizationOFF = Simulink.Variant('visON==0');\n\n%% End Pre-Processing and Output All the Simulation and Model Setting\ntoc\nsimu.listInfo(waves.typeNum);\nwaves.listInfo\nfprintf('\\nList of Body: ');\nfprintf('Number of Bodies = %u \\n',simu.numHydroBodies)\nfor i = 1:simu.numHydroBodies\n body(i).listInfo\nend; clear i\nfprintf('\\nList of PTO(s): ');\nif (exist('pto','var') == 0)\n fprintf('No PTO in the system\\n')\nelse\n fprintf('Number of PTOs = %G \\n',length(pto(1,:)))\n for i=1:simu.numPtos\n pto(i).listInfo\n end; clear i\nend\nfprintf('\\nList of Constraint(s): ');\nif (exist('constraint','var') == 0)\n fprintf('No Constraint in the system\\n')\nelse\n fprintf('Number of Constraints = %G \\n',length(constraint(1,:)))\n for i=1:simu.numConstraints\n constraint(i).listInfo\n end; clear i\nend\nfprintf('\\n')\n\n%% Load simMechanics file & Run Simulation\ntic\nfprintf('\\nSimulating the WEC device defined in the SimMechanics model %s... \\n',simu.simMechanicsFile)\n% Modify some stuff for simulation\nfor iBod = 1:simu.numHydroBodies\n body(iBod).adjustMassMatrix(simu.adjMassFactor,simu.b2b);\nend; clear iBod\nwarning('off','Simulink:blocks:TDelayTimeTooSmall');\nwarning('off','Simulink:blocks:BusSelDupBusCreatorSigNames');\nwarning('off','MATLAB:loadlibrary:FunctionNotFound');\nwarning('off','MATLAB:loadlibrary:parsewarnings');\nwarning('off','MATLAB:printf:BadEscapeSequenceInFormat');\nwarning('off','Simulink:blocks:DivideByZero');\nwarning('off','sm:sli:setup:compile:SteadyStateStartNotSupported')\nset_param(0, 'ErrorIfLoadNewModel', 'off')\n% Load parameters to Simulink model\nsimu.loadSimMechModel(simu.simMechanicsFile);\n\ntoc\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/initializeWecSim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.03161876464515654, "lm_q1q2_score": 0.010251922357072955}} {"text": "classdef MCMC < BetterHandle\n %%MCMC Simple MH and Gibbs moves for the MotorProgram Class\n %%\n %% This class provides some simple moves for sampling from\n %% some variables, with fixed dimension. It does not provide\n %% a sampler for the entire joint space.\n %%\n properties\n \n debug_full_score = false;\n \n %% book-keeping to count the number of times\n %% a move is accepted\n \n %% parameters that don't call the image evaluation\n accept_shape_type = 0;\n n_shape_type = 0;\n accept_scale_type = 0;\n n_scale_type = 0;\n accept_gpos = 0;\n n_gpos = 0;\n accept_seval = 0;\n n_seval = 0;\n accept_seval_token = 0;\n n_seval_token = 0;\n accept_sid = 0;\n n_sid = 0;\n accept_r = 0;\n n_r = 0;\n \n %% parameters that call the image evaluation function\n accept_shape_token = 0;\n n_shape_token = 0;\n accept_scale_token = 0;\n n_scale_token = 0;\n accept_pos_token = 0;\n n_pos_token = 0;\n \n end\n \n methods \n \n function this = MCMC(debug_full_score)\n if exist('debug_full_score','var')\n this.debug_full_score = debug_full_score;\n end\n end\n \n %% print the percent of times various moves are accepted\n function acceptance_ratios(this)\n fprintf(1,'Acceptance ratios\\n');\n fprintf(1,' shape type: %s%% (of %d)\\n',num2str(this.accept_shape_type/this.n_shape_type*100,3),this.n_shape_type);\n fprintf(1,' scale type: %s%% (of %d)\\n',num2str(this.accept_scale_type/this.n_shape_type*100,3),this.n_scale_type);\n fprintf(1,' global pos: %s%% (of %d)\\n',num2str(this.accept_gpos/this.n_gpos*100,3),this.n_gpos);\n if this.n_seval > 0 \n fprintf(1,' seval type: %s%% (of %d)\\n',num2str(this.accept_seval/this.n_seval*100,3),this.n_seval);\n fprintf(1,' seval tokn: %s%% (of %d)\\n',num2str(this.accept_seval_token/this.n_seval_token*100,3),this.n_seval_token);\n end\n fprintf(1,' sub-ids : %s%% (of %d)\\n',num2str(this.accept_sid/this.n_sid*100,3),this.n_sid);\n fprintf(1,' R : %s%% (of %d)\\n',num2str(this.accept_r/this.n_r*100,3),this.n_r);\n \n fprintf(1,' scale tokn: %s%% (of %d)\\n',num2str(this.accept_scale_token/this.n_scale_token*100,3),this.n_scale_token);\n fprintf(1,' shape tokn: %s%% (of %d)\\n',num2str(this.accept_shape_token/this.n_shape_token*100,3),this.n_shape_token);\n fprintf(1,' pos tokn: %s%% (of %d)\\n',num2str(this.accept_pos_token/this.n_pos_token*100,3),this.n_pos_token);\n end\n \n %% SHAPE TYPE MOVE\n function [val_new,accept] = mh_shape_type(this,sid,bid,M,lib) \n %% sid: stroke index\n %% bid: sub-stroke index\n \n %% make proposal\n curr_shape_type = M.S{sid}.shapes_type(:,:,bid);\n prop_shape_type = propose_shape_type(curr_shape_type,M.parameters);\n \n %% score proposal\n curr_score = score_shape_type(M,sid,bid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_shape_type(M,sid,bid,lib,M.parameters,true);\n end\n M.S{sid}.shapes_type(:,:,bid) = prop_shape_type;\n prop_score = score_shape_type(M,sid,bid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_shape_type(M,sid,bid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH Shape type passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.shapes_type(:,:,bid) = curr_shape_type;\n end\n val_new = M.S{sid}.shapes_type(:,:,bid);\n \n this.accept_shape_type = this.accept_shape_type + accept;\n this.n_shape_type = this.n_shape_type + 1;\n \n if isinf(scoreMP(M,lib))\n error('score should not be negative'); \n end\n end\n \n %% SHAPE TOKEN MOVE\n function [val_new,accept] = mh_shape_token(this,sid,bid,M,lib) \n %% sid: stroke index\n %% bid: sub-stroke index\n \n %% make proposal\n curr_shape_token = M.S{sid}.shapes_token(:,:,bid);\n prop_shape_token = propose_shape_token(curr_shape_token,M.parameters);\n \n %% score proposal\n curr_score = score_shape_token(M,sid,bid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_shape_token(M,sid,bid,lib,M.parameters,true);\n end\n M.S{sid}.shapes_token(:,:,bid) = prop_shape_token;\n prop_score = score_shape_token(M,sid,bid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_shape_token(M,sid,bid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH Shape token passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.shapes_token(:,:,bid) = curr_shape_token;\n end\n val_new = M.S{sid}.shapes_token(:,:,bid);\n \n this.accept_shape_token = this.accept_shape_token + accept;\n this.n_shape_token = this.n_shape_token + 1;\n \n if isinf(scoreMP(M,lib))\n error('score should not be negative'); \n end\n end\n \n \n %% SCALE TYPE MOVE\n function [val_new,accept] = mh_scale_type(this,sid,bid,M,lib)\n %% sid: stroke index\n %% bid: sub-stroke index\n \n %% make proposal\n curr_invscale_type = M.S{sid}.invscales_type(bid);\n prop_invscale_type = propose_scale_type(curr_invscale_type,M.parameters);\n \n %% score proposal\n curr_score = score_scale_type(M,sid,bid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_scale_type(M,sid,bid,lib,M.parameters,true);\n end\n M.S{sid}.invscales_type(bid) = prop_invscale_type;\n prop_score = score_scale_type(M,sid,bid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_scale_type(M,sid,bid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH Scale type passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.invscales_type(bid) = curr_invscale_type;\n end \n val_new = M.S{sid}.invscales_type(bid);\n \n this.accept_scale_type = this.accept_scale_type + accept;\n this.n_scale_type = this.n_scale_type + 1;\n \n end\n \n %% SCALE TOKEN MOVE\n function [val_new,accept] = mh_scale_token(this,sid,bid,M,lib)\n %% sid: stroke index\n %% bid: sub-stroke index\n \n %% make proposal\n curr_invscale_token = M.S{sid}.invscales_token(bid);\n prop_invscale_token = propose_scale_token(curr_invscale_token,M.parameters);\n \n %% score proposal\n curr_score = score_scale_token(M,sid,bid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_scale_token(M,sid,bid,lib,M.parameters,true);\n end\n M.S{sid}.invscales_token(bid) = prop_invscale_token;\n prop_score = score_scale_token(M,sid,bid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_scale_token(M,sid,bid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH Scale token passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.invscales_token(bid) = curr_invscale_token;\n end \n val_new = M.S{sid}.invscales_token(bid);\n \n this.accept_scale_token = this.accept_scale_token + accept;\n this.n_scale_token = this.n_scale_token + 1;\n \n end\n\n %% GLOBAL POSITION FOR UNIHIST RELATION\n function [val_new,accept] = mh_gobal_position(this,sid,M,lib)\n \n %% sid: stroke index \n assert(strcmp(M.S{sid}.R.type,'unihist'));\n \n %% make proposal\n curr_gpos = M.S{sid}.R.gpos;\n prop_gpos = propose_global_position(curr_gpos,M.parameters);\n \n %% score proposal\n curr_score = score_global_position(M,sid,lib);\n if this.debug_full_score\n curr_score2 = score_global_position(M,sid,lib,true); \n end\n M.S{sid}.R.gpos = prop_gpos;\n prop_score = score_global_position(M,sid,lib);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_global_position(M,sid,lib,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH position passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.R.gpos = curr_gpos;\n end \n val_new = M.S{sid}.R.gpos;\n \n this.accept_gpos = this.accept_gpos + accept;\n this.n_gpos = this.n_gpos + 1;\n \n end\n \n %% POSITION FOR A STROKE\n function [val_new,accept] = mh_token_position(this,sid,M,lib)\n %% sid: stroke index\n \n %% make proposal\n curr_pos_token = M.S{sid}.pos_token;\n prop_pos_token = propose_local_position(curr_pos_token,M.parameters);\n \n %% score proposal\n curr_score = score_local_position(M,sid,lib);\n if this.debug_full_score\n curr_score2 = score_local_position(M,sid,lib,true); \n end\n M.S{sid}.pos_token = prop_pos_token;\n prop_score = score_local_position(M,sid,lib);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_local_position(M,sid,lib,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH token position passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.pos_token = curr_pos_token;\n end \n val_new = M.S{sid}.pos_token;\n \n this.accept_pos_token = this.accept_pos_token + accept;\n this.n_pos_token = this.n_pos_token + 1;\n end\n \n %% EVAL-SPOT TYPE\n function [val_new,accept] = mh_eval_spot_type(this,sid,M,lib)\n %% sid: stroke index\n assert(strcmp(M.S{sid}.R.type,'mid'));\n \n %% make proposal\n curr_eval_spot_type = M.S{sid}.R.eval_spot_type;\n assert(~isempty(curr_eval_spot_type));\n prop_eval_spot_type = propose_eval_spot(curr_eval_spot_type,M.parameters);\n \n %% score proposal\n curr_score = score_eval_spot_type(M,sid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_eval_spot_type(M,sid,lib,M.parameters,true);\n end\n M.S{sid}.R.eval_spot_type = prop_eval_spot_type;\n prop_score = score_eval_spot_type(M,sid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_eval_spot_type(M,sid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH eval spot type passed score test\\n');\n end\n end \n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.R.eval_spot_type = curr_eval_spot_type;\n end \n val_new = M.S{sid}.R.eval_spot_type;\n \n this.accept_seval = this.accept_seval + accept;\n this.n_seval = this.n_seval + 1;\n \n end\n \n function [val_new,accept] = mh_eval_spot_token(this,sid,M,lib)\n %% sid: stroke index\n assert(strcmp(M.S{sid}.R.type,'mid'));\n \n %% make proposal\n curr_eval_spot_token = M.S{sid}.R.eval_spot_token;\n prop_eval_spot_token = propose_eval_spot(curr_eval_spot_token,M.parameters);\n \n %% score proposal\n curr_score = score_eval_spot_token(M,sid,lib,M.parameters);\n if this.debug_full_score\n curr_score2 = score_eval_spot_token(M,sid,lib,M.parameters,true);\n end\n M.S{sid}.R.eval_spot_token = prop_eval_spot_token;\n prop_score = score_eval_spot_token(M,sid,lib,M.parameters);\n \n if this.debug_full_score %% debug to make sure full-score matches\n prop_score2 = score_eval_spot_token(M,sid,lib,M.parameters,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH eval spot token passed score test\\n');\n end\n end \n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score);\n if ~accept\n M.S{sid}.R.eval_spot_token = curr_eval_spot_token;\n end \n val_new = M.S{sid}.R.eval_spot_token;\n \n this.accept_seval_token = this.accept_seval_token + accept;\n this.n_seval_token = this.n_seval_token + 1;\n \n end\n \n %% SUB-STROKE IDS\n function [val_new,accept] = gibbs_substroke_id(this,sid,bid,M,lib)\n % sid: stroke index\n % bid: sub-stroke index\n curr_id = M.S{sid}.ids(bid);\n nclust = lib.N;\n score = score_all_subid(M,sid,bid,lib); \n \n if this.debug_full_score\n score2 = zeros(nclust,1);\n for c=1:nclust\n M.S{sid}.ids(bid) = c;\n score2(c) = scoreMP(M,lib);\n end\n v1 = score-logsumexp(score(:));\n v2 = score2-logsumexp(score2(:));\n v1(isinf(v1)) = [];\n v2(isinf(v2)) = [];\n assert( aeq(v1,v2) );\n fprintf(1,'DEBUG: Gibbs sub-stroke ids passed score test\\n');\n end\n \n %% normalize probability distribution\n score = score - logsumexp(score);\n pvec = exp(score);\n assert(aeq(sum(pvec),1));\n pvec = pvec ./ sum(pvec);\n \n %% sample the new id\n vr = mnrnd(1,pvec);\n assert(~any(isnan(vr)));\n new_id = find(vr); \n M.S{sid}.ids(bid) = new_id;\n accept = new_id ~= curr_id;\n \n val_new = M.S{sid}.ids(bid);\n \n this.accept_sid = this.accept_sid + accept;\n this.n_sid = this.n_sid + 1;\n \n end\n \n %% RELATION (WITH TOKEN PARAMETER FOR ATTACHMENT)\n function [val_new,accept] = mh_relation(this,sid,M,lib)\n \n %% make proposal\n PM = defaultps;\n curr_R = M.S{sid}.R;\n prop_R = propose_relation(M.S{sid}.pos_token,M.S(1:sid-1),lib,PM);\n \n %% score proposal\n curr_score = score_relation(M,sid,lib);\n g_prop_to_curr = pp_relation(M,sid,lib,PM);\n if this.debug_full_score\n curr_score2 = score_relation(M,sid,lib,true);\n end\n M.S{sid}.R = prop_R;\n prop_score = score_relation(M,sid,lib);\n \n g_curr_to_prop = pp_relation(M,sid,lib,PM);\n if this.debug_full_score\n prop_score2 = score_relation(M,sid,lib,true);\n if ~isinf(prop_score)\n assert(aeq(prop_score-curr_score,prop_score2-curr_score2));\n fprintf(1,'DEBUG: MH relation passed score test\\n');\n end\n end\n \n %% accept or reject\n accept = mh_accept(prop_score,curr_score,g_curr_to_prop,g_prop_to_curr);\n if ~accept\n M.S{sid}.R = curr_R;\n end \n val_new = M.S{sid}.R;\n \n %% record keeping\n this.accept_r = this.accept_r + accept;\n this.n_r = this.n_r + 1;\n \n end\n \n \n end\nend\n\n%% general MH acceptance function\n%% \n%% Input\n%% prop_score: log-probability of model with proposal\n%% curr_score: log-probability of current model\n%% g_curr_to_prop: log-prob. of transition from current to proposal model\n%% g_prop_to_curr: reverse log-prob\nfunction accept = mh_accept(prop_score,curr_score,g_curr_to_prop,g_prop_to_curr)\n if exist('g_curr_to_prop','var')\n lr = prop_score - curr_score + g_prop_to_curr - g_curr_to_prop;\n else\n lr = prop_score - curr_score; \n end\n \n if isinf(prop_score)\n accept = false;\n return\n end\n \n r = min(1,exp(lr));\n assert(~isinf(curr_score));\n accept = rand < r;\nend\n\nfunction R = propose_relation(pos_token,prev_strokes,lib,PM)\n %% Propose new relation by sampling from prior, except the global\n %% position is sampled from near the token position\n R = CPD.sample_relation_type(lib,prev_strokes);\n if strcmp(R.type,'mid')\n R.eval_spot_token = CPD.sample_relation_token(lib,R.eval_spot_type);\n elseif strcmp(R.type,'unihist')\n R.gpos(1) = pos_token(1) + PM.mcmc_prop_relpos_mlty*lib.rel.sigma_x*randn;\n R.gpos(2) = pos_token(2) + PM.mcmc_prop_relpos_mlty*lib.rel.sigma_y*randn;\n end\nend\n\nfunction ll = pp_relation(M,sid,lib,PM)\n %% The probability of proposing relation M.S{sid}.R\n ll = CPD.score_relation_type(lib,M.S{sid}.R);\n if strcmp(M.S{sid}.R.type,'mid')\n ll = ll + CPD.score_relation_token(lib,M.S{sid}.R.eval_spot_token,...\n M.S{sid}.R.eval_spot_type); \n elseif strcmp(M.S{sid}.R.type,'unihist')\n gpos = M.S{sid}.R.gpos;\n pos_token = M.S{sid}.pos_token;\n ll = ll - lib.Spatial.score(gpos,sid); %% since this sample was not used\n ll = ll + mvnormpdfln(gpos(1),pos_token(1),PM.mcmc_prop_relpos_mlty*lib.rel.sigma_x);\n ll = ll + mvnormpdfln(gpos(2),pos_token(2),PM.mcmc_prop_relpos_mlty*lib.rel.sigma_y);\n end\nend\n\n%% RELATIONS\n\nfunction ll = score_relation(M,sid,lib,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n ll = scoreMP(M,lib);\n return \n end\n \n ll = CPD.score_relation_type(lib,M.S{sid}.R);\n if strcmp(M.S{sid}.R.type,'mid')\n ll = ll + CPD.score_relation_token(lib,M.S{sid}.R.eval_spot_token,...\n M.S{sid}.R.eval_spot_type); \n end\n pos = M.S{sid}.pos_token;\n ll = ll + CPD.score_position(lib,pos,M.S{sid}.R,M.S(1:sid-1));\nend\n\n%% SHAPE\n\nfunction shape_type = propose_shape_type(shape_type,PM)\n [~,dim,n] = size(shape_type);\n assert(dim==2 && n==1);\n shape_type = shape_type + PM.mcmc.prop_shape_sd .* randn(size(shape_type));\nend\n\nfunction shape_token = propose_shape_token(shape_token,PM)\n shape_token = propose_shape_type(shape_token,PM); \nend\n\nfunction score = score_shape_type(M,sid,bid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n shape_type = M.S{sid}.shapes_type(:,:,bid);\n shape_token = M.S{sid}.shapes_token(:,:,bid);\n id = M.S{sid}.ids(bid);\n lp = CPD.score_shape_type(lib,shape_type,id); \n ll = CPD.score_shape_token(lib,shape_token,shape_type);\n score = lp + ll;\nend\n\nfunction [score,out] = score_shape_token(M,sid,bid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n [score,out] = scoreMP(M,lib); \n return \n end\n shape_type = M.S{sid}.shapes_type(:,:,bid);\n shape_token = M.S{sid}.shapes_token(:,:,bid);\n \n %% account for future positions, which this parameter may influence\n ll_next_pos = 0;\n for i=sid+1:M.ns\n nextS = M.S{i};\n ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));\n end\n \n %% sum up scores\n score = ll_next_pos + CPD.score_image(M.I,M.pimg) + CPD.score_shape_token(lib,shape_token,shape_type); \nend\n\n%% SCALE\n\nfunction invscales_type = propose_scale_type(invscales_type,PM)\n assert(isscalar(invscales_type));\n invscales_type = invscales_type + PM.mcmc.prop_scale_sd .* randn(size(invscales_type));\nend\n\nfunction invscales_token = propose_scale_token(invscales_token,PM)\n invscales_token = propose_scale_type(invscales_token,PM);\nend\n\nfunction score = score_scale_type(M,sid,bid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return\n end\n scales_type = M.S{sid}.invscales_type(bid);\n scales_token = M.S{sid}.invscales_token(bid);\n id = M.S{sid}.ids(bid);\n lp = CPD.score_invscale_type(lib,scales_type,id); \n ll = CPD.score_invscale_token(lib,scales_token,scales_type);\n score = lp + ll;\nend\n\nfunction score = score_scale_token(M,sid,bid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n scales_type = M.S{sid}.invscales_type(bid);\n scales_token = M.S{sid}.invscales_token(bid);\n \n %% account for future positions, which this parameter may influence\n ll_next_pos = 0;\n for i=sid+1:M.ns\n nextS = M.S{i};\n ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));\n end\n \n score = ll_next_pos + CPD.score_image(M.I,M.pimg) + CPD.score_invscale_token(lib,scales_token,scales_type);\nend\n\n%% POSITION\n\nfunction pos = propose_local_position(pos,PM)\n pos = propose_global_position(pos,PM);\nend\n\nfunction gpos = propose_global_position(gpos,PM)\n gpos = gpos + PM.mcmc.prop_gpos_sd .* randn(size(gpos));\nend\n\nfunction score = score_global_position(M,sid,lib,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n R = M.S{sid}.R; \n lp = CPD.score_relation_type(lib,R);\n ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));\n score = lp + ll;\nend\n\nfunction score = score_local_position(M,sid,lib,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n R = M.S{sid}.R;\n ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));\n \n %% account for future positions, which this parameter may influence\n ll_next_pos = 0;\n for i=sid+1:M.ns\n nextS = M.S{i};\n ll_next_pos = ll_next_pos + CPD.score_position(lib,nextS.pos_token,nextS.R,M.S(1:i-1));\n end\n \n score = CPD.score_image(M.I,M.pimg) + ll + ll_next_pos;\nend\n\n%% EVALUATION SPOT RELATION\n\nfunction eval_spot_type = propose_eval_spot(eval_spot_type,PM)\n eval_spot_type = eval_spot_type + PM.mcmc.prop_relmid_sd .* randn;\nend\n\nfunction score = score_eval_spot_type(M,sid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n R = M.S{sid}.R;\n lp = CPD.score_relation_type(lib,R);\n ll = CPD.score_relation_token(lib,R.eval_spot_token,R.eval_spot_type);\n score = lp + ll;\nend \n\nfunction score = score_eval_spot_token(M,sid,lib,~,fullscore)\n if ~exist('fullscore','var')\n fullscore = false; \n end\n if fullscore\n score = scoreMP(M,lib);\n return \n end\n R = M.S{sid}.R;\n lp = CPD.score_relation_token(lib,R.eval_spot_token,R.eval_spot_type);\n ll = CPD.score_position(lib,M.S{sid}.pos_token,R,M.S(1:sid-1));\n score = lp + ll;\nend ", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/mcmc/MCMC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.022629197643649367, "lm_q1q2_score": 0.01016939507865021}} {"text": "function hplstat(HPL,HPE,HAL,src_name)\n% HPL(1xN) - Horizontal protection level \n% HPE(Nx1) - Horizontal position error = (easting.^2, northing.^2).^0.5\n% HAL - Horizontal alert limit (define how large is the area for Normal operation \n% [the line between white and yellow])\n% src_name = label of vertical axis which will go as subscript after 'HPL'\n\n%* Copyright c 1998 The board of trustees of the Leland Stanford *\n%* Junior University. All rights reserved. *\n%* This script file may be distributed and used freely, provided *\n%* this copyright notice is always kept with it. *\n%* *\n%* Questions and comments should be directed to Todd Walter at: *\n%* walter@relgyro.stanford.edu *\n%HPLSTAT\n% HPLSTAT(FNAME, HAL, PATH) reads the given file of TMS Horizontal \n% Protection Limit statistics and plots the color coded histogram. \n% In addition the regions of integrity failures and unavailability\n% are shown. The optional HAL argument is given in meters (default 30m).\n% See also : TMSSTAT, TRSNAMES, VERTSTAT, VPLSTAT\n% Example code for generating the file is included at the bottom of hplstat.m\n%\n% NOTE: To plot on a non-color printer type:\n% colormap('gray')\n% % new colormap for colorbar (HPL and HPE plot)\n color_bar =[ \n 0.6980 0.6980 0.6980;\n 0.6905 0.6905 0.6905;\n 0.6830 0.6830 0.6830;\n 0.6754 0.6754 0.6754;\n 0.6679 0.6679 0.6679;\n 0.6604 0.6604 0.6604;\n 0.6528 0.6528 0.6528;\n 0.6453 0.6453 0.6453;\n 0.6378 0.6378 0.6378;\n 0.6302 0.6302 0.6302;\n 0.6227 0.6227 0.6227;\n 0.6152 0.6152 0.6152;\n 0.6076 0.6076 0.6076;\n 0.6001 0.6001 0.6001;\n 0.5926 0.5926 0.5926;\n 0.5850 0.5850 0.5850;\n 0.5775 0.5775 0.5775;\n 0.5700 0.5700 0.5700;\n 0.5624 0.5624 0.5624;\n 0.5549 0.5549 0.5549;\n 0.5474 0.5474 0.5474;\n 0.5398 0.5398 0.5398;\n 0.5323 0.5323 0.5323;\n 0.5247 0.5247 0.5247;\n 0.5172 0.5172 0.5172;\n 0.5097 0.5097 0.5097;\n 0.5021 0.5021 0.5021;\n 0.4946 0.4946 0.4946;\n 0.4871 0.4871 0.4871;\n 0.4795 0.4795 0.4795;\n 0.4720 0.4720 0.4720;\n 0.4645 0.4645 0.4645;\n 0.4569 0.4569 0.4569;\n 0.4494 0.4494 0.4494;\n 0.4419 0.4419 0.4419;\n 0.4343 0.4343 0.4343;\n 0.4268 0.4268 0.4268;\n 0.4193 0.4193 0.4193;\n 0.4117 0.4117 0.4117;\n 0.4042 0.4042 0.4042;\n 0.3967 0.3967 0.3967;\n 0.3891 0.3891 0.3891;\n 0.3816 0.3816 0.3816;\n 0.3741 0.3741 0.3741;\n 0.3665 0.3665 0.3665;\n 0.3590 0.3590 0.3590;\n 0.3515 0.3515 0.3515;\n 0.3439 0.3439 0.3439;\n 0.3364 0.3364 0.3364;\n 0.3289 0.3289 0.3289;\n 0.3213 0.3213 0.3213;\n 0.2966 0.2966 0.2966;\n 0.2719 0.2719 0.2719;\n 0.2472 0.2472 0.2472;\n 0.2225 0.2225 0.2225;\n 0.1977 0.1977 0.1977;\n 0.1730 0.1730 0.1730;\n 0.1483 0.1483 0.1483;\n 0.1236 0.1236 0.1236;\n 0.0989 0.0989 0.0989;\n 0.0742 0.0742 0.0742;\n 0.0494 0.0494 0.0494;\n 0.0247 0.0247 0.0247;\n 0 0 0];\n colormap(color_bar)\n\n% other colors used in the plot\n%color1 = [134/255 134/255 134/255]; % - dark gray\ncolor1 = [1 0.1 0.1]; % - red (original) \n\n%color2 = [174/255 174/255 174/255]; % - middle gray\ncolor2 = [1 0.55 0.55]; % - pink (original)\n\n%color3 = [222/255 222/255 222/255]; % - light gray\ncolor3 = [1 1 0.5]; % - yellow (original)\n\n%color4 = color2; % - middle gray\ncolor4 = [1 .55 0.3]; % - orange (original)\n\nset(0,'DefaultTextFontName','Times');\nset(0,'DefaultAxesFontName','Times');\nset(0,'DefaultTextFontSize',18);\nset(0,'DefaultAxesFontSize',18);\n \nif nargin < 2\n error('Must input HPL and HPE!');\nend\nif nargin < 3\n HAL = 30;\nend\n\n% size of VPL, which should be the same for VPE as well\nn = size(HPL,2);\n\n% HPE\nj = floor(2.0*abs(HPE))+1;\nj(find(j>100)) = 100;\n% HPL\nk = floor(2.0*abs(HPL))+1;\nk(find(k>100)) = 100;\n\n% initialize hpl_stat\ndata = zeros(100,100);\ndiagonal = zeros(100,1);\nfor i = 1:n\n % statistics\n data(k(i),j(i)) = data(k(i),j(i))+1;\n % diagonal\n if((k(i) == j(i)) && (abs(HPE(i,1)) < abs(HPL(1,i))))\n diagonal(k(i),1) = diagonal(k(i),1)+1;\n end\nend\n\nc = 1;\ncolors = 'brygcmw';\nclf\n\nerr_bin = 0.25:0.5:49.75;\nsig_bin = 0.25:0.5:49.75;\n\nseconds = n;\nsec_available = n;\ndiag_cnt = sum(diagonal);\n\n% determine the number of points and axis ranges\nn_pts = sum(sum(data));\nif sec_available == 1\n epochs = seconds;\nelse\n epochs = n_pts;\nend\n\n\nd_err_bin = mean(diff(err_bin));\nx_lo_bnd = min(err_bin) - d_err_bin/2;\nx_up_bnd = max(err_bin) + d_err_bin/2;\n\nd_sig_bin = mean(diff(sig_bin));\ny_lo_bnd = min(sig_bin) - d_sig_bin/2;\ny_up_bnd = max(sig_bin) + d_sig_bin/2;\n\nz_lo_bnd = 1;\nz_up_bnd = max(max(data));\n\n% clear plot\nclf;\n\n% plot each data point as a pixel\n[i,j]=find(data);\nface_mat=[[1 2 6 5]' [2 3 7 6]' [3 4 8 7]' ...\n [4 1 5 8]' [1 2 3 4]' [5 6 7 8]']';\ncolors=colormap;\nfor idx = 1:length(i)\n z = log10(data(i(idx),j(idx)));\n vtx_mat = [err_bin(j(idx))+[-0.5 0.5 0.5 -0.5 -0.5 0.5 0.5 -0.5]'*d_err_bin ...\n sig_bin(i(idx))+[-0.5 -0.5 0.5 0.5 -0.5 -0.5 0.5 0.5]'*d_sig_bin ...\n [0 0 0 0 z z z z]'];\n c_idx = ceil(63*(log10(data(i(idx),j(idx)))/log10(z_up_bnd))) + 1;\n patch('Vertices', vtx_mat, ...\n 'Faces', face_mat, ...\n 'FaceColor', colors(c_idx,:), ...\n 'EdgeColor', 'none');\nend\n\n% determine availability and # of integrity failures\ni_diag1 = find(err_bin == HAL);\ni_diag2 = find(err_bin < HAL);\ni_diag3 = find(err_bin > HAL);\n\ni_fail1 = find(err_bin(j) >= HAL & sig_bin(i) < HAL);\nn_fail1 = sum(sum(diag(data(i(i_fail1),j(i_fail1)))))...\n - sum(diagonal(i_diag1));\ni_fail2 = find(err_bin(j)./sig_bin(i) >=1.0 & err_bin(j) < HAL);\nn_fail2 = sum(sum(diag(data(i(i_fail2),j(i_fail2)))))...\n - sum(diagonal(i_diag2));\ni_fail3 = find(err_bin(j)./sig_bin(i) >=1.0 & sig_bin(i) >= HAL);\nn_fail3 = sum(sum(diag(data(i(i_fail3),j(i_fail3)))))...\n - sum(diagonal(i_diag3));\ni_cont = find(sig_bin(i) >= HAL);\nn_cont = sum(sum(diag(data(i(i_cont),j(i_cont)))));\n%i_avail = find(err_bin(j) < HAL & sig_bin(i) < HAL);\ni_avail = find(err_bin(j)./sig_bin(i) < 1.0 & sig_bin(i) < HAL);\nn_avail = sum(sum(diag(data(i(i_avail),j(i_avail)))))...\n + sum(diagonal(i_diag2));\n\n\n% set the axes limits and color values\nset(gca,'XLim',[x_lo_bnd x_up_bnd]);\nset(gca,'YLim',[y_lo_bnd y_up_bnd]);\nset(gca,'CLim',[z_lo_bnd z_up_bnd]);\n\n\n% show the region of normal operation\nHT=text(0.37*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.93*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '{\\fontsize{14pt}Normal Operation}');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', [1 1 1]); % white\ntext(0.37*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.93*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '{\\fontsize{14pt}Normal Operation}');\nif n_avail/epochs >= .999995\n HT = text(0.33*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.86*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '> 99.999%');\n pos = get(HT, 'Position');\n pos = pos + [.05 -0.05 0];\n set(HT, 'Position', pos);\n set(HT, 'Color', [1 1 1]); % white\n set(HT, 'FontSize', 14);\n HT = text(0.33*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.86*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '> 99.999%');\n set(HT, 'FontSize', 14);\nelse\n HT = text(0.37*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.86*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n [num2str(100.0*n_avail/epochs,'%6.3f'), '%']);\n pos = get(HT, 'Position');\n pos = pos + [.05 -0.05 0];\n set(HT, 'Position', pos);\n set(HT, 'Color', [1 1 1]); % white\n set(HT, 'FontSize', 14);\n HT = text(0.37*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.86*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n [num2str(100.0*n_avail/epochs,'%6.3f'), '%']);\n set(HT, 'FontSize', 14);\nend\n\n\n% outline the region of integrity failures\npatch([HAL HAL x_up_bnd x_up_bnd], ...\n [y_lo_bnd HAL HAL y_lo_bnd], ...\n -[0.5 0.5 0.5 0.5], ...\n color1); \nHT = text(0.50*(x_up_bnd - HAL) + HAL, ...\n 0.55*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'HMI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color1); \nHT = text(0.50*(x_up_bnd - HAL) + HAL, ...\n 0.55*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'HMI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\nHT = text(0.50*(x_up_bnd - HAL) + HAL, ...\n 0.45*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail1)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color1);\nHT = text(0.50*(x_up_bnd - HAL) + HAL, ...\n 0.45*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail1)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\n\n% outline the region of HPL failures\npatch([x_lo_bnd HAL HAL], ...\n [y_lo_bnd HAL y_lo_bnd], ...\n -[0.5 0.5 0.5], ...\n color2); \nHT = text(0.67*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.35*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'MI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color2); \nHT = text(0.67*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.35*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'MI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\nHT = text(0.67*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.25*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail2)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color2); \nHT = text(0.67*(HAL - x_lo_bnd) + x_lo_bnd, ...\n 0.25*(HAL - y_lo_bnd) + y_lo_bnd, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail2)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\n\n% outline the region of unavailability\npatch([x_lo_bnd x_up_bnd x_up_bnd x_lo_bnd], ...\n [HAL HAL y_up_bnd y_up_bnd], ...\n -[0.5 0.5 0.5 0.5], ...\n color3); \nHT = text(0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 0.70*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '{\\fontsize{14pt}System Unavailable}');\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color3); \nHT = text(0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 0.70*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n '{\\fontsize{14pt}System Unavailable}');\nset(HT,'HorizontalAlignment','Center');\nHT = text(0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 0.55*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['Alarm Epochs: ', int2str(n_cont)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color3);\nHT = text(0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 0.55*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['Alarm Epochs: ', int2str(n_cont)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\n\n% outline the region where integrity failures and unavailability overlap\npatch([HAL x_up_bnd x_up_bnd], ...\n [HAL y_up_bnd HAL], ...\n -z_lo_bnd*[0.45 0.45 0.45], ...\n color4); \nHT = text(0.70*(x_up_bnd - HAL) + HAL, ...\n 0.325*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'MI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color4); \nHT = text(0.70*(x_up_bnd - HAL) + HAL, ...\n 0.325*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n 'MI');\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\nHT = text(0.70*(x_up_bnd - HAL) + HAL, ...\n 0.175*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail3)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\npos = get(HT, 'Position');\npos = pos + [.05 -0.05 0];\nset(HT, 'Position', pos);\nset(HT, 'Color', color4); \nHT = text(0.70*(x_up_bnd - HAL) + HAL, ...\n 0.175*(y_up_bnd - HAL) + HAL, ...\n 0.25*sqrt(z_up_bnd*z_lo_bnd), ...\n ['epochs: ', int2str(n_fail3)]);\nset(HT, 'FontSize', 14);\nset(HT,'HorizontalAlignment','Center');\n\nhold on;\ngrid off;\n% make the grid visible over the patch regions (integrity, unavailability)\nytick = get(gca,'YTick');\nxtick = get(gca,'XTick');\nnytick = length(ytick);\nnxtick = length(xtick);\nfor i = 1:nytick\n plot3([x_lo_bnd x_up_bnd], ytick(i)*[1 1], [0.6 0.6], 'k:');\nend\nfor i = 1:nxtick\n plot3(xtick(i)*[1 1], [y_lo_bnd y_up_bnd], [0.6 0.6], 'k:');\nend\n\n% label the axes and add a title\nxlabel('{\\fontsize{16pt}Error [m]}');\nset(get(gca,'XLabel'),'Position', ...\n [ 0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n -0.05*(y_up_bnd - y_lo_bnd) + y_lo_bnd, ...\n z_lo_bnd]);\n \nylabel(['{\\fontsize{16pt}HPL_{',src_name,'} [m]}']);\nset(get(gca,'YLabel'),'Position', ...\n [-0.06*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 0.50*(y_up_bnd - y_lo_bnd) + y_lo_bnd z_lo_bnd]);\n \ntitle (['Horizontal Performance [',int2str(seconds),' seconds]']);\n\nset(get(gca,'Title'),'FontSize',14);\nset(get(gca,'Title'),'Position', ...\n [0.50*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n 1.02*(y_up_bnd - y_lo_bnd) + y_lo_bnd, ...\n z_lo_bnd]);\n\n\n% put the sigma_H_major scale on the right hand y-axis\n% K_h_pa = 6.18;\n% for i = ceil(y_lo_bnd/K_h_pa):floor(y_up_bnd/K_h_pa)\n% if abs(i*K_h_pa - (0.5*(y_up_bnd - y_lo_bnd) + y_lo_bnd)) > ...\n% 0.05*(y_up_bnd - y_lo_bnd)\n% plot3([.99*(x_up_bnd - x_lo_bnd) + x_lo_bnd x_up_bnd], ...\n% i*K_h_pa*[1 1], ...\n% [0.65 0.65], ...\n% 'k');\n% text(1.02*(x_up_bnd - x_lo_bnd) + x_lo_bnd, i*K_h_pa, 0.65, int2str(i));\n% end\n% end\n% HT = text(1.04*(x_up_bnd - x_lo_bnd) + x_lo_bnd, ...\n% 0.50*(y_up_bnd - y_lo_bnd) + y_lo_bnd, ...\n% 0.65, ...\n% '{\\fontsize{14pt}\\sigma}_{H_{major}} (m)');\n% set(HT,'HorizontalAlignment','Center');\n% set(HT,'Rotation',90);\n\n% put the color scale up on the right hand side\nH = colorbar('vert');\nset(get(H,'Ylabel'),'String','{\\fontsize{14pt}Number of Points per Pixel}');\n%set(H,'YScale','log');\nset(H,'YLim',[z_lo_bnd z_up_bnd]);\n%set(H,'CLim', [z_lo_bnd z_up_bnd]);\n\nif sec_available == 1\n display (['EGNOS differential for ', ...\n num2str(n_pts), ...\n ' out of ', ...\n num2str(seconds), ...\n ' seconds']);\nend\n\nset(H, 'linewidth',.8);\nhold off\nset(gca,'Fontsize',18);\n\n\n%print -deps env_HPL\n\n%%%%%%%%%%%% end hplstat.m %%%%%%%%%%%%%%%%%%%%", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/example/gps_spp_test/easysuite/hplstat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.020645930965190937, "lm_q1q2_score": 0.010081065270726839}} {"text": "%{\nMIT License\n\nCopyright (c) 2018 ZjxRS\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n%}\n% This is lifted from https://github.com/ZjxRS/ImageProcess/tree/master/Matlab/ENVI_ReadAndWrite\n\nfunction info = envihdrread(hdrfile)\n% ENVIHDRREAD Reads header of ENVI image.\n% INFO = ENVIHDRREAD('HDR_FILE') reads the ASCII ENVI-generated image\n% header file and returns all the information in a structure of\n% parameters.\n%\n% Example:\n% >> info = envihdrread('my_envi_image.hdr')\n% info =\n% description: [1x101 char]\n% samples: 658\n% lines: 749\n% bands: 3\n% header_offset: 0\n% file_type: 'ENVI Standard'\n% data_type: 4\n% interleave: 'bsq'\n% sensor_type: 'Unknown'\n% byte_order: 0\n% map_info: [1x1 struct]\n% projection_info: [1x102 char]\n% wavelength_units: 'Unknown'\n% pixel_size: [1x1 struct]\n% band_names: [1x154 char]\n%\n% NOTE: This function is used by ENVIREAD to import data.\n\n% Ian M. Howat, Applied Physics Lab, University of Washington\n% ihowat@apl.washington.edu\n% Version 1: 19-Jul-2007 00:50:57\n% Modified by Felix Totir\n%\n\nfid = fopen(hdrfile);\nwhile true\n line = fgetl(fid);\n if line == -1\n break\n else\n eqsn = findstr(line,'=');\n if ~isempty(eqsn)\n param = strtrim(line(1:eqsn-1));\n param(findstr(param,' ')) = '_';\n value = strtrim(line(eqsn+1:end));\n if isempty(str2num(value))\n if ~isempty(findstr(value,'{')) && isempty(findstr(value,'}'))\n while isempty(findstr(value,'}'))\n line = fgetl(fid);\n \n %for polSARpro\n if line == -1\n break;\n end\n value = [value,strtrim(line)];\n end\n end\n eval(['info.',param,' = ''',value,''';'])\n else\n eval(['info.',param,' = ',value,';'])\n end\n end\n end\nend\nfclose(fid);\n\nif isfield(info,'map_info')\n line = info.map_info;\n line(line == '{' | line == '}') = [];\n \n %originally: line = strtrim(split(line,','));\n %replaced by\n line=textscan(line,'%s', 'Delimiter',','); %behavior is not quite the same if \"line\" ends in ','\n line=line{:};\n line=strtrim(line);\n %\n \n info.map_info = [];\n info.map_info.projection = line{1};\n info.map_info.image_coords = [str2num(line{2}),str2num(line{3})];\n info.map_info.mapx = str2num(line{4});\n info.map_info.mapy = str2num(line{5});\n info.map_info.dx = str2num(line{6});\n info.map_info.dy = str2num(line{7});\n if length(line) == 9\n info.map_info.datum = line{8};\n info.map_info.units = line{9}(7:end);\n elseif length(line) == 11\n info.map_info.zone = str2num(line{8});\n info.map_info.hemi = line{9};\n info.map_info.datum = line{10};\n info.map_info.units = line{11}(7:end);\n end\n \n %part below comes form the original enviread\n %% Make geo-location vectors\n % xi = info.map_info.image_coords(1);\n % yi = info.map_info.image_coords(2);\n % xm = info.map_info.mapx;\n % ym = info.map_info.mapy;\n % %adjust points to corner (1.5,1.5)\n % if yi > 1.5\n % ym = ym + ((yi*info.map_info.dy)-info.map_info.dy);\n % end\n % if xi > 1.5\n % xm = xm - ((xi*info.map_info.dy)-info.map_info.dx);\n % end\n %\n % info.x= xm + ((0:info.samples-1).*info.map_info.dx);\n % info.y = ym - ((0:info.lines-1).*info.map_info.dy);\nend\n\nif isfield(info,'coordinate_system_string')\n line = info.coordinate_system_string;\n line(line == '{' | line == '}' | line == '\"' | line == '[' ...\n | line == ']') = [];\n \n %originally: line = strtrim(split(line,','));\n %replaced by\n line=textscan(line,'%s', 'Delimiter',','); %behavior is not quite the same if \"line\" ends in ','\n line=line{:};\n line=strtrim(line);\n %\n \n info.coordinate_system = [];\n \n if contains(line{1},'UTM')\n info.coordinate_system.PROJCS = extractAfter(line{1},6);\n \n info.coordinate_system.GEOGCS = extractAfter(line{2},6);\n info.coordinate_system.DATUM = extractAfter(line{3},5);\n info.coordinate_system.SPHEROID = [];\n info.coordinate_system.SPHEROID.datum = extractAfter(line{4},8);\n info.coordinate_system.SPHEROID.a = line{5};\n info.coordinate_system.SPHEROID.e = line{6};\n info.coordinate_system.PRIMEM = extractAfter(line{7},6);\n info.coordinate_system.PMlongToGreenwich = line{8};\n info.coordinate_system.UNITGeo = extractAfter(line{9},4);\n info.coordinate_system.UNITGeo_value = line{10};\n \n info.coordinate_system.PROJECTION = extractAfter(line{11},10);\n info.coordinate_system.PARAMETER1 = extractAfter(line{12},9);\n info.coordinate_system.PARAMETER1_value = line{13};\n info.coordinate_system.PARAMETER2 = extractAfter(line{14},9);\n info.coordinate_system.PARAMETER2_value = line{15};\n info.coordinate_system.PARAMETER3 = extractAfter(line{16},9);\n info.coordinate_system.PARAMETER3_value = line{17};\n info.coordinate_system.PARAMETER4 = extractAfter(line{18},9);\n info.coordinate_system.PARAMETER4_value = line{19};\n info.coordinate_system.PARAMETER5 = extractAfter(line{20},9);\n info.coordinate_system.PARAMETER5_value = line{21};\n info.coordinate_system.UNITPro = extractAfter(line{22},4);\n info.coordinate_system.UNITPro_value = line{23};\n \n elseif strcmp(info.map_info.projection, 'Geographic Lat/Lon')\n info.coordinate_system.GEOGCS = extractAfter(line{1},6);\n info.coordinate_system.DATUM = extractAfter(line{2},5);\n info.coordinate_system.SPHEROID = [];\n info.coordinate_system.SPHEROID.datum = extractAfter(line{3},8);\n info.coordinate_system.SPHEROID.a = line{4};\n info.coordinate_system.SPHEROID.e = line{5};\n info.coordinate_system.PRIMEM = extractAfter(line{6},6);\n info.coordinate_system.PMlongToGreenwich = line{7};\n info.coordinate_system.UNITGeo = extractAfter(line{8},4);\n info.coordinate_system.UNITGeo_value = line{9};\n end\n \nend\n\n\nif isfield(info,'pixel_size')\n line = info.pixel_size;\n line(line == '{' | line == '}') = [];\n \n %originally: line = strtrim(split(line,','));\n %replaced by:\n line=textscan(line,'%s','Delimiter',','); %behavior is not quite the same if \"line\" ends in ','\n line=line{:};\n line=strtrim(line);\n \n info.pixel_size = [];\n info.pixel_size.x = str2num(line{1});\n info.pixel_size.y = str2num(line{2});\n info.pixel_size.units = line{3}(7:end);\nend\n\n% function split is only used when replacements above do not work\n% function A = split(s,d)\n%This function by Gerald Dalley (dalleyg@mit.edu), 2004\n% A = {};\n% while (~isempty(s))\n% [t,s] = strtok(s,d);\n% A = {A{:}, t};\n% end\n", "meta": {"author": "Bobholamovic", "repo": "ChangeDetectionToolbox", "sha": "167877b866665511d9d5e7e184f964bcda5f4016", "save_path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox", "path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox/ChangeDetectionToolbox-167877b866665511d9d5e7e184f964bcda5f4016/+Datasets/+Loaders/private/envihdrread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.26894143308897966, "lm_q2_score": 0.03732688881662312, "lm_q1q2_score": 0.01003874697109563}} {"text": "%Transcriptional Regulation\n%\n% @wholeCellModelID Process_TranscriptionalRegulation\n% @name Transcriptional Regulation\n% @description\n% Biology\n% ==============\n% The the rate of transcription of each transcription unit is known to be\n% regulated by proteins referred to as transcription factors which modulate\n% the affinity of the RNA polymerase for each promoter. Transcription factors\n% can both positively and negatively modulate RNA polymerase - promoter\n% affinity. Transcription factors can stabilize RNA polymerase - promoter\n% complexes by contributing additional negative free energy to the complex by\n% providing an additional surface for the RNA polymerase binding.\n% Transcription factors can destabilize RNA polymerase - promoter complexes\n% for example by sterically blocking promoters and preventing the RNA\n% polymerase from binding promoters.\n%\n% This process simulates the binding of transcription factors to the promoters\n% of each transcription unit (affinity), as well as the affect of the\n% transcription factors on the recruiment of the RNA polymerase to each\n% promoter (activity). The process was built using experimentally observed fold\n% change expression effect of each transcription factor on each promoter.\n%\n% Affinity\n% ++++++++++++++\n% Binds enzymes to promoters assuming:\n% 1) Transcription factors have high affinity for promoters\n% 2) Transcription factors bind promoters rapidly\n% 3) Transcription factors bind promoters stably over time\n% 4) Only 1 copy of a transcription factor can bind each promoter\n% 5) Transcription factors only compete within their species for\n% promoters. That is for each transcription unit we assume each\n% transcription factor species binds a distinct promoters region.\n%\n% Consequently, at each time step we simulate that each free\n% transcription factor binds randomly binds unoccupied promoters (no copy\n% of that transcription factor is already bound to the promoter). Random\n% transcription factor-promoter binding is weighted by the affinity of\n% each transcription factor for each promoter.\n%\n% Because transcription factor-promoter affinities are generally not\n% experimentally observed, we base them on the transcription factor fold\n% change activities.\n%\n% Activity\n% ++++++++++++++\n% The effect of bound transcription factors on the recruitment of RNA\n% polymerase and the expression of transcription units is simulated here\n% and incorporated into the calculation of the RNA polymerase\n% transcription unit promoter binding probabilities in the transcription\n% process. Specifically, the wild-type average RNA polymerase\n% transcription unit promoter binding probabilities are multiplied by the\n% binding probability fold change effects simulated in this process.\n%\n% The RNA polymerase binding probability fold change is simulated for\n% each promoter as the product of the observed expression fold change\n% effects of each bound transcription factor. When a promoter is bound by\n% a single transcription factor, the net RNA polymerase binding\n% probability fold change is the observed expression fold change of that\n% transcription factor. When a promoter is bound by multiple\n% transcription units, the net RNA polymerase binding probability fold\n% change is given by the product of the individual fold change effects of\n% the bound transcription factors.\n%\n% Knowledge Base\n% ==============\n% The list of transcriptional regulatory relationships is maintained in the\n% the knowledge base. As of 8/10/2010, it contained 31 such relationships\n% between 5 transcription factors and 29 transcription units containing 37\n% genes. The knowledge base was built from a variety of literature sources\n% and databases including:\n% - PUB_0096\n% - PUB_0110\n% - PUB_0112\n% - PUB_0196\n% - PUB_0418-20\n% - PUB_0433-8\n% - PUB_0505\n%\n% Initialization\n% =================\n% Because we assume that transcription factors have high affinity for DNA and\n% bind DNA stably, we initialize as many transcription factors as possible to\n% the promoter-bound state. We randomly assign transcription factors to\n% promoters using their relative affinities.\n%\n% Simulation\n% ==============\n% For each kind of transcription factor, bind any free transcription factors\n% to promoters that aren't already occupied by this kind of transcription\n% factor. Choose the binding sites randomly, weighted by the transcription\n% factor's affinity to them.\n%\n% References\n% ==============\n% 1) Lacramioara Bintu and Nicolas E Buchler and Hernan G Garcia and\n% Ulrich Gerland and Terence Hwa, Jane Kondev and Rob Phillips (2005).\n% Transcriptional regulation by the numbers: models. Curr Opin Genet\n% Dev. 15:116-24.\n% 2) Lacramioara Bintu and Nicolas E Buchler and Hernan G Garcia and\n% Ulrich Gerland and Terence Hwa, Jane Kondev and Rob Phillips (2005).\n% Transcriptional regulation by the numbers: applications. Curr Opin\n% Genet Dev. 15:125-35.\n%\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Author: Jared Jacobs, jmjacobs@stanford.edu\n% Affilitation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 10/19/2010\nclassdef TranscriptionalRegulation < edu.stanford.covert.cell.sim.Process & edu.stanford.covert.cell.sim.ChromosomeProcessAspect\n %property annotations\n properties (Constant)\n optionNames__ = {}; %names of option properties\n fixedConstantNames__ = { %names of fixed constant properties\n\t\t 'tfIndexs';\n 'tuIndexs';\n 'tfAffinities';\n 'tfActivities';\n 'tfPositionStrands';\n 'otherActivities';\n\t\t };\n fittedConstantNames__ = {}; %names of fitted constant properties\n localStateNames__ = {}; %names of simulation state properties redundant with timecourses in this or other processes or the simulation\n end\n\n %IDs, names, and local indices\n properties\n stimuliWholeCellModelIDs = {};\n substrateWholeCellModelIDs = {};\n\n enzymeWholeCellModelIDs\n enzymeIndexs_fur %MG_236_MONOMER ferric uptake repressor\n enzymeIndexs_gntR %MG_101_MONOMER Uncharacterized HTH-type transcriptional regulator\n enzymeIndexs_hrcA %MG_205_DIMER heat-inducible transcription repressor HrcA, putative\n enzymeIndexs_luxR %MG_428_DIMER LuxR bacterial regulatory protein, putative\n enzymeIndexs_spx %MG_127_MONOMER Spx subfamily protein\n\n transcriptionUnitWholeCellModelIDs\n end\n\n %fixed biological constants\n properties\n tfIndexs %identifying index of transcription factor that binds each site [sites X 2]\n tuIndexs %identifying index of transcription unit associated with each TF binding site [sites X 2]\n tfAffinities %affinity of each transcription factor for each promoter it binds [sites X 2]\n tfActivities %fold change expression of each transcription unit when its promoter is bound by a particular transcription factor [sites X 2]\n tfPositionStrands %start position and strand of each transcription factor DNA binding site [2*sites X 2]\n otherActivities %fold change each non-DNA-binding transcription factor has on each transcription unit's expression [nTFs X nTUs]\n end\n\n %dependent local state (implemented as dependent property for convenience)\n properties (Dependent, SetAccess = protected)\n tfBoundPromoters %number of each transcription factor bound to promoter of each transcription unit [transcription factors X promoters X 2]\n boundTFs %count of how many of each transcription factor are bound [transcription factors X 1]\n end\n \n %references to cell state\n properties\n rnaPolymerase %reference to RNA polymerase state\n end\n\n %constructor\n methods\n function this = TranscriptionalRegulation(wholeCellModelID, name)\n this = this@edu.stanford.covert.cell.sim.Process(wholeCellModelID, name);\n end\n end\n\n %communication between process/simulation\n methods\n %set references to state objects\n function storeObjectReferences(this, simulation)\n this.storeObjectReferences@edu.stanford.covert.cell.sim.Process(simulation);\n this.storeObjectReferences@edu.stanford.covert.cell.sim.ChromosomeProcessAspect(simulation);\n \n this.rnaPolymerase = simulation.state('RNAPolymerase');\n this.states = [this.states; {this.rnaPolymerase}];\n end\n \n %initialize constants\n function initializeConstants(this, knowledgeBase, varargin)\n %build object arrays of transcription factor monomers and complexes\n monomers = [];\n complexs = [];\n for i = 1:knowledgeBase.numTranscriptionUnits\n m = knowledgeBase.transcriptionUnits(i).transcriptionFactorProteinMonomers;\n c = knowledgeBase.transcriptionUnits(i).transcriptionFactorProteinComplexs;\n if ~isempty(m)\n monomers = [monomers; m]; %#ok\n end\n if ~isempty(c)\n complexs = [complexs; c]; %#ok\n end\n end\n \n %whole cell model ids of all transcription factors\n this.enzymeWholeCellModelIDs = unique({\n monomers.wholeCellModelID...\n complexs.wholeCellModelID}');\n\n %transcription factors indices\n this.enzymeIndexs_fur = this.enzymeIndexs({'MG_236_MONOMER'});\n this.enzymeIndexs_gntR = this.enzymeIndexs({'MG_101_MONOMER'});\n this.enzymeIndexs_hrcA = this.enzymeIndexs({'MG_205_DIMER'});\n this.enzymeIndexs_luxR = this.enzymeIndexs({'MG_428_DIMER'});\n this.enzymeIndexs_spx = this.enzymeIndexs({'MG_127_MONOMER'});\n\n %call super class method to compute mapping between enzymes of\n %this process, and of protein monomers and complexes of the simulation\n this.initializeConstants@edu.stanford.covert.cell.sim.Process(...\n knowledgeBase, varargin{:});\n this.initializeConstants@edu.stanford.covert.cell.sim.ChromosomeProcessAspect(...\n knowledgeBase, varargin{:});\n\n %whole cell model ids of transcription units\n this.transcriptionUnitWholeCellModelIDs = ...\n {knowledgeBase.transcriptionUnits.wholeCellModelID}';\n\n %build matrices of transcription factor positions, affinities, activities\n n = length(monomers) + length(complexs);\n this.tuIndexs = zeros(n, 2);\n this.tfIndexs = zeros(n, 2);\n this.tfActivities = zeros(n, 2);\n this.tfPositionStrands = zeros(n*2, 2);\n c = this.chromosome;\n j = 1;\n for i = 1:knowledgeBase.numTranscriptionUnits\n tu = knowledgeBase.transcriptionUnits(i);\n\n if ~isempty(tu.transcriptionFactorProteinMonomers)\n [tf, proteinIndexs] = ismember(...\n [tu.transcriptionFactorProteinMonomers.idx]',...\n this.enzymeMonomerGlobalIndexs);\n k = nnz(tf) - 1;\n this.tuIndexs(j:j+k) = i;\n\n proteinIndexs = proteinIndexs(tf);\n this.tfIndexs(j:j+k) = this.enzymeMonomerLocalIndexs(proteinIndexs);\n\n regulationIndexs = ...\n this.enzymeMonomerCompartmentIndexs(proteinIndexs) == ...\n [tu.transcriptionFactorProteinMonomerCompartments.idx]';\n this.tfActivities(j:j+k) = ...\n tu.transcriptionFactorProteinMonomerActivitys(regulationIndexs);\n\n footprints = c.monomerDNAFootprints([tu.transcriptionFactorProteinMonomers.idx]');\n startCoordinates = tu.transcriptionFactorProteinMonomerBindingSiteStartCoordinates;\n lengths = tu.transcriptionFactorProteinMonomerBindingSiteLengths;\n this.tfPositionStrands(j:j+k) = ...\n mod(ceil(startCoordinates + lengths/2 - footprints/2) - 1, c.sequenceLen) + 1;\n j = j + 1 + k;\n end\n\n if ~isempty(tu.transcriptionFactorProteinComplexs)\n [tf, proteinIndexs] = ismember(...\n [tu.transcriptionFactorProteinComplexs.idx]',...\n this.enzymeComplexGlobalIndexs);\n k = nnz(tf) - 1;\n this.tuIndexs(j:j+k) = i;\n\n proteinIndexs = proteinIndexs(tf);\n this.tfIndexs(j:j+k) = this.enzymeComplexLocalIndexs(proteinIndexs);\n \n regulationIndexs = ...\n this.enzymeComplexCompartmentIndexs(proteinIndexs) == ...\n [tu.transcriptionFactorProteinComplexCompartments.idx]';\n this.tfActivities(j:j+k) = ...\n tu.transcriptionFactorProteinComplexActivitys(regulationIndexs);\n\n footprints = c.complexDNAFootprints([tu.transcriptionFactorProteinComplexs.idx]');\n startCoordinates = tu.transcriptionFactorProteinComplexBindingSiteStartCoordinates;\n lengths = tu.transcriptionFactorProteinComplexBindingSiteLengths;\n this.tfPositionStrands(j:j+k) = ...\n mod(ceil(startCoordinates + lengths/2 - footprints/2) - 1, c.sequenceLen) + 1;\n j = j + 1 + k;\n end\n end\n\n validateattributes(this.tfActivities, {'numeric'}, {'nonnegative'});\n \n this.tuIndexs(:,2) = this.tuIndexs(:,1);\n this.tfIndexs(:,2) = this.tfIndexs(:,1);\n this.tfActivities(:,2) = this.tfActivities(:,1);\n\n this.tfPositionStrands(1:n,2) = 1;\n this.tfPositionStrands(n+1:2*n,1) = this.tfPositionStrands(1:n,1);\n this.tfPositionStrands(n+1:2*n,2) = 3;\n\n this.tfAffinities = this.tfActivities;\n this.tfActivities(this.tfActivities<1 & this.tfAffinities>0) = ...\n this.tfActivities(this.tfActivities<1 & this.tfAffinities>0) .^ -1;\n \n bind = ~isnan(this.tfPositionStrands(1:n,1));\n this.otherActivities = ones(...\n length(this.transcriptionUnitWholeCellModelIDs), ...\n length(this.enzymeWholeCellModelIDs));\n this.otherActivities(sub2ind(...\n size(this.otherActivities), ...\n this.tuIndexs(~bind), ...\n this.tfIndexs(~bind))) = ...\n this.tfActivities(~bind);\n this.tuIndexs = this.tuIndexs(bind,:);\n this.tfIndexs = this.tfIndexs(bind,:);\n this.tfAffinities = this.tfAffinities(bind,:);\n this.tfActivities = this.tfActivities(bind,:);\n this.tfPositionStrands = this.tfPositionStrands(repmat(bind, [2 1]), :);\n end\n end\n\n %model\n methods\n %Calculate\n %- contribution to FBA objective\n %- minimum expression consistent with cell cycle length\n function [bmProd, byProd, minEnzExp, maxEnzExp] = calcResourceRequirements_LifeCycle(this, ~, ~)\n %no substrate and byproducts required\n bmProd = zeros(size(this.substrateWholeCellModelIDs));\n byProd = zeros(size(this.substrateWholeCellModelIDs));\n \n %no enzymes required\n minEnzExp = zeros(size(this.enzymeWholeCellModelIDs));\n maxEnzExp = Inf(size(this.enzymeWholeCellModelIDs));\n end\n\n %initialization:\n %- Simulation initializeState method initializes 1 undamaged chromosome\n %- Various processes may bind proteins to chromosome\n %- Here we bind transcription factors to the initial chromosome\n function initializeState(this)\n this.evolveState();\n end\n\n %resource requirements\n function result = calcResourceRequirements_Current(this)\n result = zeros(size(this.substrates));\n end\n\n %simulation\n function evolveState(this)\n %Bind transcription factors to accessible sites\n tfBoundPromoters = this.bindTranscriptionFactors();\n \n %Compute new fold changes\n this.rnaPolymerase.transcriptionFactorBindingProbFoldChange = ...\n this.calcBindingProbabilityFoldChange(tfBoundPromoters);\n end\n \n %Bind transcription factors to accessible sites.\n function tfBoundPromoters = bindTranscriptionFactors(this)\n %Estimate which binding sites exist and are accessible to the\n %transcription unit. (Note chromosome class which ensure that sites\n %are truly accessible, and only allow transcription factors to bind\n %to these sites).\n tfBoundPromoters = this.tfBoundPromoters;\n accessible = ~tfBoundPromoters & reshape(this.chromosome.isRegionPolymerized(this.tfPositionStrands, 1, false), [], 2);\n \n for i = 1:size(this.enzymes, 1)\n %For each transcription factor:\n % Stochastically pick transcription unit promoters elements to\n % bind from among free promoter elements weighted by the\n % transcription factors' affinities for the promoters. (Note:\n % each transcription factor is assumed to bind a distinct\n % promoter region near each transcription unit such that\n % transcription factors only compete within their species\n % for binding to promoters.)\n \n if this.enzymes(i) <= 0\n continue;\n end\n \n sites = find((this.tfIndexs == i) & accessible);\n if isempty(sites)\n continue;\n end\n \n tf = this.bindProteinToChromosome(...\n this.tfPositionStrands(sites, :), i, this.enzymes(i), this.tfAffinities(sites), [], false, 1, false, []);\n \n tfBoundPromoters(sites(tf)) = true;\n end\n end\n \n function foldChange = calcBindingProbabilityFoldChange(this, tfBoundPromoters)\n %reset fold change\n foldChange = ones(size(this.chromosome.transcriptionUnitStartCoordinates, 1), 2);\n \n %fold change effect of bound TFs\n for i = 1:size(this.tfIndexs, 1)\n for j = 1:size(this.tfIndexs, 2)\n if ~tfBoundPromoters(i, j)\n continue;\n end\n \n foldChange(this.tuIndexs(i, j), j) = foldChange(this.tuIndexs(i, j), j) * this.tfActivities(i, j);\n end\n end\n \n otherFoldChanges = prod(this.otherActivities .^ (this.enzymes(:, ones(1, size(foldChange, 1)))' > 0), 2);\n foldChange = foldChange .* [otherFoldChanges otherFoldChanges];\n end\n end\n \n %get methods of dependent local state\n methods\n function result = get.tfBoundPromoters(this)\n result = reshape(this.isDnaBound(this.tfPositionStrands, this.tfIndexs(:)), [], 2);\n end\n \n function result = get.boundTFs(this)\n result = histc(this.tfIndexs(logical(this.tfBoundPromoters(:,1))), 1:numel(this.enzymes));\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+process/TranscriptionalRegulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.021948252915177387, "lm_q1q2_score": 0.009778594916229927}} {"text": "function om = opf_setup(mpc, mpopt)\n%OPF Constructs an OPF model object from a MATPOWER case struct.\n% OM = OPF_SETUP(MPC, MPOPT)\n%\n% Assumes that MPC is a MATPOWER case struct with internal indexing,\n% all equipment in-service, etc.\n%\n% See also OPF, EXT2INT, OPF_EXECUTE.\n\n% MATPOWER\n% Copyright (c) 1996-2016, Power Systems Engineering Research Center (PSERC)\n% by Ray Zimmerman, PSERC Cornell\n% and Carlos E. Murillo-Sanchez, PSERC Cornell & Universidad Nacional de Colombia\n%\n% This file is part of MATPOWER.\n% Covered by the 3-clause BSD License (see LICENSE file for details).\n% See https://matpower.org for more info.\n\n%% options\ndc = strcmp(upper(mpopt.model), 'DC');\nalg = upper(mpopt.opf.ac.solver);\nuse_vg = mpopt.opf.use_vg;\nvcart = ~dc && mpopt.opf.v_cartesian;\n\n%% define named indices into data matrices\n[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...\n VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;\n[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...\n MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...\n QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;\n[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...\n TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...\n ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;\n[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;\n\n%% define flag to indicate whether we are tied to legacy formulation\n%% implemented by legacy MINOS and PDIPM solvers (e.g. with hard-coded\n%% costs and constrain\nif strcmp(alg, 'MINOPF') || strcmp(alg, 'PDIPM') || ...\n strcmp(alg, 'TRALM') || strcmp(alg, 'SDPOPF')\n legacy_formulation = 1;\n if vcart\n error('Option ''opf.v_cartesian'' = 1 is not compatible with ''opf.solver.ac''=''%s''.', alg);\n end\n if mpopt.opf.current_balance\n error('Option ''opf.current_balance'' = 1 is not compatible with ''opf.solver.ac''=''%s''.', alg);\n end\nelse\n legacy_formulation = 0;\nend\nif ~dc && ( ~isempty(mpopt.exp.sys_wide_zip_loads.pw) && ...\n ~isequal(mpopt.exp.sys_wide_zip_loads.pw, [1 0 0]) || ...\n ~isempty(mpopt.exp.sys_wide_zip_loads.qw) && ...\n ~isequal(mpopt.exp.sys_wide_zip_loads.qw, [1 0 0]) )\n if vcart\n warning('Voltage dependent loads are not supported with option ''opf.v_cartesian'' = 1. Reverting to constant power load model.');\n end\n if mpopt.opf.current_balance\n warning('Voltage dependent loads are not supported with option ''opf.current_balance'' = 1. Reverting to constant power load model.');\n end\nend\n\n%% data dimensions\nnb = size(mpc.bus, 1); %% number of buses\nnl = size(mpc.branch, 1); %% number of branches\nng = size(mpc.gen, 1); %% number of dispatchable injections\nnnle = 0; %% number of nonlinear user-defined equality cons\nnnli = 0; %% number of nonlinear user-defined inequality cons\nif isfield(mpc, 'A')\n nlin = size(mpc.A, 1); %% number of linear user constraints\nelse\n nlin = 0;\nend\nif isfield(mpc, 'N')\n nw = size(mpc.N, 1); %% number of general cost vars, w\nelse\n nw = 0;\nend\n\nif dc\n %% ignore reactive costs for DC\n mpc.gencost = pqcost(mpc.gencost, ng);\n\n %% reduce A and/or N from AC dimensions to DC dimensions, if needed\n if nlin || nw\n acc = [nb+(1:nb) 2*nb+ng+(1:ng)]; %% Vm and Qg columns\n if nlin && size(mpc.A, 2) >= 2*nb + 2*ng\n %% make sure there aren't any constraints on Vm or Qg\n if any(any(mpc.A(:, acc)))\n error('opf_setup: attempting to solve DC OPF with user constraints on Vm or Qg');\n end\n mpc.A(:, acc) = []; %% delete Vm and Qg columns\n end\n if nw && size(mpc.N, 2) >= 2*nb + 2*ng\n %% make sure there aren't any costs on Vm or Qg\n if any(any(mpc.N(:, acc)))\n [ii, jj] = find(mpc.N(:, acc));\n ii = unique(ii); %% indices of w with potential non-zero cost terms from Vm or Qg\n if any(mpc.Cw(ii)) || (isfield(mpc, 'H') && ~isempty(mpc.H) && ...\n any(any(mpc.H(:, ii))))\n error('opf_setup: attempting to solve DC OPF with user costs on Vm or Qg');\n end\n end\n mpc.N(:, acc) = []; %% delete Vm and Qg columns\n end\n end\nelse %% AC\n if use_vg %% adjust bus voltage limits based on generator Vg setpoint\n %% gen connection matrix, element i, j is 1 if, generator j at bus i is ON\n Cg = sparse(mpc.gen(:, GEN_BUS), (1:ng)', mpc.gen(:, GEN_STATUS) > 0, nb, ng);\n Vbg = Cg * sparse(1:ng, 1:ng, mpc.gen(:, VG), ng, ng);\n Vmax = max(Vbg, [], 2); %% zero for non-gen buses, else max Vg of gens @ bus\n ib = find(Vmax); %% buses with online gens\n Vmin = max(2*Cg - Vbg, [], 2); %% same as Vmax, except min Vg of gens @ bus\n Vmin(ib) = 2 - Vmin(ib);\n\n if use_vg == 1 %% use Vg setpoint directly\n mpc.bus(ib, VMAX) = Vmax(ib); %% max set by max Vg @ bus\n mpc.bus(ib, VMIN) = Vmin(ib); %% min set by min Vg @ bus\n mpc.bus(ib, VM) = mpc.bus(ib, VMAX);\n elseif use_vg > 0 && use_vg < 1 %% fractional value\n %% use weighted avg between original Vmin/Vmax limits and Vg\n mpc.bus(ib, VMAX) = (1-use_vg) * mpc.bus(ib, VMAX) + use_vg * Vmax(ib);\n mpc.bus(ib, VMIN) = (1-use_vg) * mpc.bus(ib, VMIN) + use_vg * Vmin(ib);\n else\n error('opf_setup: option ''opf.use_vg'' (= %g) cannot be negative or greater than 1', use_vg);\n end\n end\n if isfield(mpc, 'user_constraints')\n if isfield(mpc.user_constraints, 'nle')\n for k = 1:length(mpc.user_constraints.nle)\n nnle = nnle + mpc.user_constraints.nle{k}{2};\n end\n end\n if isfield(mpc.user_constraints, 'nli')\n for k = 1:length(mpc.user_constraints.nli)\n nnli = nnli + mpc.user_constraints.nli{k}{2};\n end\n end\n end\nend\n\n%% convert single-block piecewise-linear costs into linear polynomial cost\npwl1 = find(mpc.gencost(:, MODEL) == PW_LINEAR & mpc.gencost(:, NCOST) == 2);\n% p1 = [];\nif ~isempty(pwl1)\n x0 = mpc.gencost(pwl1, COST);\n y0 = mpc.gencost(pwl1, COST+1);\n x1 = mpc.gencost(pwl1, COST+2);\n y1 = mpc.gencost(pwl1, COST+3);\n m = (y1 - y0) ./ (x1 - x0);\n b = y0 - m .* x0;\n mpc.gencost(pwl1, MODEL) = POLYNOMIAL;\n mpc.gencost(pwl1, NCOST) = 2;\n mpc.gencost(pwl1, COST:COST+1) = [m b];\nend\n\n%% create (read-only) copies of individual fields for convenience\n[baseMVA, bus, gen, branch, gencost, Au, lbu, ubu, mpopt, ...\n N, fparm, H, Cw, z0, zl, zu, userfcn] = opf_args(mpc, mpopt);\n\n%% warn if there is more than one reference bus\nrefs = find(bus(:, BUS_TYPE) == REF);\nif length(refs) > 1 && mpopt.verbose > 0\n errstr = ['\\nopf_setup: Warning: Multiple reference buses.\\n', ...\n ' For a system with islands, a reference bus in each island\\n', ...\n ' may help convergence, but in a fully connected system such\\n', ...\n ' a situation is probably not reasonable.\\n\\n' ];\n fprintf(errstr);\nend\n\n%% set up initial variables and bounds\nVa = bus(:, VA) * (pi/180);\nVau = Inf(nb, 1); %% voltage angle limits\nVal = -Vau;\nVau(refs) = Va(refs); %% voltage angle reference constraints\nVal(refs) = Va(refs);\nPg = gen(:, PG) / baseMVA;\nPmin = gen(:, PMIN) / baseMVA;\nPmax = gen(:, PMAX) / baseMVA;\nif ~dc\n Vm = bus(:, VM);\n Qg = gen(:, QG) / baseMVA;\n Qmin = gen(:, QMIN) / baseMVA;\n Qmax = gen(:, QMAX) / baseMVA;\n if vcart\n V = Vm .* exp(1j*Va);\n Vr = real(V);\n Vi = imag(V);\n end\nend\n\n%% find/prepare polynomial generator costs\ncpg = [];\ncqg = [];\n%% reduce order where highest order has zero coefficient\ngc = mpc.gencost;\nwhile 1\n ii = find( gc(:, MODEL) == POLYNOMIAL & ...\n gc(:, NCOST) > 2 & ...\n gc(:, COST) == 0 );\n if isempty(ii), break; end %% exit loop if there are none\n gc(ii, NCOST) = gc(ii, NCOST) - 1; %% reduce order\n gc(ii, COST:end-1) = gc(ii, COST+1:end); %% shift coefficients\n gc(ii, end) = 0;\nend\n[pcost qcost] = pqcost(gc, ng);\nip0 = find(pcost(:, MODEL) == POLYNOMIAL & pcost(:, NCOST) == 1); %% constant\nip1 = find(pcost(:, MODEL) == POLYNOMIAL & pcost(:, NCOST) == 2); %% linear\nip2 = find(pcost(:, MODEL) == POLYNOMIAL & pcost(:, NCOST) == 3); %% quadratic\nip3 = find(pcost(:, MODEL) == POLYNOMIAL & pcost(:, NCOST) > 3); %% cubic or greater\nif ~isempty(ip2) || ~isempty(ip1) || ~isempty(ip0)\n kpg = zeros(ng, 1);\n cpg = zeros(ng, 1);\n if ~isempty(ip2)\n Qpg = zeros(ng, 1);\n Qpg(ip2) = 2 * pcost(ip2, COST) * baseMVA^2;\n cpg(ip2) = cpg(ip2) + pcost(ip2, COST+1) * baseMVA;\n kpg(ip2) = kpg(ip2) + pcost(ip2, COST+2);\n else\n Qpg = []; %% no quadratic terms\n end\n if ~isempty(ip1)\n cpg(ip1) = cpg(ip1) + pcost(ip1, COST) * baseMVA;\n kpg(ip1) = kpg(ip1) + pcost(ip1, COST+1);\n end\n if ~isempty(ip0)\n kpg(ip0) = kpg(ip0) + pcost(ip0, COST);\n end\nend\nif ~isempty(qcost)\n iq0 = find(qcost(:, MODEL) == POLYNOMIAL & qcost(:, NCOST) == 1); %% constant\n iq1 = find(qcost(:, MODEL) == POLYNOMIAL & qcost(:, NCOST) == 2); %% linear\n iq2 = find(qcost(:, MODEL) == POLYNOMIAL & qcost(:, NCOST) == 3); %% quadratic\n iq3 = find(qcost(:, MODEL) == POLYNOMIAL & qcost(:, NCOST) > 3); %% cubic or greater\n if ~isempty(iq2) || ~isempty(iq1) || ~isempty(iq0)\n kqg = zeros(ng, 1);\n cqg = zeros(ng, 1);\n if ~isempty(iq2)\n Qqg = zeros(ng, 1);\n Qqg(iq2) = 2 * qcost(iq2, COST) * baseMVA^2;\n cqg(iq2) = cqg(iq2) + qcost(iq2, COST+1) * baseMVA;\n kqg(iq2) = kqg(iq2) + qcost(iq2, COST+2);\n else\n Qqg = []; %% no quadratic terms\n end\n if ~isempty(iq1)\n cqg(iq1) = cqg(iq1) + qcost(iq1, COST) * baseMVA;\n kqg(iq1) = kqg(iq1) + qcost(iq1, COST+1);\n end\n if ~isempty(iq0)\n kqg(iq0) = kqg(iq0) + qcost(iq0, COST);\n end\n end\nend\n\n%% branch voltage angle difference limits\n[Aang, lang, uang, iang] = makeAang(baseMVA, branch, nb, mpopt);\nnang = length(iang);\n\nif dc %% DC model\n %% check generator costs\n if ~isempty(ip3)\n error('opf_setup: DC OPF cannot handle polynomial costs with higher than quadratic order.');\n end\n\n %% more problem dimensions\n nv = 0; %% number of voltage magnitude vars\n nq = 0; %% number of Qg vars\n q1 = []; %% index of 1st Qg column in Ay\n\n %% power mismatch constraints\n [B, Bf, Pbusinj, Pfinj] = makeBdc(baseMVA, bus, branch);\n neg_Cg = sparse(gen(:, GEN_BUS), 1:ng, -1, nb, ng); %% Pbus w.r.t. Pg\n Amis = [B neg_Cg];\n bmis = -(bus(:, PD) + bus(:, GS)) / baseMVA - Pbusinj;\n\n %% branch flow constraints\n il = find(branch(:, RATE_A) ~= 0 & branch(:, RATE_A) < 1e10);\n nl2 = length(il); %% number of constrained lines\n if nl2\n upf = branch(il, RATE_A) / baseMVA - Pfinj(il);\n upt = branch(il, RATE_A) / baseMVA + Pfinj(il);\n else\n upf = [];\n upt = [];\n end\n\n user_vars = {'Va', 'Pg'};\n ycon_vars = {'Pg', 'y'};\nelse %% AC model\n %% more problem dimensions\n nv = nb; %% number of voltage magnitude vars\n nq = ng; %% number of Qg vars\n q1 = 1+ng; %% index of 1st Qg column in Ay\n\n %% find branches with flow limits\n il = find(branch(:, RATE_A) ~= 0 & branch(:, RATE_A) < 1e10);\n nl2 = length(il); %% number of constrained lines\n\n %% build admittance matrices\n [Ybus, Yf, Yt] = makeYbus(baseMVA, bus, branch);\n\n %% dispatchable load, constant power factor constraints\n [Avl, lvl, uvl] = makeAvl(mpc);\n\n %% generator PQ capability curve constraints\n [Apqh, ubpqh, Apql, ubpql, Apqdata] = makeApq(baseMVA, gen);\n\n if vcart\n user_vars = {'Vr', 'Vi', 'Pg', 'Qg'};\n nodal_balance_vars = {'Vr', 'Vi', 'Pg', 'Qg'};\n flow_lim_vars = {'Vr', 'Vi'};\n else\n user_vars = {'Va', 'Vm', 'Pg', 'Qg'};\n nodal_balance_vars = {'Va', 'Vm', 'Pg', 'Qg'};\n flow_lim_vars = {'Va', 'Vm'};\n end\n ycon_vars = {'Pg', 'Qg', 'y'};\n\n %% nonlinear constraint functions\n if mpopt.opf.current_balance\n mis_cons = {'rImis', 'iImis'};\n fcn_mis = @(x)opf_current_balance_fcn(x, mpc, Ybus, mpopt);\n hess_mis = @(x, lam)opf_current_balance_hess(x, lam, mpc, Ybus, mpopt);\n else\n mis_cons = {'Pmis', 'Qmis'};\n fcn_mis = @(x)opf_power_balance_fcn(x, mpc, Ybus, mpopt);\n hess_mis = @(x, lam)opf_power_balance_hess(x, lam, mpc, Ybus, mpopt);\n end\n fcn_flow = @(x)opf_branch_flow_fcn(x, mpc, Yf(il, :), Yt(il, :), il, mpopt);\n hess_flow = @(x, lam)opf_branch_flow_hess(x, lam, mpc, Yf(il, :), Yt(il, :), il, mpopt);\n if vcart\n fcn_vref = @(x)opf_vref_fcn(x, mpc, refs, mpopt);\n hess_vref = @(x, lam)opf_vref_hess(x, lam, mpc, refs, mpopt);\n veq = find(mpc.bus(:, VMIN) == mpc.bus(:, VMAX));\n viq = find(mpc.bus(:, VMIN) ~= mpc.bus(:, VMAX));\n nveq = length(veq);\n nvlims = length(viq);\n if nveq\n fcn_veq = @(x)opf_veq_fcn(x, mpc, veq, mpopt);\n hess_veq = @(x, lam)opf_veq_hess(x, lam, mpc, veq, mpopt);\n end\n fcn_vlim = @(x)opf_vlim_fcn(x, mpc, viq, mpopt);\n hess_vlim = @(x, lam)opf_vlim_hess(x, lam, mpc, viq, mpopt);\n fcn_ang = @(x)opf_branch_ang_fcn(x, Aang, lang, uang);\n hess_ang = @(x, lam)opf_branch_ang_hess(x, lam, Aang, lang, uang);\n end\n \n %% nonlinear cost functions\n if ~isempty(ip3)\n cost_Pg = @(x)opf_gen_cost_fcn(x, baseMVA, pcost, ip3);\n end\n if ~isempty(qcost) && ~isempty(iq3)\n cost_Qg = @(x)opf_gen_cost_fcn(x, baseMVA, qcost, iq3);\n end\nend\n\n%% basin constraints for piece-wise linear gen cost variables\nif (strcmp(alg, 'PDIPM') && mpopt.pdipm.step_control) || strcmp(alg, 'TRALM')\n %% SC-PDIPM or TRALM, no CCV cost vars\n ny = 0;\n Ay = sparse(0, ng+nq);\n by =[];\nelse\n ipwl = find(gencost(:, MODEL) == PW_LINEAR); %% piece-wise linear costs\n ny = size(ipwl, 1); %% number of piece-wise linear cost vars\n [Ay, by] = makeAy(baseMVA, ng, gencost, 1, q1, 1+ng+nq);\nend\nif any(gencost(:, MODEL) ~= POLYNOMIAL & gencost(:, MODEL) ~= PW_LINEAR)\n error('opf_setup: some generator cost rows have invalid MODEL value');\nend\n\n%% more problem dimensions\nnx = nb+nv + ng+nq; %% number of standard OPF control variables\nif nlin\n nz = size(mpc.A, 2) - nx; %% number of user z variables\n if nz < 0\n error('opf_setup: user supplied A matrix must have at least %d columns.', nx);\n end\nelse\n nz = 0; %% number of user z variables\n if nw %% still need to check number of columns of N\n if size(mpc.N, 2) ~= nx;\n error('opf_setup: user supplied N matrix must have %d columns.', nx);\n end\n end\nend\n\n%% construct OPF model object\nom = opf_model(mpc);\nif ~isempty(pwl1)\n om.userdata.pwl1 = pwl1;\nend\nom.userdata.iang = iang;\nif dc\n %% user data\n om.userdata.Bf = Bf;\n om.userdata.Pfinj = Pfinj;\n\n %% optimization variables\n om.add_var('Va', nb, Va, Val, Vau);\n om.add_var('Pg', ng, Pg, Pmin, Pmax);\n\n %% linear constraints\n om.add_lin_constraint('Pmis', Amis, bmis, bmis, {'Va', 'Pg'}); %% nb\n om.add_lin_constraint('Pf', Bf(il,:), -upt, upf, {'Va'}); %% nl2\n om.add_lin_constraint('ang', Aang, lang, uang, {'Va'}); %% nang\n\n %% quadratic generator costs\n if ~isempty(cpg)\n om.add_quad_cost('polPg', Qpg, cpg, kpg, {'Pg'});\n end\nelse\n %% user data\n om.userdata.Apqdata = Apqdata;\n\n %% optimization variables\n if vcart\n Vclim = 1.1 * bus(:, VMAX);\n om.add_var('Vr', nb, Vr, -Vclim, Vclim);\n om.add_var('Vi', nb, Vi, -Vclim, Vclim);\n else\n om.add_var('Va', nb, Va, Val, Vau);\n om.add_var('Vm', nb, Vm, bus(:, VMIN), bus(:, VMAX));\n end\n om.add_var('Pg', ng, Pg, Pmin, Pmax);\n om.add_var('Qg', ng, Qg, Qmin, Qmax);\n\n %% nonlinear constraints\n om.add_nln_constraint(mis_cons, [nb;nb], 1, fcn_mis, hess_mis, nodal_balance_vars);\n if legacy_formulation\n om.add_nln_constraint({'Sf', 'St'}, [nl;nl], 0, fcn_flow, hess_flow, flow_lim_vars);\n else\n om.add_nln_constraint({'Sf', 'St'}, [nl2;nl2], 0, fcn_flow, hess_flow, flow_lim_vars);\n end\n if vcart\n om.userdata.veq = veq; %% buses with voltage magnitude equality constraints\n om.userdata.viq = viq; %% buses with voltage magnitude limits\n om.add_nln_constraint('Vref', length(refs), 1, fcn_vref, hess_vref, {'Vr', 'Vi'});\n if nveq\n om.add_nln_constraint('Veq', nveq, 1, fcn_veq, hess_veq, {'Vr', 'Vi'});\n end\n om.add_nln_constraint({'Vmin', 'Vmax'}, [nvlims;nvlims], 0, fcn_vlim, hess_vlim, {'Vr', 'Vi'});\n om.add_nln_constraint({'angL', 'angU'}, [nang;nang], 0, fcn_ang, hess_ang, {'Vr', 'Vi'});\n end\n\n %% linear constraints\n om.add_lin_constraint('PQh', Apqh, [], ubpqh, {'Pg', 'Qg'}); %% npqh\n om.add_lin_constraint('PQl', Apql, [], ubpql, {'Pg', 'Qg'}); %% npql\n om.add_lin_constraint('vl', Avl, lvl, uvl, {'Pg', 'Qg'}); %% nvl\n if ~vcart\n om.add_lin_constraint('ang', Aang, lang, uang, {'Va'}); %% nang\n end\n\n %% polynomial generator costs\n if ~legacy_formulation\n %% quadratic/linear generator costs\n if ~isempty(cpg)\n om.add_quad_cost('polPg', Qpg, cpg, kpg, {'Pg'});\n end\n if ~isempty(cqg)\n om.add_quad_cost('polQg', Qqg, cqg, kqg, {'Qg'});\n end\n\n %% higher order polynomial generator costs\n if ~isempty(ip3)\n om.add_nln_cost('polPg', 1, cost_Pg, {'Pg'});\n end\n if ~isempty(qcost) && ~isempty(iq3)\n om.add_nln_cost('polQg', 1, cost_Qg, {'Qg'});\n end\n end\nend\n\n%% y vars, constraints for piece-wise linear gen costs\nif ny > 0\n om.add_var('y', ny);\n om.add_lin_constraint('ycon', Ay, [], by, ycon_vars); %% ncony\n if dc || ~legacy_formulation\n om.add_quad_cost('pwl', [], ones(ny, 1), 0, {'y'});\n end\nend\n\n%% add user vars, constraints and costs (as specified via A, ..., N, ...)\nif nz > 0\n om.add_var('z', nz, z0, zl, zu);\n user_vars{end+1} = 'z';\nend\nif nlin\n om.add_lin_constraint('usr', mpc.A, lbu, ubu, user_vars); %% nlin\nend\nif nnle\n for k = 1:length(mpc.user_constraints.nle)\n nlc = mpc.user_constraints.nle{k};\n fcn = eval(['@(x)' nlc{3} '(x, nlc{6}{:})']);\n hess = eval(['@(x, lam)' nlc{4} '(x, lam, nlc{6}{:})']);\n om.add_nln_constraint(nlc{1:2}, 1, fcn, hess, nlc{5});\n end\nend\nif nnli\n for k = 1:length(mpc.user_constraints.nli)\n nlc = mpc.user_constraints.nli{k};\n fcn = eval(['@(x)' nlc{3} '(x, nlc{6}{:})']);\n hess = eval(['@(x, lam)' nlc{4} '(x, lam, nlc{6}{:})']);\n om.add_nln_constraint(nlc{1:2}, 0, fcn, hess, nlc{5});\n end\nend\nif nw\n user_cost.N = mpc.N;\n user_cost.Cw = Cw;\n if ~isempty(fparm)\n user_cost.dd = fparm(:, 1);\n user_cost.rh = fparm(:, 2);\n user_cost.kk = fparm(:, 3);\n user_cost.mm = fparm(:, 4);\n end\n if ~isempty(H)\n user_cost.H = H;\n end\n om.add_legacy_cost('usr', user_cost, user_vars);\nend\n\n%% execute userfcn callbacks for 'formulation' stage\nom = run_userfcn(userfcn, 'formulation', om, mpopt);\n\n%% implement legacy user costs using quadratic or general non-linear costs\ncp = om.params_legacy_cost(); %% construct/fetch the parameters\n[N, H, Cw, rh, mm] = deal(cp.N, cp.H, cp.Cw, cp.rh, cp.mm);\n[nw, nx] = size(N);\nif nw\n if any(cp.dd ~= 1) || any(cp.kk) %% not simple quadratic form\n if dc %% (includes \"dead zone\" or\n if any(cp.dd ~= 1) %% quadratic \"penalty\")\n error('opf_setup: DC OPF can only handle legacy user-defined costs with d = 1');\n end\n if any(cp.kk)\n error('opf_setup: DC OPF can only handle legacy user-defined costs with no \"dead zone\", i.e. k = 0');\n end\n elseif ~legacy_formulation\n %% use general nonlinear cost to implement legacy user cost\n legacy_cost_fcn = @(x)opf_legacy_user_cost_fcn(x, cp);\n om.add_nln_cost('usr', 1, legacy_cost_fcn);\n end\n else %% simple quadratic form\n %% use a quadratic cost to implement legacy user cost\n if dc || ~legacy_formulation\n %% f = 1/2 * w'*H*w + Cw'*w, where w = diag(mm)*(N*x - rh)\n %% Let: MN = diag(mm)*N\n %% MR = M * rh\n %% HMR = H * MR;\n %% HtMR = H' * MR;\n %% => w = MN*x - MR\n %% f = 1/2 * (MN*x - MR)'*H*(MN*x - MR) + Cw'*(MN*x - MR)\n %% = 1/2 * x'*MN'*H*MN*x +\n %% (Cw'*MN - 1/2 * MR'*(H+H')*MN)*x +\n %% 1/2 * MR'*H*MR - Cw'*MR\n %% = 1/2 * x'*Q*w + c'*x + k\n \n M = sparse(1:nw, 1:nw, mm, nw, nw);\n MN = M * N;\n MR = M * rh;\n HMR = H * MR;\n HtMR = H' * MR;\n Q = MN' * H * MN;\n c = full(MN' * (Cw - 1/2*(HMR+HtMR)));\n k = (1/2 * HtMR - Cw)' * MR;\n om.add_quad_cost('usr', Q, c, k);\n end\n end\nend\n", "meta": {"author": "MATPOWER", "repo": "matpower", "sha": "7da926d978824bf675a71e0a5cb91f8967f97007", "save_path": "github-repos/MATLAB/MATPOWER-matpower", "path": "github-repos/MATLAB/MATPOWER-matpower/matpower-7da926d978824bf675a71e0a5cb91f8967f97007/lib/opf_setup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339457, "lm_q2_score": 0.02800751837488136, "lm_q1q2_score": 0.009764685034178483}} {"text": "function sensor_data = kspaceFirstOrder_extractSensorData(dim, sensor_data, file_index, sensor_mask_index, record, p, ux_sgx, uy_sgy, uz_sgz)\n% DESCRIPTION:\n% Function to extract the required sensor data from the acoustic\n% variables at each time step. This is defined as a function rather\n% than a script to avoid the computational overhead of using scripts\n% to access variables local to another function. For k-Wave < V1.1,\n% this code was included directly in the simulation functions.\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 9th July 2013\n% last update - 6th September 2013\n% \n% This function is part of the k-Wave Toolbox (http://www.k-wave.org)\n% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox\n\n% This file is part of k-Wave. k-Wave is free software: you can\n% redistribute it and/or modify it under the terms of the GNU Lesser\n% General Public License as published by the Free Software Foundation,\n% either version 3 of the License, or (at your option) any later version.\n% \n% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY\n% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n% FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for\n% more details. \n% \n% You should have received a copy of the GNU Lesser General Public License\n% along with k-Wave. If not, see .\n\n% =========================================================================\n% GRID STAGGERING\n% =========================================================================\n\n% shift the components of the velocity field onto the non-staggered\n% grid if required for output\nif (...\n record.u_non_staggered || ...\n record.I || ...\n record.I_avg)\n\n switch dim\n case 1\n ux_shifted = real(ifft(bsxfun(@times, record.x_shift_neg, fft(ux_sgx, [], 1)), [], 1));\n case 2\n ux_shifted = real(ifft(bsxfun(@times, record.x_shift_neg, fft(ux_sgx, [], 1)), [], 1));\n uy_shifted = real(ifft(bsxfun(@times, record.y_shift_neg, fft(uy_sgy, [], 2)), [], 2));\n case 3\n ux_shifted = real(ifft(bsxfun(@times, record.x_shift_neg, fft(ux_sgx, [], 1)), [], 1));\n uy_shifted = real(ifft(bsxfun(@times, record.y_shift_neg, fft(uy_sgy, [], 2)), [], 2));\n uz_shifted = real(ifft(bsxfun(@times, record.z_shift_neg, fft(uz_sgz, [], 3)), [], 3));\n end\nend\n\n% =========================================================================\n% BINARY SENSOR MASK\n% =========================================================================\n\nif record.binary_sensor_mask\n \n % store the time history of the acoustic pressure\n if record.p || record.I || record.I_avg\n if ~record.compute_directivity\n sensor_data.p(:, file_index) = p(sensor_mask_index);\n end\n end\n\n % store the maximum acoustic pressure\n if record.p_max\n if file_index == 1\n sensor_data.p_max = p(sensor_mask_index);\n else\n sensor_data.p_max = max(sensor_data.p_max, p(sensor_mask_index));\n end\n end\n\n % store the minimum acoustic pressure\n if record.p_min\n if file_index == 1\n sensor_data.p_min = p(sensor_mask_index);\n else\n sensor_data.p_min = min(sensor_data.p_min, p(sensor_mask_index));\n end \n end\n\n % store the rms acoustic pressure\n if record.p_rms\n sensor_data.p_rms = sqrt((sensor_data.p_rms.^2*(file_index - 1) + p(sensor_mask_index).^2)./file_index);\n end\n \n % store the time history of the particle velocity on the staggered grid\n if record.u\n switch dim\n case 1\n sensor_data.ux(:, file_index) = ux_sgx(sensor_mask_index);\n case 2\n sensor_data.ux(:, file_index) = ux_sgx(sensor_mask_index);\n sensor_data.uy(:, file_index) = uy_sgy(sensor_mask_index); \n case 3\n sensor_data.ux(:, file_index) = ux_sgx(sensor_mask_index);\n sensor_data.uy(:, file_index) = uy_sgy(sensor_mask_index); \n sensor_data.uz(:, file_index) = uz_sgz(sensor_mask_index); \n end\n end\n \n % store the time history of the particle velocity\n if record.u_non_staggered || record.I || record.I_avg\n switch dim\n case 1\n sensor_data.ux_non_staggered(:, file_index) = ux_shifted(sensor_mask_index);\n case 2\n sensor_data.ux_non_staggered(:, file_index) = ux_shifted(sensor_mask_index);\n sensor_data.uy_non_staggered(:, file_index) = uy_shifted(sensor_mask_index); \n case 3\n sensor_data.ux_non_staggered(:, file_index) = ux_shifted(sensor_mask_index);\n sensor_data.uy_non_staggered(:, file_index) = uy_shifted(sensor_mask_index); \n sensor_data.uz_non_staggered(:, file_index) = uz_shifted(sensor_mask_index); \n end\n end\n\n % store the maximum particle velocity\n if record.u_max\n if file_index == 1\n switch dim\n case 1\n sensor_data.ux_max = ux_sgx(sensor_mask_index);\n case 2\n sensor_data.ux_max = ux_sgx(sensor_mask_index);\n sensor_data.uy_max = uy_sgy(sensor_mask_index);\n case 3\n sensor_data.ux_max = ux_sgx(sensor_mask_index);\n sensor_data.uy_max = uy_sgy(sensor_mask_index);\n sensor_data.uz_max = uz_sgz(sensor_mask_index);\n end\n else\n switch dim\n case 1\n sensor_data.ux_max = max(sensor_data.ux_max, ux_sgx(sensor_mask_index));\n case 2\n sensor_data.ux_max = max(sensor_data.ux_max, ux_sgx(sensor_mask_index)); \n sensor_data.uy_max = max(sensor_data.uy_max, uy_sgy(sensor_mask_index)); \n case 3\n sensor_data.ux_max = max(sensor_data.ux_max, ux_sgx(sensor_mask_index)); \n sensor_data.uy_max = max(sensor_data.uy_max, uy_sgy(sensor_mask_index)); \n sensor_data.uz_max = max(sensor_data.uz_max, uz_sgz(sensor_mask_index)); \n end\n end\n end \n\n % store the minimum particle velocity\n if record.u_min\n if file_index == 1\n switch dim\n case 1\n sensor_data.ux_min = ux_sgx(sensor_mask_index); \n case 2\n sensor_data.ux_min = ux_sgx(sensor_mask_index);\n sensor_data.uy_min = uy_sgy(sensor_mask_index); \n case 3\n sensor_data.ux_min = ux_sgx(sensor_mask_index);\n sensor_data.uy_min = uy_sgy(sensor_mask_index);\n sensor_data.uz_min = uz_sgz(sensor_mask_index);\n end\n else\n switch dim\n case 1\n sensor_data.ux_min = min(sensor_data.ux_min, ux_sgx(sensor_mask_index)); \n case 2\n sensor_data.ux_min = min(sensor_data.ux_min, ux_sgx(sensor_mask_index)); \n sensor_data.uy_min = min(sensor_data.uy_min, uy_sgy(sensor_mask_index)); \n case 3\n sensor_data.ux_min = min(sensor_data.ux_min, ux_sgx(sensor_mask_index)); \n sensor_data.uy_min = min(sensor_data.uy_min, uy_sgy(sensor_mask_index)); \n sensor_data.uz_min = min(sensor_data.uz_min, uz_sgz(sensor_mask_index)); \n end \n end\n end \n\n % store the rms particle velocity\n if record.u_rms\n switch dim\n case 1\n sensor_data.ux_rms(:) = sqrt((sensor_data.ux_rms(:).^2*(file_index - 1) + ux_sgx(sensor_mask_index).^2)./file_index);\n case 2\n sensor_data.ux_rms(:) = sqrt((sensor_data.ux_rms(:).^2*(file_index - 1) + ux_sgx(sensor_mask_index).^2)./file_index);\n sensor_data.uy_rms(:) = sqrt((sensor_data.uy_rms(:).^2*(file_index - 1) + uy_sgy(sensor_mask_index).^2)./file_index);\n case 3\n sensor_data.ux_rms(:) = sqrt((sensor_data.ux_rms(:).^2*(file_index - 1) + ux_sgx(sensor_mask_index).^2)./file_index);\n sensor_data.uy_rms(:) = sqrt((sensor_data.uy_rms(:).^2*(file_index - 1) + uy_sgy(sensor_mask_index).^2)./file_index);\n sensor_data.uz_rms(:) = sqrt((sensor_data.uz_rms(:).^2*(file_index - 1) + uz_sgz(sensor_mask_index).^2)./file_index);\n end \n end \n\n% =========================================================================\n% CARTESIAN SENSOR MASK\n% =========================================================================\n \n% extract data from specified Cartesian coordinates using interpolation\n% (record.record.tri and record.record.bc are the Delaunay triangulation\n% and Barycentric coordinates returned by gridDataFast3D)\nelse\n\n % store the time history of the acoustic pressure\n if record.p || record.I || record.I_avg\n if dim == 1\n sensor_data.p(:, file_index) = interp1(record.grid_x, p, record.sensor_x);\n else\n sensor_data.p(:, file_index) = sum(p(record.tri) .* record.bc, 2);\n end\n end\n\n % store the maximum acoustic pressure\n if record.p_max\n if dim == 1\n if file_index == 1\n sensor_data.p_max = interp1(record.grid_x, p, record.sensor_x);\n else\n sensor_data.p_max = max(sensor_data.p_max, interp1(record.grid_x, p, record.sensor_x));\n end \n else\n if file_index == 1\n sensor_data.p_max = sum(p(record.tri) .* record.bc, 2);\n else\n sensor_data.p_max = max(sensor_data.p_max, sum(p(record.tri) .* record.bc, 2));\n end\n end\n end \n\n % store the minimum acoustic pressure\n if record.p_min\n if dim == 1\n if file_index == 1\n sensor_data.p_min = interp1(record.grid_x, p, record.sensor_x);\n else\n sensor_data.p_min = min(sensor_data.p_min, interp1(record.grid_x, p, record.sensor_x));\n end \n else\n if file_index == 1\n sensor_data.p_min = sum(p(record.tri) .* record.bc, 2);\n else\n sensor_data.p_min = min(sensor_data.p_min, sum(p(record.tri) .* record.bc, 2));\n end\n end\n end \n\n % store the rms acoustic pressure\n if record.p_rms\n if dim == 1\n sensor_data.p_rms = sqrt((sensor_data.p_rms.^2*(file_index - 1) + (interp1(record.grid_x, p, record.sensor_x)).^2)./file_index);\n else\n sensor_data.p_rms(:) = sqrt((sensor_data.p_rms(:).^2*(file_index - 1) + (sum(p(record.tri) .* record.bc, 2)).^2)./file_index);\n end\n end\n\n % store the time history of the particle velocity on the staggered grid\n if record.u\n switch dim\n case 1\n sensor_data.ux(:, file_index) = interp1(record.grid_x, ux_sgx, record.sensor_x);\n case 2\n sensor_data.ux(:, file_index) = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy(:, file_index) = sum(uy_sgy(record.tri) .* record.bc, 2); \n case 3\n sensor_data.ux(:, file_index) = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy(:, file_index) = sum(uy_sgy(record.tri) .* record.bc, 2);\n sensor_data.uz(:, file_index) = sum(uz_sgz(record.tri) .* record.bc, 2);\n end\n end\n\n % store the time history of the particle velocity\n if record.u_non_staggered || record.I || record.I_avg\n switch dim\n case 1\n sensor_data.ux_non_staggered(:, file_index) = interp1(record.grid_x, ux_shifted, record.sensor_x);\n case 2\n sensor_data.ux_non_staggered(:, file_index) = sum(ux_shifted(record.tri) .* record.bc, 2);\n sensor_data.uy_non_staggered(:, file_index) = sum(uy_shifted(record.tri) .* record.bc, 2); \n case 3\n sensor_data.ux_non_staggered(:, file_index) = sum(ux_shifted(record.tri) .* record.bc, 2);\n sensor_data.uy_non_staggered(:, file_index) = sum(uy_shifted(record.tri) .* record.bc, 2);\n sensor_data.uz_non_staggered(:, file_index) = sum(uz_shifted(record.tri) .* record.bc, 2);\n end\n end\n \n % store the maximum particle velocity\n if record.u_max\n if file_index == 1\n switch dim\n case 1\n sensor_data.ux_max = interp1(record.grid_x, ux_sgx, record.sensor_x);\n case 2\n sensor_data.ux_max = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy_max = sum(uy_sgy(record.tri) .* record.bc, 2); \n case 3\n sensor_data.ux_max = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy_max = sum(uy_sgy(record.tri) .* record.bc, 2);\n sensor_data.uz_max = sum(uz_sgz(record.tri) .* record.bc, 2);\n end\n else\n switch dim\n case 1\n sensor_data.ux_max = max(sensor_data.ux_max, interp1(record.grid_x, ux_sgx, record.sensor_x));\n case 2\n sensor_data.ux_max = max(sensor_data.ux_max, sum(ux_sgx(record.tri) .* record.bc, 2));\n sensor_data.uy_max = max(sensor_data.uy_max, sum(uy_sgy(record.tri) .* record.bc, 2));\n case 3\n sensor_data.ux_max = max(sensor_data.ux_max, sum(ux_sgx(record.tri) .* record.bc, 2));\n sensor_data.uy_max = max(sensor_data.uy_max, sum(uy_sgy(record.tri) .* record.bc, 2));\n sensor_data.uz_max = max(sensor_data.uz_max, sum(uz_sgz(record.tri) .* record.bc, 2));\n end\n end\n end \n\n % store the minimum particle velocity\n if record.u_min\n if file_index == 1\n switch dim\n case 1\n sensor_data.ux_min = interp1(record.grid_x, ux_sgx, record.sensor_x);\n case 2\n sensor_data.ux_min = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy_min = sum(uy_sgy(record.tri) .* record.bc, 2); \n case 3\n sensor_data.ux_min = sum(ux_sgx(record.tri) .* record.bc, 2);\n sensor_data.uy_min = sum(uy_sgy(record.tri) .* record.bc, 2);\n sensor_data.uz_min = sum(uz_sgz(record.tri) .* record.bc, 2);\n end\n else\n switch dim\n case 1\n sensor_data.ux_min = min(sensor_data.ux_min, interp1(record.grid_x, ux_sgx, record.sensor_x));\n case 2\n sensor_data.ux_min = min(sensor_data.ux_min, sum(ux_sgx(record.tri) .* record.bc, 2));\n sensor_data.uy_min = min(sensor_data.uy_min, sum(uy_sgy(record.tri) .* record.bc, 2));\n case 3\n sensor_data.ux_min = min(sensor_data.ux_min, sum(ux_sgx(record.tri) .* record.bc, 2));\n sensor_data.uy_min = min(sensor_data.uy_min, sum(uy_sgy(record.tri) .* record.bc, 2));\n sensor_data.uz_min = min(sensor_data.uz_min, sum(uz_sgz(record.tri) .* record.bc, 2));\n end\n end\n end \n\n % store the rms particle velocity\n if record.u_rms\n switch dim\n case 1\n sensor_data.ux_rms = sqrt((sensor_data.ux_rms.^2*(file_index - 1) + (interp1(record.grid_x, ux_sgx, record.sensor_x)).^2)./file_index);\n case 2\n sensor_data.ux_rms(:) = sqrt((sensor_data.ux_rms(:).^2*(file_index - 1) + (sum(ux_sgx(record.tri) .* record.bc, 2)).^2)./file_index);\n sensor_data.uy_rms(:) = sqrt((sensor_data.uy_rms(:).^2*(file_index - 1) + (sum(uy_sgy(record.tri) .* record.bc, 2)).^2)./file_index);\n case 3\n sensor_data.ux_rms(:) = sqrt((sensor_data.ux_rms(:).^2*(file_index - 1) + (sum(ux_sgx(record.tri) .* record.bc, 2)).^2)./file_index);\n sensor_data.uy_rms(:) = sqrt((sensor_data.uy_rms(:).^2*(file_index - 1) + (sum(uy_sgy(record.tri) .* record.bc, 2)).^2)./file_index);\n sensor_data.uz_rms(:) = sqrt((sensor_data.uz_rms(:).^2*(file_index - 1) + (sum(uz_sgz(record.tri) .* record.bc, 2)).^2)./file_index);\n end\n end \nend\n\n% =========================================================================\n% RECORDED VARIABLES OVER ENTIRE GRID\n% =========================================================================\n\n% store the maximum acoustic pressure over all the grid elements\nif record.p_max_all\n switch dim\n case 1\n if file_index == 1\n sensor_data.p_max_all = p(record.x1_inside:record.x2_inside);\n else\n sensor_data.p_max_all = max(sensor_data.p_max_all, p(record.x1_inside:record.x2_inside));\n end\n case 2\n if file_index == 1\n sensor_data.p_max_all = p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n else\n sensor_data.p_max_all = max(sensor_data.p_max_all, p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside));\n end\n case 3\n if file_index == 1\n sensor_data.p_max_all = p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n else\n sensor_data.p_max_all = max(sensor_data.p_max_all, p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside));\n end\n end\nend\n\n% store the minimum acoustic pressure over all the grid elements\nif record.p_min_all\n switch dim\n case 1\n if file_index == 1\n sensor_data.p_min_all = p(record.x1_inside:record.x2_inside);\n else\n sensor_data.p_min_all = min(sensor_data.p_min_all, p(record.x1_inside:record.x2_inside));\n end \n case 2\n if file_index == 1\n sensor_data.p_min_all = p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n else\n sensor_data.p_min_all = min(sensor_data.p_min_all, p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside));\n end \n case 3\n if file_index == 1\n sensor_data.p_min_all = p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n else\n sensor_data.p_min_all = min(sensor_data.p_min_all, p(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside));\n end \n end\nend \n\n% store the maximum particle velocity over all the grid elements\nif record.u_max_all\n switch dim\n case 1\n if file_index == 1\n sensor_data.ux_max_all = ux_sgx(record.x1_inside:record.x2_inside);\n else\n sensor_data.ux_max_all = max(sensor_data.ux_max_all, ux_sgx(record.x1_inside:record.x2_inside)); \n end \n case 2\n if file_index == 1\n sensor_data.ux_max_all = ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n sensor_data.uy_max_all = uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n else\n sensor_data.ux_max_all = max(sensor_data.ux_max_all, ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside)); \n sensor_data.uy_max_all = max(sensor_data.uy_max_all, uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside)); \n end \n case 3\n if file_index == 1\n sensor_data.ux_max_all = ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n sensor_data.uy_max_all = uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n sensor_data.uz_max_all = uz_sgz(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n else\n sensor_data.ux_max_all = max(sensor_data.ux_max_all, ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n sensor_data.uy_max_all = max(sensor_data.uy_max_all, uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n sensor_data.uz_max_all = max(sensor_data.uz_max_all, uz_sgz(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n end\n end\nend \n\n% store the minimum particle velocity over all the grid elements\nif record.u_min_all\n switch dim\n case 1\n if file_index == 1\n sensor_data.ux_min_all = ux_sgx(record.x1_inside:record.x2_inside);\n else\n sensor_data.ux_min_all = min(sensor_data.ux_min_all, ux_sgx(record.x1_inside:record.x2_inside)); \n end \n case 2 \n if file_index == 1\n sensor_data.ux_min_all = ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n sensor_data.uy_min_all = uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside);\n else\n sensor_data.ux_min_all = min(sensor_data.ux_min_all, ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside)); \n sensor_data.uy_min_all = min(sensor_data.uy_min_all, uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside)); \n end\n case 3\n if file_index == 1\n sensor_data.ux_min_all = ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n sensor_data.uy_min_all = uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n sensor_data.uz_min_all = uz_sgz(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside);\n else\n sensor_data.ux_min_all = min(sensor_data.ux_min_all, ux_sgx(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n sensor_data.uy_min_all = min(sensor_data.uy_min_all, uy_sgy(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n sensor_data.uz_min_all = min(sensor_data.uz_min_all, uz_sgz(record.x1_inside:record.x2_inside, record.y1_inside:record.y2_inside, record.z1_inside:record.z2_inside)); \n end\n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/private/kspaceFirstOrder_extractSensorData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108836623764, "lm_q2_score": 0.02368947052393842, "lm_q1q2_score": 0.009738999160590144}} {"text": "function r = parse_formula(varargin)\n\n% PARSE_FORMULA Parses a chemical formula to form an atomic representation.\n%\n% SYNTAX\n%\n% r = parse_formula(str)\n% r = parse_formula({str1,str2,str3, ...})\n%\n% Parses chemical formulas and returns a structure array holding the an\n% atomic representation of the chemical forulas. The input is a string or\n% a cell array of strings.\n%\n%\n% EXAMPLES\n% \n% 1. Chemical formulas of varying complexity\n% \n% parse_formula('H2O'); % Water\n% parse_formula('NaHCO3'); % Sodium Bicarbonate\n% parse_formula('(CH4)8(H2O)46'); % Methane Clathrate\n% parse_formula('CH3COOCH2CH3'); % Ethyl Acetate\n% parse_formula('MnO4-'); % Negative Charge Ion\n%\n% parse_formula('dCH4'); % Returns error message\n%\n% 2. Create an structure array of atomic representations for a set of\n% compounds\n%\n% r = parse_formula({'CH4','O2','CO2','H2O'});\n%\n%\n% USAGE NOTES\n%\n% 1. Formulas are made of up of sequences of elements followed by\n% integers indicating the number of included atoms. Omitted integers\n% are assumed to be one.\n%\n% 2. Elements are the conventional one or two character abbreviations.\n% The character is captialized. If present, the second character is\n% lower case. In addition to the standard elements, the parser allows\n% for\n%\n% Symbol Entity Interpretation\n% e electron like an element with MW = 0\n% D deuterium an element\n% T tritium an element\n% M any metal like an element, mw = NaN\n% X any halogen like an element, mw = NaN\n% Me methyl group (CH3) CH3 substituted for Me\n% Et ethyl group (C2H5) C2H5 substituted for Et\n% Bu butyl group (C4H9) C4H9 substituted for Bu\n% Ph phenol group (C6H5) C6H5 substituted for Ph\n%\n% 3. Subgroups may be included between parenthesis or brackets followed\n% by an integer indicating number of repetitions. Two levels of\n% subgrouping are allowed.\n%\n% 4. A terminal lower case suffix denoting phases will be correctly\n% parsed. The phase must be one of (aq), (l), (g), or (s).\n%\n% 5. The charge on an ionic species is appended as a + or - followed by\n% an optional integer. Examples are H+, OH-, or Ca+2.\n%\n% 6. The bare electron e- is used in balancing chemical half reactions.\n%\n% 7. Error messages are generated for invalid fomulas\n% Change for use with the cobra toolbox\n% A is accepted as the symbol for an element that could\n% represent an R group in an atom mapping scenario for an incompletely\n% defined metabolite.\n%\n% 8. str can be a cell array of chemical formula. The results is a\n% structure array. The elements of the output structure array are in\n% one-to-one correspondence with elements of the cell array. For\n% example\n%\n% r = parse_formula({'CH4','CH3OH','CHOOH'})\n%\n% r(1) holds the atomic formula for CH4, r(2) for CH3OH, and r(3) for\n% CHOOH.\n\n% AUTHOR\n%\n% Jeff Kantor\n% December 18, 2010\n\n\n assert(nargin > 0, 'parse_formula:input', ['No input. Expects a ', ...\n 'string or cell array of chemical formulas.']);\n assert(nargin < 2, 'stoich:input', 'Unexpected extra inputs.');\n \n switch class(varargin{1})\n case 'char' % Single formula\n str = varargin;\n \n case 'cell' % Cell array of formulas\n str = varargin{1};\n \n otherwise\n error('parse_formula:input',['requires cell array of ',...\n 'chemical formulas.']);\n end\n \n assert(iscellstr(str), 'parse_formula:input', ...\n 'Formulas must be strings.');\n \n % Trim any whitespace at front or back\n \n str = strtrim(str);\n \n % Remove phase information. This information is currently neglected. In\n % a later version we may wish to incorporate phase into a more complete\n % data structure for representing chemical formula.\n \n prex = '|\\((aq|g|l|s)\\)$';\n str = regexprep(str,prex,'');\n \n % Substitute for some common chemical abbreviations\n \n str = regexprep(str,'Bu','C4H9'); % Butyl\n str = regexprep(str,'Et','C2H5'); % Ethyl\n str = regexprep(str,'Me','CH3'); % Methyl\n str = regexprep(str,'Ph','C6H5'); % Phenol\n\n % Apply the main parser to every element of str\n\n q = cellfun(@(s)parse_formula_(s,3),str,'Uniform',false);\n\n % Union of all atomic species\n\n atoms = {};\n for i = 1:length(q(:))\n atoms = union(atoms, fields(q{i}));\n end\n \n % Add all atomic species to all structures.\n\n for i = 1:length(q(:))\n for j = 1:length(atoms)\n if ~ismember(atoms{j},fields(q{i}))\n q{i}.(atoms{j}) = 0;\n end\n end\n end\n\n % Form the structure array to have the same shape as str\n \n r = reshape([q{:}],size(str));\n \nend % parse_formula\n\n\nfunction r = parse_formula_(str,kdepth)\n\n assert(kdepth > 0, 'parse_formula_:Recursion', ...\n 'Reached maximum recursion depth');\n\n r = struct([]);\n \n % Regular expression returning tokens for element and number\n % sexpr matches single elements followed by a digit, or a +/-\n % followed by a digit to denote charge\n \n persistent srex; % Regexp pattern to match elements and charges\n persistent grex; % Regexp pattern to match groups\n \n if isempty(srex) || isempty(grex)\n %this was the original line\n %srex = ['(A[lrsgutcm]|B[eraik]?|C[laroudsemf]?|D[y]?|E[urs]|',...\n srex = ['(A[lrsgutcm]?|B[eraik]?|C[laroudsemf]?|D[y]?|E[urs]|', ...\n 'F[erm]?|G[aed]|H[eofgas]?|I[nr]?|Kr?|L[iaur]|', ...\n 'M[gnodt]?|N[eaibdpos]?|Os?|P[drmtboau]?|R[buhenaf]|', ...\n 'S[icernbmg]?|T[icebmalh]?|U|V|W|X[e]?|Yb?|Z[nr])', ...\n '(\\d*\\.\\d+|\\d*)', ...\n '|(e|+|-)(\\d*)'];\n grex = '|\\(([^\\)]*)\\)(\\d*\\.\\d+|\\d*)|\\[([^\\]]*)\\](\\d*\\.\\d+|\\d*)';\n end\n\n % Parse formula for chemical groups. This picks out anything that looks\n % an element followed by a number, or a subgroup within parentheses.\n % The tokens are returned in the cell array u. Each u{k} has two\n % elements, the first is a string denoting the group, and the second is\n % number string of repetitions.\n\n [u,s,e] = regexp(str,[srex,grex],'tokens','start','end');\n\n % Report any parsing errors. A parse error occurs if there are any\n % characters not matched as tokens. We scan the start and end positions\n % of the tokens to determine if there are any gaps.\n\n g(1:length(str)) = '^';\n for i = 1:length(s);\n g(s(i):e(i)) = ' ';\n end\n \n assert(all(g ~= '^'), 'parse_formula:ParseError', ...\n 'Could not parse formula:\\n %s\\n %s\\n', str, char(g));\n \n % Extract atom tokens from the first part of each token\n \n tok = cellfun(@(v)v{1},u,'Uni',false);\n\n % Extract counts from the second part of each token, convert to\n % doubles, empty counts set to 1\n \n cnt = cellfun(@(v)v{2},u,'Uni',false);\n cnt = str2double(cnt);\n cnt(isnan(cnt)) = 1;\n \n % Loop over tokens\n\n for j = 1:length(u)\n\n % See if token matches an element\n\n if strcmp(tok{j},regexp(tok{j},srex,'match'))\n\n % The token exactly matches an element.\n % Change + or - tokens to 'Q'.\n \n tok{j} = regexprep(tok{j},'+','Q');\n\n if strcmp(tok{j}, '-')\n tok{j} = 'Q';\n cnt(j) = -cnt(j);\n end\n\n % Update atomic representation, adding a field if needed.\n\n if isfield(r,tok{j})\n r.(tok{j}) = r.(tok{j}) + cnt(j);\n else\n r(1).(tok{j}) = cnt(j);\n end\n\n else \n\n % The token must be a group, so do a recursion to find\n % an atomic represenation of the group.\n\n q = parse_formula_(tok{j},kdepth-1);\n\n % Updatethe atomic representation to include the group.\n % Add fields if needed. Multiply by number of groups in the\n % formula we're parsing.\n\n f = fields(q);\n\n for k = 1:length(f)\n\n if isfield(r,f{k})\n r.(f{k}) = r.(f{k}) + cnt(j)*q.(f{k});\n else\n r(1).(f{k}) = cnt(j)*q.(f{k});\n end\n\n end\n end\n end\n \nend % parse_formula_\n\n\n\n\n\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/StoichTools/parse_formula.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2227001285074597, "lm_q2_score": 0.04272219724178409, "lm_q1q2_score": 0.009514238815866357}} {"text": "function model = setFeedingFastingConstraints(model, feedingStatus,fastingValue,storageValue)\n% This function sets constraints corresponding either to feeding (i.e.,\n% storage reactions are set to have a lower bound of 0 while\n% the upper bounds are set to >0 (storage is enabled) or to fasting (i.e.,\n% storage reactions are set to have a lower bound of <0 (use of stored metabolites is enabled) while\n% the upper bounds are set to 0 (storage is disabled).\n%\n% function model = setFeedingFastingConstraints(model, feedingStatus,fastingValue,storageValue)\n%\n% INPUT\n% model model structure\n% feedingStatus 'feeding' = default bounds for diet uptake fastingValue for all diet exchanges, use diet script to refine, organ storage is turned on;\n% 'fasting' = all diet uptakes are closed, organ storage release is turned on\n% fastingValue default: fastingValue = -10;\n% storageValue default: storageValue = 10;\n%\n% OUTPUT\n% model with updated constraints\n%\n% Ines Thiele, 2015/2016\nif ~exist('fastingValue','var')\n fastingValue = -10;\nend\nif ~exist('storageValue','var')\n storageValue = 10;\nend\n\n% load amino acids that can be stored\nAAStorage;\nstoredInLiver={'nad(c)';'nadp(c)';'fad(c)';...\n 'thmtp(c)';'pydam(c)';'pydx(c)';'pydxn(c)';...\n 'coa(c)';'thf(c)';'btn(c)';'retinol(c)';'retfa(c)';...\n '11_cis_retfa(c)';'9_cis_retfa(c)';'25hvitd2(c)';'vitd3(c)';...\n 'avite1(c)';'avite2(c)';'chol(c)';'fe3(c)';'phyQ(c)';...\n 'glygn2(c)'};\nStoreInKidney = {'ascb_L(c)';'chol(c)';};\nStoreInMuscle ={'thmpp(c)';'25hvitd2(c)';'vitd3(c)';'chol(c)';'glygn2(c)'};\n\nStoreInAdi={'25hvitd2(c)';'vitd3(c)';'avite1(c)';'avite2(c)';'phyQ(c)';...\n 'hdca(c)';'tmndnc(c)';'lnlc(c)';'tag_hs(c)';...\n 'c226coa(c)';'doco13ecoa(c)';'lnlccoa(c)';'lnlncacoa(c)';'lnlncgcoa(c)';...\n 'odecoa(c)';'pmtcoa(c)';'stcoa(c)';'tmndnccoa(c)'\n };\nif isfield(model,'rxnGeneMat')\n model = rmfield(model,'rxnGeneMat');\nend\n% set all sinks to 0\nfor i = 1 : length(model.rxns)\n if length(strfind(model.rxns{i},'sink_'))==1 ...\n && length(strfind(model.rxns{i},'sink_pre_prot(r)'))==0 ...\n && length(strfind(model.rxns{i},'sink_Ser_Gly_Ala_X_Gly(r)'))==0 ...\n && length(strfind(model.rxns{i},'sink_5hpet(c)'))==0\n %&& length(strfind(model.rxns{i},'sink_Tyr_ggn(c)'))==0 % ...\n %% && length(strfind(model.rxns{i},'sink_citr(c)'))==0\n % && length(strfind(model.rxns{i},'sink_Ser_Gly_Ala_X_Gly(r)'))==0 ...\n if isfield(model,'Microbiota') && model.Microbiota(i) ==0 %no microbe sink\n model.lb(i)=0;\n elseif ~isfield(model,'Microbiota')\n model.lb(i)=0;\n end\n end\nend\n\nDMs= (find(~cellfun(@isempty,strfind(model.rxns,'DM_'))));\nmodel.lb(DMs) = 0;\n\n% but not at the beginning of the abbr --> leaves in the\n% microbe sinks\nif 1\n tmp = strmatch('sink_',model.rxns);\n model.lb(tmp)=-10;\nend\n\nfor i = 1 : length(model.rxns)\n if strfind(model.rxns{i},'sink_')\n model.rxns{i} = regexprep(model.rxns{i},'\\[c\\]','(c)');\n model.rxns{i} = regexprep(model.rxns{i},'\\[r\\]','(r)');\n % model.rxns{i}\n end\nend\nmodelexchanges1 = strmatch('Diet_EX_',model.rxns);\nmodelexchanges2 = strmatch('Diet_Ex_',model.rxns);\nmodelexchanges = [modelexchanges1;modelexchanges2];\n\nif strcmp(feedingStatus,'feeding') % storage no sinks\n model.lb(modelexchanges)=fastingValue;\n model.ub(modelexchanges)=0;\nelseif strcmp(feedingStatus,'fasting') % storage no sinks\n model.lb(modelexchanges)=0;\n model.ub(modelexchanges)=0;\n % exception for water\n \nend\n\nif strcmp(feedingStatus,'feeding') % storage no sinks\n for i = 1 : length(storedInLiver)\n storedInLiver{i};\n rxnName = strcat('Liver_sink_',storedInLiver{i});\n % rxnName\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n end\n for i = 1 : length(StoreInKidney)\n StoreInKidney{i};\n rxnName = strcat('Kidney_sink_',StoreInKidney{i});\n % rxnName\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n end\n for i = 1 : length(StoreInMuscle)\n rxnName = strcat('Muscle_sink_',StoreInMuscle{i});\n % rxnName\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n end\n for i = 1 : length(storageAA)\n rxnName = strcat('Muscle_',storageAA{i});\n % rxnName\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n end\n for i = 1 : length(StoreInAdi)\n rxnName = strcat('Adipocytes_sink_',StoreInAdi{i});\n % rxnName\n StoreInAdi{i};\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n end\n rxnName = 'Retina_sink_crvnc(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n rxnName = 'Heart_sink_chol(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n rxnName = 'Brain_sink_crvnc(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n rxnName = 'Brain_sink_chol(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n rxnName = 'RBC_sink_glygn2(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\n rxnName = 'Skin_sink_vitd3(c)';\n model = changeRxnBounds(model,rxnName,0,'l');\n model = changeRxnBounds(model,rxnName, storageValue,'u');\nelseif strcmp(feedingStatus,'fasting')\n for i = 1 : length(storedInLiver)\n rxnName = strcat('Liver_sink_',storedInLiver{i});\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n end\n for i = 1 : length(StoreInKidney)\n rxnName = strcat('Kidney_sink_',StoreInKidney{i});\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n end\n for i = 1 : length(StoreInMuscle)\n rxnName = strcat('Muscle_sink_',StoreInMuscle{i});\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n end\n for i = 1 : length(storageAA)\n rxnName = strcat('Muscle_',storageAA{i});\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n end\n for i = 1 : length(StoreInAdi)\n rxnName = strcat('Adipocytes_sink_',StoreInAdi{i});\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n end\n rxnName = 'Retina_sink_crvnc(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n rxnName = 'Heart_sink_chol(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n rxnName = 'Brain_sink_crvnc(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n rxnName = 'Brain_sink_chol(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n rxnName = 'RBC_sink_glygn2(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\n rxnName = 'Skin_sink_vitd3(c)';\n model = changeRxnBounds(model,rxnName,fastingValue,'l');\n model = changeRxnBounds(model,rxnName,0,'u');\nend\n\nmodel.SetupInfo.FeedingStatus = feedingStatus;\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/wholeBody/PSCMToolbox/setConstraints/setFeedingFastingConstraints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.028436034794495746, "lm_q1q2_score": 0.009415732437234373}} {"text": "function C = mtimes(A, B)\n%* CHEBOP composition, multiplication, or application.\n% C = A*B, where either A or B is a scalar, returns a CHEBOP C representing\n% scalar multiplication of the original operator. Boundary conditions\n% are copied from A or B to C.\n%\n% If N is a CHEBOP and U a CHEBFUN or CHEBMATRIX of dimension compatible\n% with N.op, then N*U is equivalent to FEVAL(N, U).\n%\n% C = A*B, where A and B are CHEBOP objects, should return a CHEBOP C\n% representing the composition of the operators of A and B. Boundary\n% conditions on A or B are destroyed by this process. Note this is not yet\n% supported.\n%\n% See also CHEBOP/PLUS, CHEBOP/MINUS, CHEBOP/MLDIVIDE, CHEBOP/FEVAL\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isa(A, 'chebfun') )\n error('CHEBFUN:CHEBOP:mtimes:invalid', 'Operation is undefined.');\n \nelseif ( isa(B, 'chebfun') || isa(B, 'chebmatrix') ) \n % Let A operate on B:\n C = feval(A, B);\n \nelseif ( isnumeric(B) )\n % Switch argument to make sure A is numeric:\n C = mtimes(B, A);\n \nelseif ( isnumeric(A) )\n \n if ( ~isscalar(A) )\n error('CHEBFUN:CHEBOP:mtimes:nonScalar', ...\n 'CHEBOP * DOUBLE multiplication is defined only for scalars.');\n end\n \n % Initialize C as a CHEBOP\n C = B;\n \n % Make the pretty string:\n funArgs = getFunArgs(C);\n argStr = ['@(',funArgs,')'];\n if ( ~isempty(C.opShow) )\n op = C.opShow;\n else\n op = func2str(C.op);\n end\n C.opShow = strrep(op, argStr, [argStr num2str(A) '*']);\n \n % Multiplication of anonymous functions is not supported in Matlab. Need to\n % work around that.\n C.op = eval(['@(', funArgs, ') A*C.op(', funArgs, ')']);\n \nelseif ( isa(A,'chebop') && isa(B,'chebop') ) \n % CHEBOP composition is not yet supported. It will probably be a mess once\n % we start getting systems involved, as the inputs need to be shuffled\n % correctly. A remedy might be through a nested function in this file.\n error('CHEBFUN:CHEBOP:mtimes:notSupported1',...\n 'CHEBOP composition is not supported.'); \n \nelse \n error('CHEBFUN:CHEBOP:mtimes:notSupported2', ...\n '%s * %s multiplication is not supported.', class(A), class(B));\n \nend\n \nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebop/mtimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.02262920044500071, "lm_q1q2_score": 0.009217629157583016}} {"text": "% Source Code Listings for the Calspan Version\n% of the FlOl Engine Response Model\n% Based on Report DNA-TR-93-124 by Adam J. Baran\n% and Dr. Michael G. Dunn of Calspan Corporation\n%\n% AFRL/RQTI Sept 2012\n%\n% engine parameters:\n% xn1 - fan speed (rpm)\n% xn2 - core speed (rpm)\n% (fan speed correlation)\n% xigv - fan inlet variable guide vane angle (deg.)\n% psl4 - fan discharge static pressure (psig)\n% pt25 - fan discharge total pressure (psig)\n% xoil1 - oil pressure [xn1 correlation) (psig)\n% (core speed correlation)\n% thrust - thrust (lbf)\n% air - airflow (lbm/sec)\n% vgv -compressor inlet variable guide vane angle (deg.)\n% cdp - compressor discharge pressure Cpsig)\n% pyro - pyrometer temperature (F)\n% egt - exhaust gas temperature (F)\n% fuel - fuel flow (Pph)\n% xoil2c - oil pressure [xn2 correlation] (psig)\n%\n% (subscripts)\n% ()nom - nominal value\n% ()del - Cin/de)crement over current interval\n% ()sumc - sum of (in/de)crements over previous intervals\n% (prescripts)\n% f() - function which generates the value of the variable\n%\n% Normal syntax to run is \"Dunnv1('infile.dat','outfile.dat')\" from matlab\n% prompt. To build datafile on first run just run \"Dunnv1\"...\n%% Main Routine\nfunction Dunnv1(Infile,Outfile)\ndbstop if error\n% Check for whether a runtime datafile exists\nif nargin == 0 ; % no formatted input file exists\n defaultdata ;\n Infile = 'infile.dat';\n Outfile = 'outfile.dat';\nelseif nargin == 1 ; % formatted input file exists\n Outfile = 'outfile.dat';\nend ;\nSTOR = [];\n%% -------------------------------\n% ROUTINE - READIN DATA FILE\n% -------------------------------\n% readindata(Infile) ; Read in data from inputfile ; IN = fopen(Infile,'r') ;\n%if (Infile == ''); \n%%% Infile = 'infile.dat' ; %%% Remove this when converting to input\n%end; \nIN = fopen(Infile); %IN = fopen('infile.dat','w') \n[pla] = textread(Infile, '%f',1,'headerlines',4) ;\n[pamb] = textread(Infile, '%f',1,'headerlines',6) ;\n[tamb] = textread(Infile, '%f',1,'headerlines',8) ;\n[debug] = textread(Infile, '%u',1,'headerlines',10) ;\n[nenc] = textread(Infile, '%u',1,'headerlines',12) ;\n% Preallocate the arrays\n% ib = zeros(nenc,1); blend = zeros(nenc,1); c = zeros(nenc,1); delt = zeros(nenc,1);\n[ib blend c delt] = textread(Infile,'%u %u %f %f','headerlines',14) ;\nfclose('all') ;\n%% Start writting out Header Block of Output File\n%% -------------------------------\n% ROUTINE - WRITEOUT RESULTS\n% -------------------------------\n%if (Infile == ''); \n%%% Outfile = 'outfile.dat' ; %%% Remove this when converting to input\n%end; \nOUT = fopen(Outfile,'w') ;\nfprintf(OUT,'PEARL - F101 reponse model \\n') ;\nfprintf(OUT,'%s\\n',datestr(now)) ;\nfprintf(OUT,' \\n') ; fprintf(OUT,' \\n') ; fprintf(OUT,' \\n') ;\nfprintf(OUT,'inputs : \\n'); fprintf(OUT,' \\n') ;\nfprintf(OUT,'PLA (deg) from (16.5-80.0) => \\n') ;\nfprintf(OUT,'%-4.2e \\n',pla) ;\nfprintf(OUT,'ambient pressure (psia) => ') ; fprintf(OUT,'%-4.2e \\n',pamb) ;\nfprintf(OUT,'ambient temperature (F) => ') ; fprintf(OUT,'%-4.2e \\n',tamb) ;\nfprintf(OUT,' \\n') ;\nfprintf(OUT,'#_of_encounters(-)(1-10)=> ') ; fprintf(OUT,'%-2i \\n',nenc) ;\nfprintf(OUT,'enc#, blend (1=mpb,2=blend2), dust conc. (mg/m^3), duration (min) \\n') ;\nfprintf(OUT,' \\n') ;\nfor i = 1:1:max(ib) ; % 'max(ib) is 'nenc' \n fprintf(OUT,'%-2i \\t %-1i \\t %-4.2e \\t %-4.2e \\n', ib(i), blend(i),c(i),delt(i));\nend ;\nfprintf(OUT,' \\n') ;\nfprintf(OUT,'debug mode (0=off,1=on) => ') ; fprintf(OUT,'%-2i \\n',debug) ;\nfprintf(OUT,' \\n') ; fprintf(OUT,' \\n') ;\nfprintf(OUT,'calculation begun \\n') ; fprintf(OUT,' \\n'); fprintf(OUT,' \\n');\nfprintf(OUT,' i blend dust cnc. time int. AIR FLOW ACC DUST N2 CDP FUEL FLOW THRUST \\n');\nfprintf(OUT,' (mg/m^3) (min) lbm/sec) (kg) (rpm) (psig) (lbm/hr) (lbf) \\n');\nfprintf(OUT,'+--+---+--------+--------+-------------+----------+-------+------+----------+-------+ \\n');\n%% START MAIN LOGIC HERE\n% Initialize all Runtime Engine Parameters to zero\nienc = 0; none = 0; dust = 0.; icdpflag = 0; cdplim = 54.; accdust = 0. ;\nibug = 0; time = 0. ;\nxn2nom = 0.; xn2del = 0.; xn2sum = 0.; % Spool speeds \ncdpnom = 0.; cdpdel = 0.; cdpsum = 0.; % Compressor pressure\nfuelnom = 0.; fueldel = 0.; fuelsum = 0.; % Fuel mass flow\nthrustnom = 0.; thrustdel = 0.; thrustsum = 0.; % Engine Thrust\n%%% F101 Specific DATA Here\nconst = 1.699e-06; % F101 engine correl. parameters for dust accum in F101 \ncdprate1 = 9.36e-03; cdprate2 = 1.59e-02; % F101 engine correl. parameters for cdp w/ dust1 and 2\nfuelrate1 = 1.22e-01; fuelrate2 = 3.32e-01; % F101 engine correl. parameters for fuel mass flow w/ dust1 and 2\nthrustrate1 = 1.41e-01; thrustrate2 = 3.33e-01; % F101 engine correl. parameters for thrust w/ dust1 and 2\n%%% F101 Specific DATA Here\n% Calculate Ambient Density of Air (lbm/sec)\nrhoamb = 144.*pamb/(53.3*(tamb+460.)); % Air equation of state\n% Nominal clear air engine parameter values\nxn2nom = FXN2NOM(pla) ; % call function \"figure nominal core speed from PLA\"\nxn2 = xn2nom ; % set core speed from nominal core speed\nair = FAIR(xn2) ; % call function for \"obtain air mass flow from core speed\"\ncdpnom = FCDPNOM(xn2) ; % call function \"get nominal compress discharge pressure from core speed\"\ncdp = cdpnom ; % set comp. discharge pressure from nominal comp. discharge pressure\nfuelnom = FFUELNOM(xn2) ; % call function \"get nominal fuel flow from core speed\"\nfuel = fuelnom ; % set fuel flow from the nominal fuel flow\nthrustnom = FTHRUSTNOM(xn2) ;\nthrust = thrustnom ;\nfprintf(OUT,'%2i\\t%2i\\t%4.1f\\t%5.1f\\t\\t%4.1f\\t\\t%3.2e\\t%6.1f\\t%4.1f\\t%6.1f\\t%6.1f\\n',0,0,0,0,air,accdust,xn2,cdp,fuel,thrust) ;\nSTORBASE = [0 0 0 0 0 air accdust xn2 cdp fuel thrust];\n% LOOP over all dust clound encounters\nfor ienc = 1:1:nenc;\n %% Calculate Airflow, ingested dust over this interval and total accumulated dust\n % based on conditions at start of encounter\n air = FAIR(xn2);\n q = air/rhoamb ;\n dust = const*q*c(ienc)*delt(ienc) ; % Incremental Dust accumulation\n accdust = dust + accdust; % Cumulative Dust accumulation\n %% Calculate Core Speed %ibug %ib(ienc)%accdust %c(ienc)\n xn2rate = FXN2RATE(ibug,blend(ienc),accdust,c(ienc));\n xn2del = xn2rate*delt(ienc);\n xn2 = xn2nom - xn2del - xn2sum ;\n %% Calculate cdp\n cdpnom = FCDPNOM(xn2);\n if(blend(ienc) == 1); % If dust blend #1 (mpb)\n cdprate = cdprate1 ;\n elseif(blend(ienc) == 2); % If dust blend #2 (blend-2)\n cdprate = cdprate2 ;\n end;\n cdpdel = cdprate*c(ienc)*delt(ienc);\n cdp = cdpnom + cdpdel + cdpsum ;\n %% Check for surge probability\n if((cdpdel+cdpsum >= cdplim)&&(icdpflag == 0));\n icdpflag = 1;\n cdpdelc = cdplim - cdpsum ;\n tau = cdpdelc/(cdprate*c(ienc));\n fprintf(OUT,'%s %3.1f %s %2i %s','*** engine surge at ',tau,'minutes into the',ienc,' -th encounter');\n fprintf(OUT,' \\n') ;\n end\n %% Calculate Fuel Burn Rate\n fuelnom = FFUELNOM(xn2) ;\n if(blend(ienc) == 1); % If dust blend #1 (mpb)\n fuelrate = fuelrate1 ;\n elseif(blend(ienc) == 2); % If dust blend #2 (blend-2)\n fuelrate = fuelrate2 ;\n end;\n fueldel = fuelrate*c(ienc)*delt(ienc) ;\n fuel = fuelnom + fueldel + fuelsum ; \n %% Calculate Thrust\n thrustnom = FTHRUSTNOM(xn2) ;\n if(blend(ienc) == 1); % If dust blend #1 (mpb)\n thrustrate = thrustrate1 ;\n elseif(blend(ienc) == 2); % If dust blend #2 (blend-2)\n thrustrate = thrustrate2 ;\n end; \n thrustdel = thrustrate*c(ienc)*delt(ienc);\n thrust = thrustnom + thrustdel + thrustsum ;\n %% Updat the sum terms of each engine parameter\n xn2sum = xn2sum + xn2del ;\n cdpsum = cdpsum + cdpdel ;\n fuelsum = fuelsum + fueldel ;\n thrustsum = thrustsum + thrustdel ; \n %% Write and store out runtime results\n fprintf(OUT,'%2i\\t%2i\\t%4.1f\\t%5.1f\\t\\t%4.1f\\t\\t%3.2e\\t%6.1f\\t%4.1f\\t%6.1f\\t%6.1f\\n',ienc,blend(ienc),c(ienc),delt(ienc),air,accdust,xn2,cdp,fuel,thrust) ; \n time = time + delt(ienc);\n STOR(ienc,:) = [ienc time blend(ienc) c(ienc) delt(ienc) air accdust xn2 cdp fuel thrust];\nend\nSTOR = [STORBASE ; STOR] ;\n% Plot Out Trends\nfigure(1); scale = 0;\nsubplot(2,3,1); plot(STOR(:,2),STOR(:,4)); grid on ; axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,4))]) ;\ntitle('dust concentration at enc') ; xlabel('time (min)'); ylabel('concentration (mg/m^3)') ;\nsubplot(2,3,2); plot(STOR(:,2),STOR(:,6)); grid on ; \nif (scale == 1); axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,6))]) ; end;\ntitle('air flow') ; xlabel('time (min)'); ylabel('air mass flow (lbm/sec)') ;\nsubplot(2,3,3); plot(STOR(:,2),STOR(:,8)); grid on ; \nif (scale == 1); axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,8))]) ; end;\ntitle('fan speed') ; xlabel('time (min)'); ylabel('fan speed (rpm)') ;\nsubplot(2,3,4); plot(STOR(:,2),STOR(:,9)); grid on ;\nif (scale == 1); axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,9))]) ; end ;\ntitle('compressor discharge pressure') ; xlabel('time (min)'); ylabel('pressure (psig)') ;\nsubplot(2,3,5); plot(STOR(:,2),STOR(:,10)); grid on ;\nif (scale == 1); axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,10))]) ; end;\ntitle('fuel burn') ; xlabel('time (min)'); ylabel('fuel burn rate (pph)') ;\nsubplot(2,3,6); plot(STOR(:,2),STOR(:,11)); grid on ; \nif (scale == 1); axis([ 0 max(STOR(:,2)) 0 1.1.*max(STOR(:,11))]) ; end;\ntitle('thrust') ; xlabel('time (min)'); ylabel('thrust (lbf)') ;\n%\nfclose(OUT) ;\n% END of MAIN Routine\nend\n%% Calculate Airflow as a function a fan of fan speed\n% \"x\" is passed from \"xn2\" and \"y\" is passed from \"air\"\nfunction [y] = FAIR(x); %%% F101 Specific DATA Here\n%%% F101 Specific DATA Here\na0= 440922.79744; a1= -174.0731208; a2= 0.027346652504;\na3= -2.1376216416e-06; a4= 8.3178976743e-11; a5= -1.2891058570e-15;\np = [440922.79744 -174.0731208 0.027346652504 -2.1376216416e-06 8.3178976743e-11];\n%%% F101 Specific DATA Here\nif(x<10348.); \n y=0.;\nelseif(x>15000.); \n y=0.;\nelseif((x>=10348.)&&(x<=15000.));\n y = a0 + a1*x + a2*x^2 + a3*x^3 + a4*x^4 + a5*x^5;\n% y = polyval(p,x)\nend\nend\n%% Calculate the nominal fuel a fan of fan speed, x is passed from xn2\nfunction [y] = FFUELNOM(x) ;%%% F101 Specific DATA Here\n%%% F101 Specific DATA Here\na0 = -49816.415015; a1 = 15.16955213; a2 = -0.00090483247417;\na3 = -1.0788972042E-07; a4 = 1.3439057313e-11; a5 = -3.6898802700E-16;\n%%% F101 Specific DATA Here\nif(x<10348.);\n y = 0. ;\nelseif(x>15000.); \n y = 0. ;\nelseif((x>=10348.)&&(x<=15000.));\n y = a0 + a1*x + a2*x^2 + a3*x^3 + a4*x^4 + a5*x^5;\nend\nend\n%% Function calculates the nominal thrust a fan of fan speed\nfunction [y] = FTHRUSTNOM(x);%%% F101 Specific DATA Here\n% 'x' is 'xn2' while 'y' is 'fthrustnom'\n%%% F101 Specific DATA Here\na10=-90190833.084; a11=38206.13731; a12=-6.4537917919; a13=0.00054340227729;\na14=-2.2807645464e-08; a15=3.8182035691e-13;\na20=-26525834.184; a21=5596.7412494; a22=-0.24258263565; a23=-2.2544154617e-05;\na24=2.2276804666e-09; a25=-5.2033103514e-14;\n%%% F101 Specific DATA Here\nif(x<10543.) ; \n y = 0. ;\nelseif(x>15000.) ; \n y = 0. ;\nelseif((x>=10543.)&&(x<=13246.));\n y = a10 + a11*x + a12*x^2 + a13*x^3 + a14*x^4 + a15*x^5;\nelseif((x>13426.)&&(x<=15000.)); % else\n y = a20 + a21*x + a22*x^2 + a23*x^3 + a24*x^4 + a25*x^5;\nend\nend\n%% Calculate Nominal value of Core Speed as function of power setting\nfunction [y] = FXN2NOM(x);%%% F101 Specific DATA Here\n% \"x\" is passed from the global variable \"pla\", and \"y\" is \"xn2nom\"\n%%% F101 Specific DATA Here\na10=10353.360465; a11=0.18067978533; a20=10306.641571;\na21=220.99533596; a22=-21.326092808; a23=0.69563112177;\na24=-0.0087987179757; a25=3.8820512919e-05;\n%%% F101 Specific DATA Here\nif(x<16.5) ;\n y = 0. ;\nelseif(x>80.); \n y = 0. ;\nelseif((x>=16.5)&&(x<30.));\n y = a10 + a11*x ;\nelseif((x>=30.)&&(x<=80.));\n y = a20 + a21*x + a22*x^2 + a23*x^3 + a24*x^4 + a25*x^5 ;\nend\nend\n%% Calculate Compressor Discharge Pressure from core speed \nfunction [y]= FCDPNOM(x);%%% F101 Specific DATA Here\n% \"x\" is passed from \"xn2\" and \"y\" is passed at \"cdpnom\"\n%%% F101 Specific DATA Here\na0 = 52767.656799 ; a1 = -20.435530217 ; a2 = 0.0031594211659 ;\na3 = -2.441489353e-07 ; a4 = 9.4426267256e-12 ; a5 = -1.4592076510e-16 ;\n%%% F101 Specific DATA Here\nif(x<10348.);\n y = 0. ;\nelseif(x>15000.);\n y = 0. ;\nelseif((x>=10348.)&&(x<=15000.));\n y = a0 + a1*x + a2*x^2 + a3*x^3 + a4*x^4 + a5*x^5 ;\nend\nend\n%% Calculates core speed drop rate due to dust\nfunction [y] = FXN2RATE(libug,lblend,lacc,lc) ;%%% F101 Specific DATA Here\n%% where 'libug' is passed from 'ibug', is debug mode\n% where 'li' is passed from 'i', is cloud encounter index counter \n% where 'lacc' is passed from 'acc', is sum accumulation of dust\n% where 'lc' is passed from 'c', concentration of the dust cloud\n% where 'y' is passed back as 'fxn2rate', the core speed drop rate\n%%% F101 Specific DATA Here \na110 = 0. ; a111 = 0.031091666884 ; a120 = 2.2386 ; a130 = 0.41616348802 ; \na131= 0.062687011283 ; a210= -0.023120229598 ; a211= 0.19569725331 ;\na212= -0.001954960762 ; a213= 6.9569031307e-06;\n%%% F101 Specific DATA Here\nif(lacc<=0.); y = 0.0; end;\nif(lblend==1); % Model for the mpb blend\n if(lacc<72.);\n if((lc>=0.)&&(lc<72.));\n y = a110 + a111*lc ;\n elseif((lc>=72.)&&(lc<=293.));\n y = a120 ;\n elseif(lc>293);\n y = 1.0e10 ;\n end;\n elseif(lacc>=72.);\n if((lc>=0.)&&(lc<=282.));\n y = a130 + a131*lc ;\n elseif(lc>282.);\n y = 1.0e10;\n end;\n end;\nelseif(lblend==2); % Model for Blend #2\n if((lc>=0.)&&(lc<=295.));\n y = a210 + a211*lc + a212*lc^2 + a213*lc^3 ;\n elseif(lc>295.);\n y = 1.0e10;\n end;\nend\nend\n%% DEFAULT DATA INPUT FILE\nfunction defaultdata() ;\n%% --------------------------------\n% DEFAULT DATA INPUT FILE\n% --------------------------------\n% Write out a formatted 'infile.dat' for user editing if none exists in the\n% directory where 'Dunnv1.m' is run. \n% Defualt INPUT VALUES BLOCK\npla = 80.0 ; % 65 percent throttle (from 16.5 to 80) \ntamb = 59.0 ; % Ambient temperature (in degF)\npamb = 14.7 ; % Ambient pressure (in psia)\nnenc = 10 ; % No. of dust cloud encounters (No. of enc)\n% Dust cloud encounter index numbers\nib = [0 1 2 3 4 5 6 7 8 9 10];\n% CMAS blend (1 = mpb, 2 = blend2), as defined in DNA TR-92-121\nblend = [0 2 2 2 2 2 2 2 2 2 2];\n% dust conc. (mg/m^3) \nc = [0. 100. 100. 100. 100. 100. 100. 100. 100. 100. 100.];\n% duration (min)\ndelt = [0.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0 6.0];\n% debug mode {0=off, 1=on}\ndebug = 0;\n% Write out these properties into default file in carefully formatted\n% output \nIN = fopen('infile.dat','w') ;\nfprintf(IN,'PEARL - F101 reponse model \\n') ;\nfprintf(IN,' \\n') ;\nfprintf(IN,' \\n') ;\nfprintf(IN,'PLA (deg) from (16.5-80.0) => \\n') ;\nfprintf(IN,'%-4.2e \\n',pla) ;\nfprintf(IN,'ambient pressure (psia) => \\n') ;\nfprintf(IN,'%-4.2e \\n',pamb) ;\nfprintf(IN,'ambient temperature (F) => \\n') ;\nfprintf(IN,'%-4.2e \\n',tamb) ;\nfprintf(IN,'debug mode (0=off,1=on) => \\n') ;\nfprintf(IN,'%-2i \\n',debug) ;\nfprintf(IN,'#_of_encounters(-)(1-10)=> \\n') ;\nfprintf(IN,'%-2i \\n',nenc) ;\nfprintf(IN,'enc#, blend (1=mpb,2=blend2), dust conc. (mg/m^3), duration (min) \\n') ;\nfprintf(IN,' \\n') ;\nfor i = 1:1:nenc; fprintf(IN,'%-2i \\t %-1i \\t %-4.2e \\t %-4.2e \\n', ib(i+1),blend(i+1),c(i+1),delt(i+1));end;\nfclose(IN); % Close file\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43612-dust-injection-into-an-f101-gas-turbine-engine-b-1/Dunnv1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.021615331462730675, "lm_q1q2_score": 0.009050272164566933}} {"text": "function DPMpcOneBeam9(leak, spectrum_File, planC_File, nhist, OutputError, whichBeam, PBMaxWidth, gradsense, MCsolver, saveIM, sourceModel, doseToWater, fillWater, useWedge, inputPB, Softening, batch)\n% written by KZ, JC\n% Calculate doseV dose3D directly from DPM, without compressing it.\n% Use generateDPMdose.m instead of DPMInfluenceJing.m\n% Calculate IM struct, call DPM, get\n%\n% Usage: IIMCalc = calculateBeamIM(0.018, 'DPM_10beams_planC', 1, 1, 5)\n% leak = 0.018\n% spectrum_File = file name of photon spectrum. eg. photon6MV.spectrum\n% planC_File = file name contained planC, eg. 'DPM_10beams_planC'\n% indexBeam = Beam Index: 1, 2, ...\n% imin = Beamlet index\n% imax = Beamlet index\n%\n% eval(['load Beam',num2str(indexBeam),'_w']);\n% where, Beam1_w.mat (Beam2_w.mat) need to be in the current directory. It's the weight of\n% the beamlets for each beam.\n%\n% JC Feb 27 06\n% Call in DPMInfluence.m; use sum(10*clock) as the random seeds input to DPM.\n%\n% JC. Aug 10, 2005, Need to make planC read from the disk, since in the\n% stand-alone mode, no matlab run is expected.\n%\n% JC Dec 18 06\n% Add 'saveIM' input,\n% If it's larger than 0, say 1, then save IM\n% If it's 0, don't save IM\n%\n% LM: JC Jan 26 2007\n% Include non-zero couchAngle\n% The desination coordinates should be the patient support\n% system.\n% The previous assumption is that the \"fixed system\" is the same as\n% the \"Patient support system\".\n% test\n%\n% LM: JC Mar 03, 2007\n% Score dose to water flag. Only valid for VMC++ for now. \"doseToWater\"\n% Add \"fillWater\" flag. It 1, fill the skin strucutere with all water\n% density, i.e. CT value = 1024.\n%\n% LM: JC Mar 29, 2007\n% get rid of 'stateS' arguments to 'generateVMCdose.m', 'generateDPMdose.m'\n% get rid of the call for 'IMRTP_plancheck'\n% add 'useWedge' flag. default = 0; when useWedge == 1, use Elekta\n% universal wedge.\n% only implemented for DPM, openField == 0, sourceModel == 0;\n%\n% open planC_File\n% In matlab release 14, \"eval\" can be compiled.\nError = []; %Initialize Error to NULL.\nload(planC_File);\n%eval(['load ',planC_File]);\n% This planC_File should contains planC and stateS\n%leak = 0.018; %leakage in per *100\n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nif ischar(leak)\n leak = str2num(leak)\nend\n\nif ischar(nhist)\n nhist = str2num(nhist)\nend\n\nif ischar(OutputError)\n OutputError = str2num(OutputError)\nend\n\nif ischar(whichBeam)\n whichBeam = str2num(whichBeam)\nend\n\n\nif ischar(PBMaxWidth)\n PBMaxWidth = str2num(PBMaxWidth)\nend\n\nif ischar(gradsense)\n gradsense = str2num(gradsense)\nend\n\n% If MCsolver == 1, use DPM, default\n% If MCsolver == 2, use VMC++\n% other, throw out error\nif ischar(MCsolver)\n MCsolver = str2num(MCsolver)\nend\n\n% If saveIM == 0, calculate doseV, do not calc/save IM\n% If saveIM ~= 0, calc/save IM, only valid for DPM for now, ie. MCsolver == 1.\nif ischar(saveIM)\n saveIM = str2num(saveIM)\nend\n\n% If sourceModel == 0, no source model, only point source\n% If sourceModel == 1, source model version 1: point source (Primary) + FF\n% + electron contamination.\n% Expandable to other source models for the future development.\n\nif ischar(sourceModel)\n sourceModel = str2num(sourceModel)\nend\n\nif ischar(doseToWater)\n doseToWater = str2num(doseToWater)\nend\n\nif ischar(fillWater)\n fillWater = str2num(fillWater)\nend\n\nif ischar(useWedge)\n useWedge = str2num(useWedge)\nend\n\nif ischar(inputPB)\n inputPB = str2num(inputPB) %Flag, inputPB == 1, ask user to input .mat file storing PB info. \n % That file can be generated using\n % function generateOpenfiledPB.m\nend\n% Now, only work for DPM, planC{7} not empty.\n\nif ischar(Softening)\n Softening = str2num(Softening) %Flag, == 1, use off-axis-softening in dpm calc. \n \nend\n% Now, only work for DPM, planC{7} not empty.\n\n\nif ischar(batch)\n batch = str2num(batch)\nend\n\ncurrentDir = cd;\nif (~isempty(planC{7}))\n % When there are multiple beam definition in planC, use the first BEAM\n % data as the default.\n\n %for indexBeam = 1 : planC{7}(1).FractionGroupSequence.Item_1.NumberOfBeams\n for indexBeam = whichBeam\n \n bs = planC{7}(1).BeamSequence.(['Item_' num2str(indexBeam)]);\n\n %Parse BlockData into PB information.\n input = bs.BlockSequence.Item_1.BlockData;\n input = reshape(input, 2, [])';\n \n [xPosV, yPosV, beamlet_delta_x, beamlet_delta_y]=...\n BlockToPB(input, 10, 10); %PB size here is in mm.\n w_field = ones(size(xPosV));\n \n gA = bs.ControlPointSequence.Item_1.GantryAngle;\n iC = bs.ControlPointSequence.Item_1.IsocenterPosition;\n IMBase.beams.gantryAngle = gA;\n % couchAngle is PatientSupportAngle, in DICOM, i.e. IEC format\n % (in deg)\n IMBase.beams.couchAngle = bs.ControlPointSequence.Item_1.PatientSupportAngle;\n % JC Apr. 10 2007, \n % Add Beam Limiting Deviceing Angle, i.e. collimator angle from\n % DICOM, in IED format. (in deg) \n % Not test for \"Non-zero angle\" yet.\n IMBase.beams.collimatorAngle = bs.ControlPointSequence.Item_1.BeamLimitingDeviceAngle\n\n try\n if ~isfield(planC{7}(1).PatientSetupSequence,(['Item_' num2str(indexBeam)]))\n position = {planC{7}(1).PatientSetupSequence.(['Item_' num2str(1)]).PatientPosition};\n else\n position = {planC{7}(1).PatientSetupSequence.(['Item_' num2str(indexBeam)]).PatientPosition};\n end\n catch\n position = 'HFS';\n disp('Use default patient posiont HFS')\n end\n\n if strcmpi(position, 'HFP')\n IMBase.beams(1).isocenter.x = iC(1)/10;\n IMBase.beams(1).isocenter.y = iC(2)/10;\n IMBase.beams(1).isocenter.z = -iC(3)/10;\n else\n IMBase.beams(1).isocenter.x = iC(1)/10;\n IMBase.beams(1).isocenter.y = -iC(2)/10;\n IMBase.beams(1).isocenter.z = -iC(3)/10;\n end\n\n IMBase.beams(1).isodistance = bs.SourceAxisDistance/10;\n\n IMBase.beams(1).beamEnergy = bs.ControlPointSequence.Item_1.NominalBeamEnergy;\n \n xPosV = xPosV/10;\n yPosV = yPosV/10;\n beamlet_delta_x = beamlet_delta_x/10;\n beamlet_delta_y = beamlet_delta_y/10;\n\n\n IMBase.goals.PBMargin = 0.5;\n IMBase.goals.structNum = 2;\n IMBase.params.xyDownsampleIndex = 1;\n IMBase.goals.isTarget(1) = 'y';\n IMBase.goals.xySampleRate = 2;\n IMBase.params.numCTSamplePts = 300;\n\n IMBase.beams(1).zRel = 0;\n IMBase.beams(1).xRel = IMBase.beams(1).isodistance * sindeg(IMBase.beams(1).gantryAngle);\n IMBase.beams(1).yRel = IMBase.beams(1).isodistance * cosdeg(IMBase.beams(1).gantryAngle);\n\n % JC In the above calc. for xRel and yRel, the assumption is the couchAngle\n % == 0. i.e. the \"fixed system\" is the same as the \"patient support\n % system\".\n % LM: JC Jan 26 2007\n % Include non-zero couchAngle\n % The desination coordinates should be the patient support\n % system.\n % The previous assumption is that the \"fixed system\" is the same as\n % the \"Patient support system\".\n % test\n\n % patientVectorsM = zeros(size(RTOGVectorsM));\n patientxRel = cosdeg(IMBase.beams.couchAngle) * IMBase.beams(1).xRel- sindeg(IMBase.beams.couchAngle) * IMBase.beams(1).zRel;\n patientyRel = IMBase.beams(1).yRel;\n patientzRel = sindeg(IMBase.beams.couchAngle) * IMBase.beams(1).xRel + cosdeg(IMBase.beams.couchAngle) * IMBase.beams(1).zRel;\n IMBase.beams(1).xRel = patientxRel;\n IMBase.beams(1).yRel = patientyRel;\n IMBase.beams(1).zRel = patientzRel;\n clear patientxRel patientyRel patientzRel\n\n %IMBase.params.algorithm = 'VMC++';\n %IMCalc = IMRTP_MapCheck(IMBase);\n\n IMBase.params.algorithm = 'DPM';\n % load PB_40x40.mat beamlet_delta_x beamlet_delta_y xPosV yPosV w_field\n % load PB_15x15.mat beamlet_delta_x beamlet_delta_y xPosV yPosV w_field\n \n if inputPB % get PB info from a specified .mat file.\n setappdata(0, 'usenativesystemdialogs', false)\n currentDir = cd;\n\n [FileName,path] = uigetfile('*.mat','Select MAT file containing beamlet_delta_x beamlet_delta_y xPosV yPosV w_field');\n\n if path == 0\n errordlg('File Should exist');\n error('File Should exist');\n end\n\n cd(path);\n load (FileName, 'beamlet_delta_x', 'beamlet_delta_y', 'xPosV', 'yPosV', 'w_field')\n cd(currentDir);\n end\n\n disp('Number of pencile beams are:')\n length(xPosV)\n\n sourceS = IMBase.beams(1);\n [RTOGPBVectorsM, RTOGPBVectorsM_MC, PBMaskM, rowPBV, colPBV, xPBPosV, yPBPosV, beamlet_delta_x, beamlet_delta_y] = ...\n getPBRays(xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, sourceS);\n IMCalc = IMBase;\n IMCalc.beams(1).RTOGPBVectorsM_MC = RTOGPBVectorsM_MC;\n IMCalc.beams(1).RTOGPBVectorsM = RTOGPBVectorsM;\n IMCalc.beams(1).xPBPosV = xPBPosV;\n IMCalc.beams(1).yPBPosV = yPBPosV;\n IMCalc.beams(1).rowPBV = rowPBV;\n IMCalc.beams(1).colPBV = colPBV;\n % No need of this field\n IMCalc.beams(1).CTTraceS = struct;\n IMCalc.beams(1).beamletDelta_x = beamlet_delta_x;\n IMCalc.beams(1).beamletDelta_y = beamlet_delta_y;\n\n %RTOG positions of sources\n IMCalc.beams(1).x = IMCalc.beams(1).xRel + IMCalc.beams(1).isocenter.x;\n IMCalc.beams(1).y = IMCalc.beams(1).yRel + IMCalc.beams(1).isocenter.y;\n IMCalc.beams(1).z = IMCalc.beams(1).zRel + IMCalc.beams(1).isocenter.z;\n %IMCalc = IMRTP_MapCheck(IMBase, planC, stateS, xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, gA);\n % JC. 11 Aug, 05 Added more arguments to IMRTP_MapCheck,\n\n % JC. Aug. 3, 2005\n % Add fields to IMCalc, necessary for generateDPMInfluence.m\n IMCalc.beams.collimatorAngle = 0;\n IMCalc.params.ScatterMethod = 'exponential';\n % Use 0.002 instead the original default 0.01 as threshold value.\n % Change to 0.004, since the stored IM struct is very large.\n IMCalc.params.Scatter.Threshold = 0.004;\n IMCalc.params.Scatter.RandomStep = 30;\n IMCalc.beamlets = struct;\n\n %JC Add/porpulate VMC field in IM struct.\n IMCalc.params.VMC.NumParticles = nhist;\n IMCalc.params.VMC.NumBatches = 10;\n IMCalc.params.VMC.scoreDoseToWater = 'No';\n IMCalc.params.VMC.monoEnergy = 0; %?\n IMCalc.params.VMC.repeatHistory = 0.2510;\n IMCalc.params.VMC.splitPhotons = 'Yes';\n IMCalc.params.VMC.photonSplitFactor = -40;\n IMCalc.params.VMC.base = 2;;\n IMCalc.params.VMC.dimension = 60; %?\n IMCalc.params.VMC.skip = 0; %? 1?\n IMCalc.params.VMC.includeError = 'No';\n IMCalc.params.VMC.spectrum = spectrum_File;\n IMCalc.beams.beamModality = 'photons';\n\n if doseToWater\n IMCalc.params.VMC.scoreDoseToWater = 'Yes';\n disp('VMC++ score dose to Water.');\n end\n \n % JC Jun 06 2006\n % Still need to fill in the structure of IMCalc, but don't need put\n % it back(?), since it's not to be used to calculate dose.\n % Will also need to use 'DoseScale' inside generateDPMdose.m,\n % since DPM output dose on a per partical base.\n % Need to use w_field as a way of telling DPM how to add beamlets\n % up.\n\n % JC Aug 30. 2006\n if (MCsolver == 1)\n\n [IMCalc doseV indV numberParticles] = generateDPMdose7(IMCalc,spectrum_File,nhist, OutputError,planC, indexBeam, w_field, saveIM, sourceModel, fillWater, useWedge, Softening);\n\n elseif (MCsolver == 2)\n % use VMC++\n [doseV indV] = generateVMCdose(IMCalc, planC, w_field, sourceModel, doseToWater, fillWater,saveIM);\n else\n error('INVALID input: MCsolver == 1, DPM; MCsolver == 2, VMC++')\n end\n\n \n end\n\nelse %If it's a conventional plan, planC{7} is empty\n\n indexBeam = whichBeam;\n if (length(planC{6}(indexBeam).file) > 5)\n [xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, beamGeometry]=...\n planCToPB(planC, indexBeam, 1, 1);\n else\n % The field is shaped by Jaws, not MLC.\n [xPosV, yPosV, beamlet_delta_x, beamlet_delta_y, beamGeometry]=...\n planCToPBJaws(planC, indexBeam, 1, 1);\n end\n\n IMBase.beams(1).isocenter.x = beamGeometry.isocenter(1);\n IMBase.beams(1).isocenter.y = beamGeometry.isocenter(2);\n IMBase.beams(1).isocenter.z = beamGeometry.isocenter(3);\n % RTOG file has the same couchAngle definition as in IEC1217.\n IMBase.beams(1).couchAngle = beamGeometry.couchAngle;\n % RTOG file has different gantryAngle definition from IEC1217.\n % Use IEC 1217 coordinates.\n IMBase.beams(1).gantryAngle = - beamGeometry.gantryAngle;\n IMBase.beams(1).isodistance = beamGeometry.isoDistance;\n\n IMBase.goals.PBMargin = 0.5;\n IMBase.goals.structNum = 2;\n IMBase.params.xyDownsampleIndex = 1;\n IMBase.goals.isTarget(1) = 'y';\n IMBase.goals.xySampleRate = 1;\n IMBase.params.numCTSamplePts = 300;\n IMBase.beams(1).beamEnergy = planC{6}(1).beamEnergyMeV;\n\n IMBase.beams(1).zRel = 0;\n IMBase.beams(1).xRel = IMBase.beams(1).isodistance * sindeg(IMBase.beams(1).gantryAngle);\n IMBase.beams(1).yRel = IMBase.beams(1).isodistance * cosdeg(IMBase.beams(1).gantryAngle);\n\n % JC In the above calc. for xRel and yRel, the assumption is the couchAngle\n % == 0. i.e. the \"fixed system\" is the same as the \"patient support\n % system\".\n % LM: JC Jan 26 2007\n % Include non-zero couchAngle\n % The desination coordinates should be the patient support\n % system.\n % The previous assumption is that the \"fixed system\" is the same as\n % the \"Patient support system\".\n\n patientxRel = cosdeg(IMBase.beams.couchAngle) * IMBase.beams(1).xRel- sindeg(IMBase.beams.couchAngle) * IMBase.beams(1).zRel;\n patientyRel = IMBase.beams(1).yRel;\n patientzRel = sindeg(IMBase.beams.couchAngle) * IMBase.beams(1).xRel + cosdeg(IMBase.beams.couchAngle) * IMBase.beams(1).zRel;\n IMBase.beams(1).xRel = patientxRel;\n IMBase.beams(1).yRel = patientyRel;\n IMBase.beams(1).zRel = patientzRel;\n clear patientxRel patientyRel patientzRel\n\n IMBase.beams(1).collimatorAngle = beamGeometry.collimatorAngle;\n \n disp('Number of pencile beams are:')\n length(xPosV)\n\n % JC Mar 29, 2007\n % Repace 'IMRTP_plancheck' by the following command\n sourceS = IMBase.beams(1);\n [RTOGPBVectorsM, RTOGPBVectorsM_MC, PBMaskM, rowPBV, colPBV, xPBPosV, yPBPosV, beamlet_delta_x, beamlet_delta_y] = ...\n getPBRays(xPosV, - yPosV, beamlet_delta_x, beamlet_delta_y, sourceS);\n % Note: In the above line, use '- yPosV' instead of 'yPosV'. Since IEC and RTOG have different definition about yPosV. \n IMCalc = IMBase;\n IMCalc.beams(1).RTOGPBVectorsM_MC = RTOGPBVectorsM_MC;\n IMCalc.beams(1).RTOGPBVectorsM = RTOGPBVectorsM;\n IMCalc.beams(1).xPBPosV = xPBPosV;\n IMCalc.beams(1).yPBPosV = yPBPosV;\n IMCalc.beams(1).rowPBV = rowPBV;\n IMCalc.beams(1).colPBV = colPBV;\n % No need of this field\n IMCalc.beams(1).CTTraceS = struct;\n IMCalc.beams(1).beamletDelta_x = beamlet_delta_x;\n IMCalc.beams(1).beamletDelta_y = beamlet_delta_y;\n\n %RTOG positions of sources\n IMCalc.beams(1).x = IMCalc.beams(1).xRel + IMCalc.beams(1).isocenter.x;\n IMCalc.beams(1).y = IMCalc.beams(1).yRel + IMCalc.beams(1).isocenter.y;\n IMCalc.beams(1).z = IMCalc.beams(1).zRel + IMCalc.beams(1).isocenter.z;\n \n % JC Mar 29, 2007 \n % Replace 'IMRTP_MapCheck' by above commands.\n % IMCalc = IMRTP_MapCheck(IMBase, planC, stateS, xPosV, - yPosV, beamlet_delta_x, beamlet_delta_y, gA);\n clear IMBase beamlet_delta_x beamlet_delta_y PlanC_File xPosV yPosV\n\n % Add fields to IMCalc, necessary for generateDPMInfluence.m\n IMBase.params.algorithm = 'DPM';\n IMCalc.params.ScatterMethod = 'exponential';\n IMCalc.params.Scatter.Threshold = 0.004;\n IMCalc.params.Scatter.RandomStep = 30;\n IMCalc.beamlets = struct;\n\n % For the conventional RT. No change in w_field\n w_field = ones(length(IMCalc.beams.beamletDelta_x),1);\n %[doseV indV] = generateDPMdose(IMCalc,spectrum_File,nhist, OutputError,planC,stateS, indexBeam, w_field);\n % Dec 18, 2006\n % Use the new modified DPM, with Source Model.\n\n %JC Add/porpulate VMC field in IM struct.\n IMCalc.params.VMC.NumParticles = nhist;\n IMCalc.params.VMC.NumBatches = 10;\n IMCalc.params.VMC.scoreDoseToWater = 'No';\n IMCalc.params.VMC.monoEnergy = 0; %?\n IMCalc.params.VMC.repeatHistory = 0.2510;\n IMCalc.params.VMC.splitPhotons = 'Yes';\n IMCalc.params.VMC.photonSplitFactor = -40;\n IMCalc.params.VMC.base = 2;;\n IMCalc.params.VMC.dimension = 60; %?\n IMCalc.params.VMC.skip = 0; %? 1?\n IMCalc.params.VMC.includeError = 'No';\n IMCalc.params.VMC.spectrum = spectrum_File;\n IMCalc.beams.beamModality = 'photons';\n \n if doseToWater\n IMCalc.params.VMC.scoreDoseToWater = 'Yes';\n disp('VMC++ score dose to Water.');\n end\n \n if (MCsolver == 1)\n\n [IMCalc doseV indV numberParticles] = generateDPMdose7(IMCalc,spectrum_File,nhist, OutputError,planC, indexBeam, w_field, saveIM, sourceModel, fillWater, useWedge, Softening);\n\n elseif (MCsolver == 2)\n % use VMC++\n [doseV indV] = generateVMCdose(IMCalc, planC, w_field, sourceModel, doseToWater, fillWater,saveIM);\n else\n error('INVALID input: MCsolver == 1, DPM; MCsolver == 2, VMC++')\n end\n\n % ?? Right place to put end???\nend\n\n\n%%%%%%%%%%%%%%%\n siz = getUniformizedSize(planC);\n dose3D = zeros(siz);\n\n if (OutputError == 1) % OutputError only valid for DPM,ie., MCsolver == 1 \n doseV = doseV(:,1);\n Error_3D = zeros(siz);\n Error_3D(indV') = doseV(:,2);\n else\n disp('Do not output error')\n dose3D(indV') = doseV;\n end\n\n % filename = ['doseV_',num2str(indexBeam),'_', num2str(nhist), '_', num2str(batch)];\n % save(filename, 'doseV', 'indV');\n\n filename = ['dose3D_',num2str(indexBeam),'_', num2str(nhist), '_', num2str(batch)];\n save(filename, 'dose3D');\n\n % Only Output w_field for the first batch\n if(batch == 1)\n filename = ['w_field',num2str(indexBeam)];\n save(filename, 'w_field');%dose3D = (dose3D/max(dose3D(:)));\n end\n\nif (saveIM == 1)\n%saveIM %Only valid for DPM, i.e. IM \n filename = ['IMCalc_Beam',num2str(indexBeam),'_', num2str(nhist), '_', num2str(batch)];\n save(filename, 'IMCalc');\nend\nclear IMCalc dose3D w_field\n\nend\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/DPMpcOneBeam9Block.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.023330770675975176, "lm_q1q2_score": 0.008980296973352475}} {"text": "function [G, G_ind, related, n_genes_KO, G_time] = buildGmatrix(model_name, model, separate_isoform, numWorkers, printLevel)\n% Build the G matrix required for the calculation of genetic Minimal Cut\n% Sets (gMCSs).\n%\n% USAGE:\n%\n% [G, G_ind, related, n_genes_KO, G_time] = buildGmatrix(model_name, model_struct, separate_isoform, numWorkers, printLevel)\n%\n% INPUTS:\n% model_name: Name of the metabolic model under study.\n% model_struct: Metabolic model structure (COBRA Toolbox format).\n% separate_isoform: Character used to discriminate different isoforms of a gene.\n%\n% OPTIONAL INPUTS:\n% numWorkers: Maximum number of workers\n% * 0 - maximum provided by the system (automatic)\n% * 1 - sequential\n% * 2+ - parallel\n% printLevel: show the reactions created in models.\n% * 0 - shows nothing\n% * 1 - shows progress by reactions (default)\n% * 2+ - shows everything (reaction and network generation)\n%\n% OUTPUTS:\n% G: G matrix.\n% G_ind: Gene knockouts associated with each row in the G matrix.\n% related: Relationships among rows of the G matrix.\n% n_genes_KO: Number of genes whose knockout is added by each row of the G matrix.\n% G_time: Calculation times for each of the steps.\n%\n% EXAMPLE:\n%\n% [G, G_ind, related, n_genes_KO, G_time] = buildGmatrix('Recon2.v04', modelR204, '.')\n%\n% .. Authors:\n% - Inigo Apaolaza, 16/11/2017, University of Navarra, TECNUN School of Engineering.\n% - Luis V. Valcarcel, 19/11/2017, University of Navarra, TECNUN School of Engineering.\n% - Francisco J. Planes, 20/11/2017, University of Navarra, TECNUN School of Engineering.\n% - Inigo Apaolaza, 10/04/2018, University of Navarra, TECNUN School of Engineering.\n\ntime_a = tic;\n% Generate name for temporary folder\nglobal CBTDIR\ntmpFolderName = [CBTDIR filesep '.tmp'];\nif ~exist(tmpFolderName,'dir') % Create directories if needed\n mkdir(tmpFolderName)\nend\nif ~exist([tmpFolderName filesep 'rxn_level_gMCSs'],'dir')\n mkdir([tmpFolderName filesep 'rxn_level_gMCSs'])\nend\nif ~exist([tmpFolderName filesep 'rxn_level_gMCSs_by_rxn'],'dir')\n mkdir([tmpFolderName filesep 'rxn_level_gMCSs_by_rxn'])\nend\nif ~exist([tmpFolderName filesep 'rxn_level_models'],'dir')\n mkdir([tmpFolderName filesep 'rxn_level_models'])\nend\n\n% Analyze the GPR rules in order to set the strategy for the calculation of\n% the knockouts for the G matrix\ngrRules = model.grRules;\nrxnGeneMat = model.rxnGeneMat;\nn_rxns = size(rxnGeneMat, 1);\n\nrxns_0_genes = sum(rxnGeneMat, 2) == 0;\nrxns_1_gene = sum(rxnGeneMat, 2) == 1;\nrxns_or = cellfun(@strfind, grRules, repmat({'or'}, n_rxns, 1), 'UniformOutput', false);\nrxns_or = ~cellfun(@isempty, rxns_or) & sum(rxnGeneMat, 2) > 1;\nrxns_and = cellfun(@strfind, grRules, repmat({'and'}, n_rxns, 1), 'UniformOutput', false);\nrxns_and = ~cellfun(@isempty, rxns_and) & sum(rxnGeneMat, 2) > 1;\nrxns_only_or = rxns_or & ~rxns_and;\nrxns_only_and = ~rxns_or & rxns_and;\nrxns_or_and = rxns_or & rxns_and;\n\nn_rxns_0_genes = sum(rxns_0_genes);\nn_rxns_1_gene = sum(rxns_1_gene);\nn_rxns_only_or = sum(rxns_only_or);\nn_rxns_only_and = sum(rxns_only_and);\nn_rxns_or_and = sum(rxns_or_and);\nn_rxns_total = n_rxns_0_genes+n_rxns_1_gene+n_rxns_only_or+n_rxns_only_and+n_rxns_or_and;\n\nsummary_1 = {'n_rxns_0_genes', n_rxns_0_genes; 'n_rxns_1_gene', n_rxns_1_gene;\n 'n_rxns_only_or', n_rxns_only_or; 'n_rxns_only_and', n_rxns_only_and;\n 'n_rxns_or_and', n_rxns_or_and; 'n_rxns_total', n_rxns_total};\nif printLevel >=1\n fprintf('\\nG MATRIX - Summary\\n')\n disp(summary_1)\nend\nini_time = toc(time_a);\n\n% Step 1 - Reactions with 1 gene\n% clc\nif printLevel >=1\n disp('G MATRIX - STEP 1');\nend\ntime_b = tic;\nact_rxnGeneMat = rxnGeneMat(rxns_1_gene, :);\nnot_delete_cols = sum(act_rxnGeneMat, 1) ~= 0;\nact_rxnGeneMat = act_rxnGeneMat(:, not_delete_cols);\nG_ind_1 = model.genes(not_delete_cols);\nn_KO_1 = length(G_ind_1);\ntmp_G_1 = act_rxnGeneMat';\nG_1 = zeros(n_KO_1, n_rxns);\nG_1(:, rxns_1_gene) = tmp_G_1;\nG_time(1, 1) = toc(time_b);\n\n% Step2 - Reactions with more than one gene and only OR rules\n% clc\nif printLevel >=1\n disp('G MATRIX - STEP 2');\nend\ntime_c = tic;\nact_rxnGeneMat = rxnGeneMat(rxns_only_or, :);\npos_rxns_only_or = find(rxns_only_or);\nfor i = 1:n_rxns_only_or\n G_ind_2{i, 1} = model.genes(logical(act_rxnGeneMat(i, :)))';\nend\ntmp_G_2 = eye(n_rxns_only_or);\nG_2 = zeros(n_rxns_only_or, n_rxns);\nG_2(:, rxns_only_or) = tmp_G_2;\nG_time(2, 1) = toc(time_c);\n\n% Reactions with more than one gene and only AND rules\n% clc\nif printLevel >=1\n disp('G MATRIX - STEP 3');\nend\ntime_d = tic;\nact_rxnGeneMat = rxnGeneMat(rxns_only_and, :);\nnot_delete_cols = sum(act_rxnGeneMat, 1) ~= 0;\nact_rxnGeneMat = act_rxnGeneMat(:, not_delete_cols);\nG_ind_3 = model.genes(not_delete_cols);\nn_KO_3 = length(G_ind_3);\ntmp_G_3 = act_rxnGeneMat';\nG_3 = zeros(n_KO_3, n_rxns);\nG_3(:, rxns_only_and) = tmp_G_3;\nG_time(3, 1) = toc(time_d);\n\n% Reactions with more than one gene and both OR and AND rules\ntime_e = tic;\nsearch_filename = [tmpFolderName filesep 'rxn_level_models' filesep 'rxn_level_' model_name '_and_or.mat'];\nif exist(search_filename,'file')\n load(search_filename);\nelse\n pos_rxns_or_and = find(rxns_or_and);\n [models_or_and, rxnNumGenes_or_and] = GPR2models(model, pos_rxns_or_and, separate_isoform, numWorkers, printLevel);\n save(search_filename, 'models_or_and', 'rxnNumGenes_or_and');\nend\n\nsearch_filename_2 = [tmpFolderName filesep 'rxn_level_gMCSs' filesep 'rxn_level_gMCSs_' model_name '.mat'];\nif exist(search_filename_2,'file')\n load(search_filename_2);\nelse\n target_b = 1e-3;\n n_mcs = 100000000000;\n timelimit = 5*60;\n pos_rxns_or_and = find(rxns_or_and);\n if printLevel >=1\n disp('G MATRIX - STEP 4');\n showprogress(0);\n end\n for i = 1:n_rxns_or_and\n if printLevel >=1\n% disp([num2str(i),' of ', num2str(n_rxns_or_and)]);\n showprogress(i/n_rxns_or_and);\n end\n search_filename_3 = [tmpFolderName filesep 'rxn_level_gMCSs_by_rxn' filesep 'rxn_level_gMCSs_' model_name '_rxn' num2str(pos_rxns_or_and(i)) '.mat'];\n if exist(search_filename_3,'file')\n load(search_filename_3);\n mcs{i, 1} = act_mcs;\n else\n act_model = models_or_and{i};\n nbio = find(act_model.c);\n rxns = act_model.rxns;\n tmp = repmat({'DM_'}, length(rxns), 1);\n DM = cellfun(@strfind, rxns, tmp, 'UniformOutput', false);\n DM = ~cellfun(@isempty, DM);\n n_DM = sum(DM);\n DM = rxns(find(DM));\n% options.rxn_set = DM;\n% % options.timelimit = timelimit;\n% options.target_b = target_b;\n% options.printLevel = 0;\n max_len_mcs = length(DM);\n [act_mcs, act_mcs_time] = calculateMCS(act_model, n_mcs, max_len_mcs,...\n 'rxn_set', DM,...\n 'timelimit', timelimit,... \n 'target_b', target_b,...\n 'printLevel', 0);\n mcs{i, 1} = act_mcs;\n mcs_time{i, 1} = act_mcs_time;\n save(search_filename_3, 'act_mcs', 'act_mcs_time');\n end\n end\n save(search_filename_2);\nend\n\nk = 0;\nfor i = 1:n_rxns_or_and\n load([tmpFolderName filesep 'rxn_level_gMCSs_by_rxn' filesep 'rxn_level_gMCSs_' model_name '_rxn' num2str(pos_rxns_or_and(i)) '.mat']);\n n_act_mcs = length(act_mcs);\n\n for j = 1:n_act_mcs\n act_G_ind = act_mcs{j};\n if ~iscell(act_G_ind) && isnan(act_G_ind)\n else\n act_G_ind = cellfun(@strrep, act_G_ind, repmat({'DM_'}, length(act_G_ind), 1), repmat({''}, length(act_G_ind), 1), 'UniformOutput', false);\n act_G_ind = cellfun(@strtok, act_G_ind, repmat({separate_isoform}, length(act_G_ind), 1), 'UniformOutput', false);\n k = k+1;\n G_4(k, :) = zeros(1, n_rxns);\n G_4(k, pos_rxns_or_and(i)) = 1;\n G_ind_4{k, 1} = act_G_ind';\n end\n end\nend\nG_time(4, 1) = toc(time_e);\n\n% Delete isoforms in order to work at the gene level\ntime_f = tic;\nG_ind_1 = cellfun(@strtok, G_ind_1, repmat({separate_isoform}, length(G_ind_1), 1), 'UniformOutput', false);\n\nn_KO_2 = length(G_ind_2);\nfor i = 1:n_KO_2\n act_G_ind_2 = G_ind_2{i};\n act_G_ind_2 = cellfun(@strtok, act_G_ind_2, repmat({separate_isoform}, 1, length(act_G_ind_2)), 'UniformOutput', false);\n G_ind_2{i} = unique(act_G_ind_2);\nend\nG_ind_3 = cellfun(@strtok, G_ind_3, repmat({separate_isoform}, length(G_ind_3), 1), 'UniformOutput', false);\n\n% Delete repeats\nif printLevel >=1\n disp('G MATRIX - Delete Repeats');\nend\ntmp_G = [];\ntry tmp_G = [tmp_G; G_1]; end\ntry tmp_G = [tmp_G; G_2]; end\ntry tmp_G = [tmp_G; G_3]; end\ntry tmp_G = [tmp_G; G_4]; end\ntmp_G_ind = [];\ntry tmp_G_ind = [tmp_G_ind; G_ind_1]; end\ntry tmp_G_ind = [tmp_G_ind; G_ind_2]; end\ntry tmp_G_ind = [tmp_G_ind; G_ind_3]; end\ntry tmp_G_ind = [tmp_G_ind; G_ind_4]; end\nn_tmp_G_ind = length(tmp_G_ind);\n\nk = 0;\nclear G G_ind\nfor i = 1:n_tmp_G_ind\n if i == 1\n k = k+1;\n G(k, :) = tmp_G(i, :);\n if ~iscell(tmp_G_ind{i})\n G_ind{k, 1} = tmp_G_ind(i);\n else\n G_ind{k, 1} = sort(tmp_G_ind{i});\n end\n else\n if ~iscell(tmp_G_ind{i})\n act_G_ind = tmp_G_ind(i);\n else\n act_G_ind = sort(tmp_G_ind{i});\n end\n\n pos_equal = cellfun(@isequal, G_ind, repmat({act_G_ind}, length(G_ind), 1));\n if sum(pos_equal) > 0\n G(pos_equal, :) = G(pos_equal, :) + tmp_G(i, :);\n else\n k = k+1;\n G(k, :) = tmp_G(i, :);\n G_ind{k, 1} = act_G_ind;\n end\n end\nend\n\n% Fill the G matrix with reactions which are knocked out by a given KO\n% without being a gMCS\nn_genes_KO = cellfun(@length, G_ind);\n[n_genes_KO, ind] = sort(n_genes_KO, 'ascend');\nG_ind = G_ind(ind);\nG = G(ind, :);\nn_G_ind = length(G_ind);\nfor i = 1:n_G_ind\n act_G_ind = G_ind{i};\n n_act_G_ind = length(act_G_ind);\n pos = find(n_genes_KO > n_act_G_ind);\n greater_G_ind = G_ind(pos);\n n_greater_G_ind = length(pos);\n for j = 1:n_greater_G_ind\n if sum(ismember(G_ind{pos(j)}, act_G_ind)) == n_act_G_ind\n G(pos(j), :) = G(pos(j), :) + G(i, :);\n end\n end\nend\nG = double(G>0);\n\n% Check the interconnections between KOs\nif printLevel >=1\n disp('G MATRIX - Check Relations');\nend\nk = 0;\nn_genes_KO = cellfun(@length, G_ind);\nfor i = 2:n_G_ind\n act_G_ind = G_ind(i);\n n_act_G_ind = length(act_G_ind{:});\n pos = find(n_genes_KO < n_act_G_ind);\n if ~isempty(pos)\n pos = pos(end);\n for j = 1:pos\n act_G_ind_2 = G_ind(j);\n tmp = ismember(act_G_ind{:}, act_G_ind_2{:});\n n_act_G_ind_2 = length(act_G_ind_2{:});\n if sum(tmp) == n_act_G_ind_2\n k = k+1;\n related(k, 1) = i;\n related(k, 2) = j;\n end\n end\n end\nend\n\nif exist('related')\n un_related = unique(related(:, 1));\n n_un_related = length(un_related);\n for i = 1:n_un_related\n act_KO = un_related(i);\n ind = find(related(:, 1) == act_KO);\n act_related = related(ind, 2);\n all_genes = [G_ind{act_related}];\n un_all_genes = unique(all_genes);\n n_un_all_genes = length(un_all_genes);\n n_genes_KO(act_KO) = n_genes_KO(act_KO)-n_un_all_genes;\n end\nelse\n related = NaN;\nend\n\nfinal_filename = [pwd filesep 'G_' model_name '.mat'];\nG_time(5, 1) = toc(time_f)+ini_time;\nsave(final_filename, 'G', 'G_ind', 'related', 'n_genes_KO', 'G_time');\nif printLevel >=1\n disp('The G Matrix has been successfully calculated');\nend\nrmdir(tmpFolderName, 's');\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/gMCS/buildGmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.028007522330025302, "lm_q1q2_score": 0.008701779875695058}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2010, John T. Ramshur, jramshur@gmail.com\n% \n% This file is part of HRVAS\n%\n% HRVAS 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% HRVAS 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 HRVAS. If not, see .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction batchHRV(opt)\n%batchHRV: function that calculates hrv on all ibi files in selected\n% directory\n%\n%Inputs:\n%\n%Outputs:\n%\n\n\n%check inputs\n% if (nargin < 1) || ~isstruct(opt)\n% \n% end\n\n\n %choose file containing HRV analysis options\n reply = input('Enter full file path of HRV analysis option file: ', 's');\n if isempty(reply) || exist(reply,'file')~=2\n error('Please choose valid file path!')\n return;\n end\n opt=load(reply);\n opt=opt.settings;\n \n %choose dir containing input files\n reply = input('Enter dir path containing IBI files: ', 's');\n if isempty(reply) || exist(reply,'dir')~=7\n error('Please choose valid input dir path!')\n return;\n end\n \n %check input directory\n fileList = dir(fullfile(reply, '*.ibi')); %get list of files\n fileList(any([fileList.isdir],1))=[]; %remove folders/dir from the list\n fnames = {fileList.name}; %get file names only from fileList structure \n %build array of full file paths \n fpaths=cell(length(fnames),1);\n for ff=1:length(fnames)\n fpaths{ff}=fullfile(reply,fnames{ff});\n end \n \n %display results of input dir\n disp([reply ' contains ' num2str(length(fpaths)) ' .ibi files.'])\n \n %choose output file name to save hrv reslts \n outPath = input('Enter file name for exported HRV data: ', 's');\n if isempty(outPath)\n error('Please choose valid input dir path!')\n return;\n end\n \n %Batch process HRV\n hrv=batchGetHRV(fpaths,opt); \n\n %Export/save HRV\n saveHRV(hrv,opt,fpaths,outPath)\n disp('batchHRV Done!')\n\nend\n\nfunction saveHRV(hrv,opt,fList,outPath) \n exportHRV(outPath,fList,hrv,opt) \nend\n\nfunction hrv=batchGetHRV(fList,opt)\n %Preallocate hrv array\n %hrv=repmat(struct('b',0,'a',0),1,length(fList));\n\n %display time remaining\n disp('Processing: 0% complete.')\n tic; avgElapsed=0;\n \n %get hrv for each file\n nFiles=length(fList);\n for f=1:nFiles \n hrv(f)=getHRV(fList{f},opt);\n\n %calculate remaining time for waitbar\n elapsedTime=toc; %total time elapsed since start\n %average time elapsed to process a single file\n avgElapsed=elapsedTime/f; \n %time remaining in processing (min)\n timeRem=ceil(avgElapsed*(nFiles-f)/60);\n bar=round(f/nFiles*100);\n disp(['Processing: ' num2str(bar) ...\n '% complete. (~' num2str(timeRem) ' min)']) \n end \n \nend \n\nfunction output=getHRV(f,settings)\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % LOAD IBI\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n nIBI=[]; dIBI=[];\n IBI=loadIBI(f,settings);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %Preprocess Data\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n %build cell array of locate artifacts methods\n methods={}; methInput=[];\n if settings.ArtLocatePer\n methods=[methods,'percent'];\n methInput=[methInput,settings.ArtLocatePerVal];\n end\n if settings.ArtLocateSD\n methods=[methods,'sd'];\n methInput=[methInput,settings.ArtLocateSDVal];\n end\n if settings.ArtLocateMed\n methods=[methods,'median'];\n methInput=[methInput,settings.ArtLocateMedVal];\n end\n %determine which window/span to use\n if strcmpi(settings.ArtReplace,'mean')\n replaceWin=settings.ArtReplaceMeanVal;\n elseif strcmpi(settings.ArtReplace,'median')\n replaceWin=settings.ArtReplaceMedVal;\n else\n replaceWin=0;\n end\n\n %Note: We don't need to use all the input arguments,but we will let the\n %function handle all inputs\n [dIBI,nIBI,trend,art] = preProcessIBI(IBI, ...\n 'locateMethod', methods, 'locateInput', methInput, ...\n 'replaceMethod', settings.ArtReplace, ...\n 'replaceInput',replaceWin, ...\n 'detrendMethod', settings.Detrend, ...\n 'smoothMethod', settings.SmoothMethod, ...\n 'smoothSpan', settings.SmoothSpan, ...\n 'smoothDegree', settings.SmoothDegree, ...\n 'polyOrder', settings.PolyOrder, ...\n 'waveletType', ...\n [settings.WaveletType num2str(settings.WaveletType2)], ...\n 'waveletLevels', settings.WaveletLevels, ...\n 'lambda', settings.PriorsLambda,...\n 'resampleRate',settings.Interp,...\n 'meanCorrection',true);\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %Calculate HRV\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n output.ibiinfo.count=size(IBI,1); % total # of ibi\n output.ibiinfo.outliers=sum(art); % number of outliers\n\n %Time-Domain (using non-detrented ibi)\n output.time=timeDomainHRV(nIBI,settings.SDNNi*60,settings.pNNx);\n %output.time.mean=round(mean(nIBI(:,2).*1000)*10)/10;\n %output.time.meanHR=round(mean(60./nIBI(:,2))*10)/10;\n\n %Freq-Domain\n output.freq=freqDomainHRV(dIBI,settings.VLF,settings.LF, ...\n settings.HF,settings.AROrder,settings.WinWidth, ...\n settings.WinOverlap,settings.Points,settings.Interp); \n\n %Nonlinear (using non-detrented ibi)\n output.nl=nonlinearHRV(nIBI,settings.m,settings.r, ...\n settings.n1,settings.n2,settings.breakpoint); \n %Poincare\n output.poincare=poincareHRV(nIBI);\n\n %Time-Freq \n output.tf=timeFreqHRV(dIBI,nIBI,settings.VLF,settings.LF, ...\n settings.HF,settings.AROrder, settings.tfWinSize, ...\n settings.tfOverlap,settings.Points,settings.Interp, ...\n {'ar','lomb','wavelet'});\n %%%%%%%%%%%%%%%%%%%%%%%\n \n clear nIBI dIBI IBI\n\nend\n\nfunction ibi=loadIBI(f,opt)\n if ~exist(f,'file')\n error(['Error opening file: ' f])\n return\n end \n\n ibi=[]; \n DELIMITER = ',';\n HEADERLINES = opt.headerSize;\n\n %read ibi\n tmpData = importdata(f, DELIMITER, HEADERLINES);\n if HEADERLINES>0\n tmpData=tmpData.data; \n end \n\n %check ibi dimentions\n [rows cols] = size(tmpData);\n if rows==1\n tmpData=tmpData';\n ibi=zeros(cols,2);\n tmp=cumsum(tmpData);\n ibi(2:end,1)=tmp(1:end-1);\n ibi(:,2)=tmpData;\n elseif cols==1\n ibi=zeros(rows,2);\n tmp=cumsum(tmpData);\n ibi(2:end,1)=tmp(1:end-1);\n ibi(:,2)=tmpData;\n elseif rows.\n\n% Define as a handle class - A handle class constructor returns a handle\n% object that is a reference to the object created. You can assign the\n% handle object to multiple variables or pass it to functions without\n% causing MATLAB to make a copy of the original object. A function that\n% modifies a handle object passed as an input argument does not need to\n% return the object.\nclassdef kWaveTransducer < handle\n\n % define the properties of the transducer that cannot be modified by\n % the user after the transducer is initialised (these parameters are\n % stored). The numbers assigned here are the default values used if the\n % parameters are not set explicitly by the user.\n properties (GetAccess = 'public', SetAccess = 'private')\n \n % the total number of transducer elements\n number_elements = 128; \n \n % the width of each element in grid points\n element_width = 1;\n \n % the length of each element in grid points\n element_length = 20;\n \n % the spacing (kerf width) between the transducer elements in grid\n % points\n element_spacing = 0; \n \n % the position of the corner of the transducer in the grid\n position = [1, 1, 1]; \n \n % the radius of curvature of the transducer [m]\n radius = inf; \n \n end\n \n % define the properties of the transducer that can be modified by the\n % user after the transducer is initialised (these parameters are\n % stored). The numbers assigned here are the default values used if the\n % parameters are not set explicitly by the user.\n properties (Access = 'public')\n \n % the transducer elements that are currently active elements\n active_elements; \n \n % the focus depth in the elevation direction [m]\n elevation_focus_distance = inf;\n\n % transmit apodization\n transmit_apodization = 'Rectangular'; \n \n % receive apodization\n receive_apodization = 'Rectangular';\n \n % sound speed used to calculate beamforming delays [m/s]\n sound_speed = 1540;\n \n % focus distance used to calculate beamforming delays [m]\n focus_distance = inf;\n \n % time index to start recording if transducer is used as a sensor\n record_start_index = 1;\n \n end\n \n % define the dependent properties (these parameters are computed when\n % queried). Some of these properties act like normal user-modifiable\n % properties (e.g., steering_angle), but instead have explicit set and\n % get functions that change an internal stored value. This allows error\n % checking when the properties are changed.\n properties(Dependent = true)\n \n % binary mask of the active transducer elements\n active_elements_mask;\n \n % indexed mask of the active transducer elements, where the index\n % indicates the transducer element that each grid point belongs to.\n indexed_active_elements_mask;\n \n % binary mask of all the transducer elements (both active and\n % inactive)\n all_elements_mask;\n \n % indexed mask of all the transducer elements, where the index\n % indicates the transducer element that each grid point belongs to.\n indexed_elements_mask;\n \n % pseudonym for the active_elements_mask to maintain compatability\n % when the transducer is used in place of sensor or source.\n mask;\n \n % total width of the transducer in grid points\n transducer_width;\n \n % current number of active transducer elements\n number_active_elements;\n \n % user defined input signal with appended zeros dependent on the\n % beamforming (steering_angle, focus_distance) settings\n input_signal;\n \n % maximum steering angle - this sets the beamforming delay offset\n steering_angle_max;\n \n % number of zeros appended to input signal to allow a single time\n % series to be used within kspaceFirstOrder3D (either set to 'auto'\n % or based on the setting for steering_angle_max)\n appended_zeros;\n \n % offset used to make all the delays in the delay_mask positive\n % (either set to 'auto' or based on the setting for\n % steering_angle_max) \n beamforming_delays_offset;\n \n % steering angle used to calculate beamforming delays [deg]\n steering_angle;\n \n end\n \n % define the hidden properties - these cannot be seen or accessed\n % directly by the user, and are used to store internal properties\n properties (Hidden = true, Access = 'private')\n \n % indexed sensor mask from which the other masks are computed\n indexed_mask;\n \n % indexed mask for the voxels in each element used to compute\n % elevation focussing\n indexed_element_voxel_mask;\n \n % size of the grid in which the transducer is defined\n stored_grid_size;\n \n % corresponding grid spacing\n grid_spacing; \n \n % time spacing\n dt;\n\n % original copy of the user defined input signal\n stored_input_signal;\n \n % stored value of appended_zeros (accessed using get and\n % set methods). This is used to set the number of zeros that are\n % appended and prepended to the input signal.\n stored_appended_zeros = 'auto';\n \n % stored value of the minimum beamforming delay. This is used to\n % offset the delay mask so that all the delays are >= 0\n stored_beamforming_delays_offset = 'auto';\n \n % stored value of the steering_angle_max (accessed using get and\n % set methods). This can be set by the user and is used to derive\n % the two parameters above.\n stored_steering_angle_max = 'auto';\n \n % stored value of the steering_angle (accessed using get and\n % set methods)\n stored_steering_angle = 0;\n \n end\n \n % constructor function\n methods\n function transducer = kWaveTransducer(kgrid, transducer_properties)\n \n % allocate the grid size and spacing\n transducer.stored_grid_size = [kgrid.Nx, kgrid.Ny, kgrid.Nz];\n transducer.grid_spacing = [kgrid.dx, kgrid.dy, kgrid.dz];\n \n % allocate the temporal spacing\n if isnumeric(kgrid.dt)\n transducer.dt = kgrid.dt;\n elseif isnumeric(kgrid.t_array)\n transducer.dt = kgrid.t_array(2) - kgrid.t_array(1);\n else\n error('kgrid.dt or kgrid.t_array must be explicitly defined');\n end\n \n % check for properties input\n if nargin == 1\n transducer_properties = [];\n end\n \n % check the input fields\n checkFieldNames(transducer_properties, {...\n 'number_elements', 'element_width', 'element_length', 'element_spacing',...\n 'position', 'radius', ...\n 'active_elements', 'elevation_focus_distance', 'focus_distance', 'steering_angle',...\n 'receive_apodization', 'transmit_apodization',...\n 'sound_speed', 'input_signal', 'steering_angle_max'});\n \n % replace default settings with user defined properties if\n % given\n % -------------------------------------------------------------\n \n if isfield(transducer_properties, 'number_elements')\n % force value to be a positive integer\n transducer.number_elements = round(abs(transducer_properties.number_elements));\n end\n \n if isfield(transducer_properties, 'element_width')\n % force value to be a positive integer\n transducer.element_width = round(abs(transducer_properties.element_width));\n end\n \n if isfield(transducer_properties, 'element_length')\n % force value to be a positive integer\n transducer.element_length = round(abs(transducer_properties.element_length));\n end\n \n if isfield(transducer_properties, 'element_spacing')\n % force value to be a positive integer\n transducer.element_spacing = round(abs(transducer_properties.element_spacing));\n end\n \n if isfield(transducer_properties, 'position')\n % force values to be positive integers\n transducer.position = round(abs(transducer_properties.position));\n end\n \n if isfield(transducer_properties, 'radius')\n transducer.radius = transducer_properties.radius;\n \n % only allow an infinite radius for now\n if ~isinf(transducer.radius)\n error('Only a value of transducer.radius = inf is currently supported');\n end\n end\n \n if isfield(transducer_properties, 'active_elements')\n transducer.active_elements = transducer_properties.active_elements;\n else\n transducer.active_elements = ones(transducer_properties.number_elements, 1);\n end\n \n if isfield(transducer_properties, 'elevation_focus_distance')\n transducer.elevation_focus_distance = transducer_properties.elevation_focus_distance;\n end\n \n if isfield(transducer_properties, 'receive_apodization')\n % if a user defined apodization is given explicitly, check\n % the length of the input\n if isnumeric(transducer_properties.receive_apodization) ...\n && (length(transducer_properties.receive_apodization) ~= transducer.number_active_elements)\n error('The length of the receive apodization input must match the number of active elements');\n end\n \n % assign the input \n transducer.receive_apodization = transducer_properties.receive_apodization; \n end\n \n if isfield(transducer_properties, 'transmit_apodization')\n % if a user defined apodization is given explicitly, check\n % the length of the input\n if isnumeric(transducer_properties.transmit_apodization) ...\n && (length(transducer_properties.transmit_apodization) ~= transducer.number_active_elements)\n error('The length of the transmit apodization input must match the number of active elements');\n end\n \n % assign the input\n transducer.transmit_apodization = transducer_properties.transmit_apodization; \n end \n \n if isfield(transducer_properties, 'sound_speed')\n transducer.sound_speed = transducer_properties.sound_speed;\n \n % check to see the sound_speed is positive\n if ~(transducer.sound_speed> 0)\n error('transducer.sound_speed must be greater than 0');\n end \n end\n \n if isfield(transducer_properties, 'focus_distance')\n transducer.focus_distance = transducer_properties.focus_distance;\n end\n \n if isfield(transducer_properties, 'input_signal')\n transducer.stored_input_signal = transducer_properties.input_signal;\n \n % force the input signal to be a column vector\n if numDim(transducer.input_signal) == 1\n transducer.stored_input_signal = reshape(transducer.stored_input_signal, [], 1);\n else\n error('transducer.input_signal must be a one-dimensional array');\n end\n end\n \n if isfield(transducer_properties, 'steering_angle_max')\n % set the maximum steering angle using the set method (this\n % avoids having to duplicate error checking)\n transducer.steering_angle_max = transducer_properties.steering_angle_max;\n end\n \n if isfield(transducer_properties, 'steering_angle')\n % set the maximum steering angle using the set method (this\n % avoids having to duplicate error checking)\n transducer.steering_angle = transducer_properties.steering_angle;\n end\n \n % -------------------------------------------------------------\n \n % check the transducer fits into the grid\n if sum(transducer.position(:) == 0)\n error('The defined transducer must be positioned within the grid');\n elseif (transducer.position(2) + transducer.number_elements*transducer.element_width + (transducer.number_elements - 1)*transducer.element_spacing) > transducer.stored_grid_size(2)\n error('The defined transducer is too large or positioned outside the grid in the y-direction');\n elseif (transducer.position(3) + transducer.element_length) > transducer.stored_grid_size(3)\n transducer.position(3)\n transducer.element_length\n transducer.stored_grid_size(3)\n error('The defined transducer is too large or positioned outside the grid in the z-direction');\n elseif transducer.position(1) > transducer.stored_grid_size(1)\n error('The defined transducer is positioned outside the grid in the x-direction');\n end\n \n % assign the data type for the transducer matrix based on the\n % number of different elements (uint8 supports 255 numbers so\n % most of the time this data type will be used)\n if transducer.number_elements < intmax('uint8');\n mask_type = 'uint8';\n elseif transducer.number_elements < intmax('uint16');\n mask_type = 'uint16';\n elseif transducer.number_elements < intmax('uint32');\n mask_type = 'uint32'; \n else\n mask_type = 'uint64';\n end\n \n % create an empty transducer mask (the grid points within\n % element 'n' are all given the value 'n')\n transducer.indexed_mask = zeros(transducer.stored_grid_size, mask_type);\n \n % create a second empty mask used for the elevation beamforming\n % delays (the grid points across each element are numbered 1 to\n % M, where M is the number of grid points in the elevation\n % direction)\n transducer.indexed_element_voxel_mask = zeros(transducer.stored_grid_size, mask_type);\n \n % create the corresponding indexing variable 1:M\n element_voxel_index = repmat(1:transducer.element_length, transducer.element_width, 1);\n \n % for each transducer element, calculate the grid point indices\n for element_index = 1:transducer.number_elements\n\n % assign the current transducer position\n element_pos_x = transducer.position(1);\n element_pos_y = transducer.position(2) + (transducer.element_width + transducer.element_spacing)*(element_index - 1);\n element_pos_z = transducer.position(3);\n \n % assign the grid points within the current element the\n % index of the element\n transducer.indexed_mask(element_pos_x, element_pos_y:element_pos_y + transducer.element_width - 1, element_pos_z:element_pos_z + transducer.element_length - 1) = element_index;\n \n % assign the individual grid points an index corresponding\n % to their order across the element\n transducer.indexed_element_voxel_mask(element_pos_x, element_pos_y:element_pos_y + transducer.element_width - 1, element_pos_z:element_pos_z + transducer.element_length - 1) = element_voxel_index;\n\n end\n\n % double check the transducer fits within the desired grid size\n if any(size(transducer.indexed_elements_mask) ~= transducer.stored_grid_size)\n error('Desired transducer is larger than the input grid_size');\n end\n \n end\n end\n \n % set and get functions for dependent variables\n methods\n \n % return input signal\n function signal = get.input_signal(obj)\n \n % copy the stored input signal\n signal = obj.stored_input_signal;\n \n % check the signal is not empty\n if isempty(signal)\n error('Transducer input signal is not defined');\n end\n \n % automatically prepend and append zeros if the beamforming\n % delay offset is set\n \n % check if the beamforming delay offset is set. If so, use this\n % number to prepend and append this number of zeros to the\n % input signal. Otherwise, calculate how many zeros are needed\n % and prepend and append these.\n if ~strcmp(obj.stored_appended_zeros, 'auto')\n \n % use the current value of the beamforming offset to add\n % zeros to the input signal\n signal = [zeros(obj.stored_appended_zeros, 1); signal; zeros(obj.stored_appended_zeros, 1)];\n \n else\n \n % get the current delay beam forming \n delay_mask = obj.delay_mask;\n\n % find the maximum delay\n delay_max = max(delay_mask(:));\n\n % count the number of leading zeros in the input signal\n leading_zeros = find(signal ~= 0, 1) - 1;\n\n % count the number of trailing zeros in the input signal\n trailing_zeros = find(flipud(signal) ~= 0, 1) - 1;\n\n % check the number of leading zeros is sufficient given the\n % maximum delay\n if leading_zeros < delay_max + 1\n disp([' prepending transducer.input_signal with ' num2str(delay_max - leading_zeros + 1) ' leading zeros']);\n\n % prepend extra leading zeros\n signal = [zeros(delay_max - leading_zeros + 1, 1); signal]; \n end\n\n % check the number of leading zeros is sufficient given the\n % maximum delay\n if trailing_zeros < delay_max + 1\n disp([' appending transducer.input_signal with ' num2str(delay_max - trailing_zeros + 1) ' trailing zeros']);\n\n % append extra trailing zeros\n signal = [signal; zeros(delay_max - trailing_zeros + 1, 1)];\n end\n end\n \n end\n \n function transducer_width = get.transducer_width(obj)\n % return the overall length of the transducer\n transducer_width = obj.number_elements*obj.element_width + (obj.number_elements - 1)*obj.element_spacing;\n end\n \n function number_active_elements = get.number_active_elements(obj)\n % return the current number of active elements\n number_active_elements = sum(obj.active_elements(:));\n end\n \n % allow mask query to allow compatability with regular sensor\n % structure - return the active sensor mask\n function mask = get.mask(obj)\n mask = obj.active_elements_mask;\n end \n \n % return a binary mask showing the locations of the active elements\n function mask = get.active_elements_mask(obj)\n \n % copy the indexed elements mask\n mask = obj.indexed_mask;\n \n % remove inactive elements from the mask\n for element_index = 1:obj.number_elements\n mask(mask == element_index) = obj.active_elements(element_index);\n end\n \n % convert remaining mask to binary\n mask(mask ~= 0) = 1;\n\n end \n \n % return a binary mask showing the locations of all the elements\n % (both active and inactive)\n function mask = get.all_elements_mask(obj)\n mask = obj.indexed_mask;\n mask(mask ~= 0) = 1;\n end \n \n % return a copy of the indexed elements mask\n function mask = get.indexed_elements_mask(obj)\n mask = obj.indexed_mask;\n end\n \n % return a copy of the indexed elements mask only for the active\n % elements\n function mask = get.indexed_active_elements_mask(obj)\n \n % copy the indexed elements mask\n mask = obj.indexed_mask;\n \n % remove inactive elements from the mask\n for element_index = 1:obj.number_elements\n if ~(obj.active_elements(element_index))\n mask(mask == element_index) = 0;\n end\n end\n \n % force the lowest element index to be 1\n lowest_active_element_index = find(obj.active_elements, 1);\n mask(mask ~= 0) = mask(mask ~= 0) - lowest_active_element_index + 1;\n\n end \n \n % return the stored value of the steering angle\n function steering_angle = get.steering_angle(obj)\n steering_angle = obj.stored_steering_angle;\n end\n \n % set the stored value of the steering angle\n function set.steering_angle(obj, steering_angle)\n \n % force to be scalar\n steering_angle = steering_angle(1);\n \n % check if the steering angle is between -90 and 90\n if ~(steering_angle < 90 && steering_angle > -90)\n error('Input for steering_angle must be betweeb -90 and 90 degrees');\n end\n \n % check if the steering angle is less than the maximum steering\n % angle\n if ~strcmp(obj.stored_steering_angle_max, 'auto') && (abs(steering_angle) > obj.stored_steering_angle_max)\n error('Input for steering_angle cannot be greater than steering_angle_max');\n end\n \n % update the stored value\n obj.stored_steering_angle = steering_angle;\n \n end \n \n % return the stored value of the maximum steering angle\n function steering_angle_max = get.steering_angle_max(obj)\n steering_angle_max = obj.stored_steering_angle_max;\n end\n \n % set the stored value of the maximum steering angle and\n % beamforming offset\n function set.steering_angle_max(obj, steering_angle_max)\n \n % force input to be scalar and positive\n steering_angle_max = steering_angle_max(1);\n \n % check the steering angle is within range\n if ~(steering_angle_max < 90 && steering_angle_max > -90)\n error('Input for steering_angle_max must be between -90 and 90');\n end\n \n % check the maximum steering angle is greater than the current\n % steering angle\n if ~strcmp(obj.stored_steering_angle_max, 'auto') && (abs(obj.stored_steering_angle) > steering_angle_max)\n error('Input for steering_angle_max cannot be less than the current steering_angle');\n end\n \n % overwrite the stored value\n obj.stored_steering_angle_max = steering_angle_max;\n \n % store a copy of the current value for the steering angle\n current_steering_angle = obj.stored_steering_angle;\n \n % overwrite with the user defined maximum value\n obj.stored_steering_angle = steering_angle_max;\n \n % set the beamforming delay offset to zero (this means the\n % delays will contain negative values which we can use to\n % derive the new values for the offset)\n obj.stored_appended_zeros = 0;\n obj.stored_beamforming_delays_offset = 0;\n \n % get the element beamforming delays and reverse\n delay_times = -obj.beamforming_delays; \n \n % get the maximum and minimum beamforming delays\n max_delay = max(delay_times);\n min_delay = min(delay_times);\n \n % add the maximum and minimum elevation delay if the elevation\n % focus is not set to infinite \n if ~isinf(obj.elevation_focus_distance)\n max_delay = max_delay + max(obj.elevation_beamforming_delays);\n min_delay = min_delay + min(obj.elevation_beamforming_delays); \n end\n \n % set the beamforming offset to the difference between the\n % maximum and minimum delay \n obj.stored_appended_zeros = max_delay - min_delay;\n \n % set the minimum beamforming delay (converting to a positive\n % number)\n obj.stored_beamforming_delays_offset = - min_delay;\n \n % reset the previous value of the steering angle\n obj.stored_steering_angle = current_steering_angle;\n \n end\n \n % return the stored value of appended zeros\n function appended_zeros = get.appended_zeros(obj)\n appended_zeros = obj.stored_appended_zeros;\n end\n \n % return the stored value of the offset used to force the values in\n % delay_mask to be >= 0\n function beamforming_delays_offset = get.beamforming_delays_offset(obj)\n beamforming_delays_offset = obj.stored_beamforming_delays_offset;\n end\n \n end\n \n % general class methods\n methods\n \n % calculate the beamforming delays based on the focus and steering\n % settings\n function delay_times = beamforming_delays(obj)\n \n % calculate the element pitch in [m]\n element_pitch = (obj.element_spacing + obj.element_width)*obj.grid_spacing(2);\n\n % create indexing variable\n element_index = -(obj.number_active_elements - 1)/2:(obj.number_active_elements - 1)/2; \n\n % check for focus depth\n if isinf(obj.focus_distance)\n % calculate time delays for a steered beam \n delay_times = element_pitch*element_index*sin(obj.steering_angle*pi/180)/(obj.sound_speed); % [s]\n else \n % calculate time delays for a steered and focussed beam\n delay_times = obj.focus_distance/obj.sound_speed * (1 - sqrt(...\n 1 ... \n + (element_index*element_pitch./obj.focus_distance).^2 ... \n - 2 * (element_index*element_pitch./obj.focus_distance) * sin(obj.steering_angle*pi/180) ...\n )); % [s]\n end\n \n % convert the delays to be in units of time points\n delay_times = round(delay_times/obj.dt); \n \n end\n \n % calculate the elevation beamforming delays based on the focus \n % setting\n function delay_times = elevation_beamforming_delays(obj)\n \n if ~isinf(obj.elevation_focus_distance)\n \n % create indexing variable\n element_index = -(obj.element_length - 1)/2:(obj.element_length - 1)/2; \n\n % calculate time delays for a focussed beam\n delay_times = (obj.elevation_focus_distance - sqrt( (element_index*obj.grid_spacing(3)).^2 + obj.elevation_focus_distance^2 ))./obj.sound_speed;\n\n % convert the delays to be in units of time points and then\n % reverse \n delay_times = -round(delay_times/obj.dt);\n \n else\n \n % create an empty array\n delay_times = zeros(1, obj.element_length);\n \n end\n\n end\n \n % function to create a scan line based on the input sensor data and\n % the current apodization and beamforming setting\n function line = scan_line(obj, sensor_data)\n \n % get the current apodization setting\n apodization = obj.get_receive_apodization;\n \n % get the current beamforming weights and reverse\n delays = -obj.beamforming_delays; \n\n % offset the received sensor_data by the beamforming delays and\n % apply receive apodization \n for element_index = 1:obj.number_active_elements\n if delays(element_index) > 0\n % shift element data forwards\n sensor_data(element_index, :) = apodization(element_index).*[sensor_data(element_index, 1 + delays(element_index):end), zeros(1, delays(element_index))];\n elseif delays(element_index) < 0\n % shift element data backwards\n sensor_data(element_index, :) = apodization(element_index).*[zeros(1, -delays(element_index)), sensor_data(element_index, 1:end + delays(element_index))];\n end\n end\n\n % form the a-line summing across the elements\n line = sum(sensor_data);\n \n end\n \n % function to average the individual time series recorded at each\n % grid point of each transducer element (as returned by the C++\n % code) and return a single time series per active transducer\n % element (as returned by the MATLAB code)\n function sensor_data_sum = combine_sensor_data(obj, sensor_data)\n \n % check the data is the correct size\n if size(sensor_data, 1) ~= (obj.number_active_elements * obj.element_width * obj.element_length)\n error('The number of time series in the input sensor_data must match the number of grid points in the active tranducer elements.');\n end\n \n % get index of which element each time series belongs to \n ind = obj.indexed_active_elements_mask(obj.indexed_active_elements_mask > 0);\n\n % create empty output\n sensor_data_sum = zeros(obj.number_active_elements, size(sensor_data, 2));\n \n % check if an elevation focus is set\n if isinf(obj.elevation_focus_distance)\n \n % loop over time series and sum\n for ii = 1:length(ind)\n sensor_data_sum(ind(ii), :) = sensor_data_sum(ind(ii), :) + sensor_data(ii, :);\n end\n \n else\n \n % get the elevation delay for each grid point of each\n % active transducer element (this is given in units of grid\n % points)\n dm = obj.delay_mask(2);\n dm = dm(obj.active_elements_mask ~= 0);\n \n % loop over time series, shift and sum\n for ii = 1:length(ind)\n sensor_data_sum(ind(ii), 1:end - dm(ii)) = sensor_data_sum(ind(ii), 1:end - dm(ii)) + sensor_data(ii, 1 + dm(ii):end);\n end\n \n end\n \n % divide by number of time series in each element\n sensor_data_sum = sensor_data_sum .* (1/ (obj.element_width * obj.element_length));\n \n end\n \n % plot the transducer using voxelPlot\n function plot(obj)\n voxelPlot(double(obj.all_elements_mask));\n end\n \n % print out the transducer properties\n function properties(obj)\n disp(' ');\n disp('k-Wave Transducer Properties');\n disp([' transducer position: [' num2str(obj.position) ']']);\n disp([' transducer width: ' scaleSI(obj.transducer_width*obj.grid_spacing(2)) 'm (' num2str(obj.transducer_width) ' grid points)']);\n disp([' number of elements: ' num2str(obj.number_elements)]);\n disp([' number of active elements: ' num2str(obj.number_active_elements) ' (elements ' num2str(find(obj.active_elements, 1, 'first')) ' to ' num2str(find(obj.active_elements, 1, 'last')) ')']);\n disp([' element width: ' scaleSI(obj.element_width*obj.grid_spacing(2)) 'm (' num2str(obj.element_width) ' grid points)']);\n disp([' element spacing (kerf): ' scaleSI(obj.element_spacing*obj.grid_spacing(2)) 'm (' num2str(obj.element_spacing) ' grid points)']);\n disp([' element pitch: ' scaleSI((obj.element_spacing + obj.element_width)*obj.grid_spacing(2)) 'm (' num2str((obj.element_spacing + obj.element_width)) ' grid points)']);\n disp([' element length: ' scaleSI(obj.element_length*obj.grid_spacing(3)) 'm (' num2str(obj.element_length) ' grid points)']);\n disp([' sound speed: ' num2str(obj.sound_speed) 'm/s']);\n if isinf(obj.focus_distance)\n disp(' focus distance: infinite');\n else\n disp([' focus distance: ' scaleSI(obj.focus_distance) 'm']);\n end\n if isinf(obj.elevation_focus_distance)\n disp(' elevation focus distance: infinite');\n else\n disp([' elevation focus distance: ' scaleSI(obj.elevation_focus_distance) 'm']);\n end\n disp([' steering angle: ' num2str(obj.steering_angle) ' degrees']);\n disp([' steering angle max: ' num2str(obj.steering_angle_max) ' degrees']);\n end\n \n end\n \n % hidden class methods used with kspaceFirstOrder3D\n methods (Hidden = true, Access = 'public') \n \n % return a delay mask based on the transmit beamforming delays.\n % This is used if the transducer is a source. The delays are set\n % for each grid point of the active_elements_mask and define which\n % element of the input_signal should be used at each source point.\n % This mask is incremented within kspaceFirstOrder3D after each\n % time step. The mask is indexed from 0 and is incremented by 1\n % within kspaceFirstOrder3D .\n function mask = delay_mask(obj, mode)\n % mode == 1: both delays\n % mode == 2: elevation only\n % mode == 3: azimuth only\n \n % assign the delays to a new mask using the indexed_element_mask\n indexed_active_elements_mask = obj.indexed_active_elements_mask;\n active_elements_index = find(indexed_active_elements_mask ~= 0);\n mask = zeros(obj.stored_grid_size);\n\n % calculate azimuth focus delay times provided they are not all\n % zero\n if (~isinf(obj.focus_distance) || (obj.steering_angle ~= 0)) && (nargin == 1 || mode ~= 2)\n \n % get the element beamforming delays and reverse\n delay_times = -obj.beamforming_delays;\n \n % add delay times\n mask(active_elements_index) = delay_times(indexed_active_elements_mask(active_elements_index));\n \n end\n\n % calculate elevation focus time delays provided each element\n % is longer than one grid point\n if ~isinf(obj.elevation_focus_distance) && (obj.element_length > 1) && (nargin == 1 || mode ~= 3)\n \n % get elevation beamforming delays\n elevation_delay_times = obj.elevation_beamforming_delays;\n \n % get current mask\n element_voxel_mask = obj.indexed_element_voxel_mask;\n\n % add delay times\n mask(active_elements_index) = mask(active_elements_index) + elevation_delay_times(element_voxel_mask(active_elements_index)).';\n \n end\n \n % shift delay times (these should all be >= 0, where a value of\n % 0 means no delay)\n if strcmp(obj.stored_appended_zeros, 'auto')\n mask(active_elements_index) = mask(active_elements_index) - min(min(min(mask(active_elements_index)))); \n else\n mask(active_elements_index) = mask(active_elements_index) + obj.stored_beamforming_delays_offset;\n end \n \n end\n \n % return a binary mask based on the elevation focus. This sets the\n % elements to extract at each timestep from the sensor_data_buffer\n % used in kspaceFirstOrder3D. This is used if the transducer is a\n % sensor and the elevation focus is set. The mask is of the form: \n %\n % 1 0 0 0\n % 0 1 0 0\n % 0 0 1 0\n % 0 0 1 0\n % 0 0 0 1\n % 0 0 0 1\n % 0 0 0 1\n % 0 0 1 0\n % 0 0 1 0\n % 0 1 0 0\n % 1 0 0 0\n %\n % The mask remains constant, but extracts new elements at each time\n % step as the FIFO buffer sensor_data_buffer is updated\n function mask = elevation_beamforming_mask(obj)\n \n % get elevation beamforming mask\n delay_mask = obj.delay_mask(2);\n \n % extract the active elements\n delay_mask = delay_mask(obj.active_elements_mask ~= 0);\n \n % force delays to start from zero\n delay_mask = delay_mask - min(delay_mask(:));\n \n % create an empty output mask\n mask = zeros(length(delay_mask), max(delay_mask) + 1);\n \n % populate the mask by setting 1's at the index given by the\n % delay time\n for index = 1:length(delay_mask)\n mask(index, delay_mask(index) + 1) = 1;\n end\n \n % flip the mask so the shortest delays are at the right\n mask = fliplr(mask);\n end\n \n % convert the transmit apodization into the form of a element mask,\n % where the apodization values are placed at the grid points\n % belonging to the active transducer elements. These values are\n % then extracted in the correct order within\n % kspaceFirstOrder_inputChecking using apodization =\n % transmit_apodization_mask(active_elements_mask ~= 0) \n function mask = transmit_apodization_mask(obj)\n \n % check if a user defined apodization is given and whether this\n % is still the correct size (in case the number of active\n % elements has changed)\n if isnumeric(obj.transmit_apodization)\n if (length(obj.transmit_apodization) ~= obj.number_active_elements)\n error('The length of the transmit apodization input must match the number of active elements');\n else\n % assign apodization\n apodization = obj.transmit_apodization;\n end\n else\n % create apodization using getWin\n apodization = getWin(obj.number_active_elements, obj.transmit_apodization);\n end\n \n % create an empty mask;\n mask = zeros(obj.stored_grid_size);\n \n % assign the apodization values to every grid point in the\n % transducer\n mask_index = obj.indexed_active_elements_mask;\n mask_index = mask_index(mask_index ~= 0);\n mask(obj.active_elements_mask == 1) = apodization(mask_index);\n \n end\n \n % allow the mask to be resized by the simulation functions (this is\n % used when 'PMLInside' is set to false)\n function expand_grid(obj, expand_size)\n obj.indexed_mask = expandMatrix(obj.indexed_mask, expand_size, 0);\n end\n \n % allow the mask to be resized by the simulation functions (this is\n % used when 'PMLInside' is set to false)\n function retract_grid(obj, retract_size)\n obj.indexed_mask = obj.indexed_mask(1 + retract_size(1):end - retract_size(1), 1 + retract_size(2):end - retract_size(2), 1 + retract_size(3):end - retract_size(3));\n end \n \n % return the size of the grid\n function grid_size = grid_size(obj)\n grid_size = obj.stored_grid_size;\n end\n \n end\n \n % internal class methods only accessible by other functions within\n % kWaveTransducer \n methods (Hidden = true, Access = 'private') \n \n % return the transmit apodization, converting strings of window\n % type to actual numbers using getWin\n function apodization = get_transmit_apodization(obj)\n \n % check if a user defined apodization is given and whether this\n % is still the correct size (in case the number of active\n % elements has changed)\n if isnumeric(obj.transmit_apodization)\n if (length(obj.transmit_apodization) ~= obj.number_active_elements)\n error('The length of the transmit apodization input must match the number of active elements');\n else\n % assign apodization\n apodization = obj.transmit_apodization;\n end\n else\n % create apodization using getWin\n apodization = getWin(obj.number_active_elements, obj.transmit_apodization);\n end \n end \n \n % return the receive apodization, converting strings of window\n % type to actual numbers using getWin\n function apodization = get_receive_apodization(obj)\n \n % check if a user defined apodization is given and whether this\n % is still the correct size (in case the number of active\n % elements has changed)\n if isnumeric(obj.receive_apodization)\n if (length(obj.receive_apodization) ~= obj.number_active_elements)\n error('The length of the receive apodization input must match the number of active elements');\n else\n % assign apodization\n apodization = obj.receive_apodization;\n end\n else\n % create apodization using getWin\n apodization = getWin(obj.number_active_elements, obj.receive_apodization);\n end \n end \n \n end\nend", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/K-wave/k-Wave/kWaveTransducer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.029760092977873506, "lm_q1q2_score": 0.0074671875336400255}} {"text": "% FUZZY RULE BASE COMPRESSION SOFTWARE\n%\n% This software implements advanced inference in fuzzy rule based systems\n% by filtration of non-monotonic rules. This software is for mandani type\n% system only.\n% \n%\n% Neelamugilan Gobalakrishnan\n% 2006\n% $Revision:1.0 $ $Date: 15/03/2006 $\n\nclc\nclear all\n\ndisp('***********************************************************');\ndisp('* *');\ndisp('* FUZZY RULE BASE COMPRESSION SOFTWARE *');\ndisp('* *');\ndisp('* This software implements advanced inference in *');\ndisp('* fuzzy rule based systems by filtration of non- *');\ndisp('* monotonic rules. *');\ndisp('* *');\ndisp('***********************************************************');\n\nfprintf('\\n\\n');\n\ncondStatus = 'start'; %Condition status for choice while loop\n\nwhile strcmp(condStatus,'start') | strcmp(condStatus,'cont')\n clear choise\n fprintf('Enter 1 to create a new system\\n');\n fprintf('Enter 2 to load a system (*.fis)\\n\\n');\n fprintf('Please enter your choice : ');\n choise = input('');\n if choise == 1 % Create a new system\n fprintf('\\n');\n systemName = input('Enter the name of this system : ','s');\n % Call createinttable function to create integer table\n [sys intTable] = createinttable(systemName);\n % Arranged the rules into groups\n [groupedTable outNum] = arrangerules(sys,intTable);\n \n % Get the initial values for each inputs\n for i=1:size(sys.input, 2)\n fprintf('\\nEnter the initial %s : ', sys.input(i).name);\n initialVal(i) = input('');\n end\n \n displayOpt = 'on'; % Option to display the compressed rules\n % Find dominant rules for provided initial values\n compressRules = finddomrules(sys,intTable,outNum,initialVal,displayOpt);\n \n newSysName = input('Please enter the name for compressed system : ','s');\n fprintf('\\n');\n % Create the system with compressed rules\n createfis(newSysName,sys,compressRules);\n \n % Simulates the fuzzy inference system\n a = readfis(newSysName);\n outResult = evalfis([initialVal],a);\n \n fprintf('\\n');\n fprintf('The %s value for \\n', sys.output(outNum).name);\n \n for i=1:size(sys.input, 2)\n fprintf('%s(%.2f) \\n',sys.input(i).name ,initialVal(i));\n end\n\n fprintf('= %.2f', outResult);\n fprintf('\\n\\n');\n \n view_surface = input('Do u want to view the output surface (yes/no) : ','s');\n \n % Display the output surface\n while strcmp(view_surface,'yes') \n fprintf('\\nEnter 1 to view the original system, output surface\\n');\n fprintf('Enter 2 to view the compressed system, output surface\\n\\n');\n fprintf('Please enter your option : ');\n option = input('');\n if option == 1\n % Create output surface for the original system\n createoutsurf(sys,systemName,intTable,outNum,option);\n fprintf('\\nDo u want to view the output surface with\\n');\n view_surface = input('new points or compressed system? (yes/no) : ','s');\n elseif option == 2\n % Create output surface for the compressed system\n createoutsurf(sys,newSysName,intTable,outNum,option);\n fprintf('\\nDo u want to view the output surface with\\n');\n view_surface = input('new points or original system? (yes/no) : ','s');\n else\n disp('Invalid value has been entered! ');\n fprintf('\\n');\n view_surface = 'yes';\n end\n end \n condStatus = 'stop'; % choice while loop stopping condition\n % Load a system\n elseif choise == 2\n [fileName,pathName]=uigetfile('*.fis','Read FIS');\n if isequal(fileName,0) || isequal(pathName,0)\n % If fileName is zero, \"cancel\" was hit, or there was an error.\n errorStr='No file was loaded';\n return\n end\n systemName = [pathName fileName];\n \n sys = readfis(systemName);\n \n % Create the integer table\n for i=1:size(sys.rule,2)\n intTable(i,:) = [sys.rule(i).antecedent sys.rule(i).consequent];\n end\n \n fprintf('\\n');\n disp('-------------------------------------------------------------');\n fprintf(' ');\n disp(' Complete integer table ');\n fprintf(' ');\n disp('-------------------------------------------------------------');\n\n fprintf('\\n');\n disp('-------------------------------------------------------------');\n fprintf(' ');\n\n for i=1:size(sys.input,2)\n fprintf('Input%d ', i);\n end\n\n for i=1:size(sys.output,2)\n fprintf('Output%d ', i);\n end\n\n fprintf('\\n');\n disp('-------------------------------------------------------------');\n fprintf('\\n');\n disp(intTable);\n disp('-------------------------------------------------------------');\n fprintf('\\n');\n \n % Arranged the rules into groups\n [groupedTable outNum] = arrangerules(sys,intTable);\n \n % Get the initial values for each inputs\n for i=1:size(sys.input, 2)\n fprintf('\\nEnter the initial %s : ', sys.input(i).name);\n initialVal(i) = input('');\n end\n \n displayOpt = 'on'; % Option to display the compressed rules\n % Find dominant rules for provided initial values\n compressRules = finddomrules(sys,intTable,outNum,initialVal,displayOpt);\n \n fprintf('\\n');\n newSysName = input('Please enter the name for compressed system : ','s');\n % Create the system with compressed rules\n createfis(newSysName,sys,compressRules);\n \n % Simulates the fuzzy inference system\n a = readfis(newSysName);\n outResult = evalfis([initialVal],a);\n\n fprintf('\\n');\n fprintf('The %s value for \\n', sys.output(outNum).name);\n\n for i=1:size(sys.input, 2)\n fprintf('%s(%.2f) \\n',sys.input(i).name ,initialVal(i));\n end\n\n fprintf('= %.2f', outResult);\n fprintf('\\n\\n');\n \n view_surface = input('Do u want to view the output surface (yes/no) : ','s');\n \n % Display the output surface\n while strcmp(view_surface,'yes') \n fprintf('\\nEnter 1 to view the original system, output surface\\n');\n fprintf('Enter 2 to view the compressed system, output surface\\n\\n');\n fprintf('Please enter your option : ');\n option = input('');\n if option == 1\n % Create output surface for the original system\n createoutsurf(sys,systemName,groupedTable,outNum,option);\n fprintf('\\nDo u want to view the output surface with\\n');\n view_surface = input('new points or compressed system? (yes/no) : ','s');\n elseif option == 2\n % Create output surface for the compressed system\n createoutsurf(sys,newSysName,groupedTable,outNum,option);\n fprintf('\\nDo u want to view the output surface with\\n');\n view_surface = input('new points or original system? (yes/no) : ','s');\n else\n fprintf('\\n');\n disp('Invalid value has been entered! ');\n view_surface = 'yes';\n end\n end \n condStatus = 'stop'; % choice while loop stopping condition\n else\n disp('Invalid value has been entered! ');\n condStatus = 'cont'; % Choice while loop continue condition\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15632-software-tool-for-fuzzy-rule-base-compression/rulescompressionsoft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.017176705679195346, "lm_q1q2_score": 0.00732280026947899}} {"text": "function varargout = optionpricegui2(varargin)\n% OPTIONPRICEGUI2 M-file for optionpricegui2.fig\n% OPTIONPRICEGUI2, by itself, creates a new OPTIONPRICEGUI2 or raises the existing\n% singleton*.\n%\n% H = OPTIONPRICEGUI2 returns the handle to a new OPTIONPRICEGUI2 or the handle to\n% the existing singleton*.\n%\n% OPTIONPRICEGUI2('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in OPTIONPRICEGUI2.M with the given input arguments.\n%\n% OPTIONPRICEGUI2('Property','Value',...) creates a new OPTIONPRICEGUI2 or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before optionpricegui2_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to optionpricegui2_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help optionpricegui2\n\n% Last Modified by GUIDE v2.5 14-Aug-2008 14:18:46\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @optionpricegui2_OpeningFcn, ...\n 'gui_OutputFcn', @optionpricegui2_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before optionpricegui2 is made visible.\nfunction optionpricegui2_OpeningFcn(hObject, eventdata, handles, varargin)%#ok\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to optionpricegui2 (see VARARGIN)\n\n% Choose default command line output for optionpricegui2\nhandles.output = hObject;\n\nset(handles.editStart, 'String', datestr(today, 2))\nset(handles.editEnd, 'String', datestr(today + 91, 2))\n\nhandles = runSimulation(handles);\n\n% This is an awkward place to put the rotate3d command. If you place it in\n% the runSimulation function, however, it tends to toggle rotate3d on and\n% off after each simulation. Here, it gets set to \"on\" once and stays that\n% way.\nrotate3d(handles.surfAxes)\n\n% Update handles structure\nguidata(hObject, handles);\nend\n\n% UIWAIT makes optionpricegui2 wait for user response (see UIRESUME)\n% uiwait(handles.mainFigure);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = optionpricegui2_OutputFcn(hObject, eventdata, handles) %#ok\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\nend\n\n\n\nfunction editSpot_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editSpot (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editSpot as text\n% str2double(get(hObject,'String')) returns contents of editSpot as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editSpot_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editSpot (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editStrike_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editStrike as text\n% str2double(get(hObject,'String')) returns contents of editStrike as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editStrike_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editRFR_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editRFR (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editRFR as text\n% str2double(get(hObject,'String')) returns contents of editRFR as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editRFR_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editRFR (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editStart_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editStart (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editStart as text\n% str2double(get(hObject,'String')) returns contents of editStart as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editStart_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editStart (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editEnd_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editEnd (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editEnd as text\n% str2double(get(hObject,'String')) returns contents of editEnd as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editEnd_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editEnd (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editVol_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editVol (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editVol as text\n% str2double(get(hObject,'String')) returns contents of editVol as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editVol_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editVol (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editYield_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editYield (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editYield as text\n% str2double(get(hObject,'String')) returns contents of editYield as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editYield_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editYield (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nend\n\nfunction editIter_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editIter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editIter as text\n% str2double(get(hObject,'String')) returns contents of editIter as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editIter_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editIter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nend\n\nfunction editValue_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editValue (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editValue as text\n% str2double(get(hObject,'String')) returns contents of editValue as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editValue_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editValue (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n% --- Executes on selection change in popupmenu1.\nfunction popupmenu1_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from popupmenu1\n\n% Some options only require a single strike price; others, two. The\n% butterfly option requires one strike price and a spread.\ncontents = get(hObject,'String');\nswitch contents{get(hObject,'Value')}\n case {'Call' 'Put' 'Straddle'}\n handles = oneStrike(handles);\n case {'Strangle' 'Bull Spread' 'Bear Spread'}\n handles = twoStrikes(handles);\n case {'Butterfly'}\n handles = butterfly(handles);\nend\nguidata(hObject, handles);\nend\n% --- Executes during object creation, after setting all properties.\nfunction popupmenu1_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editStrike1_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editStrike1 as text\n% str2double(get(hObject,'String')) returns contents of editStrike1 as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editStrike1_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n\nfunction editStrike2_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editStrike2 as text\n% str2double(get(hObject,'String')) returns contents of editStrike2 as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editStrike2_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editStrike2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\nfunction editSpread_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to editSpread (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of editSpread as text\n% str2double(get(hObject,'String')) returns contents of editSpread as a double\nend\n\n% --- Executes during object creation, after setting all properties.\nfunction editSpread_CreateFcn(hObject, eventdata, handles)%#ok\n% hObject handle to editSpread (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\nend\n\n% --- Executes on button press in buttonRun.\nfunction buttonRun_Callback(hObject, eventdata, handles)%#ok\n% hObject handle to buttonRun (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nhandles = runSimulation(handles);\nguidata(hObject, handles);\nend\n\n\n% --- Helper functions follow ---\n% --- oneStrike, twoStrikes: toggle between displaying one and two strike\n% prices in the UI panel ---\nfunction handles = oneStrike(handles)\nset(handles.text3, 'String', 'Strike Price')\nset(handles.editStrike, 'Visible', 'on')\nset(handles.editStrike1, 'Visible', 'off')\nset(handles.editStrike2, 'Visible', 'off')\nset(handles.editSpread, 'Visible', 'off')\nset(handles.text11, 'Visible', 'off')\nend\n\nfunction handles = twoStrikes(handles)\nset(handles.text3, 'String', 'Strike Prices')\nset(handles.editStrike, 'Visible', 'off')\nset(handles.editStrike1, 'Visible', 'on')\nset(handles.editStrike2, 'Visible', 'on')\nset(handles.editSpread, 'Visible', 'off')\nset(handles.text11, 'Visible', 'off')\nend\n\nfunction handles = butterfly(handles)\nset(handles.text3, 'String', 'Strike Price')\nset(handles.editStrike, 'Visible', 'on')\nset(handles.editStrike1, 'Visible', 'off')\nset(handles.editStrike2, 'Visible', 'off')\nset(handles.editSpread, 'Visible', 'on')\nset(handles.text11, 'Visible', 'on')\nend\n\n%--- runSimulation: the main control program for the code ---\nfunction handles = runSimulation(handles)\n% This function has four steps:\n% Step 1: Collect inputs and find option value\n% Step 2: Plot the option value surface\n% Step 3: Run a Monte Carlo simulation\n% Step 4: Plot the Monte Carlo simulation\n%\n% In addition, there are two nested functions that allow you to incorporate\n% a WindowButtonMotionFcn and a WindowButtonDownFcn on the Monte Carlo\n% Paths axes.\n\n% Step 1: Collect inputs and find option value\ntry\n spot = str2double(get(handles.editSpot, 'String'));\n rate = str2double(get(handles.editRFR, 'String'));\n vol = str2double(get(handles.editVol, 'String'));\n yield= str2double(get(handles.editYield, 'String'));\n type = get(handles.popupmenu1,'String');\n type = type{get(handles.popupmenu1,'Value')};\n\n % No harm in getting Strike2 and Spread, even if they aren't used.\n strike2 = str2double(get(handles.editStrike2, 'String'));\n spread = str2double(get(handles.editSpread, 'String'));\n\n startDate = get(handles.editStart, 'String');\n endDate = get(handles.editEnd, 'String');\n % I only include this extra TRY/CATCH loop in order to provide a better\n % error message if the invalid dates are applied: YEARFRAC itself will\n % do all of the appropriate error checking.\n try\n time = yearfrac(startDate, endDate);\n catch %#ok\n error('optionPriceGui:InvalidDates', ...\n 'Dates must be in a valid format')\n end\n\n iter = str2double(get(handles.editIter, 'String'));\n if int32(iter) ~= iter || iter <= 0\n error('optionPriceGui:InvalidIterations',...\n 'Iteration count must be a positive integer.')\n end\n\n switch type\n case {'Call' 'Put' 'Straddle' 'Butterfly'}\n strike = str2double(get(handles.editStrike, 'String'));\n case {'Strangle' 'Bull Spread' 'Bear Spread'}\n strike = str2double(get(handles.editStrike1, 'String'));\n end\n\n value = optPriceVal(type, spot, strike, rate, time, vol, yield, strike2, spread);\n set(handles.editValue, 'String', num2str(value,'%4.3f'))\n\ncatch ME\n errordlg(ME.message, 'Invalid Input', 'modal')\n set(handles.editValue, 'String', 'error')\n return\nend\n\n% Step 2: Now that we have all the data we need, let's plot the option\n% value surface.\n\n% A 51x51 surface plot should look nice and not be too taxing on the\n% graphics processor, but you can adjust that here.\nxPoints = 51;\nyPoints = 51;\n\nT = linspace(0, time, xPoints);\n\n% The spot price axis span is a little tricky to determine in advance. We\n% will go with +/- 10% from the strike price in the case of a put, call, or\n% straddle option, +/- 50% of the strike prices' span in the case of a\n% strangle, bull spread, or bear spread option, and +/- 40% of the spread\n% from a butterfly option. Of course, we will truncate if these go below a\n% price of 0.\nswitch type\n case {'Call' 'Put' 'Straddle'}\n lPrice = 0.9 * strike;\n uPrice = 1.1 * strike;\n case {'Strangle' 'Bull Spread' 'Bear Spread'}\n span = abs(strike2 - strike);\n if strike2 > strike\n lPrice = strike - 0.5 * span;\n uPrice = strike2+ 0.5 * span;\n else\n lPrice = strike2- 0.5 * span;\n uPrice = strike + 0.5 * span;\n end\n case 'Butterfly'\n lPrice = (1 - 1.4 * spread) * strike;\n uPrice = (1 + 1.4 * spread) * strike;\nend\nlPrice(lPrice < 0) = 0;\nS = linspace(lPrice, uPrice, yPoints);\n[S,T] = meshgrid(S,T);\n\n% Get the option value for the surface\nV = optPriceVal(type, S, strike, rate, T, vol, yield, strike2, spread);\n\n% Plot the 3D surface of changing option value with spot price and time\nsurf(handles.surfAxes, S, T, V);\nbox(handles.surfAxes, 'on')\nshading(handles.surfAxes, 'interp')\naxis(handles.surfAxes, 'tight')\nxlabel(handles.surfAxes, 'Underlying ($)','fontweight','bold')\nylabel(handles.surfAxes, 'Time to Expiry (Years)','fontweight','bold')\nzlabel(handles.surfAxes, 'Option Value ($)','fontweight','bold')\n\n% Step 3: Let's now run a Monte Carlo simulation\n% We will run a single step of the simulation per day-- this is fairly\n% coarse-grained, but it gets the message across.\n\n% Assume geometric Brownian motion and apply Ito's lemma to simplify the\n% Monte Carlo equation. (see: eqn T6.9 of Kevin Dowd's _An Introduction to\n% Market Risk Measurement_, p. 224)\nnumDays = daysact(startDate, endDate);\nTT = sqrt(time/numDays) * ones(numDays, iter);\nrNum = randn(numDays, iter);\n\nBT = TT.*rNum;\n% And we pad this by an initial row of zeros to handle the initial point at\n% day 0.\nTT = [zeros(1, iter); TT];\nBT = [zeros(1, iter); BT];\n\nST = spot * exp(cumsum((rate - 0.5 * vol^2) * TT + vol * BT));\n\n% Step 4: Plot the Monte Carlo simulation\n% Create line/bar object for histogram of monte-carlo price distributions\nset(handles.axesHist,'yaxislocation','right','xaxislocation','top',...\n 'xtick',[],'xlimmode','auto')\n\n% Only pick at most 1000 lines from the Monte-Carlo simulation for plotting\n% purposes; all data is still used for the underlying math, however.\nif size(ST,2)>1000\n ind = randperm(size(ST,2))';\n STplot = ST(:,ind(1:1000));\nelse\n STplot = ST;\nend\n\n% Plot the monte-carlo underlying price paths\nhandles.pricePaths = plot(handles.axesMonte, (0:numDays), STplot,...\n 'color', [.7,.7,.7]);\n\n% Create the tracking line. Rather, create an object to hold the tracking\n% line as it is generated by the windowbuttonmotion function.\nhandles.trackLine = line('XData', NaN, 'YData', NaN,...\n 'Parent', handles.axesMonte, 'erasemode', 'xor', 'Color', 'b', 'LineWidth', 2);\nhandles.trackText = text('parent', handles.axesMonte, 'erasemode','xor','edgecolor','k',...\n 'background',[1,1,.87],'verticalalign','bot','fontsize',14, 'visible', 'off');\n% handles.pdfLine = line('XData', NaN, 'YData', NaN,...\n% 'Parent', handles.axesHist, 'erasemode', 'xor', 'Color', 'r');\n\n% Plot the mean of the underlying monte-carlo prices paths.\nSTmean = mean(ST,2);\nhandles.meanLine = line('XData', (0:numDays), 'YData', STmean, ...\n 'Parent', handles.axesMonte, 'Marker', '.' ,'MarkerSize', 10, 'Color', 'r');\n\n\n% Annotate the monte-carlo plots\nxlabel(handles.axesMonte, 'Time (Days)','fontweight','bold')\nylabel(handles.axesMonte, 'Underlying ($)','fontweight','bold')\naxis(handles.axesMonte, 'tight')\ngrid(handles.axesMonte, 'on')\nlegend(handles.axesMonte, ...\n {'$$S_{t+dt} = S_te^{(r-\\frac{{\\sigma^2}}{2})dt+\\sigma\\epsilon\\sqrt{dt}}$$'}, ...\n 'fontsize',14,'interpreter','latex', 'Location', 'NorthWest');\n\nset(handles.mainFigure,'windowbuttonmotionfcn',@wbm)\n\n% Nested function: WBM for the window button motion function\n function wbm(src, event)\n drawnow\n ylimit = get(handles.axesMonte, 'ylim');\n xlimit = get(handles.axesMonte, 'xlim');\n pos = get(handles.axesMonte, 'currentpoint');\n x = pos(1,1);\n y = pos(1,2);\n % check if the mouse is out of bounds of the axes\n if x < xlimit(1) || x > xlimit(2) || y < ylimit(1) || y>ylimit(2)\n return\n end\n\n % create a histogram of the underlying price paths at the current point\n binsC = linspace(ylimit(1), ylimit(2)+eps(ylimit(2)), 21);\n n = histc(ST(round(x)+1, :), binsC);\n n = n./max(n);\n barh(handles.axesHist, binsC, n, 'histc')\n set(handles.axesHist, 'ylim', ylimit)\n set(handles.axesHist,'YTick',[])\n set(handles.axesHist,'XTick',[])\n set(handles.trackLine,'xdata',[x,x],'ydata',ylim)\n\n % Create a maximum likelihood estimate of the histogram, assuming a\n % lognormal distribution.\n params = lognfit(ST(round(x)+1, :));\n pdfPts = ylimit(1) : ylimit(2);\n pdfVals = lognpdf(pdfPts, params(1), params(2));\n line('Parent', handles.axesHist, ...\n 'XData', pdfVals./max(pdfVals), 'YData', pdfPts,...\n 'erasemode', 'xor', 'color', 'b')\n\n % get the current datestr and mean value of the mouse position\n currentDate = datestr(round(x + datenum(startDate)), 2);\n currentMean = STmean(round(x)+1);\n\n str = sprintf(['Date: ' currentDate '\\nAvg Price: $%.2f'], currentMean);\n set(handles.trackText,...\n 'position',[x + diff(xlimit)*.02, y + diff(ylimit)*.02, 0],...\n 'string', str, 'visible', 'on')\n\n end\nend\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21675-simple-option-pricing-gui/optionpricegui2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2254166262422842, "lm_q2_score": 0.028436030986449156, "lm_q1q2_score": 0.006409954168686421}} {"text": "%Transcription\n%\n% @wholeCellModelID Process_Transcription\n% @name Transcription\n% @description\n% Biology\n% ===============\n% Transcription is the first step in the synthesis of functional gene\n% products where RNA polymerase and several accessory enzymes translate\n% transcription units, or regions of the DNA containing 1 or more genes, into\n% RNA molecules. Following transcription the RNA molecules follow one of\n% two pathways:\n% - mRNAs are used as templates for translation (see translation process)\n% - r/s/tRNAs which are transcribed as molecules containing multiple genes are\n% cleavaged into their individual genes (see RNA processing process), are\n% modified at several bases (see RNA modification process) to improve their\n% stability and enhance their catalytic activity, and finally act as\n% ribozymes (r/sRNAs) or as adaptors between mRNAs and the amino acids they\n% code for (tRNAs).\n%\n% Transcription begins with the recruitment of RNA polymerase to a promoter\n% with the help of the sigma initiation factor and possiblity transcription\n% factors. Next elongation factors are recruited, RNA begins to be\n% polymerized, and sigma factor is released. Finally the RNA polymerase\n% reaches a terminator at the the end of the transcription unit, and\n% with the help of termination factors releases the polymerized RNA and\n% dissociates from the DNA. Termination in E. coli occurs via either a\n% Rho-dependent (50%) or Rho-independent mechanism (50%). Rho-dependent\n% termination is catalyzed by the hexameric ATP-dependent helicase Rho.\n% Rho is not essential in B. subtilis [PUB_0234]. Rho-independent\n% termination occur via the intrinsic properties RNA which disrupt RNA\n% polymerase-DNA binding. Terminator hairpins are not predicted in M.\n% genitalium. In E. coli termination is incompetition with\n% antitermination. However antitermination has not been reported in any\n% mcyoplasma [PUB_0182].\n%\n% As soon as the RNA begins to polymerized, even prior to termination, the\n% mRNA transcripts may be bound by ribosomes and polymerized. For simplicity,\n% our model doesn't represent this phenomenon.\n%\n% Knowledge Base\n% ===============\n% The transcription unit structure was compiled from several sources:\n% - Primary reports of cotranscribed genes [PUB_0176, PUB_0182, PUB_0186,\n% PUB_0188, PUB_0188, PUB_0244, PUB_0247, PUB_0248, PUB_0249, PUB_0251]\n% - OperonDB database of cotranscribed genes [PUB_0250]\n% - Conservation of gene order across multiple species\n% - Related function of adjacent genes\n% - Expression levels as measured by microarrays of adjacent genes [PUB_0569]\n% - Strandedness of adjacent genes\n% - Weiner, Hermann, and Browning computational model of promoters and\n% transcription unit start sites [PUB_0411]\n%\n% The transcription unit structure is organized in the knowledge base, and is\n% loaded into this process by the initializeConstants method.\n%\n% The knowledge base also contains the measured expression and half-lives of\n% many transcripts. These values are loaded by initializeConstants and fit by\n% simulation.fitConstants to be consistent with other processes.\n%\n% Representation\n% ===============\n% substrates, enzymes, boundEnzymes, and RNAs represent the counts of\n% metabolites, free transcription enzymes, transcription enzymes bound to RNAs\n% and RNA polymerases, and nascent RNAs.\n%\n% rnaPolymerases.states represents the current state / pseudostate (actively\n% transcribing, specifically bound, non-specifically bound, free,\n% non-existent) of each RNA polymerase, where each state is indicated by the\n% enumeration:\n% - rnaPolymeraseActivelyTranscribingValue\n% - rnaPolymeraseSpecificallyBoundValue\n% - rnaPolymeraseNonSpecificallyBoundValue\n% - rnaPolymeraseFreeValue\n% - rnaPolymeraseNotExistValue (state exists as a way to account for memory\n% allocated for future RNA polymerases)\n% For actively transcribing polymerases rnaPolymerases.states also represents\n% the position of the polymerase along the transcription unit.\n%\n% That is entries of rnaPolymerases.states with the following values\n% corresponding to these states:\n% >= RNAPolymerases.activelyTranscribingValue: RNA polymerases position on genome actively transcribing\n% == RNAPolymerases.specificallyBoundValue: RNA polymerase specifically bound\n% == RNAPolymerases.nonSpecificallyBoundValue: RNA polymerase non-specifically bound\n% == RNAPolymerases.freeValue: RNA polymerase free\n% == RNAPolymerases.notExistValue: RNA polymerase doesn't exist\n%\n% transcripts.boundTranscriptionUnits represents the particular transcription\n% unit to which each actively transcribing and specifically bound polymerase\n% is bound.\n%\n% rnaPolymeraseStateExpectations represents the expected occupancies of the\n% RNA polymerase states.\n%\n% transcriptionUnitBindingProbabilities represents the relative affinity of\n% RNA polymerases for the promoters of each transcription unit.\n% transcriptionFactorBindingProbFoldChange represents the fold change affect of\n% transcription factors on the relative affinities of the RNA polymerse for\n% the promoters. RNA polymerases are assigned to\n% transcription units weighted by the product of\n% transcriptionUnitBindingProbabilities and\n% transcriptionFactorBindingProbFoldChange.\n%\n% Initialization\n% ===============\n% All RNAs are initialized to the mature state. This is implemented by the\n% simulation class initializeState method.\n%\n% RNA polymerases are initialized to their steady state:\n% - Each RNA polymerase is randomly assigned (with replacement) to one of the\n% actively transcribing, specifically bound, non-specifically bound, or free\n% states weighted by the expected occupancy of each state\n% (rnaPolymeraseStateExpectations)\n% - Actively transcribing and specifically bound polymerases randomly assigned\n% to transcription units weighted by their transcription rates\n% (transcriptionUnitBindingProbabilities)\n% - Each transcription unit to which an actively transcribing polymerase has\n% been assigned is divided into 1 segment for each polymerase\n% - Actively transcribing polymerases randomly assigned to positions within\n% the assigned segment of their assigned transcription unit (positions near\n% the segment border are not allowed to prevent polymerases from being too\n% close to each other) with uniform probably.\n%\n% Simulation\n% ===============\n% Evolves the state of RNA polymerase using a markov chain model with four\n% states:\n% - actively translating\n% - specifically bound\n% - non-specifically bound\n% - free\n%\n% Transition probabilities are designed to maintain the occupancy of each\n% state within a narrow window around their expected values. Transition\n% probability are determined by four logistic control functions. These can\n% be tuned with the constants\n% - rnaPolymeraseStateExpectations\n%\n% RNA polymerase are created in the free state.\n%\n% Actively transcribing state:\n% 1. Release sigma factor if after first second of elongation\n% 2. Elongate transcript according to nucleic acid limits (substrates)\n% if elongation factors are available\n% 3. If transcription complete and termination factor available\n% - release transcript\n% - transition RNA polymerase to free state\n% - increment gene expression\n% Otherwise remain in active state\n%\n% Specifically bound State:\n% - Can transition to active, specifically bound, non-specifically bound,\n% or free states\n% - Transition into state only if a free sigma factor is available\n% 1. Decrement number of free sigma factors\n% 2. Pick a transcription unit (tu) to bind to according to\n% Expression transcription unit i~prob(ribosome releases tu i|ribosome active)\n% =prob(ribosome within RNA polymerase elongation rate bases of length of tu i|ribosome active)\n% =prob(ribosome within RNA polymerase elongation rate bases of length of tu i|ribosome active, bound to tu i)*prob(ribosome bound to tu i|ribosome active)\n% =[(RNA polymerase transcription rate)/(length of tu i)] * [(length of tu i)*prob(binding tu i|binding)]\n% prob(binding tu i | binding)~expression tu i\n%\n% Non-specifically bound state:\n% - Can transition to specifically bound, non-specifically bound, or free\n% states\n%\n% Free state:\n% - Can transition to specifically bound, non-specifically bound, or free\n% states\n%\n% Algorithm\n% +++++++++++++++\n% 1. Randomly transition RNA polymerases among activlely transcribing,\n% specifically bound, non-specifically, bound, and free states weighted by\n% state transition probabilities. Update rnaPolymerases.states.\n% 2. Randomly assign RNA polymerases entering the specifically bound to\n% specific transcription units weighted by the product of\n% transcriptionUnitBindingProbabilities and\n% transcriptionFactorBindingProbFoldChange. Update\n% transcripts.boundTranscriptionUnits.\n% 3. Assign RNA polymerase entering the actively transcribing state sigma\n% factors. Update enzymes and boundEnzymes.\n% 4. Simulate RNA polymerization by actively transcribing RNA polymerases with\n% the aid of elongation factors. Allocate available nucleic acids among the\n% actively transcribing RNA polymerases. Release sigma factors from RNA\n% polymerases that started at the beginning of the transcription unit and\n% progressed. Update rnaPolymerases.states. Update substrates. Update enzymes\n% and boundEnzymes.\n% 5. If termination factors are available dissociate RNA polymerases which\n% have reached the terminus of the transcription they're bound to, and\n% release RNAs. Update rnaPolymerases.states and\n% transcripts.boundTranscriptionUnits. Increment RNAs.\n%\n% References\n% ===========\n% 1. McClure, W. R. 1985. Mechanism and control of transcription\n% initiation in prokaryotes. Annu. Rev. Biochem. 54:171-204.\n% [PUB_0775]\n% 2. Ciampi MS (2006). Rho-dependent terminators and transcription\n% termination. Microbiology. 152(9):2515-28 [PUB_0233].\n% 3. Nudler E, Gottesman ME (2002). Transcription termination and\n% anti-termination in E. coli. Genes Cells. 7(8):755-68. [PUB_0662]\n% 4. Washio T, Sasayama J, Tomita M (1998). Analysis of complete genomes\n% suggests that many prokaryotes do not rely on hairpin formation in\n% transcription termination. Nucleic Acids Res. 26(23):5456-63\n% [PUB_0234]\n% 5. Peterson JD, Umayam LA, Dickinson T, Hickey EK, White O (2001). The\n% Comprehensive Microbial Resource. Nucleic Acids Res. 29(1):123-5.\n% [PUB_0182]\n% 6. Shepherd N, Dennis P, Bremer H (2001). Cytoplasmic RNA Polymerase in\n% Escherichia coli. J Bacteriol. 183(8): 2527-34. [PUB_0784]\n% 7. Klumpp S, Hwa T (2008). Growth-rate-dependent partitioning of RNA\n% polymerases in bacteria. Proc Natl Acad Sci U S A. 105(21):\n% 20245-50. [PUB_0785]\n% 8. Grigorova IL, Phleger NJ, Mutalik VK, Gross CA (2006). Insights into\n% transcriptional regulation and sigma competition from an equilibrium\n% model of RNA polymerase binding to DNA. Proc Natl Acad Sci U S A.\n% 103(14): 5332-7. [PUB_0786]\n%\n% Author: Markus Covert, mcovert@stanford.edu\n% Author: Jayodita Sanghvi, jayodita@stanford.edu\n% Author: Jonathan Karr, jkarr@stanford.edu\n% Affiliation: Covert Lab, Department of Bioengineering, Stanford University\n% Last updated: 1/4/2010\n%\n%TODO: require Mg2+ or Mn2+ as cofactor for transcription\nclassdef Transcription < edu.stanford.covert.cell.sim.Process & edu.stanford.covert.cell.sim.ChromosomeProcessAspect\n %property annotations\n properties (Constant)\n optionNames__ = {}; %names of option properties\n fixedConstantNames__ = { %names of fixed constant properties\n 'rnaPolymeraseElongationRate';\n 'transcriptionUnitBaseCounts';\n 'transcriptionUnitBindingProbabilities';\n };\n fittedConstantNames__ = { %names of fitted constant properties\n 'transcriptionUnitBindingProbabilities'\n };\n localStateNames__ = { %names of simulation state properties redundant with timecourses in this or other processes or the simulation\n 'RNAs'};\n end\n \n %IDs, names, and local indices\n properties\n stimuliWholeCellModelIDs = {}; %whole cell model IDs of stimuli\n \n substrateWholeCellModelIDs = { %whole cell model IDs of substrates\n 'ATP'; 'CTP'; 'GTP'; 'UTP';\n 'AMP'; 'CMP'; 'GMP'; 'UMP';\n 'ADP'; 'PPI'; 'H2O'; 'H'};\n substrateIndexs_ntp = (1:4)'; %indices within substrates of NTPs\n substrateIndexs_nmp = (5:8)'; %indices within substrates of NMPs\n substrateIndexs_atp = 1; %index within substrates of ATP\n substrateIndexs_adp = 9; %index within substrates of ADP\n substrateIndexs_diphosphate = 10; %index within substrates of diphosphate\n substrateIndexs_water = 11; %index within substrates of water\n substrateIndexs_hydrogen = 12; %index within substrates of hydrogen\n \n enzymeWholeCellModelIDs = { %enzyme whole cell model ids\n 'MG_249_MONOMER'; %RNA polymerase sigma factor RpoD\n 'MG_282_MONOMER'; %transcription elongation factor GreA\n 'MG_141_MONOMER'; %transcription termination factor NusA\n 'MG_027_MONOMER'; %transcription termination/antitermination protein NusB\n 'RNA_POLYMERASE'; %DNA-directed RNA polymerase\n 'RNA_POLYMERASE_HOLOENZYME'}; %DNA-directed RNA polymerase holoenzyme\n enzymeIndexs_transcriptionFactors = (1:4)'; %indices within enzymes of transcription factors\n enzymeIndexs_sigmaFactor = 1; %index within enzymes of sigma factor RpoD\n enzymeIndexs_elongationFactor = 2; %index within enzymes of elongation factor GreA\n enzymeIndexs_terminationFactor = 3; %index within enzymes of termination factor NusA\n enzymeIndexs_antiterminationFactor = 4; %index within enzymes of termination/antitermination protein NusB\n enzymeIndexs_rnaPolymerase = 5; %index within enzymes of DNA-directed RNA polymerase\n enzymeIndexs_rnaPolymeraseHoloenzyme = 6; %index within enzymes of DNA-directed RNA polymerase holoenzyme\n \n complexIndexs_DnaA_ATP %indices within protein complexes of DnaA-ATP\n transcriptionUnitIndexs_DnaAR12345Boxes %indices of transcription units containing the functional DnaA boxes R1-5\n end\n \n %fixed biological constants\n properties\n rnaPolymeraseElongationRate %RNA polymerase elongation rate (50 nucleotides per second per RNA polymerase) [PUB_0562, PUB_0563]\n transcriptionUnitBaseCounts %transcription unit base counts\n transcriptionUnitBindingProbabilities %transcription unit binding probabilities\n stateTransitionProbabilities %transition probabilities among RNA polymerase states\n end\n \n %global state, stored locally for convenience\n properties\n RNAs %copy number of transcription units\n end\n \n %global state (referenced locally for convenience)\n properties\n rnaPolymerases %RNA Polymerase state class\n transcripts %New Transcripts state class\n end\n \n %constructor\n methods\n function this = Transcription(wholeCellModelID, name)\n this = this@edu.stanford.covert.cell.sim.Process(wholeCellModelID, name);\n end\n end\n \n %communication between process/simulation\n methods\n %set references to state objects\n function storeObjectReferences(this, simulation)\n this.storeObjectReferences@edu.stanford.covert.cell.sim.Process(simulation);\n this.storeObjectReferences@edu.stanford.covert.cell.sim.ChromosomeProcessAspect(simulation);\n \n this.rnaPolymerases = simulation.state('RNAPolymerase');\n this.transcripts = simulation.state('Transcript');\n \n this.states = [this.states; {this.rnaPolymerases; this.transcripts}];\n end\n \n %initialize constants\n function initializeConstants(this, knowledgeBase, simulation, varargin)\n %call super class method\n this.initializeConstants@edu.stanford.covert.cell.sim.Process(knowledgeBase, simulation, varargin{:});\n this.initializeConstants@edu.stanford.covert.cell.sim.ChromosomeProcessAspect(knowledgeBase, simulation, varargin{:});\n \n this.transcriptionUnitBaseCounts = reshape([knowledgeBase.transcriptionUnits.baseCount],[],length(knowledgeBase.transcriptionUnits))';\n this.transcriptionUnitBaseCounts = this.transcriptionUnitBaseCounts(:, this.substrateMetaboliteGlobalIndexs);\n \n this.transcriptionUnitBindingProbabilities = zeros(size(this.transcripts.transcriptionUnitLengths));\n \n this.complexIndexs_DnaA_ATP = find(ismember({knowledgeBase.proteinComplexs.wholeCellModelID}', {\n 'MG_469_1MER_ATP' %DnaA-ATP 1mer\n 'MG_469_2MER_1ATP_ADP' %DnaA 2mer-(1)ATP-(1)ADP\n 'MG_469_2MER_ATP' %DnaA-ATP 2mer\n 'MG_469_3MER_2ATP_ADP' %DnaA 3mer-(2)ATP-(1)ADP\n 'MG_469_3MER_ATP' %DnaA-ATP 3mer\n 'MG_469_4MER_3ATP_ADP' %DnaA 4mer-(3)ATP-(1)ADP\n 'MG_469_4MER_ATP' %DnaA-ATP 4mer\n 'MG_469_5MER_4ATP_ADP' %DnaA 5mer-(4)ATP-(1)ADP\n 'MG_469_5MER_ATP' %DnaA-ATP 5mer\n 'MG_469_6MER_5ATP_ADP' %DnaA 6mer-(5)ATP-(1)ADP\n 'MG_469_6MER_ATP' %DnaA-ATP 6mer\n 'MG_469_7MER_6ATP_ADP' %DnaA 7mer-(6)ATP-(1)ADP\n 'MG_469_7MER_ATP'})); %DnaA-ATP 7mer;\n [~, idxs] = ismember({\n 'Functional box R1'\n 'Functional box R2'\n 'Functional box R3'\n 'Functional box R4'\n 'Functional box R5'}, {knowledgeBase.genomeFeatures.name});\n tus = [knowledgeBase.genomeFeatures(idxs).transcriptionUnits];\n this.transcriptionUnitIndexs_DnaAR12345Boxes = unique([tus.idx])';\n end\n \n %retrieve state from simulation\n function copyFromState(this)\n this.copyFromState@edu.stanford.covert.cell.sim.Process();\n \n this.RNAs = this.rna.counts(this.rna.nascentIndexs, this.compartment.cytosolIndexs, :);\n end\n \n %send state to simulation\n function copyToState(this)\n this.copyToState@edu.stanford.covert.cell.sim.Process();\n \n this.rna.counts(this.rna.nascentIndexs, this.compartment.cytosolIndexs, :) = this.RNAs;\n end\n end\n \n %allocate memory for state\n methods\n function allocateMemoryForState(this, numTimePoints)\n this.allocateMemoryForState@edu.stanford.covert.cell.sim.Process(numTimePoints);\n \n numTranscriptionUnits = length(this.transcripts.transcriptionUnitLengths);\n \n this.RNAs = zeros(numTranscriptionUnits, 1, numTimePoints);\n end\n end\n \n %model\n methods\n %Calculate\n %- contribution to FBA objective\n %- minimum expression consistent with cell cycle length\n function [bmProd, byProd, minEnzExp, maxEnzExp] = calcResourceRequirements_LifeCycle(this, ~, states)\n %% initialize\n bmProd = zeros(size(this.substrateWholeCellModelIDs));\n byProd = zeros(size(this.substrateWholeCellModelIDs));\n minEnzExp = zeros(size(this.enzymeWholeCellModelIDs));\n maxEnzExp = Inf(size(this.enzymeWholeCellModelIDs));\n \n %% substrate and byproducts\n %Contributions, by process, to RNA metabolism:\n % NTPs + H2O --(transcription)--> nascent RNA + PPi + H\n % nascent RNA + H2O --(processing)-----> processed RNA + NMPs\n %processed RNA + metabolites --(modification)---> modified RNA + metabolites\n % modified RNA --(decay)----------> NMPs + modified NMPs\n % NMPs + 2 ATP --(charging)-------> NTPs + 2 ADP\n % modified NMPs + H2O --(catabolism)-----> modified bases + Pi\n %\n %Here we only account for the contributions of transcription.\n invMat = edu.stanford.covert.util.ComputationUtil.invertCompositionMatrix(this.rna.nascentRNAMatureRNAComposition);\n \n transcribedNTPs = this.transcriptionUnitBaseCounts(:, this.substrateIndexs_nmp)' * invMat * states.rnaProductions;\n bmProd(this.substrateIndexs_ntp) = bmProd(this.substrateIndexs_ntp) + transcribedNTPs;\n byProd(this.substrateIndexs_diphosphate) = byProd(this.substrateIndexs_diphosphate) + sum(transcribedNTPs);\n bmProd(this.substrateIndexs_water) = bmProd(this.substrateIndexs_water) + sum(states.rnaProductions);\n byProd(this.substrateIndexs_hydrogen) = byProd(this.substrateIndexs_hydrogen) + sum(states.rnaProductions);\n \n %% enzymes\n %RNA polymerase\n fractionInitiating = this.rnaPolymeraseElongationRate * sum(invMat * states.rnaProductions0) / ... %fraction of active RNA polymerases that are initiating\n (this.transcripts.transcriptionUnitLengths' * invMat * states.rnaProductions0);\n minEnzExp(this.enzymeIndexs_rnaPolymerase) = 4.5867 * ...\n (this.transcripts.transcriptionUnitLengths' * invMat * states.rnaProductions0) / ...\n this.rnaPolymeraseElongationRate / ...\n this.rnaPolymerases.stateExpectations(this.rnaPolymerases.activelyTranscribingIndex) / ...\n (1 - fractionInitiating);\n \n %sigma, elongation, termination factors\n minEnzExp(this.enzymeIndexs_sigmaFactor) = minEnzExp(this.enzymeIndexs_rnaPolymerase) * ...\n (this.rnaPolymerases.stateExpectations(this.rnaPolymerases.activelyTranscribingIndex) * fractionInitiating + ...\n this.rnaPolymerases.stateExpectations(this.rnaPolymerases.specificallyBoundIndex));\n minEnzExp(this.enzymeIndexs_elongationFactor) = 2;\n minEnzExp(this.enzymeIndexs_terminationFactor) = 2;\n end\n \n %Initialize RNA polymerase, bound transcription units, transcription factor states\n %Assumptions:\n %- Metabolic cost of the transcription of these nucleic acids is negligible\n %- Probability that so many RNA polymerases bind a given transcription unit\n % that they can't pack along the transcription unit without steric\n % interactions is negligible. Thus we don't try to handle this case\n % separately\n function initializeState(this)\n rnaPols = this.rnaPolymerases;\n trnspts = this.transcripts;\n \n %% states\n trnsptStrnds = 2 - trnspts.transcriptionUnitDirections;\n trnsptLens = trnspts.transcriptionUnitLengths;\n trnsptDirs = 2 * trnspts.transcriptionUnitDirections - 1;\n trnspt5Coords = trnspts.transcriptionUnitFivePrimeCoordinates;\n trnsptStarts = ...\n trnspt5Coords - (1 - trnspts.transcriptionUnitDirections) .* (trnspts.transcriptionUnitLengths-1);\n trnsptStarts(trnsptDirs == 1) = ...\n trnsptStarts(trnsptDirs == 1) - ...\n this.enzymeDNAFootprints5Prime(this.enzymeIndexs_rnaPolymerase);\n trnsptStarts(trnsptDirs == -1) = ...\n trnsptStarts(trnsptDirs == -1) + ...\n this.enzymeDNAFootprints5Prime(this.enzymeIndexs_rnaPolymerase);\n \n %% enzymes\n freTFs = this.enzymes(this.enzymeIndexs_transcriptionFactors);\n bndTFs = this.boundEnzymes(this.enzymeIndexs_transcriptionFactors);\n frePls = this.enzymes(this.enzymeIndexs_rnaPolymerase);\n bndPls = this.boundEnzymes(this.enzymeIndexs_rnaPolymerase);\n freHls = this.enzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme);\n bndHls = this.boundEnzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme);\n pls = frePls + bndPls + freHls + bndHls;\n \n %% allocate\n rnaPols.states = repmat(rnaPols.notExistValue, [2 * pls, 1, 1]);\n rnaPols.positionStrands = zeros([2 * pls, 2, 1]);\n trnspts.boundTranscriptionUnits = repmat(trnspts.nullTranscriptValue, [2 * pls, 1, 1]);\n trnspts.boundTranscriptProgress = repmat(trnspts.nullTranscriptValue, [2 * pls, 1, 1]);\n trnspts.boundTranscriptChromosome = repmat(trnspts.nullTranscriptValue, [2 * pls, 1, 1]);\n \n %% initialize\n pState = rnaPols.stateExpectations;\n probs = this.computeRNAPolymeraseTUBindingProbabilities();\n pBinds = trnspts.transcriptionUnitLengths .* probs(:, 1);\n pSpBinds = pBinds;\n \n for i = 1:pls\n %check whether conditions necessary for actively transcribing state are met\n if frePls == 0 || ~any(pBinds) || freTFs(this.enzymeIndexs_elongationFactor) == 0\n pState(rnaPols.activelyTranscribingIndex) = 0;\n end\n \n %check whether conditions necessary for specifically bound state are met\n if frePls == 0 || ~any(pSpBinds) || freTFs(this.enzymeIndexs_sigmaFactor) == 0\n pState(rnaPols.specificallyBoundIndex) = 0;\n end\n \n %check whether conditions necessary for non-specifically bound state are met\n if frePls == 0\n pState(rnaPols.nonSpecificallyBoundIndex) = 0;\n end\n \n if ~any(pState)\n pState(rnaPols.freeIndex) = 1;\n end\n \n %randomly select state\n state = this.randStream.randsample(4, 1, true, pState);\n \n %Actively transcribing, specifically bound: randomly select\n %transcription unit\n switch state\n case rnaPols.activelyTranscribingIndex\n tmp_pBinds = pBinds;\n posStrnds = zeros(0, 2);\n while any(tmp_pBinds)\n iTU = this.randStream.randsample(numel(pBinds), 1, true, tmp_pBinds);\n tmp_pBinds(iTU) = 0;\n [~, posStrnds] = this.bindProteinToChromosomeStochastically(...\n this.enzymeIndexs_rnaPolymerase, 1, [trnsptStarts(iTU)+1 trnsptStrnds(iTU)], trnsptLens(iTU)-2);\n if ~isempty(posStrnds)\n break;\n end\n end\n if isempty(posStrnds)\n throw(MException('Transcription:error', 'unable to bind chromosome'));\n end\n \n posStrnds( isodd(posStrnds(:, 2)), 1) = posStrnds( isodd(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints5Prime(this.enzymeIndexs_rnaPolymerase);\n posStrnds(iseven(posStrnds(:, 2)), 1) = posStrnds(iseven(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints3Prime(this.enzymeIndexs_rnaPolymerase);\n if trnspts.transcriptionUnitDirections(iTU)\n state = posStrnds(:, 1) - trnspt5Coords(iTU) + 1;\n else\n state = trnspt5Coords(iTU) - posStrnds(:, 1) + 1;\n end\n \n rnaPols.states(i) = state;\n rnaPols.positionStrands(i, :) = posStrnds;\n trnspts.boundTranscriptProgress(i) = state;\n trnspts.boundTranscriptionUnits(i) = iTU;\n trnspts.boundTranscriptChromosome(i) = 1; %initialize to first chromosome\n \n frePls = frePls - 1;\n bndPls = bndPls + 1;\n \n %freTFs(this.enzymeIndexs_elongationFactor) = freTFs(this.enzymeIndexs_elongationFactor) - 1;\n %bndTFs(this.enzymeIndexs_elongationFactor) = bndTFs(this.enzymeIndexs_elongationFactor) + 1;\n case rnaPols.specificallyBoundIndex\n while any(pSpBinds)\n iTU = this.randStream.randsample(numel(pSpBinds), 1, true, pSpBinds);\n pSpBinds(iTU) = 0;\n [~, ~, posStrnds] = this.bindProteinToChromosome([trnspt5Coords(iTU)-trnsptDirs(iTU) trnsptStrnds(iTU)], this.enzymeIndexs_rnaPolymeraseHoloenzyme, 1);\n if ~isempty(posStrnds)\n break;\n end\n end\n if isempty(posStrnds)\n throw(MException('Transcription:error', 'unable to bind chromosome'));\n end\n \n rnaPols.states(i) = rnaPols.specificallyBoundValue;\n rnaPols.positionStrands(i, :) = posStrnds;\n trnspts.boundTranscriptProgress(i) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptionUnits(i) = iTU;\n trnspts.boundTranscriptChromosome(i) = 1; %initialize to first chromosome\n \n bndHls = bndHls + 1;\n frePls = frePls - 1;\n freTFs(this.enzymeIndexs_sigmaFactor) = freTFs(this.enzymeIndexs_sigmaFactor) - 1;\n case rnaPols.nonSpecificallyBoundIndex\n [~, posStrnds] = this.bindProteinToChromosomeStochastically(this.enzymeIndexs_rnaPolymerase, 1);\n if isempty(posStrnds)\n throw(MException('Transcription:error', 'unable to bind chromosome'));\n end\n posStrnds( isodd(posStrnds(:, 2)), 1) = posStrnds( isodd(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints5Prime(this.enzymeIndexs_rnaPolymerase);\n posStrnds(iseven(posStrnds(:, 2)), 1) = posStrnds(iseven(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints3Prime(this.enzymeIndexs_rnaPolymerase);\n \n rnaPols.states(i) = rnaPols.nonSpecificallyBoundValue;\n rnaPols.positionStrands(i, :) = posStrnds;\n trnspts.boundTranscriptionUnits(i) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(i) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(i) = trnspts.nullTranscriptValue;\n \n frePls = frePls - 1;\n bndPls = bndPls + 1;\n case rnaPols.freeIndex\n rnaPols.states(i) = rnaPols.freeValue;\n rnaPols.positionStrands(i, :) = 0;\n trnspts.boundTranscriptionUnits(i) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(i) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(i) = trnspts.nullTranscriptValue;\n end\n end\n \n %% store states of enzymes\n this.enzymes(this.enzymeIndexs_transcriptionFactors) = freTFs;\n this.boundEnzymes(this.enzymeIndexs_transcriptionFactors) = bndTFs;\n this.enzymes(this.enzymeIndexs_rnaPolymerase) = frePls;\n this.boundEnzymes(this.enzymeIndexs_rnaPolymerase) = bndPls;\n this.enzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme) = freHls;\n this.boundEnzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme) = bndHls;\n \n %% decrement counts of RNAs\n this.copyToState();\n \n comp = this.compartment;\n rna = this.rna;\n \n matureRnaWt = max(0, sum(rna.dryWeight) - trnspts.dryWeight);\n initRnaCnts = rna.counts;\n while sum(rna.dryWeight) > matureRnaWt\n idx = this.randStream.randsample(size(rna.counts, 1), 1, false, rna.counts(:, comp.cytosolIndexs));\n rna.counts(idx, comp.cytosolIndexs) = rna.counts(idx, comp.cytosolIndexs) - 1;\n end\n rna.counts(:, comp.cytosolIndexs) = ...\n + rna.counts(:, comp.cytosolIndexs) ...\n + rna.updateExternalState(-(initRnaCnts(:, comp.cytosolIndexs) - rna.counts(:, comp.cytosolIndexs)), true);\n \n this.copyFromState();\n end\n \n %resource requirements\n function result = calcResourceRequirements_Current(this)\n result = zeros(size(this.substrates));\n result(this.substrateIndexs_ntp) = 2 * ...\n sum(this.metabolite.nmpComposition, 2) * this.rnaPolymerases.nActive * ...\n this.rnaPolymeraseElongationRate;\n result(this.substrateIndexs_water) = this.rnaPolymerases.nActive;\n end\n \n %simulation\n function evolveState(this)\n %% define and allocate variables\n \n %states\n c = this.chromosome;\n rnaPols = this.rnaPolymerases;\n trnspts = this.transcripts;\n \n %numbers of enzymes\n nFreTfs = this.enzymes(this.enzymeIndexs_transcriptionFactors);\n nBndTFs = this.boundEnzymes(this.enzymeIndexs_transcriptionFactors);\n nFrePols = this.enzymes(this.enzymeIndexs_rnaPolymerase);\n nBndPols = this.boundEnzymes(this.enzymeIndexs_rnaPolymerase);\n nFreHols = this.enzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme);\n nBndHols = this.boundEnzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme);\n nTotPols = nFrePols + nBndPols + nFreHols + nBndHols;\n \n %properties of RNA polymerases\n pStTrns = this.stateTransitionProbabilities; %probabilities of state transitions\n \n %transcription unit properties\n tuDirs = 2 * trnspts.transcriptionUnitDirections - 1;\n tuStrnds = c.transcriptionUnitStrands;\n tuLens = trnspts.transcriptionUnitLengths;\n tu5Coords = trnspts.transcriptionUnitFivePrimeCoordinates;\n tuSeqs = trnspts.transcriptionUnitSequences; %sequences\n \n %% Update states of RNA polymerases\n \n %allocate space to store states of new RNA polymerases\n if nTotPols > size(rnaPols.states, 1)\n rnaPols.states = [\n rnaPols.states;\n rnaPols.notExistValue(ones(2 * nTotPols - size(rnaPols.states, 1), 1), 1)];\n rnaPols.positionStrands = [\n rnaPols.positionStrands;\n zeros(2 * nTotPols - size(rnaPols.positionStrands, 1), 2)];\n trnspts.boundTranscriptionUnits = [\n trnspts.boundTranscriptionUnits;\n trnspts.nullTranscriptValue(ones(2 * nTotPols - size(trnspts.boundTranscriptChromosome, 1), 1), 1)];\n trnspts.boundTranscriptProgress = [\n trnspts.boundTranscriptProgress;\n trnspts.nullTranscriptValue(ones(2 * nTotPols - size(trnspts.boundTranscriptChromosome, 1), 1), 1)];\n trnspts.boundTranscriptChromosome = [\n trnspts.boundTranscriptChromosome;\n trnspts.nullTranscriptValue(ones(2 * nTotPols - size(trnspts.boundTranscriptChromosome, 1), 1), 1)];\n end\n \n %indices of RNA polymerases in various states\n actPols = find(rnaPols.states >= rnaPols.activelyTranscribingValue);\n sbPols = find(rnaPols.states == rnaPols.specificallyBoundValue);\n freeNsbPols = find(...\n rnaPols.states == rnaPols.nonSpecificallyBoundValue | ...\n rnaPols.states == rnaPols.freeValue);\n sbPols = sbPols(this.randStream.randperm(numel(sbPols)));\n freeNsbPols = freeNsbPols(this.randStream.randperm(numel(freeNsbPols)));\n \n %number of new RNA polymerases\n nNewPols = nTotPols - (numel(actPols) + numel(sbPols) + numel(freeNsbPols));\n \n %dissociate any free RNA polymerase holoenzymes (created say by\n %their release from chromosome by another protein) into RNA\n %polymerase core and sigma factor\n nFrePols = nFrePols + nFreHols;\n nFreTfs(this.enzymeIndexs_sigmaFactor) = nFreTfs(this.enzymeIndexs_sigmaFactor) + nFreHols;\n nFreHols = 0;\n \n %initiating specifically bound polymerases\n nInitMax = this.randStream.stochasticRound(numel(sbPols) * pStTrns(rnaPols.activelyTranscribingIndex, rnaPols.specificallyBoundIndex)); %#ok<*PROP>\n if nInitMax > 0\n releasedProteins = this.releaseProteinFromSites(rnaPols.positionStrands(sbPols(1:nInitMax), :), false, this.enzymeIndexs_rnaPolymeraseHoloenzyme, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymeraseHoloenzyme), nInitMax)\n throw(MException('Transcription:error', 'Unable to release protein'));\n end\n \n %try to initiate RNA polymerases\n positions = tu5Coords(trnspts.boundTranscriptionUnits(sbPols(1:nInitMax)));\n tfs = this.bindProteinToChromosome([positions rnaPols.positionStrands(sbPols(1:nInitMax), 2)], ...\n this.enzymeIndexs_rnaPolymeraseHoloenzyme);\n rnaPols.states(sbPols(tfs)) = rnaPols.activelyTranscribingValue;\n trnspts.boundTranscriptProgress(sbPols(tfs)) = trnspts.newTranscriptValue;\n rnaPols.positionStrands(sbPols(tfs), 1) = positions(tfs, 1);\n \n %rebind RNA polymerases that couldn't move forward\n if ~all(this.bindProteinToChromosome(rnaPols.positionStrands(sbPols(~tfs), :), ...\n this.enzymeIndexs_rnaPolymeraseHoloenzyme))\n throw(MException('Transcription:error', 'Unable to unbind protein'));\n end\n end\n \n %specifically bound polymerases becoming non-specifically bound / free\n nUnsb = max(0, numel(sbPols) - nInitMax - this.randStream.stochasticRound(numel(sbPols) * ...\n pStTrns(rnaPols.specificallyBoundIndex, rnaPols.specificallyBoundIndex)));\n if nUnsb > 0\n idxs = sbPols(end-nUnsb+1:end);\n posStrnds = rnaPols.positionStrands(idxs, :);\n releasedProteins = this.releaseProteinFromSites(posStrnds, false, this.enzymeIndexs_rnaPolymeraseHoloenzyme, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymeraseHoloenzyme), nUnsb)\n throw(MException('Transcription:error', 'Unable to unbind protein'));\n end\n \n rnaPols.states(idxs) = rnaPols.freeValue;\n rnaPols.positionStrands(idxs, :) = 0;\n trnspts.boundTranscriptionUnits(idxs) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(idxs) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(idxs) = trnspts.nullTranscriptValue;\n \n nBndHols = nBndHols - nUnsb; \n nFrePols = nFrePols + nUnsb;\n nFreTfs(this.enzymeIndexs_sigmaFactor) = nFreTfs(this.enzymeIndexs_sigmaFactor) + nUnsb;\n end\n \n %free polymerases/non-specifically bound becoming specifically bound\n nFreeNsbPols = this.randStream.stochasticRound(min([\n numel(freeNsbPols) * pStTrns(rnaPols.specificallyBoundIndex, rnaPols.freeIndex)\n nFreTfs(this.enzymeIndexs_sigmaFactor)]));\n if nFreeNsbPols > 0\n %unbind from non-specifically bound site\n idxs = freeNsbPols(1:nFreeNsbPols);\n nNsbPols = sum(rnaPols.states(idxs) == rnaPols.nonSpecificallyBoundValue);\n releasedProteins = this.releaseProteinFromSites(rnaPols.positionStrands(idxs, :), false, this.enzymeIndexs_rnaPolymerase, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymerase), nNsbPols)\n throw(MException('Transcription:error', 'Unable to release protein'));\n end\n \n rnaPols.states(idxs) = rnaPols.freeValue;\n rnaPols.positionStrands(idxs, :) = 0;\n trnspts.boundTranscriptionUnits(idxs) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(idxs) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(idxs) = trnspts.nullTranscriptValue;\n \n nFrePols = nFrePols + nNsbPols;\n nBndPols = nBndPols - nNsbPols;\n \n %bind to new specifically bound site\n pBnds = this.computeRNAPolymeraseTUBindingProbabilities();\n \n if nnz(c.polymerizedRegions) == 2\n [~, iTU, posStrnds, nFreeNsbPols] = this.bindProteinToChromosome( ...\n [tu5Coords-tuDirs tuStrnds], ...\n this.enzymeIndexs_rnaPolymeraseHoloenzyme, nFreeNsbPols, pBnds(:, 1), ...\n true, true, 1, false, []);\n iChr = 1;\n else\n [~, iTU, posStrnds, nFreeNsbPols] = this.bindProteinToChromosome( ...\n [tu5Coords-tuDirs tuStrnds\n tu5Coords-tuDirs tuStrnds + 2], ...\n this.enzymeIndexs_rnaPolymeraseHoloenzyme, nFreeNsbPols, pBnds(:), ...\n true, true, 1, false, []);\n iTU = mod(iTU - 1, numel(tuLens)) + 1;\n iChr = ceil(posStrnds(:, 2) / 2);\n end\n \n idxs = freeNsbPols(1:nFreeNsbPols);\n rnaPols.states(idxs) = rnaPols.specificallyBoundValue;\n rnaPols.positionStrands(idxs, :) = posStrnds;\n trnspts.boundTranscriptionUnits(idxs) = iTU;\n trnspts.boundTranscriptProgress(idxs) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(idxs) = iChr;\n \n nBndHols = nBndHols + nFreeNsbPols;\n nFrePols = nFrePols - nFreeNsbPols;\n nFreTfs(this.enzymeIndexs_sigmaFactor) = nFreTfs(this.enzymeIndexs_sigmaFactor) - nFreeNsbPols;\n end\n \n %free polymerases/non-specifically bound becoming free/non-specifically bound\n nsbPols = find(rnaPols.states == rnaPols.nonSpecificallyBoundValue);\n if ~isempty(nsbPols)\n %set non-specifically bound to free\n releasedProteins = this.releaseProteinFromSites(rnaPols.positionStrands(nsbPols, :), false, this.enzymeIndexs_rnaPolymerase, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymerase), numel(nsbPols))\n throw(MException('Transcription:error', 'Unable to release protein'));\n end\n \n rnaPols.states(nsbPols) = rnaPols.freeValue;\n rnaPols.positionStrands(nsbPols, :) = 0;\n trnspts.boundTranscriptionUnits(nsbPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(nsbPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(nsbPols) = trnspts.nullTranscriptValue;\n \n nFrePols = nFrePols + numel(nsbPols);\n nBndPols = nBndPols - numel(nsbPols);\n end\n \n freePols = find(rnaPols.states == rnaPols.freeValue);\n nNsbPols = this.randStream.stochasticRound(min([...\n nFrePols\n numel(freePols) * pStTrns(rnaPols.nonSpecificallyBoundIndex, rnaPols.freeIndex) / (pStTrns(rnaPols.nonSpecificallyBoundIndex, rnaPols.freeIndex) + pStTrns(rnaPols.freeIndex, rnaPols.freeIndex))]));\n if nNsbPols > 0\n %set some to non-specifically bound state\n [nNsbPols posStrnds] = this.bindProteinToChromosomeStochastically(this.enzymeIndexs_rnaPolymerase, nNsbPols);\n posStrnds( isodd(posStrnds(:, 2)), 1) = posStrnds( isodd(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints5Prime(this.enzymeIndexs_rnaPolymerase);\n posStrnds(iseven(posStrnds(:, 2)), 1) = posStrnds(iseven(posStrnds(:, 2)), 1) + this.enzymeDNAFootprints3Prime(this.enzymeIndexs_rnaPolymerase);\n \n rnaPols.states(freePols(1:nNsbPols)) = rnaPols.nonSpecificallyBoundValue;\n rnaPols.positionStrands(freePols(1:nNsbPols), :) = posStrnds;\n trnspts.boundTranscriptionUnits(freePols(1:nNsbPols)) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(freePols(1:nNsbPols)) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(freePols(1:nNsbPols)) = trnspts.nullTranscriptValue;\n \n nFrePols = nFrePols - nNsbPols;\n nBndPols = nBndPols + nNsbPols;\n end\n \n %set newly created RNA polymerases to free state\n if nNewPols > 0\n newPols = find(rnaPols.states == rnaPols.notExistValue, nNewPols, 'first');\n rnaPols.states(newPols) = rnaPols.freeValue;\n rnaPols.positionStrands(newPols, :) = 0;\n trnspts.boundTranscriptionUnits(newPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(newPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(newPols) = trnspts.nullTranscriptValue;\n end\n \n %% Transcribe active sequences\n %compute progress of transcription and cost\n usedNTPs = zeros(4, 1);\n if ~isempty(actPols) && nFreTfs(this.enzymeIndexs_elongationFactor) && this.rnaPolymeraseElongationRate > 0\n posStrnds = rnaPols.positionStrands(actPols, :);\n iTUs = trnspts.boundTranscriptionUnits(actPols);\n \n %temporarily release RNA polymerase from old position strands\n releasedProteins = ...\n this.releaseProteinFromSites(posStrnds, false, this.enzymeIndexs_rnaPolymerase, true, true) + ...\n this.releaseProteinFromSites(posStrnds, false, this.enzymeIndexs_rnaPolymeraseHoloenzyme, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymerase) + releasedProteins(this.enzymeIndexs_rnaPolymeraseHoloenzyme), numel(actPols))\n throw(MException('Transcription:error', 'Unable to unbind protein'));\n end\n \n %extract active sequences (part of sequence that should be transcribed)\n actSeqs = cell(size(actPols)); %active sequences (those can be transcribed)\n for idx = 1:numel(actPols)\n i = actPols(idx);\n left = rnaPols.states(i);\n actSeqs{idx} = tuSeqs{trnspts.boundTranscriptionUnits(i)}(left:end);\n end\n actSeqs = char(actSeqs);\n actSeqs = actSeqs(:, 1:min(end, this.rnaPolymeraseElongationRate));\n \n %elongation limits by RNA polymerase kinetic rate and transcription unit extent\n elngMax = min(this.rnaPolymeraseElongationRate, ...\n tuLens(trnspts.boundTranscriptionUnits(actPols)) - rnaPols.states(actPols) + 1);\n \n %elongation limits by RNA-polymerase / RNA-polymerase interactions\n for strnd = 1 : 4\n idxs = find(posStrnds(:, 2) == strnd);\n if numel(idxs) <= 1\n continue;\n end\n [~, order] = sort(posStrnds(idxs, 1));\n \n if isodd(strnd)\n elngMax(idxs(order)) = min(...\n elngMax(idxs(order)), ...\n diff([posStrnds(idxs(order), 1); posStrnds(idxs(order(1)), 1) + c.sequenceLen]) - ...\n this.enzymeDNAFootprints(this.enzymeIndexs_rnaPolymerase));\n else\n elngMax(idxs(order)) = min(...\n elngMax(idxs(order)), ...\n diff([posStrnds(idxs(order(end)), 1) - c.sequenceLen; posStrnds(idxs(order), 1)]) - ...\n this.enzymeDNAFootprints(this.enzymeIndexs_rnaPolymerase));\n end\n end\n \n %elongation limits by RNA-polymerase DNA interactions (Note: independent of other RNA polymerases)\n [~, ~, ~, tmp_elngMax] = c.isRegionAccessible(...\n posStrnds, (elngMax + 1) .* tuDirs(iTUs), ...\n [], this.enzymeGlobalIndexs(this.enzymeIndexs_rnaPolymerase), true, [], true, false);\n if ~all(tmp_elngMax)\n throw(MException('Transcription:error', 'Unable to bind proteins'));\n end\n elngMax = min(abs(tmp_elngMax) - 1, elngMax);\n \n %elongation limits by NTPs\n for i = 1:size(actSeqs, 1)\n actSeqs(i, elngMax(i) + 1:end) = ' ';\n end\n [elngProg, this.substrates(this.substrateIndexs_ntp), usedNTPs] = ...\n edu.stanford.covert.cell.sim.util.polymerize(...\n actSeqs, this.substrates(this.substrateIndexs_ntp), 'ACGU', ' ', 0, 0, this.randStream);\n \n %release sigma factor after initiation\n nInits = sum(...\n rnaPols.states(actPols) == rnaPols.activelyTranscribingValue & ...\n elngProg > 0);\n nBndHols = nBndHols - nInits;\n nFreTfs(this.enzymeIndexs_sigmaFactor) = nFreTfs(this.enzymeIndexs_sigmaFactor) + nInits;\n nBndPols = nBndPols + nInits;\n \n %rebind RNA polymerase to new positions\n rnaPols.states(actPols) = rnaPols.states(actPols) + elngProg;\n rnaPols.positionStrands(actPols, 1) = posStrnds(:, 1) + elngProg .* tuDirs(iTUs);\n trnspts.boundTranscriptProgress(actPols) = rnaPols.states(actPols);\n \n initPols = rnaPols.states(actPols) == rnaPols.activelyTranscribingValue;\n if ...\n ~all(this.bindProteinToChromosome(rnaPols.positionStrands(actPols(~initPols), :), this.enzymeIndexs_rnaPolymerase)) || ...\n ~all(this.bindProteinToChromosome(rnaPols.positionStrands(actPols( initPols), :), this.enzymeIndexs_rnaPolymeraseHoloenzyme))\n throw(MException('Transcription:error', 'Unable to bind proteins'));\n end\n end\n \n %release polymerases which have completed transcription, and increment\n %expression of the corresponding transcription unit\n if ~isempty(actPols) && nFreTfs(this.enzymeIndexs_elongationFactor) && nFreTfs(this.enzymeIndexs_terminationFactor)\n trmPols = actPols(rnaPols.states(actPols) > ...\n tuLens(trnspts.boundTranscriptionUnits(actPols)));\n nTrmPols = numel(trmPols);\n if nTrmPols > this.substrates(this.substrateIndexs_water)\n order = this.randStream.randperm(nTrmPols);\n nTrmPols = this.substrates(this.substrateIndexs_water);\n trmPols = trmPols(order(1:nTrmPols));\n end\n \n if nTrmPols > 0\n if isscalar(trmPols)\n this.RNAs(trnspts.boundTranscriptionUnits(trmPols)) = ...\n this.RNAs(trnspts.boundTranscriptionUnits(trmPols)) + 1;\n else\n this.RNAs = this.RNAs + ...\n histc(trnspts.boundTranscriptionUnits(trmPols, 1), 1:numel(tuLens));\n end\n \n %release proteins from chromsome\n releasedProteins = this.releaseProteinFromSites(rnaPols.positionStrands(trmPols, :), false, this.enzymeIndexs_rnaPolymerase, true, true);\n if ~isequal(releasedProteins(this.enzymeIndexs_rnaPolymerase), numel(trmPols))\n throw(MException('Transcription:error', 'Unable to unbind protein'));\n end\n \n nFrePols = nFrePols + nTrmPols;\n nBndPols = nBndPols - nTrmPols;\n \n this.substrates(this.substrateIndexs_water) = this.substrates(this.substrateIndexs_water) - nTrmPols;\n this.substrates(this.substrateIndexs_hydrogen) = this.substrates(this.substrateIndexs_hydrogen) + nTrmPols;\n \n rnaPols.states(trmPols) = rnaPols.freeValue;\n rnaPols.positionStrands(trmPols, :) = 0;\n trnspts.boundTranscriptionUnits(trmPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptProgress(trmPols) = trnspts.nullTranscriptValue;\n trnspts.boundTranscriptChromosome(trmPols) = trnspts.nullTranscriptValue;\n end\n end\n \n %% diphosphate released by polymerization\n this.substrates(this.substrateIndexs_diphosphate) = ...\n this.substrates(this.substrateIndexs_diphosphate) + ...\n sum(usedNTPs);\n \n %% store enzyme state\n this.enzymes(this.enzymeIndexs_transcriptionFactors) = nFreTfs;\n this.boundEnzymes(this.enzymeIndexs_transcriptionFactors) = nBndTFs;\n this.enzymes(this.enzymeIndexs_rnaPolymerase) = nFrePols;\n this.boundEnzymes(this.enzymeIndexs_rnaPolymerase) = nBndPols;\n this.enzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme) = nFreHols;\n this.boundEnzymes(this.enzymeIndexs_rnaPolymeraseHoloenzyme) = nBndHols;\n end\n end\n \n %model helper functions\n methods \n function pBinds = computeRNAPolymeraseTUBindingProbabilities(this, protectDnaABoxes)\n c = this.chromosome;\n r = this.rnaPolymerases;\n \n %relative probability RNA polymerase binds each transcription\n %unit\n pBinds = this.transcriptionUnitBindingProbabilities(:, ones(1, 2)) .* ...\n r.transcriptionFactorBindingProbFoldChange .* ...\n r.supercoilingBindingProbFoldChange;\n \n %if functional DnaA boxes R1-5 are occupied by DnaA-ATP,\n %don't allow RNA polymerase to bind since it would knockoff\n %DnaA-ATP\n if nargin == 1 || protectDnaABoxes\n [posStrnds, complexs] = find(...\n c.complexBoundSites(c.transcriptionUnitStartCoordinates(this.transcriptionUnitIndexs_DnaAR12345Boxes) + ...\n (1:c.transcriptionUnitLengths(this.transcriptionUnitIndexs_DnaAR12345Boxes))' - 1, :));\n if any(ismembc(complexs, this.complexIndexs_DnaA_ATP) & posStrnds(:, 2) <= 2)\n pBinds(this.transcriptionUnitIndexs_DnaAR12345Boxes, 1) = 0;\n end\n if any(ismembc(complexs, this.complexIndexs_DnaA_ATP) & posStrnds(:, 2) > 2)\n pBinds(this.transcriptionUnitIndexs_DnaAR12345Boxes, 2) = 0;\n end\n end\n end\n \n function pStProbs = calcStateTransitionProbabilities(this, nPols, ntpProdRate, tuBindingProbs, method)\n import edu.stanford.covert.util.ComputationUtil;\n import edu.stanford.covert.util.ConstantUtil;\n \n rna = this.rna;\n rnaPols = this.rnaPolymerases;\n \n pStProbs = zeros(4, 4);\n pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.activelyTranscribingIndex) = ...\n ntpProdRate / (nPols * rnaPols.stateExpectations(rnaPols.activelyTranscribingIndex)) / ...\n (tuBindingProbs' * rna.lengths(rna.nascentIndexs));\n if nargin < 5 || isequal(method, 'handTuned')\n pStProbs(rnaPols.activelyTranscribingIndex, rnaPols.specificallyBoundIndex) = 1;\n pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.specificallyBoundIndex) = 0;\n pStProbs(rnaPols.specificallyBoundIndex, rnaPols.nonSpecificallyBoundIndex) = 0.10;\n else\n pStProbs(rnaPols.activelyTranscribingIndex, rnaPols.specificallyBoundIndex) = ...\n pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.activelyTranscribingIndex) * ...\n rnaPols.stateExpectations(rnaPols.activelyTranscribingIndex) / ...\n rnaPols.stateExpectations(rnaPols.specificallyBoundIndex);\n pStProbs(rnaPols.specificallyBoundIndex, rnaPols.nonSpecificallyBoundIndex) = ...\n pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.activelyTranscribingIndex) * ...\n rnaPols.stateExpectations(rnaPols.activelyTranscribingIndex) / ...\n rnaPols.stateExpectations(rnaPols.nonSpecificallyBoundIndex);\n end\n \n pStProbs(rnaPols.activelyTranscribingIndex, rnaPols.activelyTranscribingIndex) = ...\n 1 - pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.activelyTranscribingIndex);\n pStProbs(rnaPols.specificallyBoundIndex, rnaPols.specificallyBoundIndex) = ...\n + 1 ...\n - pStProbs(rnaPols.activelyTranscribingIndex, rnaPols.specificallyBoundIndex)...\n - pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.specificallyBoundIndex);\n pStProbs(rnaPols.nonSpecificallyBoundIndex, rnaPols.nonSpecificallyBoundIndex) = ...\n 1 - pStProbs(rnaPols.specificallyBoundIndex, rnaPols.nonSpecificallyBoundIndex);\n pStProbs(:, rnaPols.freeIndex) = pStProbs(:, rnaPols.nonSpecificallyBoundIndex);\n end\n end\n \n %get methods of dependent local state\n methods\n function value = getDryWeight(this)\n if size(this.RNAs, 3) == 1\n value = this.getDryWeight@edu.stanford.covert.cell.sim.Process() + ...\n this.rna.molecularWeights(this.rna.nascentIndexs)' * this.RNAs ...\n / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n else\n value = this.getDryWeight@edu.stanford.covert.cell.sim.Process() + ...\n permute(this.rna.molecularWeights(this.rna.nascentIndexs)' * permute(this.RNAs,[1 3 2]),[1 3 2]) ...\n / edu.stanford.covert.util.ConstantUtil.nAvogadro;\n end\n end\n end\nend\n", "meta": {"author": "CovertLab", "repo": "WholeCell", "sha": "6cdee6b355aa0f5ff2953b1ab356eea049108e07", "save_path": "github-repos/MATLAB/CovertLab-WholeCell", "path": "github-repos/MATLAB/CovertLab-WholeCell/WholeCell-6cdee6b355aa0f5ff2953b1ab356eea049108e07/src/+edu/+stanford/+covert/+cell/+sim/+process/Transcription.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404566, "lm_q2_score": 0.023330766431669276, "lm_q1q2_score": 0.004650008347062919}} {"text": "function Callbacks_p_Tube_VT_GUI25(f,C)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nx=C{1,1};\ny=C{1,2};\na=C{1,3};\nb=C{1,4};\nu=C{1,5};\nv=C{1,6};\nm=C{1,7};\nn=C{1,8};\nlengthbutton=C{1,9};\nwidthbutton=C{1,10};\nenterType=C{1,11};\nenterString=C{1,12};\nenterLabel=C{1,13};\nnoPanels=C{1,14};\nnoGraphicPanels=C{1,15};\nnoButtons=C{1,16};\nlabelDist=C{1,17};%distance that the label is below the button\nnoTitles=C{1,18};\nbuttonTextSize=C{1,19};\nlabelTextSize=C{1,20};\ntextboxFont=C{1,21};\ntextboxString=C{1,22};\ntextboxWeight=C{1,23};\ntextboxAngle=C{1,24};\nlabelHeight=C{1,25};\nfileName=C{1,26};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%PANELS\nfor j=0:noPanels-1\nuipanel('Parent',f,...\n'Units','Normalized',...\n'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%GRAPHIC PANELS\nfor i=0:noGraphicPanels-1\nswitch (i+1)\ncase 1\ngraphicPanel1 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 2\ngraphicPanel2 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 3\ngraphicPanel3 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 4\ngraphicPanel4 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%TITLE BOXES\nfor k=0:noTitles-1\nswitch (k+1)\ncase 1\ntitleBox1 = uicontrol('parent',f,...\n'Units','Normalized',...\n'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...\n'Style','text',...\n'FontSize',textboxFont{k+1},...\n'String',textboxString(k+1),...\n'FontWeight',textboxWeight{k+1},...\n'FontAngle',textboxAngle{k+1});\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%BUTTONS\nfor i=0:(noButtons-1)\nenterColor='w';\nif strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1\nenterColor='default';\nend\nif (strcmp(enterLabel{1,(i+1)},'')==0 &&...\n strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label\n%creating a label for some buttons\nuicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...\n(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...\n'Style','text',...\n'String',enterLabel{i+1},...\n'FontSize', labelTextSize(i+1),...\n'HorizontalAlignment','center');\nend\nswitch (i+1)\ncase 1\nbutton1=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button1Callback);\ncase 2\nbutton2=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button2Callback);\ncase 3\nbutton3=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button3Callback);\ncase 4\nbutton4=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button4Callback);\ncase 5\nbutton5=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button5Callback);\ncase 6\nbutton6=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button6Callback);\ncase 7\nbutton7=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button7Callback);\ncase 8\nbutton8=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button8Callback);\ncase 9\nbutton9=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button9Callback);\ncase 10\nbutton10=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button10Callback);\ncase 11\nbutton11=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button11Callback);\nend\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%USER CODE FOR THE VARIABLES AND CALLBACKS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Initialize Variables\nrG=0.7; rL=0.7;\nfs=10000; ls=1.75;\nfno=1;\n% area=ones(1,10);\nc=35000;\nnfft=4000;\np=10;\nipd=100;\nfileout='out_p_tube';\nsliderpos1=0.7;\nsliderpos2=0.7;\nfilename='area_1';\nsource='figure5.40';\nseq_length=4001;\n\n% Name the GUI\n set(f,'Name','p_Tube_VT_GUI');\n\n% CALLBACKS\n% Callback for button1 -- mat file with areas and other parameters\n\nset_slider_pos()\n\n function button1Callback(h,eventdata)\n fno=get(button1,'val');\n set(button6,'val',(rG+1)/2);\n set(button7,'val',(rL+1)/2);\n end\n\n% Callback for button2 -- read in sampling rate, fs, of vocal tract\n% synthesis\n function button2Callback(h,eventdata)\n fs=str2num(get(button2,'string'));\n end\n\n% Callback for button3 -- report length of each uniform tube, ls\n function button3Callback(h,eventdata)\n ls=str2num(get(button3,'string'));\n end\n\n% Callback for button4 -- glottal reflection coefficient, rG, edit button\n function button4Callback(h,eventdata)\n set(button4,'string',num2str(sliderpos1));\n rG=sliderpos1;\n end\n\n% Callback for button5 -- lips reflection coefficient, rL, edit button\n function button5Callback(h,eventdata)\n set(button5,'string',num2str(sliderpos2));\n rL=sliderpos2;\n end\n\n% Callback for button6 -- rG slider (range of -1 to +1) edit button\n function button6Callback(h,eventdata)\n sliderpos1=get(button6,'val')*2-1;\n button4Callback(h,eventdata);\n end\n\n% Callback for button7 -- rL slider (range of -1 to +1) edit button\n function button7Callback(h,eventdata)\n sliderpos2=get(button7,'val')*2-1;\n button5Callback(h,eventdata);\n end\n\n% Callback for button8 -- name of output text file, fileout, for saving\n% p-tube vocal tract resonances\n function button8Callback(h,eventdata)\n fileout=get(button8,'string');\n end\n\n% Callback for button11 -- ipd: pitch period in samples\n function button11Callback(h,eventdata)\n ipd=num2str(get(button11,'string'));\n end\n\n% Callback for button9 -- run the p-tube VT model code\n function button9Callback(h,eventdata)\n \n% send message to change either rG or rL to be less than 1 for realistic\n% vowel sound\n if (rG == 1 & rL == 1)\n uiwait(msgbox('change rG or rL to be less than 1 for correct vowel sound',...\n 'set rG, rL','modal'));\n end\n\n\n% read in source file for areas and other parameters\n clear area;\n filename=['area_',num2str(fno),'.mat'];\n areas=load(filename);\n \n% extract p-tube vocal tract information from areas structure, including the\n% p-tube areas, areas.area. the source of the area data, areas.source, \n% the number of tubes, areas.p, the size of fft for synthesis, \n% areas.nfft, the sampling rate of the simulation, areas.fs, the\n% speed of sound in cm/sec, areas.c, and the length of each of the\n% p-uniform tubes, areas.ls\n area=areas.area;\n source=areas.source;\n p=areas.p;\n nfft=areas.nfft;\n fs=areas.fs;\n c=areas.c;\n ls=areas.ls;\n \n% update buttons for fs and ls by writing the values obtained above into\n% the appropriate edit buttons (button2 and button3)\n set(button2,'string',num2str(fs));\n set(button3,'string',num2str(ls));\n \n% open text file for saving vocal tract resonance information\n fid=fopen(fileout,'wt');\n \n% create input for plotting vocal tract area function across p sections\n yc=[area(1) area(1) area(1)];\n xc=[0 1 1 1 1];\n for index=2:p-1\n yc=[yc area(index) area(index) area(index) area(index)];\n xc=[xc index index index index];\n end\n yc=[yc area(p) area(p) area(p)];\n xc=[xc p];\n \n% plot vocal tract area function in Graphics Panel 1\n grid off;\n reset(graphicPanel1);\n axes(graphicPanel1);\n \n% plot p-tube area function\n amax=max(yc);\n plot(xc,yc,'b','LineWidth',2);\n hold on,plot(xc,-yc,'b','LineWidth',2);\n plot([0 p],[0 0],'r--','LineWidth',2);\n axis ([0 p -amax*1.1 amax*1.1]);\n xlabel('Distance from Glottis');\n ylabel('Area(square cm)');\n stitle=sprintf(' source: %s, p: %d, ls: %6.2f',source,p,ls);\n \n% set title in titleBox1; adjust font size to 20\n stitle1=strcat('p-Tube Vocal Tract -- ',stitle);\n set(titleBox1,'String',stitle1);\n set(titleBox1,'FontSize',20);\n\n% transform from vocal tract areas areas(1:p-1) to reflection coefficients,\n% k(1:p-1)\n clear k;\n k(1:p-1)=(-area(2:p)+area(1:p-1))./(area(2:p)+area(1:p-1));\n r(1:p-1)=-k(1:p-1);\n k=[rG -r rL];\n \n% plot set of reflection coefficients on Graphics Panel 2\n reset(graphicPanel2);\n axes(graphicPanel2);\n stem(0:p,k,'r','LineWidth',2);\n axis([0 p -1 1]);\n xlabel('Distance from Glottis'); ylabel('Reflection Coefficients');\n \n% print out (to ascii text file) the set of reflection coefficients and areas\n fprintf(fid,'areas-to-spectrum using p: %d, nfft: %d,',p,nfft);\n fprintf(fid,' fs: %d \\n',fs);\n for index=1:p-1\n fprintf(fid,'index: %d, k:%6.4f,',index,k(index));\n fprintf(fid,' areas:%6.3f, %6.3f \\n',area(index+1),area(index));\n end\n \n%\n% solve nodal equations for the p tubes\n%\n% matrix1 columns are uG, u1+, u2+, ..., up+, u(p+1)+\n% matrix1 rows are n=0,1,2,...,NL\n% matrix2 columns are u1-, u2-, ...,up-\n% matrix2 rows are n=1,2,...,NL+1\n%\n NL=3000; % number of time slots for solution\n \n% initialize nodal equations\n uplus=zeros(p+2,NL+1);\n uminus=zeros(p,NL+1);\n uplus(1:2,1)=[1,(1+rG)/2];\n\n% solve nodal equations for NL iterations\n for n=1:NL\n uminus(p,n+1)=-rL*uplus(p+1,n);\n for node=p-1:-1:1\n uminus(node,n+1)=-r(node)*uplus(node+1,n)+...\n (1-r(node))*uminus(node+1,n+1);\n end\n uplus(2,n+1)=uminus(1,n+1)*rG;\n for node=3:p+1\n uplus(node,n+1)=uplus(node-1,n)*(1+r(node-2))+...\n uminus(node-1,n+1)*r(node-2);\n end\n uplus(p+2,n+1)=(1+rL)*uplus(p+1,n);\n end\n \n% save output as vocal tract impulse response\n h(1:NL+1)=uplus(p+2,1:NL+1);\n \n% truncate impulse response to nl=500 samples\n nl=500;\n nir=0:nl-1;\n \n% plot resulting vocal tract impulse response in Figure 3\n reset(graphicPanel3);\n axes(graphicPanel3);\n \n plot(nir,h(1:nl),'b','LineWidth',2);\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp),ylabel('Amplitude');\n grid on, axis tight;\n s1=sprintf('source: %s, p: %d,',source,p);\n s2=sprintf(' rG,rL: %6.3f, %6.3f, fs:%6.1f',rG,rL,fs);\n stitle=strcat(s1,s2);\n legend('Vocal Tract Impulse Response');\n \n% transform to spectral domain and plot log magnitude response\n h=[h, zeros(1,nfft-NL-1)];\n \n% convert to log magnitude spectrum\n hs=fft(h,nfft);\n spectrum(1:nfft/2+1)=20*log10(1.e-1+abs(hs(1:nfft/2+1)));\n vmin=min(spectrum);\n vmax=max(spectrum);\n \n% plot log magnitude spectrum in graphics Panel 4\n reset(graphicPanel4);\n axes(graphicPanel4);\n \n freq=0:fs/nfft:fs/2;\n npts=nfft/2+1;\n plot(freq(1:npts),spectrum(1:npts),'g','LineWidth',2); grid;\n xlabel('Frequency(kHz)'); ylabel('Log Magnitude(dB)');\n axis([freq(1) freq(npts) vmin-2 vmax+2]);\n hold on;\n \n% find formant locations and include on plot\n fmt=[];\n loc=[];\n nfmt=0;\n for index=10:npts-2\n if (spectrum(index+1) > spectrum(index) && ...\n spectrum(index+1) > spectrum(index+2))\n fmt=[fmt freq(index+1)];\n loc=[loc index];\n nfmt=nfmt+1;\n end\n end\n\n% next estimate formant bandwidths\n bwlevel=6; % (db) range of bandwidth around formant peak\n if (nfmt <= 10)\n for nf=1:nfmt\n f=fmt(nf);\n index=loc(nf);\n peak=spectrum(index);\n [peakl,peakh]=findpeak(spectrum,index,peak,bwlevel);\n fr(nf)=f;\n bw(nf)=freq(peakh)-freq(peakl);\n end\n else\n peakspectrum=max(spectrum);\n nfe=1;\n for nf=1:nfmt\n f=fmt(nf);\n index=loc(nf);\n peak=spectrum(index);\n if (peak >= peakspectrum-20)\n fr(nfe)=f;\n bw(nfe)=0;\n fmt(nfe)=f;\n nfe=nfe+1;\n end\n end\n nfmt=nfe-1;\n end\n \n% print out results to output text file\n fprintf(fid,'p-tube model results: \\n');\n fprintf(fid,'rL,rG: %4.1f %4.1f \\n',rL,rG);\n for formant=1:nfmt\n fprintf(fid,'formant frequency: %6.1f,',fr(formant));\n fprintf(fid,' formant bandwidth: %6.1f \\n',bw(formant));\n end\n fprintf(fid,'\\n \\n');\n \n% print formant locations on plots\n for nf=1:nfmt\n frfmt=[fmt(nf) fmt(nf)];\n vrfmt=[vmin vmax];\n plot(frfmt,vrfmt,'r','LineWidth',2);\n string=strcat('fmt',int2str(nf),':',int2str(fmt(nf)));\n if (mod(nf,2) == 0)\n text(fmt(nf)-200,vmax*.9,string);\n else\n text(fmt(nf)-200,vmin*1.1,string);\n end\n end\n \n% convolve p-tube impulse response with periodic pulse train of period ipd\n% samples (default is 100 Hz fundamental at fs=10000 Hz), and play out resulting\n% speech waveform -- note wierd sound for rG=rL=1 since impulse response\n% never dies out with no loss\n ipd=str2num(get(button11,'string'));\n if (ipd < 0)\n waitfor(errordlg('IPD must be positive'));\n end\n seq_length=40*ipd; % sequence length in samples\n xin=zeros(1,seq_length);\n xin(1:ipd:seq_length)=1;\n yout=conv(xin,h);\n soundsc(yout,fs);\n \n% close up printing file\n fclose('all'); \n end\n\n% Callback for button10 -- close the GUI\n function button10Callback(h,eventdata)\n close(gcf);\n end\n\nfunction set_slider_pos()\n set(button6,'val',rG+0.15); %when set at exactly rG, slider bar is at 0.4\n set(button7,'val',rL+0.15); %when set at exactly rL, slider bar is at 0.4\nend\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43668-p-tube-vocal-tract/p_Tube_VT/Callbacks_p_Tube_VT_GUI25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1778108520503478, "lm_q2_score": 0.024053553943839557, "lm_q1q2_score": 0.0042769829215931155}} {"text": "function [model,secretionRxnsAdded] = secretionProductGapfill(model,microbeID,database,inputDataFolder)\n% This function adds exchange, transport and biosynthesis reactions for \n% experimentally shown secreted metabolites according to data collected for\n% the DEMETER pipeline.\n%\n% USAGE:\n%\n% [model,secretionRxnsAdded] = secretionProductGapfill(model,microbeID,database,inputDataFolder)\n%\n% INPUTS\n% model: COBRA model structure\n% microbeID: ID of the reconstructed microbe that serves as the\n% reconstruction name and to identify it in input tables\n% database: rBioNet reaction database containing min. 3 columns:\n% Column 1: reaction abbreviation, Column 2: reaction\n% name, Column 3: reaction formula.\n% inputDataFolder: Folder with input tables with experimental data\n% and databases that inform the refinement process\n%\n% OUTPUTS\n% model: COBRA model structure with added pathways if applies\n% secretionRxnsAdded: Reactions added based on experimental data\n%\n% .. Author:\n% - Almut Heinken, 2019-2020\n% - Bronson R. Weston, 2022, introduced global additional secretion\n% reactions\nglobal additionalSecretionRxns\n\n% structure of lists of reactions to add per secretion product\n% non-alphanumeric characters are removed from secretion product names in\n% the structure; the script accounts for this when matching with the\n% experimental data input\nsecretionRxns = struct();\n% secretionRxns.Folate = {'EX_fol(e)','FOLte','EX_5mthf(e)','MTHFTe','EX_thf(e)','THFte'};\nsecretionRxns.Folate = {'EX_fol(e)','FOLte','EX_5mthf(e)','MTHFTe','EX_thf(e)','THFte','EX_4abz(e)','4ABZt2','DM_GCALD','DHPS','DHNPA','AKP1','GTPCI'};\nsecretionRxns.Thiamin = {'EX_thm(e)','THMte'};\n% secretionRxns.Riboflavin = {'EX_ribflv(e)','RIBFLVt2r'};\nsecretionRxns.Riboflavin = {'EX_ribflv(e)','RIBFLVt2r','PMDPHT'};\nsecretionRxns.Niacin = {'EX_nac(e)','EX_ncam(e)','NACt2r','EX_ncam(e)','NCAMt2r'};\nsecretionRxns.Pyridoxine = {'EX_pydx(e)','EX_pydxn(e)','EX_pydam(e)','PYDXtr','PYDXNtr','PYDAMtr'};\n% secretionRxns.Cobalamin = {'EX_cbl1(e)','CBl1te','EX_adocbl(e)','CBLTDe'};\nsecretionRxns.Cobalamin = {'EX_cbl1(e)','CBl1te','EX_adocbl(e)','CBLTDe','sink_dmbzid','CPC4MT','CPC5MT','LTHRK','SHCHD2','CYRDAR'};\n% secretionRxns.Menaquinone = {'EX_mqn7(e)','MQN7te','EX_mqn8(e)','MK8t'};\nsecretionRxns.Menaquinone = {'EX_mqn7(e)','MQN7te','EX_mqn8(e)','MK8t','AMMQT8r','AMMQT72','DHNAOT7','DHNAOT4','DHNAOT','NCOAH','DHNAS','NPHS','SUCBZL','SUCBZS','2S6HCC','ICHORS','HETT','PREN','EX_2obut(e)','2OBUTt2r','EX_adn(e)','ADNCNT3tc','DHQTi'};\n% secretionRxns.GABA = {'EX_4abut(e)','ABUTt2r'};\nsecretionRxns.GABA = {'EX_4abut(e)','ABUTt2r','GLUDC'};\nsecretionRxns.Biotin ={'EX_btn(e)','BTNT5r'};\nsecretionRxns.Cholate = {'EX_cholate(e)','BIACt1'};\nsecretionRxns.Chenodeoxycholate = {'EX_C02528(e)','BIACt2'};\nsecretionRxns.Deoxycholate = {'EX_dchac(e)','DCAT'};\n% secretionRxns.Tyramine = {'EX_tym(e)','TYMt2r'};\n% secretionRxns.Tryptamine = {'EX_trypta(e)', 'TRYPTAte'};\nsecretionRxns.Tyramine = {'EX_tym(e)','TYMt2r','TYRCBOX'};\nsecretionRxns.Tryptamine = {'EX_trypta(e)','TRYPTAte','LTDCL'};\nsecretionRxns.Dimethylamine = {'EX_dma(e)', 'DMAt2r'};\nsecretionRxns.TrimethylamineNoxide = {'EX_tmao(e)'};\nsecretionRxns.Trimethylamine = {'EX_tmao(e)', 'EX_tma(e)'};\nsecretionRxns.Spermine = {'EX_sprm(e)','SPRMTDe'};\nsecretionRxns.Spermidine = {'EX_spmd(e)','SPMDtex2'};\nsecretionRxns.Putrescine = {'EX_ptrc(e)','PTRCtex2'};\n% secretionRxns.pCresol = {'EX_pcresol(e)','PCRESOLt2r'};\nsecretionRxns.pCresol = {'EX_pcresol(e)','PCRESOLt2r','4HPHACDC'};\nsecretionRxns.Ammonia = {'EX_nh4(e)','NH4tb'};\nsecretionRxns.Nitrogen = {'EX_n2(e)','N2t','N2OFO','EX_n2o(e)','N2Ot'};\nsecretionRxns.Methylamine = {'EX_mma(e)','MMAt2e'};\nsecretionRxns.Methanol = {'EX_meoh(e)','MEOHt2'};\nsecretionRxns.Lthreonine = {'EX_thr_L(e)','THRt2r'};\nsecretionRxns.Linoleicacid = {'EX_lnlc(e)','LNLCt'};\nsecretionRxns.Lithocholate = {'EX_HC02191(e)','LCAT'};\nsecretionRxns.Lglutamate = {'EX_glu_L(e)','GLUt2r'};\nsecretionRxns.Lglutamine = {'EX_gln_L(e)','GLNt2r'};\nsecretionRxns.Lalanine = {'EX_ala_L(e)','ALAt2r'};\nsecretionRxns.Indole3acetate = {'EX_ind3ac(e)','IND3ACt2r'};\n% secretionRxns.Histamine = {'EX_hista(e)','HISTAt2'};\nsecretionRxns.Histamine = {'EX_hista(e)','HISTAt2','HISDC'};\nsecretionRxns.Peroxide = {'EX_h2o2(e)','H2O2t'};\nsecretionRxns.x_5Aminovalerate = {'EX_5aptn(e)','5APTNt2r'};\nsecretionRxns.x_2Oxobutyrate = {'EX_2obut(e)','2OBUTt2r'};\n% secretionRxns.x_12Ethanediol = {'EX_12ethd(e)','12ETHDt'};\nsecretionRxns.x_12Ethanediol = {'EX_12ethd(e)','12ETHDt','LCAR2'};\n% secretionRxns.Hydrogen = {'EX_h2(e)','H2td'};\nsecretionRxns.Hydrogen = {'EX_h2(e)','H2td','HYD4'};\n% secretionRxns.Propionate = {'EX_ppa(e)','PPAtr'};\n% secretionRxns.x_2Aminobutyrate = {'EX_C02356(e)','C02356t2r'};\nsecretionRxns.x_2Aminobutyrate = {'EX_C02356(e)','C02356t2r','RE2034C'};\n% secretionRxns.x_13Propanediol = {'EX_13ppd(e)','13PPDt'};\nsecretionRxns.x_13Propanediol = {'EX_13ppd(e)','13PPDt','13PPDH','GLYCDH'};\n% secretionRxns.x_12propanediol = {'EX_12ppd_S(e)','12PPDt'};\nsecretionRxns.x_12propanediol = {'EX_12ppd_S(e)','12PPDt','LCARS'};\n% secretionRxns.Acetone = {'EX_acetone(e)','ACETONEt2'};\nsecretionRxns.Acetone = {'EX_acetone(e)','ACETONEt2','ADCi'};\n% secretionRxns.Butylamine = {'EX_butam(e)','BUTAMt2r','EX_norval_L(e)','NORVALt2r','EX_M03134(e)','M03134t2r'};\nsecretionRxns.Butylamine = {'EX_butam(e)','BUTAMt2r','EX_norval_L(e)','NORVALt2r','EX_M03134(e)','M03134t2r','AKVALS','NORVALS','NORVALDC'};\n% secretionRxns.Cadaverine = {'EX_15dap(e)','15DAPt'};\nsecretionRxns.Cadaverine = {'EX_15dap(e)','15DAPt','LYSDC'};\nsecretionRxns.Formaldehyde = {'EX_fald(e)','r1421'};\n% secretionRxns.Urea = {'EX_urea(e)','UREAt'};\nsecretionRxns.Urea = {'EX_urea(e)','UREAt','ARGN'};\n% secretionRxns.Propanol = {'EX_ppoh(e)','PPOHt2r','PPALt2r','EX_ppal(e)'};\nsecretionRxns.Propanol = {'EX_ppoh(e)','PPOHt2r','PPALt2r','EX_ppal(e)','ALCD3ir'};\n% secretionRxns.Propanal = {'EX_ppal(e)','PPALt2r','EX_12ppd_S(e)','12PPDt'};\nsecretionRxns.Propanal = {'EX_ppal(e)','PPALt2r','EX_12ppd_S(e)','12PPDt','12PPDSDH'};\n% secretionRxns.Phenylethylamine = {'EX_peamn(e)','PEAMNt2r'};\nsecretionRxns.Phenylethylamine = {'EX_peamn(e)','PEAMNt2r','PHYCBOXL'};\n% secretionRxns.Isopropanol = {'EX_2ppoh(e)','2PPOHt2r','EX_acetone(e)','ACETONEt2'};\nsecretionRxns.Isopropanol = {'EX_2ppoh(e)','2PPOHt2r','EX_acetone(e)','ACETONEt2','ALCD20y'};\nsecretionRxns.Lmalate = {'EX_mal_L(e)','MALt2r'};\nsecretionRxns.Sulfide = {'EX_h2s(e)','H2St'};\n\n%Add any additional secretion rxns if specified\nif ~isempty(additionalSecretionRxns)\n addFields=fields(additionalSecretionRxns);\n for f=1:length(addFields)\n secretionRxns.(addFields{f})=additionalSecretionRxns.(addFields{f});\n end\nend\n\n% read in the secretion product data\nsecretionTable = readInputTableForPipeline([inputDataFolder filesep 'secretionProductTable.txt']);\nsecretionTable(:,find(strncmp(secretionTable(1,:),'Ref',3)))=[];\n\nsecretionGapfillAddConditional = {\n % secretion products, condition, add reaction(s)\n 'Sulfide', '~any(ismember(model.rxns, {''CYSDS'',''CYSTS_H2S''}))', {'CYSDS'}\n 'Trimethylamine', '~any(ismember(model.rxns, {''TMAOR1e'',''TMAOR2e''}))', {'TMAOt2r','TMAt2r','TMAOR1','TMAOR2'}\n };\n\n% secretion product list from input table\n% modify names to agree with structure\n% can only contain alphabetic, numeric, or underscore characters and cannot\n% start with a number or underscore.\n% Any non-alphabetic, numeric, or underscore characters removed. Any names\n% starting with a number changed to x_number.\nproducts = secretionTable(1, 2:end);\nnumStart = find(~cellfun(@isempty, regexp(products, '^\\d+')));% find names that start with numbers\nproducts(numStart) = strcat('x_', products(numStart));\nproducts = regexprep(products, '\\W', '');% remove special characters\n\n% microbe index in file\norgRow = find(strcmp(microbeID, secretionTable(:, 1)));\n\n% find the secretion products for this microbe\nif contains(version,'(R202') % for Matlab R2020a and newer\nspCols = find(cell2mat(secretionTable(orgRow, 2:end)) == 1);\nelse\n spCols = find(str2double(secretionTable(orgRow, 2:end)) == 1);\nend\n\n% added rxns list\nsecretionRxnsAdded = {};\n\nif ~isempty(spCols)\n secProds = products(spCols);\n for i = 1:length(secProds)\n % add rxns that are not already in model\n rxns2Add = setdiff(secretionRxns.(secProds{i}), model.rxns)\n if ~isempty(rxns2Add)\n for j = 1:length(rxns2Add)\n RxnForm = database.reactions(find(ismember(database.reactions(:, 1), rxns2Add{j})), 3);\n model = addReaction(model, rxns2Add{j}, 'reactionFormula', RxnForm{1, 1}, 'geneRule','secretionProductGapfill');\n end\n secretionRxnsAdded = union(secretionRxnsAdded, rxns2Add);\n end\n % add conditional reactions\n if any(ismember(secretionGapfillAddConditional(:, 1), secProds{i}))\n conditions = find(ismember(secretionGapfillAddConditional(:, 1), secProds{i}));\n for k = 1:length(conditions)\n if eval(secretionGapfillAddConditional{conditions(k), 2})\n addRxns = secretionGapfillAddConditional{conditions(k), 3};\n for j = 1:length(addRxns)\n if ~any(ismember(model.rxns, addRxns{j}))\n formula = database.reactions{ismember(database.reactions(:, 1), addRxns{j}), 3};\n model = addReaction(model, addRxns{j}, 'reactionFormula', formula, 'geneRule', 'secretionProductGapfill');\n secretionRxnsAdded = union(secretionRxnsAdded, addRxns{j});\n end\n end\n end\n end\n end\n end\nend\n\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/reconstruction/demeter/src/refinement/secretionProductGapfill.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733751090819795, "lm_q2_score": 0.01854656569879111, "lm_q1q2_score": 0.0040308644248706225}} {"text": "function ROIInterpretedType = initROIInterpretedType\n% ROIInterpretedType\n% Written DK Sept-2009 \n% \n% \n% This function lists in alphabetical order ROIInterpretedType as per DICOM PS 3.3 - 2008\n% Page 519. \n%\n% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.\n% \n% This file is part of The Computational Environment for Radiotherapy Research (CERR).\n% \n% CERR development has been led by: Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.\n% \n% CERR has been financially supported by the US National Institutes of Health under multiple grants.\n% \n% CERR is distributed under the terms of the Lesser GNU Public License. \n% \n% This version of CERR is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n% See the GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with CERR. If not, see .\n\nROIInterpretedType = struct(...\n 'AVOIDANCE' , 'region in which dose is to be minimized',... \n 'BOLUS' , 'patient bolus to be used for external beam therapy',... \n 'BRACHY_ACCESSORY' , 'brachytherapy accessory device',... \n 'BRACHY_CHANNEL' , 'brachytherapy channel',... \n 'BRACHY_CHNL_SHLD' , 'brachytherapy channel shield',... \n 'BRACHY_SRC_APP' , 'brachytherapy source applicator',... \n 'CAVITY' , 'patient anatomical cavity',... \n 'CONTRAST_AGENT' , 'volume into which a contrast agent has been injected',... \n 'CONTROL' , 'ROI to be used in control of dose optimization and calculation',...\n 'CTV' , 'Clinical Target Volume (as defined in ICRU50)',... \n 'DOSE_REGION' , 'ROI to be used as a dose reference',... \n 'EXTERNAL' , 'external patient contour',... \n 'FIXATION' , 'external patient fixation or immobilisation device',... \n 'GTV' , 'Gross Tumor Volume (as defined in ICRU50)',... \n 'IRRAD_VOLUME' , 'Irradiated Volume (as defined in ICRU50)',... \n 'ISOCENTER' , 'treatment isocenter to be used for external beam therapy',... \n 'MARKER' , 'patient marker or marker on a localizer',... \n 'ORGAN' , 'patient organ',... \n 'PTV' , 'Planning Target Volume (as defined in ICRU50)',... \n 'REGISTRATION' , 'registration ROI',... \n 'SUPPORT' , 'external patient support device',... \n 'TREATED_VOLUME' , 'Treated Volume (as defined in ICRU50)'... \n);\n\n\n", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/CERR_core/Importing/initROIInterpretedType.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12592277467581975, "lm_q2_score": 0.022977368321044828, "lm_q1q2_score": 0.0028933739737342467}} {"text": "function varargout = Robust_sys(varargin)\n% ROBUST_SYS M-file for Robust_sys.fig\n% ROBUST_SYS, by itself, creates a new ROBUST_SYS or raises the existing\n% singleton*.\n%\n% H = ROBUST_SYS returns the handle to a new ROBUST_SYS or the handle to\n% the existing singleton*.\n%\n% ROBUST_SYS('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in ROBUST_SYS.M with the given input arguments.\n%\n% ROBUST_SYS('Property','Value',...) creates a new ROBUST_SYS or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before Robust_sys_OpeningFunction gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to Robust_sys_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Copyright 2002-2003 The MathWorks, Inc.\n\n% Edit the above text to modify the response to help Robust_sys\n\n% Last Modified by GUIDE v2.5 07-Dec-2007 09:40:52\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @Robust_sys_OpeningFcn, ...\n 'gui_OutputFcn', @Robust_sys_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before Robust_sys is made visible.\nfunction Robust_sys_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to Robust_sys (see VARARGIN)\n\n% Choose default command line output for Robust_sys\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes Robust_sys wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = Robust_sys_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit4_Callback(hObject, eventdata, handles)\n% hObject handle to edit4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit4 as text\n% str2double(get(hObject,'String')) returns contents of edit4 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit4_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit5_Callback(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit5 as text\n% str2double(get(hObject,'String')) returns contents of edit5 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit6_Callback(hObject, eventdata, handles)\n% hObject handle to edit6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit6 as text\n% str2double(get(hObject,'String')) returns contents of edit6 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit6_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit7_Callback(hObject, eventdata, handles)\n% hObject handle to edit7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit7 as text\n% str2double(get(hObject,'String')) returns contents of edit7 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit7_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit7 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit8_Callback(hObject, eventdata, handles)\n% hObject handle to edit8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit8 as text\n% str2double(get(hObject,'String')) returns contents of edit8 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit8_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit9_Callback(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit9 as text\n% str2double(get(hObject,'String')) returns contents of edit9 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit9_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit10_Callback(hObject, eventdata, handles)\n% hObject handle to edit10 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit10 as text\n% str2double(get(hObject,'String')) returns contents of edit10 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit10_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit10 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit11_Callback(hObject, eventdata, handles)\n% hObject handle to edit11 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit11 as text\n% str2double(get(hObject,'String')) returns contents of edit11 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit11_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit11 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n\nfunction edit12_Callback(hObject, eventdata, handles)\n% hObject handle to edit12 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit12 as text\n% str2double(get(hObject,'String')) returns contents of edit12 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit12_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit12 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc\n set(hObject,'BackgroundColor','white');\nelse\n set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));\nend\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nx1 = str2double(get(handles.edit1,'String'));\nx2= str2double(get(handles.edit2,'String'));\nx3= str2double(get(handles.edit3,'String'));\nx4= str2double(get(handles.edit4,'String'));\n\nx5 = str2double(get(handles.edit5,'String'));\nx6 = str2double(get(handles.edit6,'String'));\nx7 = str2double(get(handles.edit7,'String'));\nx8 = str2double(get(handles.edit8,'String'));\n\nx9 = str2double(get(handles.edit9,'String'));\nx10 = str2double(get(handles.edit10,'String'));\nx11 = str2double(get(handles.edit11,'String'));\nx12 = str2double(get(handles.edit12,'String'));\n\nA=[x1,x2;x3,x4];\nB=[x5,x6;x7,x8];\nC=[x9,x10;x11,x12];\nD=0;\n[h2n] = normh2(A,B,C,D); \n\nset(handles.text3,'String',num2str(h2n))\n% --- Executes on button press in pushbutton2.\nfunction pushbutton2_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nx1 = str2double(get(handles.edit1,'String'));\nx2= str2double(get(handles.edit2,'String'));\nx3= str2double(get(handles.edit3,'String'));\nx4= str2double(get(handles.edit4,'String'));\n\nx5 = str2double(get(handles.edit5,'String'));\nx6 = str2double(get(handles.edit6,'String'));\nx7 = str2double(get(handles.edit7,'String'));\nx8 = str2double(get(handles.edit8,'String'));\n\nx9 = str2double(get(handles.edit9,'String'));\nx10 = str2double(get(handles.edit10,'String'));\nx11 = str2double(get(handles.edit11,'String'));\nx12 = str2double(get(handles.edit12,'String'));\n\nA=[x1,x2;x3,x4]\nB=[x5,x6;x7,x8]\nC=[x9,x10;x11,x12]\nD=0;\n[hinfn] = normhinf(A,B,C,D); \nset(handles.text4,'String',num2str(hinfn))\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/18882-gui-for-optimal-and-robust-control/Gui_Robust_Optimal/Robust_sys.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14608723217744243, "lm_q2_score": 0.01971912875544488, "lm_q1q2_score": 0.0028807129408335574}} {"text": "function varargout = ma_AerobrakingCdCalcGUI(varargin)\n% MA_AEROBRAKINGCDCALCGUI MATLAB code for ma_AerobrakingCdCalcGUI.fig\n% MA_AEROBRAKINGCDCALCGUI, by itself, creates a new MA_AEROBRAKINGCDCALCGUI or raises the existing\n% singleton*.\n%\n% H = MA_AEROBRAKINGCDCALCGUI returns the handle to a new MA_AEROBRAKINGCDCALCGUI or the handle to\n% the existing singleton*.\n%\n% MA_AEROBRAKINGCDCALCGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in MA_AEROBRAKINGCDCALCGUI.M with the given input arguments.\n%\n% MA_AEROBRAKINGCDCALCGUI('Property','Value',...) creates a new MA_AEROBRAKINGCDCALCGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before ma_AerobrakingCdCalcGUI_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to ma_AerobrakingCdCalcGUI_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help ma_AerobrakingCdCalcGUI\n\n% Last Modified by GUIDE v2.5 30-Oct-2014 21:31:32\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @ma_AerobrakingCdCalcGUI_OpeningFcn, ...\n 'gui_OutputFcn', @ma_AerobrakingCdCalcGUI_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before ma_AerobrakingCdCalcGUI is made visible.\nfunction ma_AerobrakingCdCalcGUI_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to ma_AerobrakingCdCalcGUI (see VARARGIN)\n\n% Choose default command line output for ma_AerobrakingCdCalcGUI\nhandles.output = hObject;\nhandles.ma_MainGUI = varargin{1};\n\n%GUI setup\npopulateBodiesCombo(getappdata(handles.ma_MainGUI,'celBodyData'), handles.bodiesCombo);\ndragModelCombo_Callback(handles.dragModelCombo, [], handles);\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes ma_AerobrakingCdCalcGUI wait for user response (see UIRESUME)\n% uiwait(handles.ma_AerobrakingCdCalcGUI);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = ma_AerobrakingCdCalcGUI_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on selection change in bodiesCombo.\nfunction bodiesCombo_Callback(hObject, eventdata, handles)\n% hObject handle to bodiesCombo (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns bodiesCombo contents as cell array\n% contents{get(hObject,'Value')} returns selected item from bodiesCombo\n\n\n% --- Executes during object creation, after setting all properties.\nfunction bodiesCombo_CreateFcn(hObject, eventdata, handles)\n% hObject handle to bodiesCombo (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction preAeroRpText_Callback(hObject, eventdata, handles)\n% hObject handle to preAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of preAeroSmaText as text\n% str2double(get(hObject,'String')) returns contents of preAeroSmaText as a double\nnewInput = get(hObject,'String');\nnewInput = attemptStrEval(newInput);\nset(hObject,'String', newInput);\n\n% --- Executes during object creation, after setting all properties.\nfunction preAeroRpText_CreateFcn(hObject, eventdata, handles)\n% hObject handle to preAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction preAeroSmaText_Callback(hObject, eventdata, handles)\n% hObject handle to preAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of preAeroSmaText as text\n% str2double(get(hObject,'String')) returns contents of preAeroSmaText as a double\nnewInput = get(hObject,'String');\nnewInput = attemptStrEval(newInput);\nset(hObject,'String', newInput);\n\n% --- Executes during object creation, after setting all properties.\nfunction preAeroSmaText_CreateFcn(hObject, eventdata, handles)\n% hObject handle to preAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction postAeroSmaText_Callback(hObject, eventdata, handles)\n% hObject handle to postAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of postAeroSmaText as text\n% str2double(get(hObject,'String')) returns contents of postAeroSmaText as a double\nnewInput = get(hObject,'String');\nnewInput = attemptStrEval(newInput);\nset(hObject,'String', newInput);\n\n% --- Executes during object creation, after setting all properties.\nfunction postAeroSmaText_CreateFcn(hObject, eventdata, handles)\n% hObject handle to postAeroSmaText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction dragCoeffAnsText_Callback(hObject, eventdata, handles)\n% hObject handle to dragCoeffAnsText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of dragCoeffAnsText as text\n% str2double(get(hObject,'String')) returns contents of dragCoeffAnsText as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction dragCoeffAnsText_CreateFcn(hObject, eventdata, handles)\n% hObject handle to dragCoeffAnsText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in calcCdButton.\nfunction calcCdButton_Callback(hObject, eventdata, handles)\n% hObject handle to calcCdButton (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n set(handles.dragCoeffAnsText,'String',''); drawnow;\n\n errMsg = validateInputs(handles);\n\n if(isempty(errMsg))\n computeDragCoefficient(handles);\n else\n set(handles.dragCoeffAnsText,'String','');\n msgbox(errMsg,'Errors were found while computing the drag coefficient.','error');\n end\n\nfunction errMsg = validateInputs(handles)\n errMsg = {};\n\n rawDouble = str2double(get(handles.preAeroRpText,'String'));\n enteredStr = get(handles.preAeroSmaText,'String');\n numberName = 'Pre-Aerobrake Periapsis Altitude';\n lb = 0;\n ub = Inf;\n isInt = false;\n errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);\n \n rawDouble = str2double(get(handles.preAeroSmaText,'String'));\n enteredStr = get(handles.preAeroSmaText,'String');\n numberName = 'Pre-Aerobrake Semi-major Axis';\n lb = -Inf;\n ub = Inf;\n isInt = false;\n errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);\n \n rawDouble = str2double(get(handles.postAeroSmaText,'String'));\n enteredStr = get(handles.postAeroSmaText,'String');\n numberName = 'Post-Aerobrake Semi-major Axis';\n lb = -Inf;\n ub = Inf;\n isInt = false;\n errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);\n \n rawDouble = str2double(get(handles.incText,'String'));\n enteredStr = get(handles.incText,'String');\n numberName = 'Orbital Inclination';\n lb = 0;\n ub = 180;\n isInt = false;\n errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);\n\n\tcontents = cellstr(get(handles.dragModelCombo,'String'));\n\tdragModel = contents{get(handles.dragModelCombo,'Value')};\n \n if(~strcmpi(dragModel,'Stock'))\n rawDouble = str2double(get(handles.preAeroMass,'String'));\n enteredStr = get(handles.preAeroMass,'String');\n numberName = 'Pre-Aerobraking Mass';\n lb = eps;\n ub = Inf;\n isInt = false;\n errMsg = validateNumber(rawDouble, numberName, lb, ub, isInt, errMsg, enteredStr);\n end\n \n celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');\n \n contents = cellstr(get(handles.bodiesCombo,'String'));\n\tselBody = contents{get(handles.bodiesCombo,'Value')};\n bodyInfo = celBodyData.(strtrim(lower(selBody)));\n \n preSMA = str2double(get(handles.preAeroSmaText,'String'));\n postSMA = str2double(get(handles.postAeroSmaText,'String'));\n \n preEnergy = -bodyInfo.gm/(2*preSMA);\n postEnergy = -bodyInfo.gm/(2*postSMA);\n if(postEnergy >= preEnergy)\n errMsg{end+1} = 'The entered post-aerobrake SMA does not represent a loss in orbital energy w.r.t. the pre-aerobrake SMA. Your orbital energy must decrease through the aerobrake.';\n end\n \n preRpAlt = str2double(get(handles.preAeroRpText,'String'));\n if(preRpAlt >= bodyInfo.atmohgt)\n errMsg{end+1} = sprintf('Pre-Aerobrake Periapsis is located outside the atmosphere (%f km). Lower the pre-aerobrake periapsis altitude to below %f km and above 0 km.', bodyInfo.atmohgt, bodyInfo.atmohgt);\n end\n \n\nfunction computeDragCoefficient(handles)\n celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');\n\n contents = cellstr(get(handles.dragModelCombo,'String'));\n\tdragModel = contents{get(handles.dragModelCombo,'Value')};\n \n contents = cellstr(get(handles.bodiesCombo,'String'));\n\tselBody = contents{get(handles.bodiesCombo,'Value')};\n bodyInfo = celBodyData.(strtrim(lower(selBody)));\n\n preRp = str2double(get(handles.preAeroRpText,'String')) + bodyInfo.radius;\n preSMA = str2double(get(handles.preAeroSmaText,'String'));\n postSMA = str2double(get(handles.postAeroSmaText,'String'));\n inc = deg2rad(str2double(get(handles.incText,'String')));\n mass = str2double(get(handles.preAeroMass,'String'));\n\n preEcc = getEccFromRpAndSma(preSMA, preRp); %we assume that Rp remains constant\n \n raan = 0; %arbitary here\n arg = 0; %arbitary here\n tru = -computeTrueAFromRadiusEcc(bodyInfo.radius+bodyInfo.atmohgt, preSMA, preEcc)-0.001; %NOT ARBITRARY, SET JUST OUTSIDE ATMOSPHERE\n \n [rVect,vVectPre]=getStatefromKepler(preSMA, preEcc, inc, raan, arg, tru, bodyInfo.gm);\n% [~,vVectPost]=getStatefromKepler(postSMA, postEcc, inc, raan, arg, tru, bodyInfo.gm);\n %%%\n initialState = buildInitialState(rVect, vVectPre, mass, bodyInfo.id);\n aeroFun = @(dragCoeff) aerobrakeFunc(dragCoeff, initialState, dragModel, postSMA, bodyInfo.gm, celBodyData);\n \n if(strcmpi(dragModel,'Stock'))\n x0 = 10;\n else\n x0 = 10;\n end\n \n options = optimset('Display','iter');\n set(handles.dragCoeffAnsText,'Enable','off');\n [Cd, ~, exitflag, ~] = fzero(aeroFun, x0, options);\n Cd = abs(Cd);\n \n if(exitflag < 0)\n set(handles.dragCoeffAnsText,'String', '');\n set(handles.dragCoeffAnsText,'Enable','on');\n else\n set(handles.dragCoeffAnsText,'String', num2str(Cd, 10));\n set(handles.dragCoeffAnsText,'Enable','on');\n end\n\nfunction dEnergy = aerobrakeFunc(dragCoeff, initialState, dragModel, postSMADesired, gmu, celBodyData)\n dragCoeff = abs(dragCoeff);\n \n aerobrake = ma_createAerobrake('NA', dragCoeff, dragModel, 'r', '-', 1.5);\n eventLog = ma_executeAerobrake(initialState, -1, aerobrake, celBodyData);\n \n newRVect = eventLog(end,2:4);\n newVVect = eventLog(end,5:7);\n [postSMAActual, ~, ~, ~, ~, ~] = getKeplerFromState(newRVect,newVVect,gmu);\n \n desiredEnergy = getSpecOrbitEnergyFromSma(postSMADesired, gmu);\n actEnergy = getSpecOrbitEnergyFromSma(postSMAActual, gmu);\n \n dEnergy = actEnergy - desiredEnergy;\n \nfunction initialState = buildInitialState(rVect, vVect, mass, bodyId) \n rVect = reshape(rVect,1,3);\n vVect = reshape(vVect,1,3);\n\n initialState = zeros(1,13);\n initialState(1,:) = [0 rVect vVect bodyId mass 0 0 0 1];\n \n\n% --- Executes on button press in closeButton.\nfunction closeButton_Callback(hObject, eventdata, handles)\n% hObject handle to closeButton (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n close(handles.ma_AerobrakingCdCalcGUI);\n\n% --- Executes on key press with focus on ma_AerobrakingCdCalcGUI or any of its controls.\nfunction ma_AerobrakingCdCalcGUI_WindowKeyPressFcn(hObject, eventdata, handles)\n% hObject handle to ma_AerobrakingCdCalcGUI (see GCBO)\n% eventdata structure with the following fields (see FIGURE)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n switch(eventdata.Key)\n case 'return'\n calcCdButton_Callback(handles.calcCdButton, [], handles);\n case 'enter'\n calcCdButton_Callback(handles.calcCdButton, [], handles);\n case 'escape'\n close(handles.ma_AerobrakingCdCalcGUI);\n end\n\n\nfunction incText_Callback(hObject, eventdata, handles)\n% hObject handle to incText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of incText as text\n% str2double(get(hObject,'String')) returns contents of incText as a double\nnewInput = get(hObject,'String');\nnewInput = attemptStrEval(newInput);\nset(hObject,'String', newInput);\n\n% --- Executes during object creation, after setting all properties.\nfunction incText_CreateFcn(hObject, eventdata, handles)\n% hObject handle to incText (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in dragModelCombo.\nfunction dragModelCombo_Callback(hObject, eventdata, handles)\n% hObject handle to dragModelCombo (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns dragModelCombo contents as cell array\n% contents{get(hObject,'Value')} returns selected item from dragModelCombo\n contents = cellstr(get(hObject,'String'));\n dragModel = contents{get(hObject,'Value')};\n\n if(strcmpi(dragModel,'Stock'))\n% set(handles.preAeroMass,'Enable','off');\n% set(handles.cdLabel,'String','');\n set(handles.preAeroMass,'Enable','on');\n set(handles.cdLabel,'String','m^2');\n elseif(strcmpi(dragModel,'FAR'))\n set(handles.preAeroMass,'Enable','on');\n set(handles.cdLabel,'String','m^2');\n elseif(strcmpi(dragModel,'NEAR'))\n set(handles.preAeroMass,'Enable','on');\n set(handles.cdLabel,'String','m^2');\n else\n error(['Invalid drag model in aerobraking DV calculations: ', dragModel]);\n end\n\n% --- Executes during object creation, after setting all properties.\nfunction dragModelCombo_CreateFcn(hObject, eventdata, handles)\n% hObject handle to dragModelCombo (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction preAeroMass_Callback(hObject, eventdata, handles)\n% hObject handle to preAeroMass (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of preAeroMass as text\n% str2double(get(hObject,'String')) returns contents of preAeroMass as a double\nnewInput = get(hObject,'String');\nnewInput = attemptStrEval(newInput);\nset(hObject,'String', newInput);\n\n% --- Executes during object creation, after setting all properties.\nfunction preAeroMass_CreateFcn(hObject, eventdata, handles)\n% hObject handle to preAeroMass (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/kspTOT_MissionArchitect/ma_AerobrakingCdCalcGUI.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14223189500989633, "lm_q2_score": 0.018833130372297655, "lm_q1q2_score": 0.0026786718218203298}} {"text": "function Callbacks_glottal_pulse_GUI25(f,C)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nx=C{1,1};\ny=C{1,2};\na=C{1,3};\nb=C{1,4};\nu=C{1,5};\nv=C{1,6};\nm=C{1,7};\nn=C{1,8};\nlengthbutton=C{1,9};\nwidthbutton=C{1,10};\nenterType=C{1,11};\nenterString=C{1,12};\nenterLabel=C{1,13};\nnoPanels=C{1,14};\nnoGraphicPanels=C{1,15};\nnoButtons=C{1,16};\nlabelDist=C{1,17};%distance that the label is below the button\nnoTitles=C{1,18};\nbuttonTextSize=C{1,19};\nlabelTextSize=C{1,20};\ntextboxFont=C{1,21};\ntextboxString=C{1,22};\ntextboxWeight=C{1,23};\ntextboxAngle=C{1,24};\nlabelHeight=C{1,25};\nfileName=C{1,26};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%PANELS\nfor j=0:noPanels-1\nuipanel('Parent',f,...\n'Units','Normalized',...\n'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%GRAPHIC PANELS\nfor i=0:noGraphicPanels-1\nswitch (i+1)\ncase 1\ngraphicPanel1 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 2\ngraphicPanel2 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 3\ngraphicPanel3 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 4\ngraphicPanel4 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 5\ngraphicPanel5 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%TITLE BOXES\nfor k=0:noTitles-1\nswitch (k+1)\ncase 1\ntitleBox1 = uicontrol('parent',f,...\n'Units','Normalized',...\n'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...\n'Style','text',...\n'FontSize',textboxFont{k+1},...\n'String',textboxString(k+1),...\n'FontWeight',textboxWeight{k+1},...\n'FontAngle',textboxAngle{k+1});\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%BUTTONS\nfor i=0:(noButtons-1)\nenterColor='w';\nif strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1\nenterColor='default';\nend\nif (strcmp(enterLabel{1,(i+1)},'')==0 &&...\n strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label\n%creating a label for some buttons\nuicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...\n(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...\n'Style','text',...\n'String',enterLabel{i+1},...\n'FontSize', labelTextSize(i+1),...\n'HorizontalAlignment','center');\nend\nswitch (i+1)\ncase 1\nbutton1=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button1Callback);\ncase 2\nbutton2=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button2Callback);\ncase 3\nbutton3=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button3Callback);\ncase 4\nbutton4=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button4Callback);\ncase 5\nbutton5=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button5Callback);\ncase 6\nbutton6=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button6Callback);\ncase 7\nbutton7=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button7Callback);\ncase 8\nbutton8=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button8Callback);\ncase 9\nbutton9=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button9Callback);\nend\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%USER CODE FOR THE VARIABLES AND CALLBACKS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Initialize Variables\nalpha1=25;\nalpha2=10;\nperiod=100;\nnfft=1024;\nfs=10000;\nivowel=1;\nfsd=10000;\nimp_train=[];\npulse_train=[];\nzout=[];\ng=[];\nvowels='IY';\n\n% Name the GUI\n set(f,'Name','glottal_pulse_GUI');\n\n\n% CALLBACKS\n% Callback for button1 -- alpha1, editable button value for glottal pulse \n% opening cycle (in %) \n function button1Callback(h,eventdata)\n alpha1=str2num(get(button1,'string'))/100;\n if alpha1 < 0\n waitfor(msgbox('alpha1 must lie between 0 and 100'));\n elseif alpha1 > 1\n waitfor(msgbox('alpha1 must lie between 0 and 100'));\n end\n end\n\n% Callback for button2 -- alpha2, editable button value for glottal pulse\n% closing cycle (in %)\n function button2Callback(h,eventdata)\n alpha2=str2num(get(button2,'string'))/100;\n if alpha2 < 0 \n waitfor(msgbox('alpha2 must lie between 0 and 100'));\n elseif (alpha2 > 1)\n waitfor(msgbox('alpha2 must lie between 0 and 100'));\n end\n end\n\n% Callback for button3 -- period, editable button duration of pitch \n% period (in samples) at fs=10000 Hz\n function button3Callback(h,eventdata)\n period=str2num(get(button3,'string'));\n if period < 10\n waitfor(msgbox('pitch period must lie between 10 and 250 samples'));\n elseif period > 250\n waitfor(msgbox('pitch period must lie between 10 and 250 samples'));\n end\n end\n\n% Callback for button4 -- ivowel: editable button for vowel sound impulse\n% response to be convolved with glottal pulse\n function button4Callback(h,eventdata)\n ivowel=get(button4,'val');\n end\n\n% Callback for button9 -- Generate Excitation -- both Rosenberg pulse and\n% periodic extension at designated pitch period\n function button9Callback(h,eventdata)\n button3Callback(h,eventdata);\n button4Callback(h,eventdata);\n\n alpha1=str2num(get(button1,'string'))/100;\n alpha2=str2num(get(button2,'string'))/100;\n \n% form rosenberg glottal pulse, g\n n1=round(period*alpha1);\n n2=round(period*alpha2);\n g=[];\n x1=0:n1;\n g=[g 0.5*(1-cos(pi*x1/n1))];\n x2=1:n2;\n g=[g cos(pi*x2/(2*n2))];\n g=[g zeros(1,period-length(g))];\n \n% plot g as a time domain signal over a single period in graphics Panel 1\n reset(graphicPanel2);\n axes(graphicPanel2);\n \n x=0:length(g)-1;\n plot(x,g,'b','LineWidth',2);\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp);\n ylabel('Pulse Amplitude');axis tight; grid on;\n s1=sprintf('Rosenberg pulse -- period: %d,',period);\n s2=sprintf(' alpha1, alpha2: %6.3f, %6.3f ',alpha1,alpha2);\n stitle=strcat(s1,s2);\n legend('Rosenberg Pulse');\n \n% display glottal pulse parameters in titleBox1\n set(titleBox1,'String',stitle);\n set(titleBox1,'FontSize',25);\n \n% plot log magnitude spectrum of glottal pulse, g, in graphics Panel 1\n ge=[g zeros(1,nfft-length(g))];\n gs=20*log10(abs(fft(ge)));\n freq=0:fs/nfft:fs/2;\n x2=[0 fs/2];\n s2=[0 0];\n \n reset(graphicPanel1);\n axes(graphicPanel1);\n plot(freq,gs(1:nfft/2+1),'r','LineWidth',2);\n hold on;\n plot(x2,s2,'g','LineWidth',2);\n xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');\n axis tight; grid on;legend('Rosenberg Pulse Spectrum');\n \n% play out periodic pulse train of impulses spaced period samples apart, \n% and of total length of fsd=10000 samples (fsd defined in list of\n% variables at beginning of Callbacks)\n imp_train=zeros(1,fsd);\n imp_train(1:period:fsd)=1;\n\n % display impulse train for 1000 samples on Graphics Panel 5\n reset(graphicPanel5);\n axes(graphicPanel5);\n plot(0:1000,imp_train(1:1001),'r','LineWidth',2);\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp),ylabel('Value'),axis tight, grid on; legend('Periodic Impulses');\n \n% generate excitation pulses using Rosenberg pulse\n pulse_train=conv(g,imp_train);\n \n% display glottal pulse train for 1000 samples on Graphics Panel 4\n reset(graphicPanel4);\n axes(graphicPanel4);\n plot(0:1000,pulse_train(1:1001),'b','LineWidth',2);\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp),ylabel('Value'),axis tight, grid on; legend('Glottal Pulses');\n\n% load vowel info (formants and bandwidths)\n% load 'vowels_fmts_bw.mat'\n str=load('vowels_fmts_bw.mat');\n vowels=str.vowels;\n formants=str.formants;\n bandwidths=str.bandwidths;\n \n% generate vowel impulse response\n fmts=formants(ivowel,:);\n fmts=[fmts 4500];\n yout=vowel_ir(fmts,bandwidths,fsd);\n \n% convolve vowel impulse response with excitation\n zout=conv(yout,pulse_train);\n\n% display periodic vowel sequence for 1000 samples on Graphics Panel 3\n reset(graphicPanel3);\n axes(graphicPanel3);\n plot(0:1000,zout(1:1001),'k','LineWidth',2);\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp),ylabel('Value'),axis tight, grid on; \n\n xleg=['Vowel Response:',vowels(ivowel,:),' Period:',num2str(period)];\n legend(xleg);\n end\n\n% Callback for button5 -- Play Periodic Impulses\n function button5Callback(h,eventdata)\n soundsc(imp_train,fsd);\n end\n\n% Callback for button6 -- Play Glottal Pulses\n function button6Callback(h,eventdata)\n soundsc(pulse_train,fsd);\n end\n\n% Callback for button7 -- Play Vowel Excited by Glottal Pulses\n function button7Callback(h,eventdata)\n soundsc(zout,fsd);\n end\n\n% Callback for button8 -- close GUI\n function button8Callback(h,eventdata)\n close(gcf);\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43358-rosenberg-glottal-pulse/glottal_pulse/Callbacks_glottal_pulse_GUI25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608725076600915, "lm_q2_score": 0.017442483874298725, "lm_q1q2_score": 0.0025481245157267488}} {"text": "%%%\n%{\nCopyright (c) 2010, Jake Hughey\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and/or other materials provided with the distribution\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n%}\n%%%\n\nfunction [sortedStruct index] = nestedSortStruct(aStruct, fieldNamesCell, directions)\n% [sortedStruct index] = nestedSortStruct(aStruct, fieldNamesCell, directions)\n% nestedSortStruct returns a nested sort of a (one-dimensional) struct array\n% (aStruct), and can also return an index vector. The fields by which to sort are\n% specified in a cell array of strings fieldNamesCell. Fields must be single numbers or\n% logicals, or chars (usually simple strings).\n%\n% fieldNamesCell can also be a simple string of one fieldname, in which case\n% nestedSortStruct will simply call sortStruct. This will be faster than putting the\n% single fieldname in a cell array.\n%\n% directions is an optional argument to specify whether the struct array should be sorted\n% in ascending or descending order for the fields. By default, the struct array will be\n% sorted in ascending order for each field. If supplied, directions must be\n% 1) a single 1 to sort in ascending order for all fields, or\n% 2) a single -1 to sort in descending order for all fields, or\n% 3) a vector of 1's and -1's, the same length as fieldNamesCell, where the struct\n% array will be sorted in the order specified by directions(ii) for\n% fieldNamesCell(ii).\n%\n% nestedSortStruct basically converts the struct array to a cell array, then converts\n% relevants parts of the cell array to a matrix, on which sortrows is run.\n%\n% nestedSortStruct will usually be faster than nestedSortStruct2. For nestedSortStruct,\n% the speed of sorting is mostly independent of the order of the fieldnames in fieldNamesCell.\n%\n% For nestedSortStruct2, the order of the fields in fieldNamesCell affects the speed. The\n% sooner a field for which most entries in the struct array have unique values will be\n% used to sort the struct array (i.e., the earlier that field's location in\n% fieldNamesCell), the faster nestedSortStruct2 will be. If a field with mostly unique\n% entries is the first field by which the struct array will be sorted, nestedSortStruct2\n% could be faster than nestedSortStruct.\n\n%% check struct\nif ~isstruct(aStruct)\n error('first input supplied is not a struct.')\nend % if\n\nif sum(size(aStruct)>1)>1 % if more than one non-singleton dimension\n error('I don''t want to sort your multidimensional struct array.')\nend % if\n\n%% check fieldnames\nif ~iscell(fieldNamesCell)\n if isfield(aStruct, fieldNamesCell) % if fieldNamesCell is a simple string of a valid fieldname\n [sortedStruct index] = sortStruct(aStruct, fieldNamesCell);\n return\n else\n error('second input supplied is not a cell array or simple string of a fieldname.')\n end % if isfield\nend % if ~iscell\n\nif ~isfield(aStruct, fieldNamesCell)\n for ii=find(~isfield(aStruct, fieldNamesCell))\n fprintf('%s is not a fieldname in the struct.\\n', fieldNamesCell{ii})\n end % for\n error('at least one entry in fieldNamesCell is not a fieldname in the struct.')\nend % if\n\n%% check classes of fieldnames\nfieldFlag = 0;\nfor ii=1:length(fieldNamesCell)\n fieldEntry = aStruct(1).(fieldNamesCell{ii});\n if ~( ((isnumeric(fieldEntry) || islogical(fieldEntry)) && numel(fieldEntry)==1) || ischar(fieldEntry) )\n fprintf('%s is not a valid fieldname by which to sort.\\n', fieldNamesCell{ii})\n fieldFlag = 1;\n end % if\nend % for ii\n\nif fieldFlag\n error('at least one fieldname is not a valid one by which to sort.')\nend\n\n%% check directions, create if necessary (1 for ascending, -1 for descending)\nif nargin < 3 % if directions doesn't exist\n directions = ones(1, length(fieldNamesCell));\nelse % check directions if it does exist\n if ~(isnumeric(directions) && all(ismember(directions, [-1 1])))\n error('directions, if given, must be a single number or a vector with 1 (ascending) and -1 (descending).')\n end % if ~(...\n \n if numel(directions)==1\n directions = directions * ones(1, length(fieldNamesCell)); % create vector from single element\n elseif length(fieldNamesCell)~=length(directions)\n error('fieldNamesCell and directions vector are different lengths.')\n end % if numel...\nend % if exist...\n\n%% fieldNamesIdx is a vector of the indices of the fields by which to sort\n[dummy fieldNamesIdx] = ismember(fieldNamesCell, fieldnames(aStruct));\n\n%% convert the struct to a cell, squeeze makes sure both row and column arrays are sorted properly, transpose for sortrows\naCell = squeeze(struct2cell(aStruct))';\n\n%% sortrows of aCell, using indices from fieldNamesIdx and directions\n[sortedCell index] = sortrows(aCell, fieldNamesIdx .* directions);\n\nsortedStruct = aStruct(index); % apply the index to the struct array", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/hga_image_denoising-master/code/nestedSortStruct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608723589515565, "lm_q2_score": 0.01640302957108039, "lm_q1q2_score": 0.002396273250345635}} {"text": "function Callbacks_ideal_vocal_tract_GUI25(f,C)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nx=C{1,1};\ny=C{1,2};\na=C{1,3};\nb=C{1,4};\nu=C{1,5};\nv=C{1,6};\nm=C{1,7};\nn=C{1,8};\nlengthbutton=C{1,9};\nwidthbutton=C{1,10};\nenterType=C{1,11};\nenterString=C{1,12};\nenterLabel=C{1,13};\nnoPanels=C{1,14};\nnoGraphicPanels=C{1,15};\nnoButtons=C{1,16};\nlabelDist=C{1,17};%distance that the label is below the button\nnoTitles=C{1,18};\nbuttonTextSize=C{1,19};\nlabelTextSize=C{1,20};\ntextboxFont=C{1,21};\ntextboxString=C{1,22};\ntextboxWeight=C{1,23};\ntextboxAngle=C{1,24};\nlabelHeight=C{1,25};\nfileName=C{1,26};\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%PANELS\nfor j=0:noPanels-1\nuipanel('Parent',f,...\n'Units','Normalized',...\n'Position',[x(1+4*j) y(1+4*j) x(2+4*j)-x(1+4*j) y(3+4*j)-y(2+4*j)]);\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%GRAPHIC PANELS\nfor i=0:noGraphicPanels-1\nswitch (i+1)\ncase 1\ngraphicPanel1 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 2\ngraphicPanel2 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 3\ngraphicPanel3 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 4\ngraphicPanel4 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 5\ngraphicPanel5 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\ncase 6\ngraphicPanel6 = axes('parent',f,...\n'Units','Normalized',...\n'Position',[a(1+4*i) b(1+4*i) a(2+4*i)-a(1+4*i) b(3+4*i)-b(2+4*i)],...\n'GridLineStyle','--');\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%TITLE BOXES\nfor k=0:noTitles-1\nswitch (k+1)\ncase 1\ntitleBox1 = uicontrol('parent',f,...\n'Units','Normalized',...\n'Position',[u(1+4*k) v(1+4*k) u(2+4*k)-u(1+4*k) v(3+4*k)-v(2+4*k)],...\n'Style','text',...\n'FontSize',textboxFont{k+1},...\n'String',textboxString(k+1),...\n'FontWeight',textboxWeight{k+1},...\n'FontAngle',textboxAngle{k+1});\nend\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%BUTTONS\nfor i=0:(noButtons-1)\nenterColor='w';\nif strcmp(enterType{i+1},'pushbutton')==1 ||strcmp(enterType{i+1},'text')==1\nenterColor='default';\nend\nif (strcmp(enterLabel{1,(i+1)},'')==0 &&...\n strcmp(enterLabel{1,(i+1)},'...')==0) %i.e. there is a label\n%creating a label for some buttons\nuicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i)-labelDist-labelHeight(i+1) ...\n(m(2+2*i)-m(1+2*i)) labelHeight(i+1)],...\n'Style','text',...\n'String',enterLabel{i+1},...\n'FontSize', labelTextSize(i+1),...\n'HorizontalAlignment','center');\nend\nswitch (i+1)\ncase 1\nbutton1=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button1Callback);\ncase 2\nbutton2=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button2Callback);\ncase 3\nbutton3=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button3Callback);\ncase 4\nbutton4=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button4Callback);\ncase 5\nbutton5=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button5Callback);\ncase 6\nbutton6=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button6Callback);\ncase 7\nbutton7=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button7Callback);\ncase 8\nbutton8=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button8Callback);\ncase 9\nbutton9=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button9Callback);\ncase 10\nbutton10=uicontrol('Parent',f,...\n'Units','Normalized',...\n'Position',[m(1+2*i) n(1+2*i) (m(2+2*i)-m(1+2*i)) (n(2+2*i)-n(1+2*i))],...\n'Style',enterType{i+1},...\n'String',enterString{i+1},...\n'FontSize', buttonTextSize(1+i),...\n'BackgroundColor',enterColor,...\n'HorizontalAlignment','center',...\n'Callback',@button10Callback);\nend\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%USER CODE FOR THE VARIABLES AND CALLBACKS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Initialize Variables\nvowel_index=1;\nipd=100;\nLm=40;\nL=400;\nilog=1;\nftable=[270 2290 3010; 390 1990 2550; 530 1840 2480; 660 1720 2410;...\n 520 1190 2390; 730 1090 2390; 570 840 2410; 490 1350 1690;...\n 440 1020 2240; 300 870 2240; 300 870 2240; 500 1500 2500];\nbtable=[40 60 75];\nfk=[270 2290 3010];\nbk=[40 60 75];\nM=3;\nfs=10000;\nhn=[];\ng=[];\niglottal=0;\nvowels=['IY'; 'IH'; 'EH'; 'AE'; 'AH'; 'AA'; 'AO'; 'ER'; 'UH'; 'UW'; 'OO'; 'Ne'];\nfilename=vowels(1,:);\nalpha1=40;\nalpha2=20;\n\n% nfft: size of fft and ifft for conversion from time to frequency or\n% frequency to time domain\n nfft=1000;\n\n% Name GUI\n set(f,'Name','ideal_vocal_tract_GUI');\n\n% CALLBACKS\n% Callback for button1 -- vowel choice from popuplist\n function button1Callback(h,eventdata)\n vowel_index=get(button1,'val');\n fk=ftable(vowel_index,:);\n bk=btable;\n filename=vowels(vowel_index,:);\n end\n\n% Callback for button2 -- ipd: pitch period in msec\n function button2Callback(h,eventdata)\n ipd=str2num(get(button2,'string'));\n if ipd < 2\n waitfor(msgbox('pitch period must lie between 2 and 15 msec'));\n elseif ipd > 15\n waitfor(msgbox('pitch period must lie between 2 and 15 msec'));\n end\n ipd=ipd*fs/1000;\n end\n\n% Callback for button3 -- Lm: frame duration in msec, (editable)\n function button3Callback(h,eventdata)\n Lm=str2num(get(button3,'string'));\n if Lm < 0\n waitfor(msgbox('The frame duration cannot be negative'));\n end\n L=round(Lm*fs/1000);\n end\n\n% Callback for button4 -- log/linear popuplist (1=log, 2=linear); option\n% for plotting vowel and ideal frequency responses\n function button4Callback(h,eventdata)\n ilog=get(button4,'val');\n end\n\n% Callback for button10 -- iglottal: use glottal puse (1) or skip glottal\n% pulse (0)\n function button10Callback(h,eventdata)\n iglottal=get(button10,'val');\n end\n\n% Callback for button8 -- alpha1 for glottal pulse\n function button8Callback(h,eventdata)\n alpha1=str2num(get(button8,'string'))/100;\n if alpha1 < 0\n waitfor(msgbox('alpha1 must lie between 0 and 100'));\n elseif alpha1 > 1\n waitfor(msgbox('alpha1 must lie between 0 and 100'));\n end\n end\n\n% Callback for button9 -- alpha2 for glottal pulse\n function button9Callback(h,eventdata)\n alpha2=str2num(get(button9,'string'))/100;\n if alpha2 < 0\n waitfor(msgbox('alpha2 must lie between 0 and 100'));\n elseif alpha2 > 1\n waitfor(msgbox('alpha2 must lie between 0 and 100'));\n end\n end\n\n% Callback for button5 -- Run ideal vocal tract responses\n function button5Callback(h,eventdata)\n \n% eps: smallest spectral magnitude for plotting log magnitude spectra\n eps=1.e-3;\n \n% form rosenberg glottal pulse, g; rise % from alpha1; fall % from alpha2\n button8Callback(h,eventdata);\n button9Callback(h,eventdata);\n button10Callback(h,eventdata);\n button2Callback(h,eventdata);\n button3Callback(h,eventdata);\n button4Callback(h,eventdata);\n \n n1=round(ipd*alpha1);\n n2=round(ipd*alpha2);\n g=[];\n x1=0:n1;\n g=[g 0.5*(1-cos(pi*x1/n1))];\n x2=1:n2;\n g=[g cos(pi*x2/(2*n2))];\n g=[g zeros(1,ipd-length(g))];\n \n% create periodic voiced excitation\n e=zeros(1,nfft);\n e(1:ipd:nfft)=1;\n EM=zeros(1,nfft);\n EM(1:round(nfft/ipd):nfft)=1;\n \n% glottal_pulse excitation based on iglottal (1: use glottal pulse, 0 skip \n% glottal pulse\nif (iglottal == 1)\n eg=conv(e,g);\nelse\n eg=e;\nend\n ege(1:nfft)=0;\n ege(1:nfft)=eg(1:nfft);\n EGM=abs(fft(ege,nfft));\n \n% convert to second order system format\n zk=exp(-2*pi*bk/fs);\n fkn=cos(2*pi*fk/fs);\n \n% transform into frequency domain \n HR=[];\n HT=zeros(1,nfft);\n HP=(complex(ones(1,nfft),zeros(1,nfft)))';\n for k=1:M\n B=1-2*zk(k)*fkn(k)+zk(k)*zk(k);\n A=[1 -2*zk(k)*fkn(k) zk(k)*zk(k)];\n [H,W]=freqz(B,A,nfft,'whole',fs);\n HP=HP.*H;\n HL=(abs(H));\n HT=HT.*HL';\n end\n \n% inverse transform to give vocal tract impulse response\n hn=ifft(HP,nfft);\n hmax=max(max(hn),-min(hn));\n for index=1:nfft\n if (max(max(hn(index:nfft)),-min(hn(index:nfft)))) < hmax/50\n nl=index;\n break;\n end\n end\n \n% plot elements of composite response in the 6 graphics Panels\n% plot ideal impulse excitation signal in graphics Panel 5 (top left panel)\n reset(graphicPanel5);\n axes(graphicPanel5);\n \n if (iglottal == 0)\n stem(0:nfft-1,e(1:nfft),'b','LineWidth',2),axis tight;\n else\n plot(0:nfft-1,eg(1:nfft),'b','LineWidth',2),axis tight;\n end\n xpp=['Time in Samples; fs=',num2str(fs),' samples/second'];\n xlabel(xpp),ylabel('Amplitude');grid on;legend('Excitation Pulses');\n \n% plot vowel impulse response in graphics Panel 3 (middle left panel)\n reset(graphicPanel3);\n axes(graphicPanel3);\n \n plot(0:nl,hn(1:nl+1),'r','LineWidth',2);\n xlabel(xpp),ylabel('Amplitude');\n axis tight, grid on;legend('Vowel Vocal Tract Impulse Response');\n \n% plot linear or log magnitude frequency response of ideal impulse\n% excitation signal in graphics Panel 6 (top right panel); use lin/log\n% option to decide whether to plot linear or log magnitude responses\n if (ilog == 1)\n reset(graphicPanel6);\n axes(graphicPanel6);\n plot(W(1:nfft/2+1),20*log10(EGM(1:nfft/2+1)+eps),'b','LineWidth',2);\n axis tight,xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');\n legend('Excitation Pulses Log Spectrum');\n \n% plot linear or log magnitude frequency response of ideal vocal tract\n% impulse response in graphics Panel 4 (middle right panel); use lin/log\n% option to decide whether to plot linear or log magnitude response\n reset(graphicPanel4);\n axes(graphicPanel4);\n plot(W(1:nfft/2+1),20*log10(abs(HP(1:nfft/2+1))),'r','LineWidth',2);\n axis tight,grid on, xlabel('Frequency in Hz');\n ylabel('Log Magnitude (dB)');legend('Vocal Tract Log Spectrum');\n else\n reset(graphicPanel6);\n axes(graphicPanel6);\n plot(W(1:nfft/2+1),EGM(1:nfft/2+1),'b','LineWidth',2);\n axis tight,xlabel('Frequency in Hz'),ylabel('Magnitude');\n legend('Excitation Pulses Linear Spectrum');\n \n reset(graphicPanel4);\n axes(graphicPanel4);\n plot(W(1:nfft/2+1),abs(HP(1:nfft/2+1)),'r','LineWidth',2);\n xlabel('Frequency in Hz'),ylabel('Magnitude'),axis tight,grid on;\n legend('Vocal Tract Linear Spectrum');\n end\n axis tight;\n \n% take product of magnitudes, convolve time responses\n he=zeros(1,L+nfft-1);\n for index=1:ipd:L\n he(index:index+nfft-1)=he(index:index+nfft-1)+hn(1:nfft)';\n end\n EMV=EGM(1:nfft/2+1).*abs(HP(1:nfft/2+1))';\n \n% plot ideal periodic vowel impulse response in graphics Panel 1 (lower\n% left panel); note: no glottal pulse used in this simple ideal vocal tract\n% model\n reset(graphicPanel1);\n axes(graphicPanel1);\n plot(0:L-1,he(1:L),'b','LineWidth',2);\n xlabel(xpp),ylabel('Amplitude');\n axis tight,grid on;legend('Vowel Waveform');\n \n% plot linear or log magnitude frequency response of ideal synthetic vowel\n% impulse response in graphics Panel 2 (bottom right panel); use lin/log\n% option to decide whether to plot linear or log magnitude response\n if (ilog == 1)\n reset(graphicPanel2);\n axes(graphicPanel2);\n plot(W(1:nfft/2+1),20*log10(EMV(1:nfft/2+1)+eps),'r','LineWidth',2);\n xlabel('Frequency in Hz'),ylabel('Log Magnitude (dB)');\n axis tight,grid on;legend('Vowel Log Spectrum');\n else\n reset(graphicPanel2);\n axes(graphicPanel2);\n plot(W(1:nfft/2+1),EMV(1:nfft/2+1),'r','LineWidth',2);\n xlabel('Frequency in Hz'),ylabel('Magnitude');\n axis tight, grid on;legend('Vowel Linear Spectrum');\n end\n \n% set titleBox1 information for display\n stitle=sprintf('Ideal Vocal Tract -- Vowel:%s, ipd:%d, L:%d, fs:%d, eps:%6.3f',filename,ipd,L,fs,eps);\n set(titleBox1,'String',stitle);\n set(titleBox1,'FontSize',20);\n end\n\n% Callback for button7 -- Play Synthetic Vowel\n function button7Callback(h,eventdata)\n% play back synthetic speech output\n e=zeros(1,fs);\n e(1:ipd:fs)=1;\n if (iglottal == 1)\n y1=conv(e,g);\n yout=conv(y1,hn);\n else\n yout=conv(e,hn);\n end\n % uiwait(msgbox('Play out synthetic speech','speech out'));\n soundsc(yout,fs);\n end\n\n% Callback for button6 -- Close GUI\n function button6Callback(h,eventdata)\n close(gcf);\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43360-ideal-vocal-tract/ideal_vocal_tract/Callbacks_ideal_vocal_tract_GUI25.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203224546424318, "lm_q2_score": 0.01495708308044074, "lm_q1q2_score": 0.002273958926314645}} {"text": "function annModel = annotateGEM(model,annPath,annType,addMiriams,addFields,overwrite)\n% Add reaction, metabolite, and/or gene annotation to a model.\n%\n% Input:\n%\n% model Model structure.\n%\n% annPath Path to the annotation files, which suppose to be named as\n% 'reactions.tsv', 'metabolites.tsv', and 'genes.tsv'。\n%\n% annType String or cell array of strings specifying the type(s) of \n% annotation data to add: 'rxn', 'met', and/or 'gene'. To\n% add all annotation types, use 'all'.\n% For example, annType={'rxn','gene'} will add reaction and\n% gene annotation information, but not metabolite.\n% (Opt, default 'all')\n%\n% addMiriams If TRUE, annotation information will be added to the \n% metMiriams field. If the metMiriams field does not exist,\n% it will be created.\n% (Opt, default TRUE) \n%\n% addFields If TRUE, separate model fields will be added for each \n% added ID type, e.g., reaction KEGG IDs will be added to a\n% rxnKEGGID field.\n% (Opt, default TRUE)\n%\n% overwrite If TRUE, any existing metMiriam or model ID field entries\n% will be overwritten. If FALSE, they will be appended with\n% the new data.\n% (Opt, default TRUE)\n%\n%\n% Output:\n%\n% annModel Model structure with added annotation information.\n%\n%\n% Usage:\n%\n% annModel = annotateGEM(model,annPath,annType,addMiriams,addFields,overwrite);\n%\n\n\n%% Inputs and setup\n\nif nargin < 2\n [ST, I] = dbstack('-completenames');\n annPath = strcat(fileparts(ST(I).file),'/../model');\nend\n\nif nargin < 3 || isempty(annType) || isequal(annType,'all')\n annType = {'rxn','met','gene'};\nelseif ~all(ismember(annType,{'rxn','met','gene','reaction','metabolite'}))\n error('annType input(s) not recognized. Valid options are \"rxn\", \"met\", and/or \"gene\", or \"all\"');\nend\n\nif nargin < 4 || isempty(addMiriams)\n addMiriams = true;\nend\n\nif nargin < 5 || isempty(addFields)\n addFields = true;\nend\n\nif nargin < 6\n overwrite = true;\nend\n\nif (~addMiriams) && (~addFields)\n error('addMiriams and addFields are both FALSE - no annotation will be added.')\nend\n\n% map field names to those on identifiers.org (used for building Miriams)\nid2miriam = {%reactions\n 'rxnKEGGID' 'kegg.reaction'\n 'rxnBiGGID' 'bigg.reaction'\n 'rxnREACTOMEID' 'reactome'\n 'rxnRecon3DID' 'vmhreaction'\n 'rxnMetaNetXID' 'metanetx.reaction'\n 'rxnTCDBID' 'tcdb'\n 'rxnRheaID' 'rhea'\n 'rxnRheaMasterID' 'rhea'\n % metabolites\n 'metBiGGID' 'bigg.metabolite'\n 'metKEGGID' 'kegg.compound'\n 'metHMDBID' 'hmdb'\n 'metChEBIID' 'chebi'\n 'metPubChemID' 'pubchem.compound'\n 'metLipidMapsID' 'lipidmaps'\n 'metRecon3DID' 'vmhmetabolite'\n 'metMetaNetXID' 'metanetx.chemical'\n % genes\n 'genes' 'ensembl'\n 'geneENSTID' 'ensembl'\n 'geneENSPID' 'ensembl'\n 'geneUniProtID' 'uniprot'\n 'geneSymbols' 'hgnc.symbol'\n 'geneEntrezID' 'ncbigene'\n };\n\n\n%% Load and organize annotation data\n\n% load reaction annotation data\nif any(ismember({'rxn','reaction'},lower(annType)))\n tmpfile = fullfile(annPath,'reactions.tsv');\n rxnAssoc = importTsvFile(tmpfile);\n \n % strip \"RHEA:\" prefix from Rhea IDs since it should not be included in\n % the identifiers.org URL\n rxnAssoc.rxnRheaID = regexprep(rxnAssoc.rxnRheaID, 'RHEA:', '');\n rxnAssoc.rxnRheaMasterID = regexprep(rxnAssoc.rxnRheaMasterID, 'RHEA:', '');\n \n rxnAssocArray = struct2cell(rxnAssoc);\n numericFields = find(cellfun(@isnumeric, rxnAssocArray));\n for i = 1:numel(numericFields)\n % numeric fields must be converted to text for miriams\n rxnAssocArray{numericFields(i)} = arrayfun(@num2str, rxnAssocArray{numericFields(i)}, 'UniformOutput', false);\n end\n rxnAssocArray = horzcat(rxnAssocArray{:});\nelse\n rxnAssoc = [];\nend\n\n% load metabolite annotation data\nif any(ismember({'met','metabolite'},lower(annType)))\n tmpfile = fullfile(annPath,'metabolites.tsv');\n metAssoc = importTsvFile(tmpfile);\n \n % ChEBI IDs should be of the form \"CHEBI:#####\"\n metAssoc.metChEBIID = regexprep(metAssoc.metChEBIID,'(^)(\\d+)|(;\\s*)(\\d+)','$1CHEBI:$2');\n \n metAssocArray = struct2cell(metAssoc);\n numericFields = find(cellfun(@isnumeric, metAssocArray));\n for i = 1:numel(numericFields)\n % numeric fields need to be converted to text for miriams\n metAssocArray{numericFields(i)} = arrayfun(@num2str, metAssocArray{numericFields(i)}, 'UniformOutput', false);\n end\n metAssocArray = horzcat(metAssocArray{:});\nelse\n metAssoc = [];\nend\n\n% load and organize gene annotation data\nif ismember('gene',lower(annType))\n tmpfile = fullfile(annPath,'genes.tsv');\n geneAssoc = importTsvFile(tmpfile);\n \n % add geneEnsemblID field if missing\n if ~isfield(geneAssoc, 'geneEnsemblID')\n geneAssoc.geneEnsemblID = geneAssoc.genes;\n end\n \n geneAssocArray = struct2cell(geneAssoc);\n geneAssocArray = horzcat(geneAssocArray{:});\nelse\n geneAssoc = [];\nend\n\n\n%% Add annotation data to model MIRIAM fields\n\nif ( addMiriams )\n \n % Reactions\n if ~isempty(rxnAssoc)\n % map model rxns to those in the association structures\n [hasRxn,rxnInd] = ismember(model.rxns,rxnAssoc.rxns);\n \n % add rxnMiriams field if it does not exist or if overwrite is TRUE\n if ~isfield(model,'rxnMiriams') || overwrite\n model.rxnMiriams = repmat({''},size(model.rxns));\n end\n \n % map rxn ID fields to the proper identifiers.org terms\n [hasRxnField,rxnFieldInd] = ismember(fieldnames(rxnAssoc),id2miriam(:,1));\n miriamNames = id2miriam(rxnFieldInd(hasRxnField),2);\n miriamValues = rxnAssocArray(:,hasRxnField);\n \n \n % assign SBO terms to model reactions\n rxnSBO = repmat({'SBO:0000176'},size(model.rxns)); % default is \"biochemical reaction\"\n \n biomass_rxn = contains(lower(model.rxns),'biomass');\n biomass_met = ismember(lower(model.metNames),'biomass') & ismember(model.comps(model.metComps),'c');\n biomass_rxn = biomass_rxn | (model.S(biomass_met,:) > 0)';\n rxnSBO(biomass_rxn) = {'SBO:0000629'}; % \"biomass production\"\n \n transport_rxn = getTransportRxns(model);\n rxnSBO(transport_rxn) = {'SBO:0000185'}; % \"translocation reaction\"\n \n [~,exchange_rxn] = getExchangeRxns(model);\n rxnSBO(exchange_rxn) = {'SBO:0000627'}; % \"exchange reaction\"\n \n \n % add new data to the rxnMiriams field\n for i = 1:numel(model.rxns)\n if hasRxn(i)\n % add annotation\n model.rxnMiriams{i} = appendMiriamData(model.rxnMiriams{i}, miriamNames, miriamValues(rxnInd(i),:)');\n end\n % add SBO terms\n model.rxnMiriams{i} = appendMiriamData(model.rxnMiriams{i}, {'sbo'}, rxnSBO(i));\n end\n end\n \n % Metabolites\n if ~isempty(metAssoc)\n % map model mets to those in the association structures\n [hasMet,metInd] = ismember(model.mets,metAssoc.mets);\n \n % add metMiriams field if it does not exist or if overwrite is TRUE\n if ~isfield(model,'metMiriams') || overwrite\n model.metMiriams = repmat({''},size(model.mets));\n end\n \n % map met ID fields to the proper identifiers.org terms\n [hasMetField,metFieldInd] = ismember(fieldnames(metAssoc),id2miriam(:,1));\n miriamNames = id2miriam(metFieldInd(hasMetField),2);\n miriamValues = metAssocArray(:,hasMetField);\n \n % add new data to the metMiriams field\n for i = 1:numel(model.mets)\n if hasMet(i)\n % add annotation\n model.metMiriams{i} = appendMiriamData(model.metMiriams{i}, miriamNames, miriamValues(metInd(i),:)');\n end\n % add SBO term (SBO:0000247, \"simple chemical\" for all mets)\n model.metMiriams{i} = appendMiriamData(model.metMiriams{i}, {'sbo'}, {'SBO:0000247'});\n end\n end\n \n % Genes\n if ~isempty(geneAssoc)\n % Note: because geneAssoc was built using geneIDs directly from the\n % model, we do not need to map model.genes to the geneAssoc\n % structure - the indexing should be identical.\n \n % map model genes to those in the association structures\n [hasGene,geneInd] = ismember(model.genes,geneAssoc.genes);\n \n % add geneMiriams field if it does not exist or if overwrite is TRUE\n if ~isfield(model,'geneMiriams') || overwrite\n model.geneMiriams = repmat({''},size(model.genes));\n end\n \n % map gene ID fields to the proper identifiers.org terms\n [hasGeneField,geneFieldInd] = ismember(fieldnames(geneAssoc),id2miriam(:,1));\n miriamNames = id2miriam(geneFieldInd(hasGeneField),2);\n miriamValues = geneAssocArray(:,hasGeneField);\n \n % add new data to the geneMiriams field\n for i = 1:numel(model.genes)\n if hasGene(i)\n % add annotation\n model.geneMiriams{i} = appendMiriamData(model.geneMiriams{i}, miriamNames, miriamValues(geneInd(i),:)');\n end\n % add SBO term (SBO:0000243, \"gene\" for all genes)\n model.geneMiriams{i} = appendMiriamData(model.geneMiriams{i}, {'sbo'}, {'SBO:0000243'});\n end\n end\n \nend\n\n\n%% Add annotation data to individual model fields\n\nif ( addFields )\n \n % merge association structures\n allAssoc = mergeStructures({rxnAssoc,metAssoc,geneAssoc});\n \n % some fields should not be added to the model\n remFields = {'rxns','mets','metsNoComp','genes'};\n allAssoc = rmfield(allAssoc, intersect(fieldnames(allAssoc),remFields));\n \n % get fields and their types\n f = fieldnames(allAssoc);\n \n if ~isempty(rxnAssoc)\n fieldType = repmat({'rxn'}, numel(f), 1);\n end\n \n if ~isempty(metAssoc)\n fieldType(ismember(f, fieldnames(metAssoc))) = {'met'};\n end\n \n if ~isempty(geneAssoc)\n fieldType(ismember(f, fieldnames(geneAssoc))) = {'gene'};\n end\n \n % add individual ID fields to the model\n for i = 1:numel(f)\n \n switch fieldType{i}\n case 'rxn'\n [hasRxn,rxnInd] = ismember(model.rxns,rxnAssoc.rxns);\n if isnumeric(allAssoc.(f{i}))\n ids = NaN(size(model.rxns));\n else\n ids = repmat({''},size(model.rxns));\n end\n ids(hasRxn) = allAssoc.(f{i})(rxnInd(hasRxn));\n case 'met'\n [hasMet,metInd] = ismember(model.mets,metAssoc.mets);\n if isnumeric(allAssoc.(f{i}))\n ids = NaN(size(model.mets));\n else\n ids = repmat({''},size(model.mets));\n end\n ids(hasMet) = allAssoc.(f{i})(metInd(hasMet));\n case 'gene'\n [hasGene,geneInd] = ismember(model.genes,geneAssoc.genes);\n if isnumeric(allAssoc.(f{i}))\n ids = NaN(size(model.genes));\n else\n ids = repmat({''},size(model.genes));\n end\n ids(hasGene) = allAssoc.(f{i})(geneInd(hasGene));\n otherwise\n continue\n end\n \n if ~isfield(model,f{i}) || overwrite\n model.(f{i}) = ids;\n else\n % merge new IDs with existing IDs\n merged_ids = join([model.(f{i}), ids],';');\n merged_ids = arrayfun(@(id) strjoin(unique(split(id,';')),';'), merged_ids, 'UniformOutput', false);\n model.(f{i}) = regexprep(merged_ids,'^;\\s*',''); % remove any preceding semicolons\n end\n \n end\n \nend\n\n%%\n\n% assign output\nannModel = model;\n\nend\n\n\n\n%% Additional functions\n\nfunction miriam_new = appendMiriamData(miriam,names,values)\n% Append new entries to an existing miriam structure.\n\n% ignore empty entries\nremove = cellfun(@isempty,values);\nnames(remove) = [];\nvalues(remove) = [];\nif isempty(names)\n miriam_new = miriam;\n return\nend\n\n% convert existing miriam entry to cell array\nif ~isempty(miriam)\n miriam = [miriam.name(:), miriam.value(:)];\nend\n\n% append miriam entry with new data\nfor i = 1:numel(names)\n if contains(values{i},';')\n % handle multiple values separated by semicolon (;)\n val = strtrim(split(values{i},';'));\n name = repmat(names(i),numel(val),1);\n miriam = [miriam; [name, val]];\n else\n miriam = [miriam; [names(i), values(i)]];\n end\nend\n\n% remove any repeated entries\n[~,miriam_num] = ismember(miriam,miriam);\n[~,uniq_ind] = unique(miriam_num,'rows');\nmiriam = miriam(uniq_ind,:);\n\n% convert back to structure\nmiriam_new.name = miriam(:,1);\nmiriam_new.value = miriam(:,2);\n\nend\n\n\nfunction mergedStruct = mergeStructures(structs)\n% Merge multiple structures into a single structure.\n\nmergedStruct = {};\nfor i = 1:numel(structs)\n \n s = structs{i};\n \n if isempty(s)\n continue\n end\n \n f = fieldnames(s);\n for j = 1:numel(f)\n mergedStruct.(f{j}) = s.(f{j});\n end\n \nend\n\nend\n\n\n\n", "meta": {"author": "SysBioChalmers", "repo": "Human-GEM", "sha": "0b1bd42adaa2e1d7ac52ee83b989fad8a695759d", "save_path": "github-repos/MATLAB/SysBioChalmers-Human-GEM", "path": "github-repos/MATLAB/SysBioChalmers-Human-GEM/Human-GEM-0b1bd42adaa2e1d7ac52ee83b989fad8a695759d/code/annotateGEM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08632347423570946, "lm_q2_score": 0.0216153307930765, "lm_q1q2_score": 0.0018659104508124765}} {"text": "function varargout = FAULT(varargin)\n% FAULT M-file for FAULT.fig\n% FAULT, by itself, creates a new FAULT or raises the existing\n% singleton*.\n%\n% H = FAULT returns the handle to a new FAULT or the handle to\n% the existing singleton*.\n%\n% FAULT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in FAULT.M with the given input arguments.\n%\n% FAULT('Property','Value',...) creates a new FAULT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before FAULT_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to FAULT_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help FAULT\n\n% Last Modified by GUIDE v2.5 28-Nov-2012 12:06:59\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @FAULT_OpeningFcn, ...\n 'gui_OutputFcn', @FAULT_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before FAULT is made visible.\nfunction FAULT_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to FAULT (see VARARGIN)\n\n% Choose default command line output for FAULT\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes FAULT wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = FAULT_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n\nfunction edit1_Callback(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit1 as text\n% str2double(get(hObject,'String')) returns contents of edit1 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit2_Callback(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit2 as text\n% str2double(get(hObject,'String')) returns contents of edit2 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit2_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit2 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit3_Callback(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit3 as text\n% str2double(get(hObject,'String')) returns contents of edit3 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit3_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit3 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit4_Callback(hObject, eventdata, handles)\n% hObject handle to edit4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit4 as text\n% str2double(get(hObject,'String')) returns contents of edit4 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit4_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit4 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit5_Callback(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit5 as text\n% str2double(get(hObject,'String')) returns contents of edit5 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit5_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit5 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit6_Callback(hObject, eventdata, handles)\n% hObject handle to edit6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit6 as text\n% str2double(get(hObject,'String')) returns contents of edit6 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit6_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit6 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit8_Callback(hObject, eventdata, handles)\n% hObject handle to edit8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit8 as text\n% str2double(get(hObject,'String')) returns contents of edit8 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit8_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit8 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit9_Callback(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit9 as text\n% str2double(get(hObject,'String')) returns contents of edit9 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit9_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\na=(get(handles.popupmenu1,'value'));\nreal=str2num(get(handles.edit1,'string'));\nimg=str2num(get(handles.edit2,'string'));\nZ0= real+img*i;\nreal1=str2num(get(handles.edit3,'string'));\nimg1=str2num(get(handles.edit4,'string'));\nZ1=real1+img1*i;\nreal2=str2num(get(handles.edit5,'string'));\nimg2=str2num(get(handles.edit6,'string'));\nZ2=real2+img2*i;\nline_voltage=str2num(get(handles.edit9,'string'));\nphase_voltage=line_voltage/(sqrt(3));\nkva=str2num(get(handles.edit8,'string'));\n% for popup menu commond\na=(get(handles.popupmenu1,'value'));switch a\n case 1\n %LINE TO GROUND FAULT\nIo=(phase_voltage)/(Z0+Z1+Z2);\nfault_current=(3*(phase_voltage)/(Z0+Z1+Z2));\nset(handles.edit10,'string',imag(fault_current)); \n case 2\n %LINE TO LINE FAULT\nfault_current2=(-i*sqrt(3)*phase_voltage)/(Z1+Z1); \nset(handles.edit10,'string',(fault_current2));\nend\n\n\n\n\nfunction edit10_Callback(hObject, eventdata, handles)\n% hObject handle to edit10 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit10 as text\n% str2double(get(hObject,'String')) returns contents of edit10 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit10_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit10 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit11_Callback(hObject, eventdata, handles)\n% hObject handle to edit11 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit11 as text\n% str2double(get(hObject,'String')) returns contents of edit11 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit11_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit11 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in popupmenu1.\nfunction popupmenu1_Callback(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array\n% contents{get(hObject,'Value')} returns selected item from popupmenu1\n\n\n% --- Executes during object creation, after setting all properties.\nfunction popupmenu1_CreateFcn(hObject, eventdata, handles)\n% hObject handle to popupmenu1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n", "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/39327-power-system-fault-analysis/FAULT_Calculation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.08882029240011771, "lm_q2_score": 0.018833130750904273, "lm_q1q2_score": 0.0016727641801049659}}