plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
cocoanlab/humanfmri_preproc_bids-master
nii_tool.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/nii_tool.m
48,496
utf_8
b25318c88e1f9bee05462b06ac0f8cca
function varargout = nii_tool(cmd, varargin) % Basic function to create, load and save NIfTI file. % % rst = nii_tool('cmd', para); % % To list all command, type % nii_tool ? % % To get help information for each command, include '?' in cmd, for example: % nii_tool init? % nii_tool('init?') % % Here is a list of all command: % % nii_tool('default', 'version', 1, 'rgb_dim', 1); % nii = nii_tool('init', img); % nii = nii_tool('update', nii); % nii_tool('save', nii, filename, force_3D); % hdr = nii_tool('hdr', filename); % img = nii_tool('img', filename_or_hdr); % ext = nii_tool('ext', filename_or_hdr); % nii = nii_tool('load', filename_or_hdr); % nii = nii_tool('cat3D', filenames); % nii_tool('RGBStyle', 'afni'); % % Detail for each command is described below. % % oldVal = nii_tool('default', 'version', 1, 'rgb_dim', 1); % oldVal = nii_tool('default', struct('version', 1, 'rgb_dim', 1)); % % - Set/query default NIfTI version and/or rgb_dim. To check the setting, run % nii_tool('default') without other input. The input for 'default' command can % be either a struct with fields of 'version' and/or 'rgb_dim', or % parameter/value pairs. See nii_tool('RGBstyle') for meaning of rgb_dim. % % Note that the setting will be saved for future use. If one wants to change the % settting temporarily, it is better to return the oldVal, and to restore it % after done: % % oldVal = nii_tool('default', 'version', 2); % set version 2 as default % % 'init' and 'save' NIfTI using above version % nii_tool('default', oldVal); % restore default setting % % The default version setting affects 'init' command only. If you 'load' a NIfTI % file, modify it, and then 'save' it, the version will be the same as the % original file, unless it is changed explicitly (see help for 'save' command). % All 'load' command ('load', 'hdr', 'ext', 'img') will read any version % correctly, regardless of version setting. % % % nii = nii_tool('init', img, RGB_dim); % % - Initialize nii struct based on img, normally 3D or 4D array. Most fields in % the returned nii.hdr contain default values, and need to be updated based on % dicom or other information. Important ones include pixdim, s/qform_code and % related parameters. % % The NIfTI datatype will depend on data type of img. Most Matlab data types are % supported, including 8/16/32/64 bit signed and unsigned integers, single and % double floating numbers. Single/double complex and logical array are also % supported. % % The optional third input, RGB_dim, is needed only if img contains RGB/RGBA % data. It specifies which dimension in img encodes RGB or RGBA. In other words, % if a non-empty RGB_dim is provided, img will be interpreted as RGB/RGBA data. % % Another way to signify RGB/RGBA data is to permute color dim to 8th-dim of img % (RGB_dim of 8 can be omitted then). Since NIfTI img can have up to 7 dim, % nii_tool chooses to store RGB/RGBA in 8th dim. Although this looks lengthy % (4th to 7th dim are often all ones), nii_tool can deal with up to 7 dim % without causing any confusion. This is why the returned nii.img always stores % RGB in 8th dim. % % % nii = nii_tool('update', nii); % % - Update nii.hdr according to nii.img. This is useful if one changes nii.img % type or dimension. The 'save' command calls this internally, so it is not % necessary to call this before 'save'. A useful case to call 'update' is that % one likes to use nii struct without saving it to a file, and 'update' will % make nii.hdr.dim and others correct. % % % hdr = nii_tool('hdr', filename); % % - Return hdr struct of the provided NIfTI file. This is useful to check NIfTI % hdr, and it is much faster than 'load', especially for .gz file. % % % img = nii_tool('img', filename_or_hdr); % % - Return image data in a NIfTI file. The second input can be NIfTI file name, % or hdr struct returned by nii_tool('hdr', filename). % % % ext = nii_tool('ext', filename_or_hdr); % % - Return NIfTI extension in a NIfTI file. The second input can be NIfTI file % name, or hdr struct returned by nii_tool('hdr', filename). The returned ext % will have field 'edata_decoded' if 'ecode' is of known type, such as dicom % (2), text (4 or 6) or Matlab (40). % % Here is an example to add data in myFile.mat as extension to nii struct, which % can be from 'init' or 'load': % % fid = fopen('myFile.mat'); % open the MAT file % myEdata = fread(fid, inf, '*uint8'); % load all bytes as byte column % fclose(fid); % len = int32(numel(myEdata)); % number of bytes in int32 % myEdata = [typecast(len, 'uint8')'; myEdata]; % include len in myEdata % nii.ext.ecode = 40; % 40 for Matlab extension % nii.ext.edata = myEdata; % myEdata must be uint8 array % % nii_tool will take care of rest when you 'save' nii to a file. % % In case a NIfTI ext causes problem (for example, some FSL builds have problem % in reading NIfTI img with ecode>30), one can remove the ext easily: % % nii = nii_tool('load', 'file_with_ext.nii'); % load the file with ext % nii.ext = []; % or nii = rmfield(nii, 'ext'); % remove ext % nii_tool('save', nii, 'file_without_ext.nii'); % save it % % % nii = nii_tool('load', filename_or_hdr); % % - Load NIfTI file into nii struct. The returned struct includes NIfTI 'hdr' % and 'img', as well as 'ext' if the file contains NIfTI extension. % % nii_tool returns nii.img with the same data type as stored in the file, while % numeric values in hdr are in double precision for convenience. % % % nii_tool('save', nii, filename, force_3D); % % - Save struct nii into filename. The format of the file is determined by the % file extension, such as .img, .nii, .img.gz, .nii.gz etc. If filename is not % provided, nii.hdr.file_name must contain a file name. Note that 'save' command % always overwrites file in case of name conflict. % % If filename has no extension, '.nii' will be used as default. % % If the 4th input, force_3D, is true (default false), the output file will be % 3D only, which means multiple volume data will be split into multiple files. % This is the format SPM likes. You can use this command to convert 4D into 3D % by 'load' a 4D file, then 'save' it as 3D files. The 3D file names will have % 5-digit like '_00001' appended to indicate volume index. % % The NIfTI version can be set by nii_tool('default'). One can override the % default version by specifying it in nii.hdr.version. To convert between % versions, load a NIfTI file, specify new version, and save it. For example: % % nii = nii_tool('load', 'file_nifti1.nii'); % load version 1 file % nii.hdr.version = 2; % force to NIfTI-2 % nii_tool('save', nii, 'file_nifti2.nii'); % save as version 2 file % % Following example shows how to change data type of a nii file: % nii = nii_tool('load', 'file_int16.nii'); % load int16 type file % nii.img = single(nii.img); % change data type to single/float32 % nii_tool('save', nii, 'file_float.nii'); % nii_tool will take care of hdr % % % nii = nii_tool('cat3D', files); % % - Concatenate SPM 3D files into a 4D dataset. The input 'files' can be cellstr % with file names, or char with wildcards (* or ?). If it is cellstr, the volume % order in the 4D data corresponds to those files. If wildcards are used, the % volume order is based on alphabetical order of file names. % % Note that the files to be concatenated must have the same datatype, dim, voxel % size, scaling slope and intercept, transformation matrix, etc. This is % normally true if files are for the same dicom series. % % Following example shows how to convert a series of 3D files into a 4D file: % % nii = nii_tool('cat3D', './data/fSubj2-0003*.nii'); % load files for series 3 % nii_tool('save', nii, './data/fSubj2-0003_4D.nii'); % save as a 4D file % % % oldStyle = nii_tool('RGBStyle', 'afni'); % % - Set/query the method to read/save RGB or RGBA NIfTI file. The default method % can be set by nii_tool('default', 'rgb_dim', dimN), where dimN can be 1, 3 or % 4, or 'afni', 'mricron' or 'fsl', as explained below. % % The default is 'afni' style (or 1), which is defined by NIfTI standard, but is % not well supported by fslview till v5.0.8 or mricron till v20140804. % % If the second input is set to 'mricron' (or 3), nii_tool will save file using % the old RGB fashion (dim 3 for RGB). This works for mricron v20140804 or % earlier. % % If the second input is set to 'fsl' (or 4), nii_tool will save RGB or RGBA % layer into 4th dimension, and the file is not encoded as RGB data, but as % normal 4D NIfTI. This violates the NIfTI rule, but it seems it is the only way % to work for fslview (at least till fsl v5.0.8). % % If no new style (second input) is provided, it means to query the current % style (one of 'afni', 'mricron' and 'fsl'). % % The GUI method to convert between different RGB style can be found in % nii_viewer. Following shows how to convert other style into fsl style: % % nii_tool('RGBStyle', 'afni'); % we are loading afni style RGB % nii = nii_tool('load', 'afni_style.nii'); % load RGB file % nii_tool('RGBStyle', 'fsl'); % switch to fsl style for later save % nii_tool('save', nii, 'fslRGB.nii'); % fsl can read it as RGB % % Note that, if one wants to convert fsl style (non-RGB file by NIfTI standard) % to other styles, an extra step is needed to change the RGB dim from 4th to 8th % dim before 'save': % % nii = nii_tool('load', 'fslStyleFile.nii'); % it is normal NIfTI % nii.img = permute(nii.img, [1:3 5:8 4]); % force it to be RGB data % nii_tool('RGBStyle', 'afni'); % switch to NIfTI RGB style if needed % nii_tool('save', nii, 'afni_RGB.nii'); % now AFNI can read it as RGB % % Also note that the setting by nii_tool('RGBStyle') is effective only for % current Matlab session. If one clears all or starts a new Matlab session, the % default style by nii_tool('default') will take effect. % % See also NII_VIEWER, NII_XFORM, DICM2NII % More information for NIfTI format: % Official NIfTI website: http://nifti.nimh.nih.gov/ % Another excellent site: http://brainder.org/2012/09/23/the-nifti-file-format/ % History (yymmdd) % 150109 Write it based on Jimmy Shen's NIfTI tool ([email protected]) % 150202 Include renamed pigz files for Windows % 150203 Fix closeFile and deleteTmpFile order % 150205 Add hdr.machine: needed for .img fopen % 150208 Add 4th input for 'save', allowing to save SPM 3D files % 150210 Add 'cat3D' to load SPM 3D files % 150226 Assign all 8 char for 'magic' (version 2 needs it) % 150321 swapbytes(nByte) for ecode=40 with big endian % 150401 Add 'default' to set/query version and rgb_dim default setting % 150514 read_ext: decode txt edata by dicm2nii.m % 150517 func_handle: provide a way to use gunzipOS etc from outside % 150617 auto detect rgb_dim 1&3 for 'load' etc using ChrisR method % 151025 Change subfunc img2datatype as 'update' for outside access % 151109 Include dd.exe from WinAVR-20100110 for partial gz unzip % 151205 Partial gunzip: fix fname with space & unknown pigz | dd error. % 151222 Take care of img for intent_code 2003/2004: anyone uses it? % 160110 Use matlab pref method to replace para file. % 160120 check_gzip: use "" for included pigz; ignore dd error if err is false. % 160326 fix setpref for older Octave: set each parameter separately. % 160531 fopen uses 'W' for 'w': performance benefit according to Yair. % 160701 subFuncHelp: bug fix for mfile case. % 161018 gunzipOS: use unique name for outName, to avoid problem with parfor. % 161025 Make included linux pigz executible; fix "dd" for windows. % 161031 gunzip_mem(), nii_bytes() for hdr/ext read: read uint8 then parse; % Replace hdr.machine with hdr.swap_endian. % 170212 Extract decode_ext() from 'ext' cmd so call it in 'update' cmd. % 170215 gunzipOS: use -c > rather than copyfile for performance. % 170322 gzipOS: stop using background gz to avoid file not exist error. % 170410 read_img(): turn off auto RGB dim detection, and use rgb_dim. % 170714 'save': force to version 2 if img dim exceeds 2^15-1. % 170716 Add functionSignatures.json file for tab auto-completion. % 171031 'LocalFunc' makes eaiser to call local functions. % 171206 Allow file name ext other than .nii, .hdr, .img. % 180104 check_gzip: add /usr/local/bin to PATH for unix if needed. % 180119 use jsystem for better speed. % 180710 bug fix for cal_max/cal_min in 'update'. persistent C para; % C columns: name, length, format, value, offset if isempty(C) [C, para] = niiHeader; if exist('OCTAVE_VERSION', 'builtin') warning('off', 'Octave:fopen-mode'); % avoid 'W' warning more off; end end if ~ischar(cmd) error('Provide a string command as the first input for nii_tool'); end if any(cmd=='?'), subFuncHelp(mfilename, cmd); return; end if strcmpi(cmd, 'init') if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end nii.hdr = cell2struct(C(:,4), C(:,1)); nii.img = varargin{1}; if numel(size(nii.img))>8 error('NIfTI img can have up to 7 dimension'); end if nargin>2 i = varargin{2}; if i<0 || i>8 || mod(i,1)>0, error('Invalid RGB_dim number'); end nii.img = permute(nii.img, [1:i-1 i+1:8 i]); % RGB to dim8 end varargout{1} = nii_tool('update', nii); % set datatype etc elseif strcmpi(cmd, 'save') if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end nii = varargin{1}; if ~isstruct(nii) || ~isfield(nii, 'hdr') || ~isfield(nii, 'img') error(['nii_tool(''save'') needs a struct from nii_tool(''init'')' ... ' or nii_tool(''load'') as the second input']); end % Check file name to save if nargin>2 fname = varargin{2}; if ~ischar(fname), error('Invalid name for NIfTI file: %s', fname); end elseif isfield(nii.hdr, 'file_name') fname = nii.hdr.file_name; else error('Provide a valid file name as the third input'); end if ~ispc && strncmp(fname, '~/', 2) % matlab may err with this abbrevation fname = [getenv('HOME') fname(2:end)]; end [pth, fname, fext] = fileparts(fname); do_gzip = strcmpi(fext, '.gz'); if do_gzip [~, fname, fext] = fileparts(fname); % get .nii .img .hdr end if isempty(fext), fext = '.nii'; end % default single .nii file fname = fullfile(pth, fname); % without file ext isNii = strcmpi(fext, '.nii'); % will use .img/.hdr if not .nii % Deal with NIfTI version and sizeof_hdr niiVer = para.version; if isfield(nii.hdr, 'version'), niiVer = nii.hdr.version; end if niiVer==1 && any(nii.hdr.dim(2:end) > 32767), niiVer = 2; end if niiVer == 1 nii.hdr.sizeof_hdr = 348; % in case it was loaded from other version elseif niiVer == 2 nii.hdr.sizeof_hdr = 540; % version 2 else error('Unsupported NIfTI version: %g', niiVer); end if niiVer ~= para.version C0 = niiHeader(niiVer); else C0 = C; end % Update datatype/bitpix/dim in case nii.img is changed [nii, fmt] = nii_tool('update', nii); % This 'if' block: lazy implementation to split into 3D SPM files if nargin>3 && ~isempty(varargin{3}) && varargin{3} && nii.hdr.dim(5)>1 if do_gzip, fext = [fext '.gz']; end nii0 = nii; for i = 1:nii.hdr.dim(5) fname0 = sprintf('%s_%05g%s', fname, i, fext); nii0.img = nii.img(:,:,:,i,:,:,:,:); % one vol if i==1 && isfield(nii, 'ext'), nii0.ext = nii.ext; elseif i==2 && isfield(nii0, 'ext'), nii0 = rmfield(nii0, 'ext'); end nii_tool('save', nii0, fname0); end return; end % re-arrange img for special datatype: RGB/RGBA/Complex. if any(nii.hdr.datatype == [128 511 2304]) % RGB or RGBA if para.rgb_dim == 1 % AFNI style nii.img = permute(nii.img, [8 1:7]); elseif para.rgb_dim == 3 % old mricron style nii.img = permute(nii.img, [1 2 8 3:7]); elseif para.rgb_dim == 4 % for fslview nii.img = permute(nii.img, [1:3 8 4:7]); % violate nii rule dim = size(nii.img); if numel(dim)>6 % dim7 is not 1 i = find(dim(5:7)==1, 1, 'last') + 4; nii.img = permute(nii.img, [1:i-1 i+1:8 i]); end nii = nii_tool('update', nii); % changed to non-RGB datatype end elseif any(nii.hdr.datatype == [32 1792]) % complex single/double nii.img = [real(nii.img(:))'; imag(nii.img(:))']; end % Check nii extension: update esize to x16 nExt = 0; esize = 0; nii.hdr.extension = [0 0 0 0]; % no nii ext if isfield(nii, 'ext') && isstruct(nii.ext) ... && isfield(nii.ext(1), 'edata') && ~isempty(nii.ext(1).edata) nExt = numel(nii.ext); nii.hdr.extension = [1 0 0 0]; % there is nii ext for i = 1:nExt if ~isfield(nii.ext(i), 'ecode') || ~isfield(nii.ext(i), 'edata') error('NIfTI header ext struct must have ecode and edata'); end n0 = numel(nii.ext(i).edata) + 8; % 8 byte for esize and ecode n1 = ceil(n0/16) * 16; % esize: multiple of 16 nii.ext(i).esize = n1; nii.ext(i).edata(end+(1:n1-n0)) = 0; % pad zeros esize = esize + n1; end end % Set magic, vox_offset, and open file for .nii or .hdr if isNii % version 1 will take only the first 4 nii.hdr.magic = sprintf('n+%g%s', niiVer, char([0 13 10 26 10])); nii.hdr.vox_offset = nii.hdr.sizeof_hdr + 4 + esize; fid = fopen([fname fext], 'W'); else nii.hdr.magic = sprintf('ni%g%s', niiVer, char([0 13 10 26 10])); nii.hdr.vox_offset = 0; fid = fopen([fname '.hdr'], 'W'); end % Write nii hdr for i = 1:size(C0,1) if isfield(nii.hdr, C0{i,1}) val = nii.hdr.(C0{i,1}); else % niiVer=2 omit some fields, also take care of other cases val = C0{i,4}; end n = numel(val); len = C0{i,2}; if n>len val(len+1:n) = []; % remove extra, normally for char elseif n<len val(n+1:len) = 0; % pad 0, normally for char end fwrite(fid, val, C0{i,3}); end % Write nii ext: extension is in hdr for i = 1:nExt % nExt may be 0 fwrite(fid, nii.ext(i).esize, 'int32'); fwrite(fid, nii.ext(i).ecode, 'int32'); fwrite(fid, nii.ext(i).edata, 'uint8'); end if ~isNii fclose(fid); % done with .hdr fid = fopen([fname '.img'], 'W'); end % Write nii image fwrite(fid, nii.img, fmt); fclose(fid); % all written % gzip if asked if do_gzip if isNii gzipOS([fname '.nii']); else gzipOS([fname '.hdr']); % better not to compress .hdr gzipOS([fname '.img']); end end elseif strcmpi(cmd, 'hdr') if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end if ~ischar(varargin{1}) error('nii_tool(''hdr'') needs nii file name as second input'); end fname = nii_name(varargin{1}, '.hdr'); % get .hdr if it is .img [b, fname] = nii_bytes(fname, 600); % v2: 544+10 gzip header varargout{1} = read_hdr(b, C, fname); elseif any(strcmpi(cmd, {'img' 'load'})) if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end if ischar(varargin{1}) % file name input fname = nii_name(varargin{1}, '.hdr'); nii = struct; elseif isstruct(varargin{1}) && isfield(varargin{1}, 'file_name') nii.hdr = varargin{1}; fname = nii.hdr.file_name; else error(['nii_tool(''%s'') needs a file name or hdr struct from ' ... 'nii_tool(''hdr'') as second input'], cmd); end if strcmpi(cmd, 'load') [ext, nii.hdr] = nii_tool('ext', varargin{1}); if ~isempty(ext), nii.ext = ext; end elseif ~isfield(nii, 'hdr') nii.hdr = nii_tool('hdr', fname); end nii.img = read_img(nii.hdr, para); if strcmpi(cmd, 'load') varargout{1} = nii; else % img varargout{1} = nii.img; end elseif strcmpi(cmd, 'ext') if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end if ischar(varargin{1}) % file name input fname = nii_name(varargin{1}, '.hdr'); hdr = nii_tool('hdr', fname); elseif isstruct(varargin{1}) && isfield(varargin{1}, 'file_name') hdr = varargin{1}; fname = hdr.file_name; else error(['nii_tool(''%s'') needs a file name or hdr struct from ' ... 'nii_tool(''hdr'') as second input'], cmd); end if isempty(hdr.extension) || hdr.extension(1)==0 varargout{1} = []; else if hdr.vox_offset>0, nByte = hdr.vox_offset + 64; % .nii arbituary +64 else, nByte = inf; end b = nii_bytes(fname, nByte); varargout{1} = read_ext(b, hdr); end if nargout>1, varargout{2} = hdr; end elseif strcmpi(cmd, 'RGBStyle') styles = {'afni' '' 'mricron' 'fsl'}; curStyle = styles{para.rgb_dim}; if nargin<2, varargout{1} = curStyle; return; end % query only irgb = varargin{1}; if isempty(irgb), irgb = 1; end % default as 'afni' if ischar(irgb) if strncmpi(irgb, 'fsl', 3), irgb = 4; elseif strncmpi(irgb, 'mricron', 4), irgb = 3; else, irgb = 1; end end if ~any(irgb == [1 3 4]) error('nii_tool(''RGBStyle'') can have 1, 3, or 4 as second input'); end if nargout, varargout{1} = curStyle; end % return old one para.rgb_dim = irgb; % no save to pref elseif strcmpi(cmd, 'cat3D') if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end fnames = varargin{1}; if ischar(fnames) % guess it is like run1*.nii f = dir(fnames); f = sort({f.name}); fnames = strcat([fileparts(fnames) '/'], f); end n = numel(fnames); if n<2 || ~iscellstr(fnames) error('Invalid input for nii_tool(''cat3D''): %s', varargin{1}); end nii = nii_tool('load', fnames{1}); % all for first file nii.img(:,:,:,2:n) = 0; % pre-allocate % For now, omit all consistence check between files for i = 2:n, nii.img(:,:,:,i) = nii_tool('img', fnames{i}); end varargout{1} = nii_tool('update', nii); % update dim elseif strcmpi(cmd, 'default') flds = {'version' 'rgb_dim'}; % may add more in the future pf = getpref('nii_tool_para'); for i = 1:numel(flds), val.(flds{i}) = pf.(flds{i}); end if nargin<2, varargout{1} = val; return; end % query only if nargout, varargout{1} = val; end % return old val in2 = varargin; if ~isstruct(in2), in2 = struct(in2{:}); end nam = fieldnames(in2); for i = 1:numel(nam) ind = strcmpi(nam{i}, flds); if isempty(ind), continue; end para.(flds{ind}) = in2.(nam{i}); setpref('nii_tool_para', flds{ind}, in2.(nam{i})); end if val.version ~= para.version, C = niiHeader(para.version); end elseif strcmpi(cmd, 'update') % old img2datatype subfunction if nargin<2, error('nii_tool(''%s'') needs second input', cmd); end nii = varargin{1}; if ~isstruct(nii) || ~isfield(nii, 'hdr') || ~isfield(nii, 'img') error(['nii_tool(''save'') needs a struct from nii_tool(''init'')' ... ' or nii_tool(''load'') as the second input']); end dim = size(nii.img); ndim = numel(dim); dim(ndim+1:7) = 1; if ndim == 8 % RGB/RGBA data. Change img type to uint8/single if needed valpix = dim(8); if valpix == 4 % RGBA typ = 'RGBA'; % error info only nii.img = uint8(nii.img); % NIfTI only support uint8 for RGBA elseif valpix == 3 % RGB, must be single or uint8 typ = 'RGB'; if max(nii.img(:))>1, nii.img = uint8(nii.img); else, nii.img = single(nii.img); end else error('Color dimension must have length of 3 for RGB and 4 for RGBA'); end dim(8) = []; % remove color-dim so numel(dim)=7 for nii.hdr ndim = find(dim>1, 1, 'last'); % update it elseif isreal(nii.img) typ = 'real'; valpix = 1; else typ = 'complex'; valpix = 2; end if islogical(nii.img), imgFmt = 'ubit1'; else, imgFmt = class(nii.img); end ind = find(strcmp(para.format, imgFmt) & para.valpix==valpix); if isempty(ind) % only RGB and complex can have this problem error('nii_tool does not support %s image of ''%s'' type', typ, imgFmt); elseif numel(ind)>1 % unlikely error('Non-unique datatype found for %s image of ''%s'' type', typ, imgFmt); end fmt = para.format{ind}; nii.hdr.datatype = para.datatype(ind); nii.hdr.bitpix = para.bitpix(ind); nii.hdr.dim = [ndim dim]; mx = double(max(nii.img(:))); mn = double(min(nii.img(:))); if nii.hdr.cal_min>mx || nii.hdr.cal_max<mn % reset wrong value nii.hdr.cal_min = 0; nii.hdr.cal_max = 0; end if nii.hdr.sizeof_hdr == 348 nii.hdr.glmax = round(mx); % we may remove these nii.hdr.glmin = round(mn); end if isfield(nii, 'ext') try swap = nii.hdr.swap_endian; catch, swap = false; end nii.ext = decode_ext(nii.ext, swap); end varargout{1} = nii; if nargout>1, varargout{2} = fmt; end elseif strcmp(cmd, 'func_handle') % make a local function avail to outside varargout{1} = str2func(varargin{1}); elseif strcmp(cmd, 'LocalFunc') % call local function from outside [varargout{1:nargout}] = feval(varargin{:}); else error('Invalid command for nii_tool: %s', cmd); end % End of main function %% Subfunction: all nii header in the order in NIfTI-1/2 file function [C, para] = niiHeader(niiVer) pf = getpref('nii_tool_para'); if isempty(pf) setpref('nii_tool_para', 'version', 1); setpref('nii_tool_para', 'rgb_dim', 1); pf = getpref('nii_tool_para'); end if nargin<1 || isempty(niiVer), niiVer = pf.version; end if niiVer == 1 C = { % name len format value offset 'sizeof_hdr' 1 'int32' 348 0 'data_type' 10 'char*1' '' 4 'db_name' 18 'char*1' '' 14 'extents' 1 'int32' 16384 32 'session_error' 1 'int16' 0 36 'regular' 1 'char*1' 'r' 38 'dim_info' 1 'uint8' 0 39 'dim' 8 'int16' ones(1,8) 40 'intent_p1' 1 'single' 0 56 'intent_p2' 1 'single' 0 60 'intent_p3' 1 'single' 0 64 'intent_code' 1 'int16' 0 68 'datatype' 1 'int16' 0 70 'bitpix' 1 'int16' 0 72 'slice_start' 1 'int16' 0 74 'pixdim' 8 'single' zeros(1,8) 76 'vox_offset' 1 'single' 352 108 'scl_slope' 1 'single' 1 112 'scl_inter' 1 'single' 0 116 'slice_end' 1 'int16' 0 120 'slice_code' 1 'uint8' 0 122 'xyzt_units' 1 'uint8' 0 123 'cal_max' 1 'single' 0 124 'cal_min' 1 'single' 0 128 'slice_duration' 1 'single' 0 132 'toffset' 1 'single' 0 136 'glmax' 1 'int32' 0 140 'glmin' 1 'int32' 0 144 'descrip' 80 'char*1' '' 148 'aux_file' 24 'char*1' '' 228 'qform_code' 1 'int16' 0 252 'sform_code' 1 'int16' 0 254 'quatern_b' 1 'single' 0 256 'quatern_c' 1 'single' 0 260 'quatern_d' 1 'single' 0 264 'qoffset_x' 1 'single' 0 268 'qoffset_y' 1 'single' 0 272 'qoffset_z' 1 'single' 0 276 'srow_x' 4 'single' [1 0 0 0] 280 'srow_y' 4 'single' [0 1 0 0] 296 'srow_z' 4 'single' [0 0 1 0] 312 'intent_name' 16 'char*1' '' 328 'magic' 4 'char*1' '' 344 'extension' 4 'uint8' [0 0 0 0] 348 }; elseif niiVer == 2 C = { 'sizeof_hdr' 1 'int32' 540 0 'magic' 8 'char*1' '' 4 'datatype' 1 'int16' 0 12 'bitpix' 1 'int16' 0 14 'dim' 8 'int64' ones(1,8) 16 'intent_p1' 1 'double' 0 80 'intent_p2' 1 'double' 0 88 'intent_p3' 1 'double' 0 96 'pixdim' 8 'double' zeros(1,8) 104 'vox_offset' 1 'int64' 544 168 'scl_slope' 1 'double' 1 176 'scl_inter' 1 'double' 0 184 'cal_max' 1 'double' 0 192 'cal_min' 1 'double' 0 200 'slice_duration' 1 'double' 0 208 'toffset' 1 'double' 0 216 'slice_start' 1 'int64' 0 224 'slice_end' 1 'int64' 0 232 'descrip' 80 'char*1' '' 240 'aux_file' 24 'char*1' '' 320 'qform_code' 1 'int32' 0 344 'sform_code' 1 'int32' 0 348 'quatern_b' 1 'double' 0 352 'quatern_c' 1 'double' 0 360 'quatern_d' 1 'double' 0 368 'qoffset_x' 1 'double' 0 376 'qoffset_y' 1 'double' 0 384 'qoffset_z' 1 'double' 0 392 'srow_x' 4 'double' [1 0 0 0] 400 'srow_y' 4 'double' [0 1 0 0] 432 'srow_z' 4 'double' [0 0 1 0] 464 'slice_code' 1 'int32' 0 496 'xyzt_units' 1 'int32' 0 500 'intent_code' 1 'int32' 0 504 'intent_name' 16 'char*1' '' 508 'dim_info' 1 'uint8' 0 524 'unused_str' 15 'char*1' '' 525 'extension' 4 'uint8' [0 0 0 0] 540 }; else error('Nifti version %g is not supported', niiVer); end if nargout<2, return; end % class datatype bitpix valpix D = { 'ubit1' 1 1 1 % neither mricron nor fsl support this 'uint8' 2 8 1 'int16' 4 16 1 'int32' 8 32 1 'single' 16 32 1 'single' 32 64 2 % complex 'double' 64 64 1 'uint8' 128 24 3 % RGB 'int8' 256 8 1 'single' 511 96 3 % RGB, not in NIfTI standard? 'uint16' 512 16 1 'uint32' 768 32 1 'int64' 1024 64 1 'uint64' 1280 64 1 % 'float128' 1536 128 1 % long double, for 22nd century? 'double' 1792 128 2 % complex % 'float128' 2048 256 2 % long double complex 'uint8' 2304 32 4 % RGBA }; para.format = D(:,1)'; para.datatype = [D{:,2}]; para.bitpix = [D{:,3}]; para.valpix = [D{:,4}]; para.rgb_dim = pf.rgb_dim; % dim of RGB/RGBA in NIfTI FILE para.version = niiVer; %% Subfunction: use pigz or system gzip if available (faster) function gzipOS(fname) persistent cmd; % command to gzip if isempty(cmd) cmd = check_gzip('gzip'); if ischar(cmd) cmd = @(nam){cmd '-nf' nam}; elseif islogical(cmd) && ~cmd fprintf(2, ['None of system pigz, gzip or Matlab gzip available. ' ... 'Files are not compressed into gz.\n']); end end if islogical(cmd) if cmd, gzip(fname); deleteFile(fname); end return; end [err, str] = jsystem(cmd(fname)); if err && ~exist([fname '.gz'], 'file') try gzip(fname); deleteFile(fname); catch fprintf(2, 'Error during compression: %s\n', str); end end %% Deal with pigz/gzip on path or in nii_tool folder, and matlab gzip/gunzip function cmd = check_gzip(gz_unzip) m_dir = fileparts(mfilename('fullpath')); % away from pwd, so use OS pigz if both exist. Avoid error if pwd changed later if strcmpi(pwd, m_dir), cd ..; clnObj = onCleanup(@() cd(m_dir)); end if isunix pth1 = getenv('PATH'); if isempty(strfind(pth1, '/usr/local/bin')) pth1 = [pth1 ':/usr/local/bin']; setenv('PATH', pth1); end end % first, try system pigz [err, ~] = jsystem({'pigz' '-V'}); if ~err, cmd = 'pigz'; return; end % next, try pigz included with nii_tool cmd = [m_dir '/pigz']; if ismac % pigz for mac is not included in the package if strcmp(gz_unzip, 'gzip') fprintf(2, [' Please install pigz for fast compression: ' ... 'http://macappstore.org/pigz/\n']); end elseif isunix % linux [st, val] = fileattrib(cmd); if st && ~val.UserExecute, fileattrib(cmd, '+x'); end end [err, ~] = jsystem({cmd '-V'}); if ~err, return; end % Third, try system gzip/gunzip [err, ~] = jsystem({gz_unzip '-V'}); % gzip/gunzip on system path? if ~err, cmd = gz_unzip; return; end % Lastly, use Matlab gzip/gunzip if java avail cmd = usejava('jvm'); %% check dd command, return empty if not available function dd = check_dd m_dir = fileparts(mfilename('fullpath')); if strcmpi(pwd, m_dir), cd ..; clnObj = onCleanup(@() cd(m_dir)); end [err, ~] = jsystem({'dd' '--version'}); if ~err, dd = 'dd'; return; end % dd with linix/mac, and maybe windows if ispc % rename it as exe dd = [m_dir '\dd']; [err, ~] = jsystem({dd '--version'}); if ~err, return; end end dd = ''; %% Try to use in order of pigz, system gunzip, then matlab gunzip function outName = gunzipOS(fname, nByte) persistent cmd dd pth uid; % command to run gupzip, dd tool, and temp_path if isempty(cmd) cmd = check_gzip('gunzip'); % gzip -dc has problem in PC if ischar(cmd) cmd = @(nam)sprintf('"%s" -nfdc "%s" ', cmd, nam); % f for overwrite elseif islogical(cmd) && ~cmd cmd = []; error('None of system pigz, gunzip or Matlab gunzip is available'); end dd = check_dd; if ~isempty(dd) dd = @(n,out)sprintf('| "%s" count=%g of="%s"', dd, ceil(n/512), out); end if ispc % matlab tempdir could be slow due to cd in and out pth = getenv('TEMP'); if isempty(pth), pth = pwd; end else pth = getenv('TMP'); if isempty(pth), pth = getenv('TMPDIR'); end if isempty(pth), pth = '/tmp'; end % last resort end uid = @()sprintf('_%s_%03x', datestr(now, 'yymmddHHMMSSfff'), randi(999)); end if islogical(cmd) outName = gunzip(fname, pth); outName = outName{1}; return; end [~, outName, ext] = fileparts(fname); if strcmpi(ext, '.gz') % likely always true [~, outName, ext1] = fileparts(outName); outName = [outName uid() ext1]; else outName = [outName uid()]; end outName = fullfile(pth, outName); if ~isempty(dd) && nargin>1 && ~isinf(nByte) % unzip only part of data try [err, ~] = system([cmd(fname) dd(nByte, outName)]); if err==0, return; end end end [err, str] = system([cmd(fname) '> "' outName '"']); % [err, str] = jsystem({'pigz' '-nfdc' fname '>' outName}); if err try outName = gunzip(fname, pth); catch error('Error during gunzip:\n%s', str); end end %% cast bytes into a type, swapbytes if needed function out = cast_swap(b, typ, swap) out = typecast(b, typ); if swap, out = swapbytes(out); end out = double(out); % for convenience %% subfunction: read hdr function hdr = read_hdr(b, C, fname) n = typecast(b(1:4), 'int32'); if n==348, niiVer = 1; swap = false; elseif n==540, niiVer = 2; swap = false; else n = swapbytes(n); if n==348, niiVer = 1; swap = true; elseif n==540, niiVer = 2; swap = true; else, error('Not valid NIfTI file: %s', fname); end end if niiVer>1, C = niiHeader(niiVer); end % C defaults for version 1 for i = 1:size(C,1) try a = b(C{i,5}+1 : C{i+1,5}); catch if C{i,5}==numel(b), a = []; else, a = b(C{i,5} + (1:C{i,2})); % last item extension is in bytes end end if strcmp(C{i,3}, 'char*1') a = deblank(char(a)); else a = cast_swap(a, C{i,3}, swap); a = double(a); end hdr.(C{i,1}) = a; end hdr.version = niiVer; % for 'save', unless user asks to change hdr.swap_endian = swap; hdr.file_name = fname; %% subfunction: read ext, and decode it if known ecode function ext = read_ext(b, hdr) ext = []; % avoid error if no ext but hdr.extension(1) was set nEnd = hdr.vox_offset; if nEnd == 0, nEnd = numel(b); end % .hdr file swap = hdr.swap_endian; j = hdr.sizeof_hdr + 4; % 4 for hdr.extension while j < nEnd esize = cast_swap(b(j+(1:4)), 'int32', swap); j = j+4; % x16 if isempty(esize) || mod(esize,16), return; end % just to be safe i = numel(ext) + 1; ext(i).esize = esize; %#ok<*AGROW> ext(i).ecode = cast_swap(b(j+(1:4)), 'int32', swap); j = j+4; ext(i).edata = b(j+(1:esize-8))'; % -8 for esize & ecode j = j + esize - 8; end ext = decode_ext(ext, swap); %% subfunction function ext = decode_ext(ext, swap) % Decode edata if we know ecode for i = 1:numel(ext) if isfield(ext(i), 'edata_decoded'), continue; end % done if ext(i).ecode == 40 % Matlab: any kind of matlab variable nByte = cast_swap(ext(i).edata(1:4), 'int32', swap); % MAT data tmp = [tempname '.mat']; % temp MAT file to save edata fid1 = fopen(tmp, 'W'); fwrite(fid1, ext(i).edata(5:nByte+4)); % exclude padded zeros fclose(fid1); deleteMat = onCleanup(@() deleteFile(tmp)); % delete temp file after done ext(i).edata_decoded = load(tmp); % load into struct elseif any(ext(i).ecode == [4 6 32]) % 4 AFNI, 6 plain text, 32 CIfTI str = char(ext(i).edata(:)'); if isempty(strfind(str, 'dicm2nii.m')) ext(i).edata_decoded = deblank(str); else % created by dicm2nii.m ss = struct; ind = strfind(str, [';' char([0 10])]); % strsplit error in Octave ind = [-2 ind]; % -2+3=1: start of first para for k = 1:numel(ind)-1 a = str(ind(k)+3 : ind(k+1)); a(a==0) = []; % to be safe. strtrim wont remove null a = strtrim(a); if isempty(a), continue; end try eval(['ss.' a]); % put all into struct catch try a = regexp(a, '(.*?)\s*=\s*(.*?);', 'tokens', 'once'); ss.(a{1}) = a{2}; catch me fprintf(2, '%s\n', me.message); fprintf(2, 'Unrecognized text: %s\n', a); end end end flds = fieldnames(ss); % make all vector column for k = 1:numel(flds) val = ss.(flds{k}); if isnumeric(val) && isrow(val), ss.(flds{k}) = val'; end end ext(i).edata_decoded = ss; end elseif ext(i).ecode == 2 % dicom tmp = [tempname '.dcm']; fid1 = fopen(tmp, 'W'); fwrite(fid1, ext(i).edata); fclose(fid1); deleteDcm = onCleanup(@() deleteFile(tmp)); ext(i).edata_decoded = dicm_hdr(tmp); end end %% subfunction: read img % memory gunzip may be slow and error for large img, so use file unzip function img = read_img(hdr, para) ind = para.datatype == hdr.datatype; if ~any(ind) error('Datatype %g is not supported by nii_tool.', hdr.datatype); end dim = hdr.dim(2:8); dim(hdr.dim(1)+1:7) = 1; % avoid some error in file dim(dim<1) = 1; valpix = para.valpix(ind); fname = nii_name(hdr.file_name, '.img'); % in case of .hdr/.img pair fid = fopen(fname); sig = fread(fid, 2, '*uint8')'; if isequal(sig, [31 139]) % .gz fclose(fid); fname = gunzipOS(fname); cln = onCleanup(@() deleteFile(fname)); % delete gunzipped file fid = fopen(fname); end % if ~exist('cln', 'var') && valpix==1 && ~hdr.swap_endian % m = memmapfile(fname, 'Offset', hdr.vox_offset, ... % 'Format', {para.format{ind}, dim, 'img'}); % nii = m.Data; % return; % end if hdr.swap_endian % switch between LE and BE [~, ~, ed] = fopen(fid); % default endian: almost always ieee-le fclose(fid); if isempty(strfind(ed, '-le')), ed = strrep(ed, '-be', '-le'); %#ok<*STREMP> else, ed = strrep(ed, '-le', '-be'); end fid = fopen(fname, 'r', ed); % re-open with changed endian end fseek(fid, hdr.vox_offset, 'bof'); img = fread(fid, prod(dim)*valpix, ['*' para.format{ind}]); % * to keep original class fclose(fid); if any(hdr.datatype == [128 511 2304]) % RGB or RGBA % a = reshape(single(img), valpix, n); % assume rgbrgbrgb... % d1 = abs(a - a(:,[2:end 1])); % how similar are voxels to their neighbor % a = reshape(a, prod(dim(1:2)), valpix*prod(dim(3:7))); % rr...rgg...gbb...b % d2 = abs(a - a([2:end 1],:)); % j = (sum(d1(:))>sum(d2(:)))*2 + 1; % 1 for afni, 3 for mricron j = para.rgb_dim; % auto detection may get wrong for noisy background dim = [dim(1:j-1) valpix dim(j:7)]; % length=8 now img = reshape(img, dim); img = permute(img, [1:j-1 j+1:8 j]); % put RGB(A) to dim8 elseif any(hdr.datatype == [32 1792]) % complex single/double img = reshape(img, [2 dim]); img = complex(permute(img(1,:,:,:,:,:,:,:), [2:8 1]), ... % real permute(img(2,:,:,:,:,:,:,:), [2:8 1])); % imag else % all others: valpix=1 if hdr.datatype==1, img = logical(img); end img = reshape(img, dim); end % RGB triplet in 5th dim OR RGBA quadruplet in 5th dim c = hdr.intent_code; if (c == 2003 && dim(5) == 3) || (c == 2004 && dim(5) == 4) img = permute(img, [1:4 6:8 5]); end %% Return requested fname with ext, useful for .hdr and .img files function fname = nii_name(fname, ext) if strcmpi(ext, '.img') i = regexpi(fname, '.hdr(.gz)?$'); if ~isempty(i), fname(i(end)+(0:3)) = ext; end elseif strcmpi(ext, '.hdr') i = regexpi(fname, '.img(.gz)?$'); if ~isempty(i), fname(i(end)+(0:3)) = ext; end end %% Read NIfTI file as bytes, gunzip if needed, but ignore endian function [b, fname] = nii_bytes(fname, nByte) if nargin<2, nByte = inf; end [fid, err] = fopen(fname); % system default endian if fid<1, error([err ': ' fname]); end b = fread(fid, nByte, '*uint8')'; fname = fopen(fid); fclose(fid); if isequal(b(1:2), [31 139]) % gz, tgz file b = gunzip_mem(b, fname, nByte)'; end %% subfunction: get help for a command function subFuncHelp(mfile, cmd) str = fileread(which(mfile)); i = regexp(str, '\n\s*%', 'once'); % start of 1st % line str = regexp(str(i:end), '.*?(?=\n\s*[^%])', 'match', 'once'); % help text str = regexprep(str, '\r?\n\s*%', '\n'); % remove '\r' and leading % dashes = regexp(str, '\n\s*-{1,4}\s+') + 1; % lines starting with 1 to 4 - if isempty(dashes), disp(str); return; end % Show all help text prgrfs = regexp(str, '(\n\s*){2,}'); % blank lines nTopic = numel(dashes); topics = ones(1, nTopic+1); for i = 1:nTopic ind = regexpi(str(1:dashes(i)), [mfile '\s*\(']); % syntax before ' - ' if isempty(ind), continue; end % no syntax before ' - ', assume start with 1 ind = find(prgrfs < ind(end), 1, 'last'); % previous paragraph if isempty(ind), continue; end topics(i) = prgrfs(ind) + 1; % start of this topic end topics(end) = numel(str); % end of last topic cmd = strrep(cmd, '?', ''); % remove ? in case it is in subcmd if isempty(cmd) % help for main function disp(str(1:topics(1))); % subfunction list before first topic return; end expr = [mfile '\s*\(\s*''' cmd '''']; for i = 1:nTopic if isempty(regexpi(str(topics(i):dashes(i)), expr, 'once')), continue; end disp(str(topics(i):topics(i+1))); return; end fprintf(2, ' Unknown command for %s: %s\n', mfile, cmd); % no cmd found %% gunzip bytes in memory if possible. 2nd/3rd input for fallback file gunzip % Trick: try-block avoid error for partial file unzip. function bytes = gunzip_mem(gz_bytes, fname, nByte) bytes = []; try bais = java.io.ByteArrayInputStream(gz_bytes); try, gzis = java.util.zip.GZIPInputStream(bais); %#ok<*NOCOM> catch, try, gzis = java.util.zip.InflaterInputStream(bais); catch me; end end buff = java.io.ByteArrayOutputStream; try org.apache.commons.io.IOUtils.copy(gzis, buff); catch me; end gzis.close; bytes = typecast(buff.toByteArray, 'uint8'); if isempty(bytes), error(me.message); end catch if nargin<3 || isempty(nByte), nByte = inf; end if nargin<2 || isempty(fname) fname = [tempname '.gz']; % temp gz file fid = fopen(fname, 'W'); if fid<0, return; end cln = onCleanup(@() deleteFile(fname)); % delete temp gz file fwrite(fid, gz_bytes, 'uint8'); fclose(fid); end try %#ok<*TRYNC> fname = gunzipOS(fname, nByte); fid = fopen(fname); bytes = fread(fid, nByte, '*uint8'); fclose(fid); deleteFile(fname); % unzipped file end end %% Delete file in background function deleteFile(fname) if ispc, system(['start "" /B del "' fname '"']); else, system(['rm "' fname '" &']); end %% faster than system: based on https://github.com/avivrosenberg/matlab-jsystem function [err, out] = jsystem(cmd) % cmd is cell str, no quotation marks needed for file names with space. try pb = java.lang.ProcessBuilder(cmd); pb.redirectErrorStream(true); % ErrorStream to InputStream process = pb.start(); scanner = java.util.Scanner(process.getInputStream).useDelimiter('\A'); if scanner.hasNext(), out = char(scanner.next()); else, out = ''; end err = process.exitValue; % err = process.waitFor() may hang if err, error('java.lang.ProcessBuilder error'); end catch % fallback to system() if java fails like for Octave cmd = regexprep(cmd, '.+? .+', '"$0"'); % double quotes if with middle space [err, out] = system(sprintf('%s ', cmd{:})); end %%
github
cocoanlab/humanfmri_preproc_bids-master
dicm2nii.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/dicm2nii.m
128,433
utf_8
9017400933423c6f35d9ec43a688b5d3
function varargout = dicm2nii(src, niiFolder, fmt, varargin) % Convert dicom and more into nii or img/hdr files. % % DICM2NII(dcmSource, niiFolder, outFormat) % % The input arguments are all optional: % 1. source file or folder. It can be a zip or tgz file, a folder containing % dicom files, or other convertible files. It can also contain wildcards % like 'run1_*' for all files start with 'run1_'. % 2. folder to save result files. % 3. output file format: % 0 or '.nii' for single nii uncompressed. % 1 or '.nii.gz' for single nii compressed (default). % 2 or '.hdr' for hdr/img pair uncompressed. % 3 or '.hdr.gz' for hdr/img pair compressed. % 4 or '.nii 3D' for 3D nii uncompressed (SPM12). % 5 or '.nii.gz 3D' for 3D nii compressed. % 6 or '.hdr 3D' for 3D hdr/img pair uncompressed (SPM8). % 7 or '.hdr.gz 3D' for 3D hdr/img pair compressed. % 'bids' for bids data structure (http://bids.neuroimaging.io/) % % Typical examples: % DICM2NII; % bring up user interface if there is no input argument % DICM2NII('D:/myProj/zip/subj1.zip', 'D:/myProj/subj1/data'); % zip file % DICM2NII('D:/myProj/subj1/dicom/', 'D:/myProj/subj1/data'); % folder % % Less useful examples: % DICM2NII('D:/myProj/dicom/', 'D:/myProj/subj2/data', 'nii'); % no gz compress % DICM2NII('D:/myProj/dicom/run2*', 'D:/myProj/subj/data'); % convert run2 only % DICM2NII('D:/dicom/', 'D:/data', '3D.nii'); % SPM style files % % If there is no input, or any of the first two input is empty, the graphic user % interface will appear. % % If the first input is a zip/tgz file, such as those downloaded from a dicom % server, DICM2NII will extract files into a temp folder, create NIfTI files % into the data folder, and then delete the temp folder. For this reason, it is % better to keep the compressed file as backup. % % If a folder is the data source, DICM2NII will convert all files in the folder % and its subfolders (there is no need to sort files for different series). % % The output file names adopt SeriesDescription or ProtocolName of each series % used on scanner console. If both original and MoCo series are present, '_MoCo' % will be appended for MoCo series. For phase image, such as those from field % map, '_phase' will be appended to the name. If multiple subjects data are % mixed (highly discouraged), subject name will be in file name. In case of name % conflict, SeriesNumber, such as '_s005', will be appended to make file names % unique. It is suggested to use short, descriptive and distinct % SeriesDescription on the scanner console. % % For SPM 3D files, the file names will have volume index in format of '_00001' % appended to above name. % % Please note that, if a file in the middle of a series is missing, the series % will normally be skipped without converting, and a warning message in red text % will be shown in Command Window. The message will also be saved into a text % file under the data folder. % % A Matlab data file, dcmHeaders.mat, is always saved into the data folder. This % file contains dicom header from the first file for created series and some % information from last file in field LastFile. Some extra information is also % saved into this file. For MoCo series, motion parameters (RBMoCoTrans and % RBMoCoRot) are also saved. % % Slice timing information, if available, is stored in nii header, such as % slice_code and slice_duration. But the simple way may be to use the field % SliceTiming in dcmHeaders.mat. That timing is actually those numbers for FSL % when using custom slice timing. This is the universal method to specify any % kind of slice order, and for now, is the only way which works for multiband. % Slice order is one of the most confusing parameters, and it is recommended to % use this method to avoid mistake. Following shows how to convert this timing % into slice timing in ms and slice order for SPM: % % load('dcmHeaders.mat'); % or drag and drop the MAT file into Command Window % s = h.myFuncSeries; % field name is the same as nii file name % spm_ms = (0.5 - s.SliceTiming) * s.RepetitionTime; % [~, spm_order] = sort(-s.SliceTiming); % % Some information, such as TE, phase encoding direction and effective dwell % time, are stored in descrip of nii header. These are useful for fieldmap B0 % unwarp correction. Acquisition start time and date are also stored, and this % may be useful if one wants to align the functional data to some physiological % recording, like pulse, respiration or ECG. % % If there is DTI series, bval and bvec files will be generated for FSL etc. % bval and bvec are also saved in the dcmHeaders.mat file. % % Starting from 20150514, the converter stores some useful information in NIfTI % text extension (ecode=6). nii_tool can decode these information easily: % ext = nii_tool('ext', 'myNiftiFile.nii'); % read NIfTI extension % ext.edata_decoded contains all above mentioned information, and more. The % included nii_viewer can show the extension by Window->Show NIfTI ext. % % Several preference can be set from dicm2nii GUI. The preference change will % take effect until it is changed next time. % % One of preference is to save a .json file for each converted NIfTI. For more % information about the purpose of json file, check % http://bids.neuroimaging.io/ % % By default, the converter will use parallel pool for dicom header reading if % there are +2000 files. User can turn this off from GUI. % % By default, the PatientName is stored in NIfTI hdr and ext. This can be turned % off from GUI. % % Please note that some information, such as the slice order information, phase % encoding direction and DTI bvec are in image reference, rather than NIfTI % coordinate system. This is because most analysis packages require information % in image space. For this reason, in case the image in a NIfTI file is flipped % or re-oriented, these information may not be correct anymore. % % Please report any bug to [email protected] or at % http://www.mathworks.com/matlabcentral/fileexchange/42997 % % To cite the work and for more detail about the conversion, check the paper at % http://www.sciencedirect.com/science/article/pii/S0165027016300073 % % See also NII_VIEWER, NII_MOCO, NII_STC % Thanks to: % Jimmy Shen's Tools for NIfTI and ANALYZE image, % Chris Rorden's dcm2nii pascal source code, % Przemyslaw Baranski for direction cosine matrix to quaternions. % History (yymmdd): % 130512 Publish to CCBBI users (Xiangrui Li). % 130513 Convert img from uint16 to int16 if range allows; % Support output file format of img/hdr/mat. % 130515 Change creation order to acquisition order (more natural). % If MoCo series is included, append _MoCo in file names. % 130516 Use SpacingBetweenSlices, if exists, for SliceThickness. % 130518 Use NumberOfImagesInMosaic in CSA header (work for some old data). % 130604 Add scl_inter/scl_slope and special naming for fieldmap. % 130614 Work out the way to get EffectiveEchoSpacing for B0 unwarp. % 130616 Add needed dicom field check, so it won't err later. % 130618 Reorient if non-mosaic or slice_dim is still 3 and no slice flip. % 130619 Simplify DERIVED series detection. No '_mag' in fieldmap name. % 130629 Improve the method to get phase direction; % Permute img dim1&2 (no -90 rotation) & simplify xform accordingly. % 130711 Make MoCoOption smarter: create nii if only 1 of 2 series exists. % 130712 Remove 5th input (allHeader). Save memory by using partial header. % 130712 Bug fix: dim_info with reorient. No problem since no EPI reorient. % 130715 Use 2 slices for xform. No slice flip needed except revNum mosaic. % 130716 Take care of lower/upper cases for output file names; % Apply scl_slope and inter to img if range allows and no rounding; % Save motion parameters, if any, into dcmHeader.mat. % 130722 Ugly fix for isMos, so it works for '2004A 4VA25A' phase data; % Store dTE instead of TE if two TE are used, such as fieldmap. % 130724 Add two more ways for dwell time, useful for '2004A 4VA25A' dicom. % 130801 Can't use DERIVED since MoCoSeries may be labeled as DERIVED. % 130807 Check PixelSpacing consistency for a series; % Prepare to publish to Matlab Central. % 130809 Add 5th input for subjName, so one can choose a subject. % 130813 Store ImageComments, if exists and is meaningful, into aux_file. % 130818 Expand source to dicom file(s) and wildcards like run1*.dcm. % Update fields in dcmHeader.mat, rather than overwriting the file. % Include save_nii etc in the code for easy distribution. % 130821 Bug fix for cellstr input as dicom source. % Change file name from dcm2nii.m to reduce confusion from MRICron. % GUI implemented into the single file. % 130823 Remove dependency on Image Processing Toolbox. % 130826 Bug fix for '*' src input. Minor improvement for dicm_hdr. % 130827 Try and suggest to use pigz for compression (thanks Chris R.). % 130905 Avoid the missing-field error for DTI data with 2 excitations. % Protect GUI from command line plotting. % 130912 Use lDelayTimeInTR for slice_dur, possibly useful for old data. % 130916 Store B_matrix for DTI image, if exists. % 130919 Work for GE and Philips dicom at Chris R website. % 130922 Remove dependence on normc from nnet toolbox (thank Zhiwei); % 130923 Work for Philips PAR/REC pair files. % 130926 Take care of non-mosaic DTI for Siemens (img/bval/bvec); % 130930 Use verify_slice_dir subfun to get slice_dir even for a single file. % 131001 dicm_hdr can deal with VR of SQ. This slows down it a little. % 131002 Avoid fullfile for cellstr input (not supported in old matlab). % 131006 Tweak dicm_hdr for multiframe dicom (some bug fixes); % First working version for multiframe (tested with Philips dicom). % 131009 Put dicm_hdr, dicm_img, dicm_dict outside this file; % dicm_hdr can read implicit VR, and is faster with single fread; % Fix problem in gzipOS when folder name contains space. % 131020 Make TR & ProtocolName non-mandatory; Set cal_min & cal_max. % 131021 Implement conversion for AFNI HEAD/BRIK. % 131024 Bug fix for dealing with current folder as src folder. % 131029 Bug fix: Siemens, 2D, non-mosaic, rev-num slices were flipped. % 131105 DTI parameters: field names more consistent across vendors; % Read DTI flds in save_dti_para for GE/Philips (make others faster); % Convert Philips bvec from deg into vector (need to be verified). % 131114 Treak for multiframe dicm_hdr: MUCH faster by using only 1,2,n frames; % Bug fix for Philips multiframe DTI parameters; % Split multiframe Philips B0 map into mag and phase nii. % 131117 Make the order of phase/mag image in Philips B0 map irrelevant. % 131219 Write warning message to a file in data folder (Gui's suggestion). % 140120 Bug fix in save_dti_para due to missing Manufacturer (Thank Paul). % 140121 Allow missing instance at beginning of a series. % 140123 save_nii: bug fix for gzip.m detection, take care of ~ as home dir. % 140206 bug fix: MoCo detetion bug introduced by removing empty cell earlier. % 140223 add missing-file check for Philips data by slice locations. % 140312 use slice timing to set slice_code for both GE and Siemens. % Interleaved order was wrong for GE data with even number of slices. % 140317 Use MosaicRefAcqTimes from last vol for multiband (thank Chris). % Don't re-orient fieldmap, so make FSL happy in case of non_axial. % Ugly fix for wrong dicom item VR 'OB': Avoid using main header % in csa_header(), convert DTI parameters to correct type. % 140319 Store SliceTiming field in dcmHeaders.mat for FSL custom slice timing. % Re-orient even if flipping slices for 2D MRAcquisitionType. % 140324 Not set cal_min, cal_max anymore. % 140327 Return unconverted subject names in 2nd output. % 140401 Always flip image so phase dir is correct. % 140409 Store nii extension (not enabled due to nifti ext issue). % 140501 Fix for GE: use LocationsInAcquisition to replace ImagesInAcquisition; % isDTI=DiffusionDirection>0; Gradient already in image reference. % 140505 Always re-orient DTI. bvec fix for GE DTI (thx Chris). % 140506 Remove last DTI vol if it is computed ADC (as dcm2niix); % Use SeriesDescription to replace ProtocolName for file name; % Improved dim_info and phase direction. % 140512 Decode GE ProtocolDataBlock for phase direction; % strtrim SeriesDescription for nii file name. % 140513 change stored phase direction to image reference for FSL unwarp; % Simplify code for dim_info. % 140516 Switch back to ProtocolName for SIEMENS to take care of MOCO series; % Detect Philips XYTZ (for multi files) during dicom check; % Work for GE interleaved slices even if InstanceNumber is in time order; % Do ImagePositionPatient check for all vendors; % Simplify code for save_dti_para. % 140517 Store img with first dim flipped, to take care of DTI bvec problems. % 140522 Use SliceNormalVector for mosaic slice_dir, so no worry for revNumb; % Bug fix for interleaved descending slice_code. % 140525 xform sliceCenter to SliceLocation in verify_slice_dir. % 140526 Take care of non-unique ixyz. % 140608 Bug fix for GE interleaved slices; % Take care all ixyz, put verify_slice_dir into xform_mat. % 140610 Compute readout time for DTI, rather than dwell time. % 140621 Support tgz file as data source. % 140716 Bug fix due to empty src for GUI subject option. % 140808 Simplify mosaic detection, and remove isMosaic. % 140816 Simplify DTI detection. % 140911 Minor fix for Siemens ProtocolName for error message. % 141016 Remember GUI settings from last conversion; % Make multi-subject error message friendly. % 141023 Get LocationsInAcquisition for GE multiframe dicom. % 141024 Use unique ImagePositionPatient to determine LocationsInAcquisition. % 141028 Use matlabpool if available and worthy. % 141125 Store NumberOfTemporalPositions in dicom header. % 141128 Minor tweaks for Octave 3.8.1 command line (GUI not working). % 141216 Use ImagePositionPatient to derive SliceThickness if possible. % 141217 Override LocationsInAcquisition with computed nSL (thx Luigi); % Check RescaleIntercept and RescaleSlope consistency. % 141218 Allow 1e-4 diff for ImagePositionPatient of same slice location. % 141223 multiFrameFields: return earlier if only single frame (thx Sander); % No re-orient for single slice (otherwise problem for mricron to read). % 141224 mos2vol: use nSL loop (faster unless many slices). % 141229 Save nii ext (ecode=40) if FSL is detected & it is not 5.0.5/5.0.6. % 141230 nojvm: no matlabpool; no dicm_hdr progress due to '\b' issue for WIN. % 150109 dicm_img(s, 0) to follow the update for dicm_img. % 150112 Use nii_tool.m, remove make_nii, save_nii etc from this file. % 150115 Allow SamplesPerPixel>1, but likely not very useful. % 150117 Store seq name in intent_name. % 150119 Add phase img detection for Philips. % 150120 No fieldmap file skip by EchoTime: keep all data by using EchoNumber. % 150209 Add more output format for SPM style: 3D output; % GUI includes SPM 3D, separates GZ option. % 150211 No missing file check for all vendors, relying on ImagePosition check; % csa_header() relies on dicm_hdr decoding (avoid error on old data); % Deal with dim3-RGB and dim4-frames due to dicm_img.m update. % 150222 Remove useless, mis-used TriggerTime for partial hdr; also B_matrix. % 150302 No hardcoded sign change for DTI bvec, except for GE; % set_nii_hdr: do flip only once after permute; % 150303 Bug fix for phPos: result was right by lucky mistake; % Progress shows nii dim, more informative than number of files. % 150305 Replace null with cross: null gives inconsistent signs; % Use SPM method for xform: account for shear; no qform setting if shear. % 150306 GE: fully sort slices by loc to ease bvec sign (test data needed); % bvec sign simplified by above sort & corrected R for Philips/Siemens. % 150309 GUI: added the little popup for 'about/license'. % 150323 Siemens non-mosaic: timing from ucMode, AcquisitionTime(disabled). % 150324 mandatory flds reduced to 5; get info by asc_header if possible; % 150325 Use SeriesInstanceUID to take care of multiple Study and PatientName; % Remove 5th input (subj); GUI updated; subjName in file name if needed; % Deal with MoCo series by output file names; % Convert GLM and DTI junk too; no Manufacturer check in advance. % 150405 Implement BrainVoyager dmr/fmr/vmr conversion; GUI updated accordingly. % 150413 InstanceNumber is not mandatory (now total 4); % Check missing files for non-DTI mosaic by InstanceNumber. % 150418 phaseDirection: bug fix for Philips, simplify for others. % 150423 fix matlabpool for later matlab versions; no auto-close anymore; % GUI figure handle can't be uint32 for matlab 2015; % Turn off saveExt40: FSL 5.0.8 may read vox_offset as 352. % 150430 xform_mat: GE, no LastScanLoc needed since sorted by ImagePosition. % 150508 csa2pos: bug fix for revNum, iSL==1; treat dInPlaneRot specially. % 150514 set_nii_ext: start to store txt edata (ecode=6). % Avoid dict change in dicm_hdr due to vendor change (GE/Philips faster); % 150517 Octave compatibility fix in multiple files. % 150526 multiFrameFields: LocationsInAcquisition by ImagePosition if needed. % 150531 Check slice loc for all volumes to catch missing files (thx CarloR). % 150604 phaseDirection: typo fix for Philips 'RLAPFH'; Show converter version. % 150606 csa_header read both CSA image/series header. % 150609 No t_unit and SliceTiming for DTI. % 150613 mb_slicetiming: try to fix SOME broken multiband slice timing. % 150620 use 'bval' for nii.ext and dcmHeaders.mat, so keep original B_value. % 150910 bug fix for scl_slope/inter: missing double for max/min(nii.img(:)). % 150924 PAR: fix weird SliceNumber; fix mean-ADC removal if not last vol. % 150925 Bug fix for nSL=1 (vol-dim was at slice-dim); % 150926 multiFrameFields: add SliceNumber & simplify code; % save_dti_para: tidy format; try to avoid genvarname. % 150927 Repalce misused length with numel in all files. % 150928 checkImagePosition: skip most irregular spacing. % 150929 Take care of SL order for regular dicom: GE no longer special case. % 150930 Remove slice_dir guess; Use NiftiName for error info. % 151115 GUI: remove srcType; Implement drag&drop for src and dst. % 151117 save_json proposed by ChrisG; won't flush nii_viewer para. % 151212 Bug fix for missing pref_file. % 151217 gui callback uses subfunc directly, also include fh as argument. % 151221 dim_info stores phaseDir at highest 2 bits (1 pos, 2 neg, 0 unknown). % 160110 Implement "Check update" based on findjobj; Preference method updated. % 160112 SeriesInstanceUID & SeriesNumber only need one (thx DavidR). % 160115 checkUpdate: fix problem to download & unzip to pwd. % 160127 dicm_hdr & dicm_img: support big endian dicom. % 160229 flip now makes det<0, instead negative 1st axis (cor slice affected). % 160304 undo some changes on 140808 so it works for syngo 2004 phase masaic. % 160309 nMosaic(): use CSAHeader to detect above unlabeled mosaic. % 160324 nMosaic(): unsecure fix for dicom without CSA header. % 160329 GUI: add link to the JNM paper about dicom to nifti conversion. % 160330 nMosaic(): take care of case of uc2DInterpolation. % 160404 Bug fix: put back nFile<2 continue for series check. % 160405 Remove 4th input arg MoCoOption: always convert all series. % 160405 nMosaic(): get nMos by finding zeros in img. % 160407 remove ang2vec: likely never used and may be wrong. % 160409 multi .m files: use sscanf/strfind/regexp, avoid str2double/strtok. % 160504 asc_header: ignore invalid CSASeriesHeaderInfo in B15 (thx LaureSA). % 160512 get_dti_para: fix bvec sign for GE cor/sag slices (thx paul for data). % 160514 csa2pos: make it safer so it won't err. % 160516 checkImagePosition: assign isTZ for missing files (thx TanH). % 160519 set nii.hdr.slice_duration for MB although it is useless. % 160601 Update ReadoutSeconds, and store it even if ~isDTI. % 160607 Avoid skipping series by ignoring empty-image dicom (thx QR). % 160610 Add pref save_patientName and use_parfor; simplify save_json flag. % 160807 Store InversionTime for nii ext and json. % 160826 Add pref use_seriesUID to take care of missed-up SeriesIntanceUID. % 160829 fix problem with large SeriesNumber; only 3 dicm fields are must. % 160901 Put pref onto GUI. % 160920 Convert series with varying Rescale slope/inter. % 160921 Quick bug fix introduced on 160920: slope/inter applied for 2nd+ files. % 161129 Bug fix for irregular slice order in Philips multiframe dicm. % 161216 xform_mat: only override SliceThickness if it is >1% off. % 161227 Convert a series by ignoring the only inconsistent file; % checkImagePositions(): allow 10% error for gantry tilt (thx Qinwan). % 161229 xform CT img with gantry tilt; add some flds in ext for CT. % 170202 nMosaic(): bug fix for using LocationsInAcquisition. % 170211 implement no_save for nii_viewer: return first nii without saving; % Bug fix: double(val) for fldsCk (needed for Rows and Columns). % 170225 nMosaic: minor fix. % 170320 check_ipp: slice tol = max(diff(sort(ipp)))/100. Thx navot. % 170322 split_philips_phase: bug fix for vol>2. Thx RobertW. % 170403 save_jason: add DelayTime for BIDS. % 170404 set MB slice_code to 0 to avoid FreeSurfer error. Thx JacobM. % 170417 checkUpdate(): use 'user_version' due to Matlab Central web change. % 170625 phaseDirection(): GE VIEWORDER update due to dicm_hdr() update. % 170720 Allow regularly missing InstanceNumbers, like CMRR ISSS. % 170810 Use GE SLICEORDER for SliceTiming if needed (thx PatrickS). % 170826 Use 'VolumeTiming' for missing volumes based on BIDS. % 170923 Correct readout (thx Chris R and MH); Always store readout in descrip; % 170924 Bug fix for long file name (avoid genvarname now). % 170927 Store TE in descrip even if multiple TEs. % 171211 Make it work for Siemens multiframe dicom (seems 3D only). % 180116 Bug fix for EchoTime1 for phase image (thx DylanW) % 180219 json: PhaseEncodingDirection use ijk, fix pf.save_PatientName (thx MichaelD) % 180312 json: ImageType uses BIDS format (thx ChrisR). % 180419 bug fix for long file name (thx NedaK). % 180430 store VolumeTiming from FrameReferenceTime (thx ChrisR). % 180519 get_dti_para: bug fix to remove Philips ADC vol (thx ChrisR). % 180520 Make copy for vida CSA, so asc_header/csa_header faster if non-Siemens. % 180523 set_nii_hdr: use MRScaleSlope for Philips, same as dcm2niiX default. % 180526 split_philips_phase: fix the long time slope/inter bug for phase image; % move some code (eg SliceTiming related) out of main function. % 180527 fix vida SliceTiming unit, but now turn it off, and rely on ucMode. % 180530 store EchoTimes and CardiacTriggerDelayTimes; % split_components: not only phase, json for each file (thx ChrisR). % 180601 use SortFrames for multiframe and PAR (thx JulienB & ChrisR); % 180602 extract sort_frames() for multiFrameFields() and philips_par() % 180605 multiFrameFields: B=0 to first vol. % 180614 Implement scale_16bit: free precision for tools using 16-bit datatype. % 180619 use GetFullPath from Jan: (thx JulienB). % 180721 accept mixture of files and folders as input; GUI uses jFileChooser(). % 180914 support UIH dicm, both GRID (mosaic) and regular. % 180922 fix for UIH masaic -1 col; GE phPos from dcm2niix. % 190122 add BIDS support. [email protected] % TODO: need testing files to figure out following parameters: % flag for MOCO series for GE/Philips % GE non-axial slice (phase: ROW) bvec sign % Phase image flag for GE if nargout, varargout{1} = ''; end if nargin==3 && ischar(fmt) && strcmp(fmt, 'func_handle') % special purpose varargout{1} = str2func(niiFolder); return; end %% Deal with output format first, and error out if invalid if nargin<3 || isempty(fmt), fmt = 1; end % default .nii.gz no_save = ischar(fmt) && strcmp(fmt, 'no_save'); if no_save, fmt = 'nii'; end bids = false; if ischar(fmt) && strcmpi(fmt,'BIDS') bids = true; fmt = '.nii.gz'; end if ischar(fmt) && strcmpi(fmt,'BIDSNII') bids = true; fmt = '.nii'; end if bids && verLessThan('matlab','9.4') fprintf('BIDS conversion requires MATLAB R2018a or more. return.') end if (isnumeric(fmt) && any(fmt==[0 1 4 5])) || ... (ischar(fmt) && ~isempty(regexpi(fmt, 'nii'))) ext = '.nii'; elseif (isnumeric(fmt) && any(fmt==[2 3 6 7])) || (ischar(fmt) && ... (~isempty(regexpi(fmt, 'hdr')) || ~isempty(regexpi(fmt, 'img')))) ext = '.img'; else error(' Invalid output file format (the 3rd input).'); end if (isnumeric(fmt) && mod(fmt,2)) || (ischar(fmt) && ~isempty(regexpi(fmt, '.gz'))) ext = [ext '.gz']; % gzip file end rst3D = (isnumeric(fmt) && fmt>3) || (ischar(fmt) && ~isempty(regexpi(fmt, '3D'))); if nargin<1 || isempty(src) || (nargin<2 || isempty(niiFolder)) create_gui; % show GUI if input is not enough return; end %% Deal with niiFolder if ~isdir(niiFolder), mkdir(niiFolder); end niiFolder = [GetFullPath(niiFolder) filesep]; converter = ['dicm2nii.m ' getVersion]; if errorLog('', niiFolder) && ~no_save % remember niiFolder for later call more off; disp(['Xiangrui Li''s ' converter ' (feedback to [email protected])']); end %% Deal with data source tic; if isnumeric(src) error('Invalid dicom source.'); elseif iscellstr(src) % multiple files/folders fnames = {}; for i = 1:numel(src) if isdir(src{i}) fnames = [fnames filesInDir(src{i})]; else a = dir(src{i}); if isempty(a), continue; end dcmFolder = fileparts(GetFullPath(src{i})); fnames = [fnames fullfile(dcmFolder, a.name)]; end end elseif isdir(src) % folder fnames = filesInDir(src); elseif ~exist(src, 'file') % like input: run1*.dcm fnames = dir(src); if isempty(fnames), error('%s does not exist.', src); end fnames([fnames.isdir]) = []; dcmFolder = filepars(GetFullPath(src)); fnames = strcat(dcmFolder, filesep, {fnames.name}); elseif ischar(src) % 1 dicom or zip/tgz file dcmFolder = fileparts(GetFullPath(src)); unzip_cmd = compress_func(src); if isempty(unzip_cmd) fnames = dir(src); fnames = strcat(dcmFolder, filesep, {fnames.name}); else % unzip if compressed file is the source [~, fname, ext1] = fileparts(src); dcmFolder = sprintf('%stmpDcm%s/', niiFolder, fname); if ~isdir(dcmFolder) mkdir(dcmFolder); delTmpDir = onCleanup(@() rmdir(dcmFolder, 's')); end disp(['Extracting files from ' fname ext1 ' ...']); if strcmp(unzip_cmd, 'unzip') cmd = sprintf('unzip -qq -o %s -d %s', src, dcmFolder); err = system(cmd); % first try system unzip if err, unzip(src, dcmFolder); end % Matlab's unzip is too slow elseif strcmp(unzip_cmd, 'untar') if isempty(which('untar')) error('No untar found in matlab path.'); end untar(src, dcmFolder); end fnames = filesInDir(dcmFolder); end else error('Unknown dicom source.'); end nFile = numel(fnames); if nFile<1, error(' No files found in the data source.'); end %% user preference pf.save_patientName = getpref('dicm2nii_gui_para', 'save_patientName', true); pf.save_json = getpref('dicm2nii_gui_para', 'save_json', false); pf.use_parfor = false; % getpref('dicm2nii_gui_para', 'use_parfor', true); pf.use_seriesUID = getpref('dicm2nii_gui_para', 'use_seriesUID', true); pf.lefthand = getpref('dicm2nii_gui_para', 'lefthand', true); pf.scale_16bit = getpref('dicm2nii_gui_para', 'scale_16bit', false); %% Parsing out varargin (optional input) if there is any: added by Wani, 10/2/2017 addtask = false; for i = 1:length(varargin) if ischar(varargin{i}) switch varargin{i} case 'save_json' pf.save_json = true; case 'taskname' addtask = true; taskname = varargin{i+1}; case 'use_parfor' pf.use_parfor = true; end end end %% Check each file, store partial header in cell array hh % first 2 fields are must. First 10 indexed in code flds = {'Columns' 'Rows' 'BitsAllocated' 'SeriesInstanceUID' 'SeriesNumber' ... 'ImageOrientationPatient' 'ImagePositionPatient' 'PixelSpacing' ... 'SliceThickness' 'SpacingBetweenSlices' ... % these 10 indexed in code 'PixelRepresentation' 'BitsStored' 'HighBit' 'SamplesPerPixel' ... 'PlanarConfiguration' 'EchoTime' 'RescaleIntercept' 'RescaleSlope' ... 'InstanceNumber' 'NumberOfFrames' 'B_value' 'DiffusionGradientDirection' ... 'RTIA_timer' 'RBMoCoTrans' 'RBMoCoRot' 'AcquisitionNumber'}; dict = dicm_dict('SIEMENS', flds); % dicm_hdr will update vendor if needed % read header for all files, use parpool if available and worthy if ~no_save, fprintf('Validating %g files ...\n', nFile); end hh = cell(1, nFile); errStr = cell(1, nFile); doParFor = pf.use_parfor && nFile>2000 && useParTool; for k = 1:nFile [hh{k}, errStr{k}, dict] = dicm_hdr(fnames{k}, dict); if doParFor && ~isempty(hh{k}) % parfor wont allow updating dict parfor i = k+1:nFile [hh{i}, errStr{i}] = dicm_hdr(fnames{i}, dict); end break; end end %% sort headers into cell h by SeriesInstanceUID, EchoTime and InstanceNumber h = {}; % in case of no dicom files at all errInfo = ''; seriesUIDs = {}; ETs = {}; for k = 1:nFile s = hh{k}; if isempty(s) || any(~isfield(s, flds(1:2))) || ~isfield(s, 'PixelData') ... || (isstruct(s.PixelData) && s.PixelData.Bytes<1) if ~isempty(errStr{k}) % && isempty(strfind(errInfo, errStr{k})) errInfo = sprintf('%s\n%s\n', errInfo, errStr{k}); end continue; % skip the file end if isfield(s, flds{4}) && (pf.use_seriesUID || ~isfield(s, 'SeriesNumber')) sUID = s.SeriesInstanceUID; else if isfield(s, 'SeriesNumber'), sN = s.SeriesNumber; else, sN = fix(toc*1e6); end sUID = num2str(sN); % make up UID if isfield(s, 'SeriesDescription') sUID = [s.SeriesDescription sUID]; end end m = find(strcmp(sUID, seriesUIDs)); if isempty(m) m = numel(seriesUIDs)+1; seriesUIDs{m} = sUID; ETs{m} = []; end % EchoTime is needed for Siemens fieldmap mag series et = tryGetField(s, 'EchoTime'); if isempty(et), i = 1; else i = find(et == ETs{m}); % strict equal? if isempty(i) i = numel(ETs{m}) + 1; ETs{m}(i) = et; if i>1 [ETs{m}, ind] = sort(ETs{m}); i = find(et == ETs{m}); h{m}{end+1}{1} = []; h{m} = h{m}(ind); end end end j = tryGetField(s, 'InstanceNumber'); if isempty(j) || j<1 try j = numel(h{m}{i}) + 1; catch, j = 1; end end h{m}{i}{j} = s; % sort partial header end clear hh errStr; %% Check headers: remove dim-inconsistent series nRun = numel(h); if nRun<1 % no valid series errorLog(sprintf('No valid files found:\n%s.', errInfo)); return; end keep = true(1, nRun); % true for useful runs subjs = cell(1, nRun); vendor = cell(1, nRun); sNs = ones(1, nRun); studyIDs = cell(1, nRun); fldsCk = {'ImageOrientationPatient' 'NumberOfFrames' 'Columns' 'Rows' ... 'PixelSpacing' 'RescaleIntercept' 'RescaleSlope' 'SamplesPerPixel' ... 'SpacingBetweenSlices' 'SliceThickness'}; % last for thickness for i = 1:nRun h{i} = [h{i}{:}]; % concatenate different EchoTime ind = cellfun(@isempty, h{i}); h{i}(ind) = []; % remove all empty cell for all vendors s = h{i}{1}; if ~isfield(s, 'LastFile') % avoid re-read for PAR/HEAD/BV file s = dicm_hdr(s.Filename); % full header for 1st file end if ~isfield(s, 'Manufacturer'), s.Manufacturer = 'Unknown'; end subjs{i} = PatientName(s); vendor{i} = s.Manufacturer; if isfield(s, 'SeriesNumber'), sNs(i) = s.SeriesNumber; else, sNs(i) = fix(toc*1e6); end studyIDs{i} = tryGetField(s, 'StudyID', '1'); series = sprintf('Subject %s, %s (Series %g)', subjs{i}, ProtocolName(s), sNs(i)); s = multiFrameFields(s); % no-op if non multi-frame if isempty(s), keep(i) = 0; continue; end % invalid multiframe series s.isDTI = isDTI(s); if ~isfield(s, 'AcquisitionDateTime') % assumption: 1st instance is earliest try s.AcquisitionDateTime = [s.AcquisitionDate s.AcquisitionTime]; end end h{i}{1} = s; % update record in case of full hdr or multiframe nFile = numel(h{i}); if nFile>1 && tryGetField(s, 'NumberOfFrames', 1) > 1 % seen in vida for k = 2:nFile % this can be slow h{i}{k} = dicm_hdr(h{i}{k}.Filename); % full header h{i}{k} = multiFrameFields(h{i}{k}); end if ~isfield(s, 'EchoTimes') && isfield(s, 'EchoTime') h{i}{1}.EchoTimes = nan(1, nFile); for k = 1:nFile, h{i}{1}.EchoTimes(k) = h{i}{k}.EchoTime; end end end % check consistency in 'fldsCk' nFlds = numel(fldsCk); if isfield(s, 'SpacingBetweenSlices'), nFlds = nFlds - 1; end % check 1 of 2 for k = 1:nFlds*(nFile>1) if isfield(s, fldsCk{k}), val = s.(fldsCk{k}); else, continue; end val = repmat(double(val), [1 nFile]); for j = 2:nFile if isfield(h{i}{j}, fldsCk{k}), val(:,j) = h{i}{j}.(fldsCk{k}); else, keep(i) = 0; break; end end if ~keep(i), break; end % skip silently ind = any(abs(bsxfun(@minus, val, val(:,1))) > 1e-4, 1); if sum(ind)>1 % try 2nd, in case only 1st is inconsistent ind = any(abs(bsxfun(@minus, val, val(:,2))) > 1e-4, 1); end if ~any(ind), continue; end % good if any(strcmp(fldsCk{k}, {'RescaleIntercept' 'RescaleSlope'})) h{i}{1}.ApplyRescale = true; continue; end if numel(ind)>2 && sum(ind)==1 % 2+ files but only 1 inconsistent h{i}(ind) = []; % remove first or last, but keep the series nFile = nFile - 1; if ind(1) % re-do full header for new 1st file s = dicm_hdr(h{i}{1}.Filename); s.isDTI = isDTI(s); h{i}{1} = s; end else errorLog(['Inconsistent ''' fldsCk{k} ''' for ' series '. Series skipped.']); keep(i) = 0; break; end end nSL = nMosaic(s); % nSL>1 for mosaic if ~isempty(nSL) && nSL>1 h{i}{1}.isMos = true; h{i}{1}.LocationsInAcquisition = nSL; if s.isDTI, continue; end % allow missing directions for DTI a = zeros(1, nFile); for j = 1:nFile, a(j) = tryGetField(h{i}{j}, 'InstanceNumber', 1); end if any(diff(a) ~= 1) % like CMRR ISSS seq or multi echo. Error for UIH errorLog(['InstanceNumber discontinuity detected for ' series '.' ... 'See VolumeTiming in NIfTI ext or dcmHeaders.mat.']); dict = dicm_dict('', {'AcquisitionDate' 'AcquisitionTime'}); vTime = nan(1, nFile); for j = 1:nFile s2 = dicm_hdr(h{i}{j}.Filename, dict); dt = [s2.AcquisitionDate s2.AcquisitionTime]; vTime(j) = datenum(dt, 'yyyymmddHHMMSS.fff'); end vTime = vTime - min(vTime); h{i}{1}.VolumeTiming = vTime * 86400; % day to seconds end continue; % no other check for mosaic end if ~keep(i) || nFile<2 || ~isfield(s, 'ImagePositionPatient'), continue; end if tryGetField(s, 'NumberOfFrames', 1) > 1, continue; end % Siemens Vida ipp = zeros(nFile, 1); iSL = xform_mat(s); iSL = iSL(3); for j = 1:nFile, ipp(j,:) = h{i}{j}.ImagePositionPatient(iSL); end gantryTilt = abs(tryGetField(s, 'GantryDetectorTilt', 0)) > 0.1; [err, nSL, sliceN, isTZ] = checkImagePosition(ipp, gantryTilt); if ~isempty(err) errorLog([err ' for ' series '. Series skipped.']); keep(i) = 0; continue; % skip end h{i}{1}.LocationsInAcquisition = uint16(nSL); % best way for nSL? nVol = nFile / nSL; if isTZ % Philips ind = reshape(1:nFile, [nVol nSL])'; h{i} = h{i}(ind(:)); end % re-order slices within vol. No SliceNumber since files are organized if all(diff(sliceN, 2) == 0), continue; end % either 1:nSL or nSL:-1:1 if sliceN(end) == 1, sliceN = sliceN(nSL:-1:1); end % not important inc = repmat((0:nVol-1)*nSL, nSL, 1); ind = repmat(sliceN(:), nVol, 1) + inc(:); h{i} = h{i}(ind); % sorted by slice locations if sliceN(1) == 1, continue; end % first file kept: following update h{i}{1} h{i}{1} = dicm_hdr(h{i}{1}.Filename); % read full hdr s = h{i}{sliceN==1}; % original first file fldsCp = {'AcquisitionDateTime' 'isDTI' 'LocationsInAcquisition'}; for j = 1:numel(fldsCp) if isfield(h{i}{1}, fldsCk{k}), h{i}{1}.(fldsCp{j}) = s.(fldsCp{j}); end end end h = h(keep); sNs = sNs(keep); studyIDs = studyIDs(keep); subjs = subjs(keep); vendor = vendor(keep); %% sort h by PatientName, then StudyID, then SeriesNumber % Also get correct order for subjs/studyIDs/nStudy/sNs for nii file names [subjs, ind] = sort(subjs); subj = unique(subjs); h = h(ind); sNs = sNs(ind); studyIDs = studyIDs(ind); % by subjs now nStudy = ones(1, nRun); % one for each series for i = 1:numel(subj) iSub = find(strcmp(subj{i}, subjs)); study = studyIDs(iSub); [study, iStudy] = sort(study); % by study for each subject a = h(iSub); h(iSub) = a(iStudy); a = sNs(iSub); sNs(iSub) = a(iStudy); studyIDs(iSub) = study; % done for h/sNs/studyIDs by studyIDs for a subj uID = unique(study); nStudy(iSub) = numel(uID); for k = 1:numel(uID) % now sort h/sNs by sNs for each studyID iStudy = strcmp(uID{k}, study); ind = iSub(iStudy); [sNs(ind), iSN] = sort(sNs(ind)); a = h(ind); h(ind) = a(iSN); end end %% Generate unique result file names % Unique names are in format of SeriesDescription_s007. Special cases are: % for phase image, such as field_map phase, append '_phase' to the name; % for MoCo series, append '_MoCo' to the name if both series are present. % for multiple subjs, it is SeriesDescription_subj_s007 % for multiple Study, it is SeriesDescription_subj_Study1_s007 nRun = numel(h); % update it, since we have removed some if nRun<1 errorLog('No valid series found'); return; end rNames = cell(1, nRun); multiSubj = numel(subj)>1; j_s = nan(nRun, 1); % index-1 for _s003. needed if 4+ length SeriesNumbers maxLen = namelengthmax - 3; for i = 1:nRun s = h{i}{1}; sN = sNs(i); a = strtrim(ProtocolName(s)); if isPhase(s), a = [a '_phase']; end % phase image if i>1 && sN-sNs(i-1)==1 && isType(s, '\MOCO\'), a = [a '_MoCo']; end if multiSubj, a = [a '_' subjs{i}]; end if nStudy(i)>1, a = [a '_Study' studyIDs{i}]; end if ~isstrprop(a(1), 'alpha'), a = ['x' a]; end % genvarname behavior a(~isstrprop(a, 'alphanum')) = '_'; % make str valid for field name a = regexprep(a, '_{2,}', '_'); % remove repeated underscore if sN>100 && strncmp(s.Manufacturer, 'Philips', 7) sN = tryGetField(s, 'AcquisitionNumber', floor(sN/100)); end j_s(i) = numel(a); rNames{i} = sprintf('%s_s%03.0f', a, sN); d = numel(rNames{i}) - maxLen; if d>0, rNames{i}(j_s(i)+(-d+1:0)) = ''; j_s(i) = j_s(i)-d; end % keep _s007 end vendor = strtok(unique(vendor)); if nargout>0, varargout{1} = subj; end % return converted subject IDs % After following sort, we need to compare only neighboring names. Remove % _s007 if there is no conflict. Have to ignore letter case for Windows & MAC fnames = rNames; % copy it, reserve letter cases [rNames, iRuns] = sort(lower(fnames)); j_s = j_s(iRuns); for i = 1:nRun if i>1 && strcmp(rNames{i}, rNames{i-1}) % truncated StudyID to PatientName a = num2str(i); rNames{i}(j_s(i)+(-numel(a)+1:0)) = a; % not 100% unique end a = rNames{i}(1:j_s(i)); % remove _s003 % no conflict with both previous and next name if nRun==1 || ... % only one run (i==1 && ~strcmpi(a, rNames{2}(1:j_s(2)))) || ... % first (i==nRun && ~strcmpi(a, rNames{i-1}(1:j_s(i-1)))) || ... % last (i>1 && i<nRun && ~strcmpi(a, rNames{i-1}(1:j_s(i-1))) ... && ~strcmpi(a, rNames{i+1}(1:j_s(i+1)))) % middle ones fnames{iRuns(i)}(j_s(i)+1:end) = []; end end if numel(unique(fnames)) < nRun % may happen to user-modified dicom/par fnames = matlab.lang.makeUniqueStrings(fnames); % since R2014a end fmtStr = sprintf(' %%-%gs %%dx%%dx%%dx%%d\n', max(cellfun(@numel, fnames))+12); %% Now ready to convert nii series by series subjStr = sprintf('''%s'', ', subj{:}); subjStr(end+(-1:0)) = []; vendor = sprintf('%s, ', vendor{:}); vendor(end+(-1:0)) = []; if ~no_save fprintf('Converting %g series (%s) into %g-D %s: subject %s\n', ... nRun, vendor, 4-rst3D, ext, subjStr); end %% Parse BIDS if bids if multiSubj fprintf('Multiple subjects detected!!!!! Skipping...\nPlease convert subjects one by one with BIDS options\n') fprintf('%s\n',subj{:}) return; end % Table: subject Name try asciiInds=[1:47 58:64 91:96 123:127]; for j=1:numel(asciiInds) subj=strrep(subj,char(asciiInds(j)),''); end Subject = subj; catch Subject = {'01'}; end Session = {'01'}; S = table(Subject,Session); % Table: Type/Modality valueset = {'skip','skip'; 'anat','T1w'; 'anat','T2w'; 'anat','T1rho'; 'anat','T1map'; 'anat','T2map'; 'anat','T2star'; 'anat','FLAIR'; 'anat','FLASH'; 'anat','PD'; 'anat','PDmap'; 'dwi' ,'dwi'; 'fmap','phasediff'; 'fmap','phase1'; 'fmap','phase2'; 'fmap','magnitude1'; 'fmap','magnitude2'; 'fmap','fieldmap'}; Modality = categorical(repmat({'skip'},[length(fnames),1]),valueset(:,2)); Type = categorical(repmat({'skip'},[length(fnames),1]),unique(valueset(:,1))); Name = fnames'; T = table(Name,Type,Modality); ModalityTablePref = getpref('dicm2nii_gui_para', 'ModalityTable', T); for i = 1:nRun match = strcmp(T{i,1},ModalityTablePref{:,1}); if any(match) T{i,2:3} = ModalityTablePref{match,2:3}; end end % GUI scrSz = get(0, 'ScreenSize'); clr = [1 1 1]*206/256; hf = uifigure('bids' * 256.^(0:3)','Position',[min(scrSz(4)+420,620) scrSz(4)-600 420 300],'Color', clr); set(hf,'Name', 'dicm2nii - BIDS Converter', 'NumberTitle', 'off') % tables TS = uitable(hf,'Data',S,'Position',[20 hf.Position(4)-110 hf.Position(3)-160 90]); TT = uitable(hf,'Data',T,'Position',[20 20 hf.Position(3)-160 hf.Position(4)-120]); TS.ColumnEditable = [true true]; TT.ColumnEditable = [false true true]; setappdata(0,'ModalityTable',TT.Data) setappdata(0,'SubjectTable',TS.Data) % button B = uibutton(hf,'Position',[hf.Position(3)-120 20 100 30]); B.Text = 'OK'; B.ButtonPushedFcn = @(btn,event) BtnModalityTable(hf,TT, TS); waitfor(hf); % get results ModalityTable = getappdata(0,'ModalityTable'); SubjectTable = getappdata(0,'SubjectTable'); % setpref ModalityTableSavePref = ModalityTable(~any(ismember(ModalityTable{:,2:3},'skip'),2),:); for imod = 1:size(ModalityTableSavePref,1) match = strcmp(ModalityTableSavePref{imod,1},ModalityTablePref{:,1}); if any(match) % replace old pref ModalityTablePref{match,2:3} = ModalityTableSavePref{imod,2:3}; else % append new pref ModalityTablePref{end+1,1} = ModalityTableSavePref{imod,1}; ModalityTablePref{end,2:3} = ModalityTableSavePref{imod,2:3}; end end setpref('dicm2nii_gui_para', 'ModalityTable', ModalityTablePref); end %% Convert for i = 1:nRun if bids if any(ismember(ModalityTable{i,2:3},'skip')), continue; end if isempty(char(SubjectTable{1,2})) % no session ses = ''; else ses = ['ses-' char(SubjectTable{1,2})]; end % folder modalityfolder = fullfile(['sub-' char(SubjectTable{1,1})],... ses,... char(ModalityTable{i,2})); mkdir(fullfile(niiFolder, modalityfolder)); % filename fnames{i} = fullfile(modalityfolder,... ['sub-' char(SubjectTable{1,1}) '_' ses '_' char(ModalityTable{i,3})]); fnames{i} = strrep(fnames{i},'__','_'); end nFile = numel(h{i}); h{i}{1}.NiftiName = fnames{i}; % for convenience of error info s = h{i}{1}; if nFile>1 && ~isfield(s, 'LastFile') h{i}{1}.LastFile = h{i}{nFile}; % store partial last header into 1st end for j = 1:nFile if j==1 img = dicm_img(s, 0); % initialize img with dicm data type if ndims(img)>4 % err out, likely won't work for other series error('Image with 5 or more dim not supported: %s', s.NiftiName); end applyRescale = tryGetField(s, 'ApplyRescale', false); if applyRescale, img = single(img); end else if j==2, img(:,:,:,:,nFile) = 0; end % pre-allocate for speed img(:,:,:,:,j) = dicm_img(h{i}{j}, 0); end if applyRescale slope = tryGetField(h{i}{j}, 'RescaleSlope', 1); inter = tryGetField(h{i}{j}, 'RescaleIntercept', 0); img(:,:,:,:,j) = img(:,:,:,:,j) * slope + inter; end end if strcmpi(tryGetField(s, 'DataRepresentation', ''), 'COMPLEX') img = complex(img(:,:,:,1:2:end,:), img(:,:,:,2:2:end,:)); end [~, ~, d3, d4, ~] = size(img); if strcmpi(tryGetField(s, 'SignalDomainColumns', ''), 'TIME') % no permute elseif d3<2 && d4<2, img = permute(img, [1 2 5 3 4]); % remove dim3,4 elseif d4<2, img = permute(img, [1:3 5 4]); % remove dim4: Frames elseif d3<2, img = permute(img, [1 2 4 5 3]); % remove dim3: RGB end nSL = double(tryGetField(s, 'LocationsInAcquisition')); if tryGetField(s, 'SamplesPerPixel', 1) > 1 % color image img = permute(img, [1 2 4:8 3]); % put RGB into dim8 for nii_tool elseif tryGetField(s, 'isMos', false) % mosaic img = mos2vol(img, nSL, strncmpi(s.Manufacturer, 'UIH', 3)); elseif ndims(img)==3 && ~isempty(nSL) % may need to reshape to 4D if isfield(s, 'SortFrames'), img = img(:,:,s.SortFrames); end dim = size(img); dim(3:4) = [nSL dim(3)/nSL]; % verified integer earlier img = reshape(img, dim); end if any(~isfield(s, flds(6:8))) || ~any(isfield(s, flds(9:10))) h{i}{1} = csa2pos(h{i}{1}, size(img,3)); end if isa(img, 'uint16') && max(img(:))<32768 img = int16(img); % use int16 if lossless end h{i}{1}.ConversionSoftware = converter; nii = nii_tool('init', img); % create nii struct based on img [nii, h{i}] = set_nii_hdr(nii, h{i}, pf); % set most nii hdr % Save bval and bvec files after bvec perm/sign adjusted in set_nii_hdr fname = fullfile(niiFolder,fnames{i}); % name without ext if s.isDTI && ~no_save, save_dti_para(h{i}{1}, fname); end nii = split_components(nii, h{i}{1}); % split Philips vol components if no_save % only return the first nii nii(1).hdr.file_name = [fnames{i} '_no_save.nii']; nii(1).hdr.magic = 'n+1'; varargout{1} = nii_tool('update', nii(1)); if nRun>1, fprintf(2, 'Only one series is converted.\n'); end return; end for j = 1:numel(nii) nam = fnames{i}; if numel(nii)>1, nam = nii(j).hdr.file_name; end fprintf(fmtStr, nam, nii(j).hdr.dim(2:5)); nii(j).ext = set_nii_ext(nii(j).json); % NIfTI extension if addtask, nii(j).json.TaskName = taskname; end % *** Modified for cocoanlab *** if pf.save_json, save_json(nii(j).json, fname); end % *** Modified for cocoanlab *** nii_tool('save', nii(j), fullfile(niiFolder,[nam ext]), rst3D); end if isfield(nii(1).hdr, 'hdrTilt') nii = nii_xform(nii(1), nii.hdr.hdrTilt); fprintf(fmtStr, [fnames{i} '_Tilt'], nii.hdr.dim(2:5)); nii_tool('save', nii, fullfile(fname, ['_Tilt' ext]), rst3D); % save xformed nii end h{i} = h{i}{1}; % keep 1st dicm header only if isnumeric(h{i}.PixelData), h{i} = rmfield(h{i}, 'PixelData'); end % BV end if ~bids h = cell2struct(h, fnames, 2); % convert into struct fname = [niiFolder 'dcmHeaders.mat']; if exist(fname, 'file') % if file exists, we update fields only S = load(fname); for i = 1:numel(fnames), S.h.(fnames{i}) = h.(fnames{i}); end h = S.h; end save(fname, 'h', '-v7'); % -v7 better compatibility else rmappdata(0,'ModalityTable'); rmappdata(0,'SubjectTable'); end fprintf('Elapsed time by dicm2nii is %.1f seconds\n\n', toc); return; %% Subfunction: return PatientName function subj = PatientName(s) subj = tryGetField(s, 'PatientName'); if isempty(subj), subj = tryGetField(s, 'PatientID', 'Anonymous'); end %% Subfunction: return SeriesDescription function name = ProtocolName(s) name = tryGetField(s, 'SeriesDescription'); if isempty(name) || (strncmp(s.Manufacturer, 'SIEMENS', 7) && any(regexp(name, 'MoCoSeries$'))) name = tryGetField(s, 'ProtocolName'); end if isempty(name), [~, name] = fileparts(s.Filename); end %% Subfunction: return true if keyword is in s.ImageType function tf = isType(s, keyword) typ = tryGetField(s, 'ImageType', ''); tf = ~isempty(strfind(typ, keyword)); %#ok<*STREMP> %% Subfunction: return true if series is DTI function tf = isDTI(s) tf = isType(s, '\DIFFUSION'); % Siemens, Philips if tf, return; end if isfield(s, 'ProtocolDataBlock') % GE, not labeled as \DIFFISION IOPT = tryGetField(s.ProtocolDataBlock, 'IOPT'); if isempty(IOPT), tf = tryGetField(s, 'DiffusionDirection', 0)>0; else, tf = ~isempty(regexp(IOPT, 'DIFF', 'once')); end elseif strncmpi(s.Manufacturer, 'Philips', 7) tf = strcmp(tryGetField(s, 'MRSeriesDiffusion', 'N'), 'Y'); elseif isfield(s, 'ApplicationCategory') % UIH tf = ~isempty(regexp(s.ApplicationCategory, 'DTI', 'once')); elseif isfield(s, 'AcquisitionContrast') % Bruker tf = ~isempty(regexpi(s.AcquisitionContrast, 'DIFF', 'once')); else % Some Siemens DTI are not labeled as \DIFFUSION tf = ~isempty(csa_header(s, 'B_value')); end %% Subfunction: return true if series is phase img function tf = isPhase(s) tf = isType(s, '\P\') || ... strcmpi(tryGetField(s, 'ComplexImageComponent', ''), 'PHASE'); % Philips %% Subfunction: get field if exist, return default value otherwise function val = tryGetField(s, field, dftVal) if isfield(s, field), val = s.(field); elseif nargin>2, val = dftVal; else, val = []; end %% Subfunction: Set most nii header and re-orient img function [nii, h] = set_nii_hdr(nii, h, pf) dim = nii.hdr.dim(2:4); nVol = nii.hdr.dim(5); fld = 'NumberOfTemporalPositions'; if ~isfield(h{1}, fld) && nVol>1, h{1}.(fld) = nVol; end % Transformation matrix: most important feature for nii [ixyz, R, pixdim, xyz_unit] = xform_mat(h{1}, dim); % R: dicom xform matrix R(1:2,:) = -R(1:2,:); % dicom LPS to nifti RAS, xform matrix before reorient % Compute bval & bvec in image reference for DTI series before reorienting if h{1}.isDTI, [h, nii] = get_dti_para(h, nii); end % Store CardiacTriggerDelayTime fld = 'CardiacTriggerDelayTime'; if ~isfield(h{1}, 'CardiacTriggerDelayTimes') && nVol>1 && isfield(h{1}, fld) if numel(h) == 1 % multi frames iFrames = 1:dim(3):dim(3)*nVol; if isfield(h{1}, 'SortFrames'), iFrames = h{1}.SortFrames(iFrames); end s2 = struct(fld, nan(1,nVol)); s2 = dicm_hdr(h{1}, s2, iFrames); tt = s2.(fld); else tt = zeros(1, nVol); inc = numel(h) / nVol; for j = 1:nVol tt(j) = tryGetField(h{(j-1)*inc+1}, fld, 0); end end if ~all(diff(tt)==0), h{1}.CardiacTriggerDelayTimes = tt; end end % Get EchoTime for each vol if ~isfield(h{1}, 'EchoTimes') && nVol>1 && isfield(h{1}, 'EchoTime') if numel(h) == 1 % 4D multi frames iFrames = 1:dim(3):dim(3)*nVol; if isfield(h{1}, 'SortFrames'), iFrames = h{1}.SortFrames(iFrames); end s2 = struct('EffectiveEchoTime', nan(1,nVol)); s2 = dicm_hdr(h{1}, s2, iFrames); ETs = s2.EffectiveEchoTime; else % regular dicom. Vida done previously ETs = zeros(1, nVol); inc = numel(h) / nVol; for j = 1:nVol ETs(j) = tryGetField(h{(j-1)*inc+1}, 'EchoTime', 0); end end if ~all(diff(ETs)==0), h{1}.EchoTimes = ETs; end end % set TR and slice timing related info before re-orient [h, nii.hdr] = sliceTiming(h, nii.hdr); nii.hdr.xyzt_units = xyz_unit + nii.hdr.xyzt_units; % normally: mm (2) + sec (8) s = h{1}; % Store motion parameters for MoCo series if all(isfield(s, {'RBMoCoTrans' 'RBMoCoRot'})) && nVol>1 inc = numel(h) / nVol; trans = zeros(nVol, 3); rotat = zeros(nVol, 3); for j = 1:nVol trans(j,:) = tryGetField(h{(j-1)*inc+1}, 'RBMoCoTrans', [0 0 0]); rotat(j,:) = tryGetField(h{(j-1)*inc+1}, 'RBMoCoRot', [0 0 0]); end s.RBMoCoTrans = trans; s.RBMoCoRot = rotat; end % Store FrameReferenceTime: seen in Philips PET if isfield(s, 'FrameReferenceTime') && nVol>1 inc = numel(h) / nVol; vTime = zeros(1, nVol); dict = dicm_dict('', 'FrameReferenceTime'); for j = 1:nVol s2 = dicm_hdr(h{(j-1)*inc+1}.Filename, dict); vTime(j) = tryGetField(s2, 'FrameReferenceTime', 0); end if vTime(1) > vTime(end) % could also re-read sorted h{i}{1} vTime = flip(vTime); nii.img = flip(nii.img, 4); end s.VolumeTiming = vTime / 1000; % ms to seconds end % dim_info byte: freq_dim, phase_dim, slice_dim low to high, each 2 bits [phPos, iPhase] = phaseDirection(s); % phPos relative to image in FSL feat! if iPhase == 2, fps_bits = [1 4 16]; elseif iPhase == 1, fps_bits = [4 1 16]; else, fps_bits = [0 0 16]; end % Reorient if MRAcquisitionType==3D || isDTI && nSL>1 % If FSL etc can read dim_info for STC, we can always reorient. [~, perm] = sort(ixyz); % may permute 3 dimensions in this order if (strcmp(tryGetField(s, 'MRAcquisitionType', ''), '3D') || s.isDTI) && ... dim(3)>1 && (~isequal(perm, 1:3)) % skip if already XYZ order R(:, 1:3) = R(:, perm); % xform matrix after perm fps_bits = fps_bits(perm); ixyz = ixyz(perm); % 1:3 after perm dim = dim(perm); pixdim = pixdim(perm); nii.hdr.dim(2:4) = dim; nii.img = permute(nii.img, [perm 4:8]); if isfield(s, 'bvec'), s.bvec = s.bvec(:, perm); end end iSL = find(fps_bits==16); iPhase = find(fps_bits==4); % axis index for phase_dim in re-oriented img nii.hdr.dim_info = (1:3) * fps_bits'; % useful for EPI only nii.hdr.pixdim(2:4) = pixdim; % voxel zize flp = R(ixyz+[0 3 6])<0; % flip an axis if true d = det(R(:,1:3)) * prod(1-flp*2); % det after all 3 axis positive if (d>0 && pf.lefthand) || (d<0 && ~pf.lefthand) flp(1) = ~flp(1); % left or right storage end rotM = diag([1-flp*2 1]); % 1 or -1 on diagnal rotM(1:3, 4) = (dim-1) .* flp; % 0 or dim-1 R = R / rotM; % xform matrix after flip for k = 1:3, if flp(k), nii.img = flip(nii.img, k); end; end if flp(iPhase), phPos = ~phPos; end if isfield(s, 'bvec'), s.bvec(:, flp) = -s.bvec(:, flp); end if flp(iSL) && isfield(s, 'SliceTiming') % slices flipped s.SliceTiming = flip(s.SliceTiming); sc = nii.hdr.slice_code; if sc>0, nii.hdr.slice_code = sc+mod(sc,2)*2-1; end % 1<->2, 3<->4, 5<->6 end % sform frmCode = all(isfield(s, {'ImageOrientationPatient' 'ImagePositionPatient'})); frmCode = tryGetField(s, 'TemplateSpace', frmCode); nii.hdr.sform_code = frmCode; % 1: SCANNER_ANAT nii.hdr.srow_x = R(1,:); nii.hdr.srow_y = R(2,:); nii.hdr.srow_z = R(3,:); R0 = normc(R(:, 1:3)); sNorm = null(R0(:, setdiff(1:3, iSL))'); if sign(sNorm(ixyz(iSL))) ~= sign(R(ixyz(iSL),iSL)), sNorm = -sNorm; end shear = norm(R0(:,iSL)-sNorm) > 0.01; R0(:,iSL) = sNorm; % qform nii.hdr.qform_code = frmCode; nii.hdr.qoffset_x = R(1,4); nii.hdr.qoffset_y = R(2,4); nii.hdr.qoffset_z = R(3,4); [q, nii.hdr.pixdim(1)] = dcm2quat(R0); % 3x3 dir cos matrix to quaternion nii.hdr.quatern_b = q(2); nii.hdr.quatern_c = q(3); nii.hdr.quatern_d = q(4); if shear nii.hdr.hdrTilt = nii.hdr; % copy all hdr for tilt version nii.hdr.qform_code = 0; % disable qform gantry = tryGetField(s, 'GantryDetectorTilt', 0); nii.hdr.hdrTilt.pixdim(iSL+1) = norm(R(1:3, iSL)) * cosd(gantry); R(1:3, iSL) = sNorm * nii.hdr.hdrTilt.pixdim(iSL+1); nii.hdr.hdrTilt.srow_x = R(1,:); nii.hdr.hdrTilt.srow_y = R(2,:); nii.hdr.hdrTilt.srow_z = R(3,:); end % store some possibly useful info in descrip and other text fields str = tryGetField(s, 'ImageComments', ''); if isType(s, '\MOCO\'), str = ''; end % useless for MoCo foo = tryGetField(s, 'StudyComments'); if ~isempty(foo), str = [str ';' foo]; end str = [str ';' sscanf(s.Manufacturer, '%s', 1)]; foo = tryGetField(s, 'ProtocolName'); if ~isempty(foo), str = [str ';' foo]; end nii.hdr.aux_file = str; % char[24], info only seq = asc_header(s, 'tSequenceFileName'); % like '%SiemensSeq%\ep2d_bold' if isempty(seq) seq = tryGetField(s, 'ScanningSequence'); else ind = strfind(seq, '\'); if ~isempty(ind), seq = seq(ind(end)+1:end); end % like 'ep2d_bold' end if pf.save_patientName, nii.hdr.db_name = PatientName(s); end % char[18] nii.hdr.intent_name = seq; % char[16], meaning of the data foo = tryGetField(s, 'AcquisitionDateTime'); descrip = sprintf('time=%s;', foo(1:min(18,end))); TE0 = asc_header(s, 'alTE[0]')/1000; % s.EchoTime stores only 1 TE if isempty(TE0), TE0 = tryGetField(s, 'EchoTime'); end % GE, philips TE1 = asc_header(s, 'alTE[1]')/1000; if ~isempty(TE1), s.SecondEchoTime = TE1; s.EchoTime = TE0; end dTE = abs(TE1 - TE0); % TE difference if isempty(dTE) && tryGetField(s, 'NumberOfEchoes', 1)>1 dTE = tryGetField(s, 'SecondEchoTime') - TE0; % need to update end if ~isempty(dTE) descrip = sprintf('dTE=%.4g;%s', dTE, descrip); s.deltaTE = dTE; end if ~isempty(TE0), descrip = sprintf('TE=%.4g;%s', TE0, descrip); end % Get dwell time if ~strcmp(tryGetField(s, 'MRAcquisitionType'), '3D') && ~isempty(iPhase) dwell = double(tryGetField(s, 'EffectiveEchoSpacing')) / 1000; % GE % http://www.spinozacentre.nl/wiki/index.php/NeuroWiki:Current_developments if isempty(dwell) % Philips wfs = tryGetField(s, 'WaterFatShift'); epiFactor = tryGetField(s, 'EPIFactor'); dwell = wfs ./ (434.215 * (double(epiFactor)+1)) * 1000; end if isempty(dwell) % Siemens hz = csa_header(s, 'BandwidthPerPixelPhaseEncode'); dwell = 1000 ./ hz / dim(iPhase); % in ms end if isempty(dwell) % true for syngo MR 2004A % ppf = [1 2 4 8 16] represent [4 5 6 7 8] 8ths PartialFourier % ppf = asc_header(s, 'sKSpace.ucPhasePartialFourier'); lns = asc_header(s, 'sKSpace.lPhaseEncodingLines'); dur = csa_header(s, 'SliceMeasurementDuration'); dwell = dur ./ lns; % ./ (log2(ppf)+4) * 8; end if isempty(dwell) % next is not accurate, so as last resort dur = csa_header(s, 'RealDwellTime') * 1e-6; % ns to ms dwell = dur * asc_header(s, 'sKSpace.lBaseResolution'); end if isempty(dwell) && strncmpi(s.Manufacturer, 'UIH', 3) try dwell = s.AcquisitionDuration; % not confirmed yet catch try dwell = s.MRVFrameSequence.Item_1.AcquisitionDuration; end end if ~isempty(dwell), dwell = dwell / dim(iPhase); end end if ~isempty(dwell) s.EffectiveEPIEchoSpacing = dwell; % https://github.com/rordenlab/dcm2niix/issues/130 readout = dwell * (dim(iPhase)- 1) / 1000; % since 170923 s.ReadoutSeconds = readout; descrip = sprintf('readout=%.3g;dwell=%.3g;%s', readout, dwell, descrip); end end if ~isempty(iPhase) if isempty(phPos), pm = '?'; b67 = 0; elseif phPos, pm = ''; b67 = 1; else, pm = '-'; b67 = 2; end nii.hdr.dim_info = nii.hdr.dim_info + b67*64; axes = 'xyz'; % actually ijk phDir = [pm axes(iPhase)]; s.UnwarpDirection = phDir; descrip = sprintf('phase=%s;%s', phDir, descrip); end nii.hdr.descrip = descrip; % char[80], drop from end if exceed % slope and intercept: apply to img if no rounding error sclApplied = tryGetField(s, 'ApplyRescale', false); if any(isfield(s, {'RescaleSlope' 'RescaleIntercept'})) && ~sclApplied slope = tryGetField(s, 'RescaleSlope', 1); inter = tryGetField(s, 'RescaleIntercept', 0); if isfield(s, 'MRScaleSlope') % Philips: see PAR file for detail inter = inter / (slope * double(s.MRScaleSlope)); slope = 1 / double(s.MRScaleSlope); end val = sort(double([max(nii.img(:)) min(nii.img(:))]) * slope + inter); dClass = class(nii.img); if isa(nii.img, 'float') || (mod(slope,1)==0 && mod(inter,1)==0 ... && val(1)>=intmin(dClass) && val(2)<=intmax(dClass)) nii.img = nii.img * slope + inter; % apply to img if no rounding else nii.hdr.scl_slope = slope; nii.hdr.scl_inter = inter; end elseif sclApplied && isfield(s, 'MRScaleSlope') slope = tryGetField(s, 'RescaleSlope', 1) * s.MRScaleSlope; nii.img = nii.img / slope; end if pf.scale_16bit && any(nii.hdr.datatype==[4 512]) % like dcm2niix if nii.hdr.datatype == 4 % int16 scale = floor(32000 / double(max(abs(nii.img(:))))); else % datatype==512 % uint16 scale = floor(64000 / double((max(nii.img(:))))); end nii.img = nii.img * scale; nii.hdr.scl_slope = nii.hdr.scl_slope / scale; end h{1} = s; % Possible patient position: HFS/HFP/FFS/FFP / HFDR/HFDL/FFDR/FFDL % Seems dicom takes care of this, and maybe nothing needs to do here. % patientPos = tryGetField(s, 'PatientPosition', ''); flds = { % store for nii.ext and json 'ConversionSoftware' 'SeriesNumber' 'SeriesDescription' 'ImageType' 'Modality' ... 'AcquisitionDateTime' 'bval' 'bvec' 'VolumeTiming' ... 'ReadoutSeconds' 'DelayTimeInTR' 'SliceTiming' 'RepetitionTime' ... 'UnwarpDirection' 'EffectiveEPIEchoSpacing' 'EchoTime' 'deltaTE' 'EchoTimes' ... 'SecondEchoTime' 'InversionTime' 'CardiacTriggerDelayTimes' ... 'PatientName' 'PatientSex' 'PatientAge' 'PatientSize' 'PatientWeight' ... 'PatientPosition' 'SliceThickness' 'FlipAngle' 'RBMoCoTrans' 'RBMoCoRot' ... 'Manufacturer' 'SoftwareVersion' 'MRAcquisitionType' ... 'InstitutionName' 'InstitutionAddress' 'DeviceSerialNumber' ... 'ScanningSequence' 'SequenceVariant' 'ScanOptions' 'SequenceName' ... 'TableHeight' 'DistanceSourceToPatient' 'DistanceSourceToDetector'}; if ~pf.save_patientName, flds(strcmp(flds, 'PatientName')) = []; end for i = 1:numel(flds) if ~isfield(s, flds{i}), continue; end nii.json.(flds{i}) = s.(flds{i}); end %% Subfunction, reshape mosaic into volume, remove padded zeros function vol = mos2vol(mos, nSL, isUIH) nMos = ceil(sqrt(nSL)); % nMos x nMos tiles for Siemens, maybe nMos x nMos-1 UIH [nr, nc, nv] = size(mos); % number of row, col and vol in mosaic nr = nr / nMos; nc = nc / nMos; % number of row and col in slice if isUIH && nMos*(nMos-1)>=nSL, nc = size(mos,2) / (nMos-1); end % one col less vol = zeros([nr nc nSL nv], class(mos)); for i = 1:nSL r = mod(i-1, nMos) * nr + (1:nr); % 2nd slice is tile(2,1) c = floor((i-1)/nMos) * nc + (1:nc); vol(:, :, i, :) = mos(r, c, :); end %% subfunction: set slice timing related info function [h, hdr] = sliceTiming(h, hdr) s = h{1}; TR = tryGetField(s, 'RepetitionTime'); % in ms if isempty(TR), TR = tryGetField(s, 'TemporalResolution'); end if isempty(TR), return; end hdr.pixdim(5) = TR / 1000; if tryGetField(s, 'isDTI', 0), return; end hdr.xyzt_units = 8; % seconds if hdr.dim(5)<3, return; end % skip structual, fieldmap etc nSL = hdr.dim(4); delay = asc_header(s, 'lDelayTimeInTR')/1000; % in ms now if isempty(delay), delay = 0; else, h{1}.DelayTimeInTR = delay; end TA = TR - delay; % Siemens mosaic t = csa_header(s, 'MosaicRefAcqTimes'); % in ms if ~isempty(t) && isfield(s, 'LastFile') && max(t)-min(t)>TA % MB wrong vol 1 try t = mb_slicetiming(s, TA); end %#ok<*TRYNC> end if isempty(t) && strncmpi(s.Manufacturer, 'UIH', 3) t = zeros(nSL, 1); if isfield(s, 'MRVFrameSequence') % mosaic for j = 1:nSL item = sprintf('Item_%g', j); str = s.MRVFrameSequence.(item).AcquisitionDateTime; t(j) = datenum(str, 'yyyymmddHHMMSS.fff'); end else dict = dicm_dict('', 'AcquisitionDateTime'); for j = 1:nSL s1 = dicm_hdr(h{j}.Filename, dict); t(j) = datenum(s1.AcquisitionDateTime, 'yyyymmddHHMMSS.fff'); end end t = (t - min(t)) * 24 * 3600 * 1000; % day to ms end if isempty(t) && isfield(s, 'RTIA_timer') % GE t = zeros(nSL, 1); nFile = numel(h); % seen problem for 1st vol, so use last vol for j = 1:nSL, t(j) = tryGetField(h{nFile-nSL+j}, 'RTIA_timer', 0); end if all(diff(t)==0), t = []; else t = t - min(t); ma = max(t) / TA; if ma>1, t = t / 10; % was ms*10, old dicom elseif ma<1e-3, t = t * 1000; % was sec, new dicom? end end end if isempty(t) && isfield(s, 'ProtocolDataBlock') && ... isfield(s.ProtocolDataBlock, 'SLICEORDER') % GE with invalid RTIA_timer SliceOrder = s.ProtocolDataBlock.SLICEORDER; t = (0:nSL-1)' * TA/nSL; if strcmp(SliceOrder, '1') % 0/1: sequential/interleaved based on limited data t([1:2:nSL 2:2:nSL]) = t; elseif ~strcmp(SliceOrder, '0') errorLog(['Unknown SLICEORDER (' SliceOrder ') for ' s.NiftiName]); return; end end % Siemens multiframe: read TimeAfterStart from last file if isempty(t) && strncmpi(s.Manufacturer, 'SIEMENS', 7) % Use TimeAfterStart, not FrameAcquisitionDatetime. See % https://github.com/rordenlab/dcm2niix/issues/240#issuecomment-433036901 try s.PerFrameFunctionalGroupsSequence.Item_1.CSAImageHeaderInfo.Item_1.TimeAfterStart; % s2 = struct('FrameAcquisitionDatetime', {cell(nSL,1)}); % s2 = dicm_hdr(h{end}, s2, 1:nSL); % avoid 1st volume % t = datenum(s2.FrameAcquisitionDatetime, 'yyyymmddHHMMSS.fff'); % t = (t - min(t)) * 24 * 3600 * 1000; % day to ms s2 = struct('TimeAfterStart', nan(1, nSL)); s2 = dicm_hdr(h{end}, s2, 1:nSL); % avoid 1st volume t = s2.TimeAfterStart; % in secs t = (t - min(t)) * 1000; end end % Get slice timing for non-mosaic Siemens file. Could remove Manufacturer % check, but GE/Philips AcquisitionTime seems useless if isempty(t) && ~tryGetField(s, 'isMos', 0) && strncmpi(s.Manufacturer, 'SIEMENS', 7) dict = dicm_dict('', {'AcquisitionDate' 'AcquisitionTime'}); t = zeros(nSL, 1); for j = 1:nSL s1 = dicm_hdr(h{j}.Filename, dict); str = [s1.AcquisitionDate s1.AcquisitionTime]; t(j) = datenum(str, 'yyyymmddHHMMSS.fff'); end t = (t - min(t)) * 24 * 3600 * 1000; % day to ms end if isempty(t) % non-mosaic Siemens: create 't' based on ucMode ucMode = asc_header(s, 'sSliceArray.ucMode'); % 1/2/4: Asc/Desc/Inter if isempty(ucMode), return; end t = (0:nSL-1)' * TA/nSL; if ucMode==2 t = t(nSL:-1:1); elseif ucMode==4 if mod(nSL,2), t([1:2:nSL 2:2:nSL]) = t; else, t([2:2:nSL 1:2:nSL]) = t; end end if asc_header(s, 'sSliceArray.ucImageNumb'), t = t(nSL:-1:1); end % rev-num end if numel(t)<2, return; end t = t - min(t); % it may be relative to 1st slice t1 = sort(t); dur = sum(diff(t1)) / (nSL-1); dif = sum(diff(t)) / (nSL-1); if dur==0 || (t1(end)>TA), sc = 0; % no useful info, or bad timing MB elseif t1(1) == t1(2), sc = 0; t1 = unique(t1); % was 7 for MB but error in FS elseif abs(dif-dur)<1e-3, sc = 1; % ascending elseif abs(dif+dur)<1e-3, sc = 2; % descending elseif t(1)<t(3) % ascending interleaved if t(1)<t(2), sc = 3; % odd slices first else, sc = 5; % Siemens even number of slices end elseif t(1)>t(3) % descending interleaved if t(1)>t(2), sc = 4; else, sc = 6; % Siemens even number of slices end else, sc = 0; % unlikely to reach end h{1}.SliceTiming = 0.5 - t/TR; % as for FSL custom timing hdr.slice_code = sc; hdr.slice_end = nSL-1; % 0-based, slice_start default to 0 hdr.slice_duration = min(diff(t1))/1000; %% subfunction: extract bval & bvec, store in 1st header function [h, nii] = get_dti_para(h, nii) nDir = nii.hdr.dim(5); if nDir<2, return; end bval = nan(nDir, 1); bvec = nan(nDir, 3); s = h{1}; nSL = nii.hdr.dim(4); nFile = numel(h); if isfield(s, 'bvec_original') % from BV or PAR file bval = s.B_value; bvec = s.bvec_original; elseif isfield(s, 'PerFrameFunctionalGroupsSequence') if nFile== 1 % all vol in 1 file, for Philips iDir = 1:nSL:nSL*nDir; if isfield(s, 'SortFrames'), iDir = s.SortFrames(iDir); end s2 = struct('B_value', bval', 'DiffusionGradientDirection', bvec'); s2 = dicm_hdr(s, s2, iDir); % call search_MF_val bval = s2.B_value'; bvec = s2.DiffusionGradientDirection'; % if all(isnan(bvec(:))) % Bruker % a = nan(1, nDir); % s2 = struct('DiffusionB_ValueXX', a, 'DiffusionB_ValueXY', a, ... % 'DiffusionB_ValueXZ', a, 'DiffusionB_ValueYY', a, ... % 'DiffusionB_ValueYZ', a, 'DiffusionB_ValueZZ', a); % s2 = dicm_hdr(s, s2, iDir); % bm = reshape(struct2array(s2), [nDir 6]); % a = zeros(3); % for i = 1:nDir % https://github.com/rordenlab/dcm2niix/issues/265 % a(:) = bm(i, [1:3 2 4 5 3 5 6]); % [V, ~] = eig(a); % bvec(i,:) = V(:,3); % end % end % if isfield(s, 'Private_0177_1101') && all(isnan(bvec(:))) % Bruker % str = char(s.Private_0177_1101'); % expr = 'DiffusionBMatrix\s*=\s*\(\s*(\d+),\s*(\d+)\s*\)\s+'; % [C, ind] = regexp(str, expr, 'tokens', 'end', 'once'); % if isequal(str2double(C), [nDir 9]) % bm = sscanf(str(ind:end), '%f', nDir*9); % bm = reshape(bm, 3, 3, []); % [~, i] = sort(iDir); bm(:,:,i) = bm; % for i = 1:nDir % [V, ~] = eig(bm(:,:,i)); % bvec(i,:) = V(:,3); % end % % errorLog('bvec is from B-matrix, so sign may be wrong.'); % end % end if isfield(s, 'Private_0177_1100') && all(isnan(bvec(:))) % Bruker str = char(s.Private_0177_1100'); expr = 'DwGradVec\s*=\s*\(\s*(\d+),\s*(\d+)\s*\)\s+'; % DwDir incomplete [C, ind] = regexp(str, expr, 'tokens', 'end', 'once'); if isequal(str2double(C), [nDir 3]) bvec = sscanf(str(ind+1:end), '%f', nDir*3); bvec = normc(reshape(bvec, 3, []))'; [~, i] = sort(iDir); bvec(i,:) = bvec; end end else % 1 vol per file, e.g. Siemens for i = 1:nFile bval(i) = MF_val('B_value', h{i}, 1); bvec(i,:) = MF_val('DiffusionGradientDirection', h{i}, 1); end end elseif nFile>1 % multiple files: order already in slices then volumes dict = dicm_dict(s.Manufacturer, {'B_value' 'B_factor' 'SlopInt_6_9' ... 'DiffusionDirectionX' 'DiffusionDirectionY' 'DiffusionDirectionZ'}); iDir = (0:nDir-1) * nFile/nDir + 1; % could be mosaic for j = 1:nDir % no bval/bvec for B0 volume s2 = h{iDir(j)}; val = tryGetField(s2, 'B_value'); if val == 0, continue; end vec = tryGetField(s2, 'DiffusionGradientDirection'); % Siemens/Philips/UIH if isempty(val) || isempty(vec) % likely GE s2 = dicm_hdr(s2.Filename, dict); end if isempty(val), val = tryGetField(s2, 'B_factor'); end % old Philips if isempty(val) && isfield(s2, 'SlopInt_6_9') % GE val = s2.SlopInt_6_9(1); end if isempty(val), val = 0; end % may be B_value=0 bval(j) = val; if isempty(vec) % GE, old Philips vec(1) = tryGetField(s2, 'DiffusionDirectionX', 0); vec(2) = tryGetField(s2, 'DiffusionDirectionY', 0); vec(3) = tryGetField(s2, 'DiffusionDirectionZ', 0); end bvec(j,:) = vec; end end if all(isnan(bval)) && all(isnan(bvec(:))) errorLog(['Failed to get DTI parameters: ' s.NiftiName]); return; end bval(isnan(bval)) = 0; bvec(isnan(bvec)) = 0; if strncmpi(s.Manufacturer, 'Philips', 7) % Remove computed ADC: it may not be the last vol ind = find(bval>1e-4 & sum(abs(bvec),2)<1e-4); if ~isempty(ind) % DiffusionDirectionality: 'ISOTROPIC' bval(ind) = []; bvec(ind,:) = []; nii.img(:,:,:,ind) = []; nii.hdr.dim(5) = nDir - numel(ind); end end h{1}.bvec_original = bvec; % original from dicom % http://wiki.na-mic.org/Wiki/index.php/NAMIC_Wiki:DTI:DICOM_for_DWI_and_DTI [ixyz, R] = xform_mat(s, nii.hdr.dim(2:4)); % R takes care of slice dir if strncmpi(s.Manufacturer, 'UIH', 3) || strncmpi(s.Manufacturer, 'Bruker', 6) % assume real image reference: unlike confusing GE scheme elseif strncmpi(s.Manufacturer, 'GE', 2) % GE bvec already in image reference if strcmp(tryGetField(s, 'InPlanePhaseEncodingDirection'), 'ROW') bvec = bvec(:, [2 1 3]); % dicom bvec in Freq/Phase/Slice order bvec(:, 2) = -bvec(:, 2); % because of transpose? if ixyz(3)<3 errorLog(sprintf(['%s: bvec sign for non-axial acquisition with' ... ' ROW phase direction not tested.\n Please check ' ... 'the result and report problem to author.'], s.NiftiName)); end end flp = R(ixyz+[0 3 6]) < 0; % negative sign flp(3) = ~flp(3); % GE slice dir opposite to LPS for all sag/cor/tra if ixyz(3)==1, flp(1) = ~flp(1); end % Sag slice: don't know why bvec(:, flp) = -bvec(:, flp); else % Siemens/Philips R = normc(R(:, 1:3)); bvec = bvec * R; % dicom plane to image plane end % bval may need to be scaled by norm(bvec) % https://mrtrix.readthedocs.io/en/latest/concepts/dw_scheme.html nm = sum(bvec .^ 2, 2); if any(nm>1e-4 & nm<0.999) % this check may not be necessary h{1}.bval_original = bval; % before scaling bval = bval .* nm; nm(nm<1e-4) = 1; % remove zeros after correcting bval bvec = bsxfun(@rdivide, bvec, sqrt(nm)); end h{1}.bval = bval; % store all into header of 1st file h{1}.bvec = bvec; % computed bvec in image ref %% subfunction: save bval & bvec files function save_dti_para(s, fname) if ~isfield(s, 'bvec') || all(s.bvec(:)==0), return; end if isfield(s, 'bval') fid = fopen([fname '.bval'], 'w'); fprintf(fid, '%.5g\t', s.bval); % one row fclose(fid); end str = repmat('%9.6f\t', 1, size(s.bvec,1)); fid = fopen([fname '.bvec'], 'w'); fprintf(fid, [str '\n'], s.bvec); % 3 rows by # direction cols fclose(fid); %% Subfunction, return a parameter from CSA Image/Series header function val = csa_header(s, key) val = []; fld = 'CSAImageHeaderInfo'; if isfield(s, fld) && isfield(s.(fld), key), val = s.(fld).(key); return; end fld = 'CSASeriesHeaderInfo'; if isfield(s, fld) && isfield(s.(fld), key), val = s.(fld).(key); return; end %% Subfunction, Convert 3x3 direction cosine matrix to quaternion % Simplied from Quaternions by Przemyslaw Baranski function [q, proper] = dcm2quat(R) % [q, proper] = dcm2quat(R) % Retrun quaternion abcd from normalized matrix R (3x3) proper = sign(det(R)); if proper<0, R(:,3) = -R(:,3); end q = sqrt([1 1 1; 1 -1 -1; -1 1 -1; -1 -1 1] * diag(R) + 1) / 2; if ~isreal(q(1)), q(1) = 0; end % if trace(R)+1<0, zero it [mx, ind] = max(q); mx = mx * 4; if ind == 1 q(2) = (R(3,2) - R(2,3)) /mx; q(3) = (R(1,3) - R(3,1)) /mx; q(4) = (R(2,1) - R(1,2)) /mx; elseif ind == 2 q(1) = (R(3,2) - R(2,3)) /mx; q(3) = (R(1,2) + R(2,1)) /mx; q(4) = (R(3,1) + R(1,3)) /mx; elseif ind == 3 q(1) = (R(1,3) - R(3,1)) /mx; q(2) = (R(1,2) + R(2,1)) /mx; q(4) = (R(2,3) + R(3,2)) /mx; elseif ind == 4 q(1) = (R(2,1) - R(1,2)) /mx; q(2) = (R(3,1) + R(1,3)) /mx; q(3) = (R(2,3) + R(3,2)) /mx; end if q(1)<0, q = -q; end % as MRICron %% Subfunction: get dicom xform matrix and related info function [ixyz, R, pixdim, xyz_unit] = xform_mat(s, dim) haveIOP = isfield(s, 'ImageOrientationPatient'); if haveIOP, R = reshape(s.ImageOrientationPatient, 3, 2); else, R = [1 0 0; 0 1 0]'; end R(:,3) = cross(R(:,1), R(:,2)); % right handed, but sign may be wrong foo = abs(R); [~, ixyz] = max(foo); % orientation info: perm of 1:3 if ixyz(2) == ixyz(1), foo(ixyz(2),2) = 0; [~, ixyz(2)] = max(foo(:,2)); end if any(ixyz(3) == ixyz(1:2)), ixyz(3) = setdiff(1:3, ixyz(1:2)); end if nargout<2, return; end iSL = ixyz(3); % 1/2/3 for Sag/Cor/Tra slice signSL = sign(R(iSL, 3)); try pixdim = s.PixelSpacing([2 1]); xyz_unit = 2; % mm catch pixdim = [1 1]'; % fake xyz_unit = 0; % no unit information end thk = tryGetField(s, 'SpacingBetweenSlices'); if isempty(thk), thk = tryGetField(s, 'SliceThickness', pixdim(1)); end pixdim = [pixdim; thk]; haveIPP = isfield(s, 'ImagePositionPatient'); if haveIPP, ipp = s.ImagePositionPatient; else, ipp = -(dim'.* pixdim)/2; end % Next is almost dicom xform matrix, except mosaic trans and unsure slice_dir R = [R * diag(pixdim) ipp]; % rest are former: R = verify_slice_dir(R, s, dim, iSL) if dim(3)<2, return; end % don't care direction for single slice if s.Columns>dim(1) && ~strncmpi(s.Manufacturer, 'UIH', 3) % Siemens mosaic R(:,4) = R * [ceil(sqrt(dim(3))-1)*dim(1:2)/2 0 1]'; % real slice location vec = csa_header(s, 'SliceNormalVector'); % mosaic has this if ~isempty(vec) % exist for all tested data if sign(vec(iSL)) ~= signSL, R(:,3) = -R(:,3); end return; end elseif isfield(s, 'LastFile') && isfield(s.LastFile, 'ImagePositionPatient') R(:, 3) = (s.LastFile.ImagePositionPatient - R(:,4)) / (dim(3)-1); thk = norm(R(:,3)); % override slice thickness if it is off if abs(pixdim(3)-thk)/thk > 0.01, pixdim(3) = thk; end return; % almost all non-mosaic images return from here end % Rest of the code is almost unreachable if isfield(s, 'CSASeriesHeaderInfo') % Siemens both mosaic and regular ori = {'Sag' 'Cor' 'Tra'}; ori = ori{iSL}; sNormal = asc_header(s, ['sSliceArray.asSlice[0].sNormal.d' ori]); if asc_header(s, ['sSliceArray.ucImageNumb' ori]), sNormal = -sNormal; end if sign(sNormal) ~= signSL, R(:,3) = -R(:,3); end if ~isempty(sNormal), return; end end pos = []; % volume center we try to retrieve if isfield(s, 'LastScanLoc') && isfield(s, 'FirstScanLocation') % GE pos = (s.LastScanLoc + s.FirstScanLocation) / 2; % mid-slice center if iSL<3, pos = -pos; end % RAS convention! pos = pos - R(iSL, 1:2) * (dim(1:2)'-1)/2; % mid-slice location end if isempty(pos) && isfield(s, 'Stack') % Philips ori = {'RL' 'AP' 'FH'}; ori = ori{iSL}; pos = tryGetField(s.Stack.Item_1, ['MRStackOffcentre' ori]); pos = pos - R(iSL, 1:2) * dim(1:2)'/2; % mid-slice location end if isempty(pos) % keep right-handed, and warn user if haveIPP && haveIOP errorLog(['Please check whether slices are flipped: ' s.NiftiName]); else errorLog(['No orientation/location information found for ' s.NiftiName]); end elseif sign(pos-R(iSL,4)) ~= signSL % same direction? R(:,3) = -R(:,3); end %% Subfunction: get a parameter in CSA series ASC header: MrPhoenixProtocol function val = asc_header(s, key) val = []; csa = 'CSASeriesHeaderInfo'; if ~isfield(s, csa), return; end if isfield(s.(csa), 'MrPhoenixProtocol') str = s.(csa).MrPhoenixProtocol; elseif isfield(s.(csa), 'MrProtocol') % older version dicom str = s.(csa).MrProtocol; else % in case of failure to decode CSA header str = char(s.(csa)(:)'); str = regexp(str, 'ASCCONV BEGIN(.*)ASCCONV END', 'tokens', 'once'); if isempty(str), return; end str = str{1}; end % tSequenceFileName = ""%SiemensSeq%\gre_field_mapping"" expr = ['\n' regexptranslate('escape', key) '.*?=\s*(.*?)\n']; str = regexp(str, expr, 'tokens', 'once'); if isempty(str), return; end str = strtrim(str{1}); if strncmp(str, '""', 2) % str parameter val = str(3:end-2); elseif strncmp(str, '"', 1) % str parameter for version like 2004A val = str(2:end-1); elseif strncmp(str, '0x', 2) % hex parameter, convert to decimal val = sscanf(str(3:end), '%x', 1); else % decimal val = sscanf(str, '%g', 1); end %% Subfunction: return matlab decompress command if the file is compressed function func = compress_func(fname) func = ''; if any(regexpi(fname, '\.mgz$')), return; end fid = fopen(fname); if fid<0, return; end sig = fread(fid, 2, '*uint8')'; fclose(fid); if isequal(sig, [80 75]) % zip file func = 'unzip'; elseif isequal(sig, [31 139]) % gz, tgz, tar func = 'untar'; end % ! "c:\program Files (x86)\7-Zip\7z.exe" x -y -oF:\tmp\ F:\zip\3047ZL.zip %% Subfuction: for GUI callbacks function gui_callback(h, evt, cmd, fh) hs = guidata(fh); drawnow; switch cmd case 'do_convert' src = get(fh, 'UserData'); dst = hs.dst.Text; if isempty(src) || isempty(dst) str = 'Source folder/file(s) and Result folder must be specified'; errordlg(str, 'Error Dialog'); return; end rstFmt = (get(hs.rstFmt, 'Value') - 1) * 2; % 0 or 2 if rstFmt == 4 if verLessThan('matlab','9.4') warndlg('BIDS conversion requires MATLAB R2018a or more.','MATLAB outdated'); return; end if get(hs.gzip, 'Value') rstFmt = 'bids'; else rstFmt = 'bidsnii'; end % 1 or 3 else if get(hs.gzip, 'Value'), rstFmt = rstFmt + 1; end % 1 or 3 if get(hs.rst3D, 'Value'), rstFmt = rstFmt + 4; end % 4 to 7 end set(h, 'Enable', 'off', 'string', 'Conversion in progress'); clnObj = onCleanup(@()set(h, 'Enable', 'on', 'String', 'Start conversion')); drawnow; dicm2nii(src, dst, rstFmt); % save parameters if last conversion succeed pf = getpref('dicm2nii_gui_para'); pf.rstFmt = get(hs.rstFmt, 'Value'); pf.rst3D = get(hs.rst3D, 'Value'); pf.gzip = get(hs.gzip, 'Value'); pf.src = hs.src.Text; ind = strfind(pf.src, '{'); if ~isempty(ind), pf.src = strtrim(pf.src(1:ind-1)); end pf.dst = hs.dst.Text; setpref('dicm2nii_gui_para', fieldnames(pf), struct2cell(pf)); case 'dstDialog' folder = hs.dst.Text; % current folder if ~isdir(folder), folder = hs.src.Text; end if ~isdir(folder), folder = fileparts(folder); end if ~isdir(folder), folder = pwd; end dst = uigetdir(folder, 'Select a folder for result files'); if isnumeric(dst), return; end hs.dst.Text = dst; case 'srcDir' folder = hs.src.Text; % initial folder if ~isdir(folder), folder = fileparts(folder); end if ~isdir(folder), folder = pwd; end src = jFileChooser(folder, 'Select folders/files to convert'); if isnumeric(src), return; end set(hs.fig, 'UserData', src); txt = src{1}; if numel(src) > 1, txt = [txt ' {and more}']; end hs.src.Text = txt; case 'set_src' str = hs.src.Text; ind = strfind(str, '{'); if ~isempty(ind), return; end % no check with multiple files if ~isempty(str) && ~exist(str, 'file') val = dir(str); folder = fileparts(str); if isempty(val) val = get(fh, 'UserData'); if iscellstr(val) val = [fileparts(val{1}), sprintf(' {%g files}', numel(val))]; end if ~isempty(val), hs.src.Text = val; end errordlg('Invalid input', 'Error Dialog'); return; end str = {val.name}; str = strcat(folder, filesep, str); end set(fh, 'UserData', str); case 'set_dst' str = hs.dst.Text; if isempty(str), return; end if ~exist(str, 'file') && ~mkdir(str) hs.dst.Text = ''; errordlg(['Invalid folder name ''' str ''''], 'Error Dialog'); return; end case 'SPMStyle' % turn off compression if get(hs.rst3D, 'Value'), set(hs.gzip, 'Value', 0); end case 'about' item = get(hs.about, 'Value'); if item == 1 % about str = sprintf(['dicm2nii.m by Xiangrui Li\n\n' ... 'Feedback to: [email protected]\n\n' ... 'Last updated on %s\n'], getVersion); helpdlg(str, 'About dicm2nii') elseif item == 2 % license try str = fileread([fileparts(mfilename('fullpath')) '/LICENSE']); catch str = 'license.txt file not found'; end helpdlg(strtrim(str), 'License') elseif item == 3 doc dicm2nii; elseif item == 4 checkUpdate(mfilename); elseif item == 5 web('www.sciencedirect.com/science/article/pii/S0165027016300073', '-browser'); end set(hs.about, 'Value', 1); case 'drop_src' % Java drop source try if strcmp(evt.DropType, 'file') n = numel(evt.Data); if n == 1 hs.src.Text = evt.Data{1}; set(hs.fig, 'UserData', evt.Data{1}); else hs.src.Text = sprintf('%s {%g files}', ... fileparts(evt.Data{1}), n); set(fh, 'UserData', evt.Data); end else % string hs.src.Text = strtrim(evt.Data); gui_callback([], [], 'set_src', fh); end catch me errordlg(me.message); end case 'drop_dst' % Java drop dst try if strcmp(evt.DropType, 'file') nam = evt.Data{1}; if ~isdir(nam), nam = fileparts(nam); end hs.dst.Text = nam; else hs.dst.Text = strtrim(evt.Data); gui_callback([], [], 'set_dst', fh); end catch me errordlg(me.message); end otherwise create_gui; end %% Subfuction: create GUI or bring it to front if exists function create_gui fh = figure('dicm' * 256.^(0:3)'); % arbitury integer if strcmp('dicm2nii_fig', get(fh, 'Tag')), return; end scrSz = get(0, 'ScreenSize'); fSz = 9; % + ~(ispc || ismac); clr = [1 1 1]*206/256; clrButton = [1 1 1]*216/256; cb = @(cmd) {@gui_callback cmd fh}; % callback shortcut uitxt = @(txt,pos) uicontrol('Style', 'text', 'Position', pos, 'FontSize', fSz, ... 'HorizontalAlignment', 'left', 'String', txt, 'BackgroundColor', clr); getpf = @(p,dft)getpref('dicm2nii_gui_para', p, dft); chkbox = @(parent,val,str,cbk,tip) uicontrol(parent, 'Style', 'checkbox', ... 'FontSize', fSz, 'HorizontalAlignment', 'left', 'BackgroundColor', clr, ... 'Value', val, 'String', str, 'Callback', cbk, 'TooltipString', tip); set(fh, 'Toolbar', 'none', 'Menubar', 'none', 'Resize', 'off', 'Color', clr, ... 'Tag', 'dicm2nii_fig', 'Position', [200 scrSz(4)-600 420 300], 'Visible', 'off', ... 'Name', 'dicm2nii - DICOM to NIfTI Converter', 'NumberTitle', 'off'); uitxt('Move mouse onto button, text box or check box for help', [8 274 400 16]); str = sprintf(['Browse convertible files or folders (can have subfolders) ' ... 'containing files.\nConvertible files can be dicom, Philips PAR,' ... ' AFNI HEAD, BrainVoyager files, or a zip file containing those files']); uicontrol('Style', 'Pushbutton', 'Position', [6 235 112 24], ... 'FontSize', fSz, 'String', 'DICOM folder/files', 'Background', clrButton, ... 'TooltipString', str, 'Callback', cb('srcDir')); jSrc = javaObjectEDT('javax.swing.JTextField'); hs.src = javacomponent(jSrc, [118 234 294 24], fh); hs.src.FocusLostCallback = cb('set_src'); hs.src.Text = getpf('src', pwd); % hs.src.ActionPerformedCallback = cb('set_src'); % fire when pressing ENTER hs.src.ToolTipText = ['<html>This is the source folder or file(s). You can<br>' ... 'Type the source folder name into the box, or<br>' ... 'Click DICOM folder/files button to browse, or<br>' ... 'Drag and drop a folder or file(s) into the box']; uicontrol('Style', 'Pushbutton', 'Position', [6 199 112 24], ... 'FontSize', fSz, 'String', 'Result folder', 'Background', clrButton, ... 'TooltipString', 'Browse result folder', 'Callback', cb('dstDialog')); jDst = javaObjectEDT('javax.swing.JTextField'); hs.dst = javacomponent(jDst, [118 198 294 24], fh); hs.dst.FocusLostCallback = cb('set_dst'); hs.dst.Text = getpf('dst', pwd); hs.dst.ToolTipText = ['<html>This is the result folder name. You can<br>' ... 'Type the folder name into the box, or<br>' ... 'Click Result folder button to set the value, or<br>' ... 'Drag and drop a folder into the box']; uitxt('Output format', [8 166 82 16]); hs.rstFmt = uicontrol('Style', 'popup', 'Background', 'white', 'FontSize', fSz, ... 'Value', getpf('rstFmt',1), 'Position', [92 162 82 24], 'String', {' .nii' ' .hdr/.img' ' BIDS (http://bids.neuroimaging.io)'}, ... 'TooltipString', 'Choose output file format'); hs.gzip = chkbox(fh, getpf('gzip',true), 'Compress', '', 'Compress into .gz files'); sz = get(hs.gzip, 'Extent'); set(hs.gzip, 'Position', [220 166 sz(3)+24 sz(4)]); hs.rst3D = chkbox(fh, getpf('rst3D',false), 'SPM 3D', cb('SPMStyle'), ... 'Save one file for each volume (SPM style)'); sz = get(hs.rst3D, 'Extent'); set(hs.rst3D, 'Position', [330 166 sz(3)+24 sz(4)]); hs.convert = uicontrol('Style', 'pushbutton', 'Position', [104 8 200 30], ... 'FontSize', fSz, 'String', 'Start conversion', ... 'Background', clrButton, 'Callback', cb('do_convert'), ... 'TooltipString', 'Dicom source and Result folder needed before start'); hs.about = uicontrol('Style', 'popup', 'String', ... {'About' 'License' 'Help text' 'Check update' 'A paper about conversion'}, ... 'Position', [326 12 88 20], 'Callback', cb('about')); ph = uipanel(fh, 'Units', 'Pixels', 'Position', [4 50 410 102], 'FontSize', fSz, ... 'BackgroundColor', clr, 'Title', 'Preferences (also apply to command line and future sessions)'); setpf = @(p)['setpref(''dicm2nii_gui_para'',''' p ''',get(gcbo,''Value''));']; p = 'lefthand'; h = chkbox(ph, getpf(p,true), 'Left-hand storage', setpf(p), ... 'Left hand storage works well for FSL, and likely doesn''t matter for others'); sz = get(h, 'Extent'); set(h, 'Position', [4 60 sz(3)+24 sz(4)]); p = 'save_patientName'; h = chkbox(ph, getpf(p,true), 'Store PatientName', setpf(p), ... 'Store PatientName in NIfTI hdr, ext and json'); sz = get(h, 'Extent'); set(h, 'Position', [180 60 sz(3)+24 sz(4)]); p = 'use_parfor'; h = chkbox(ph, getpf(p,true), 'Use parfor if needed', setpf(p), ... 'Converter will start parallel tool if necessary'); sz = get(h, 'Extent'); set(h, 'Position', [4 36 sz(3)+24 sz(4)]); p = 'use_seriesUID'; h = chkbox(ph, getpf(p,true), 'Use SeriesInstanceUID if exists', setpf(p), ... 'Only uncheck this if SeriesInstanceUID is messed up by some third party archive software'); sz = get(h, 'Extent'); set(h, 'Position', [180 36 sz(3)+24 sz(4)]); p = 'save_json'; h = chkbox(ph, getpf(p,false), 'Save json file', setpf(p), ... 'Save json file for BIDS (http://bids.neuroimaging.io/)'); sz = get(h, 'Extent'); set(h, 'Position', [4 12 sz(3)+24 sz(4)]); p = 'scale_16bit'; h = chkbox(ph, getpf(p,false), 'Use 16-bit scaling', setpf(p), ... 'Losslessly scale 16-bit integers to use dynamic range'); sz = get(h, 'Extent'); set(h, 'Position', [180 12 sz(3)+24 sz(4)]); hs.fig = fh; guidata(fh, hs); % store handles drawnow; set(fh, 'Visible', 'on', 'HandleVisibility', 'callback'); try % java_dnd is based on dndcontrol by Maarten van der Seijs java_dnd(jSrc, cb('drop_src')); java_dnd(jDst, cb('drop_dst')); catch me fprintf(2, '%s\n', me.message); end gui_callback([], [], 'set_src', fh); %% subfunction: return phase positive and phase axis (1/2) in image reference function [phPos, iPhase] = phaseDirection(s) phPos = []; iPhase = []; fld = 'InPlanePhaseEncodingDirection'; if isfield(s, fld) if strncmpi(s.(fld), 'COL', 3), iPhase = 2; % based on dicm_img(s,0) elseif strncmpi(s.(fld), 'ROW', 3), iPhase = 1; else, errorLog(['Unknown ' fld ' for ' s.NiftiName ': ' s.(fld)]); end end if isfield(s, 'CSAImageHeaderInfo') % SIEMENS phPos = csa_header(s, 'PhaseEncodingDirectionPositive'); % image ref % elseif isfield(s, 'ProtocolDataBlock') % GE % try % VIEWORDER "1" == bottom_up % phPos = s.ProtocolDataBlock.VIEWORDER == '1'; % end elseif isfield(s, 'UserDefineData') % GE % https://github.com/rordenlab/dcm2niix/issues/163 try b = s.UserDefineData; i = typecast(b(25:26), 'uint16'); % hdr_offset v = typecast(b(i+1:i+4), 'single'); % 5.0 to 40.0 if v >= 25.002, i = i + 76; flag2_off = 777; else, flag2_off = 917; end sliceOrderFlag = bitget(b(i+flag2_off), 2); phasePolarFlag = bitget(b(i+49), 3); phPos = ~xor(phasePolarFlag, sliceOrderFlag); end else if isfield(s, 'Stack') % Philips try d = s.Stack.Item_1.MRStackPreparationDirection(1); catch, return; end elseif isfield(s, 'PEDirectionDisplayed') % UIH try d = s.PEDirectionDisplayed(1); catch, return; end elseif isfield(s, 'Private_0177_1100') % Bruker expr ='(?<=\<\+?)[LRAPSI]{1}(?=;\s*phase\>)'; d = regexp(char(s.Private_0177_1100'), expr, 'match', 'once'); id = regexp('LRAPSI', d); id = id + mod(id,2)*2-1; str = 'LRAPFH'; d = str(id); else % unknown Manufacturer return; end try R = reshape(s.ImageOrientationPatient, 3, 2); catch, return; end [~, ixy] = max(abs(R)); % like [1 2] if isempty(iPhase) % if no InPlanePhaseEncodingDirection iPhase = strfind('RLAPFH', d); iPhase = ceil(iPhase/2); % 1/2/3 for RL/AP/FH iPhase = find(ixy==iPhase); % now 1 or 2 end if any(d == 'LPH'), phPos = false; % in dicom ref elseif any(d == 'RAF'), phPos = true; end if R(ixy(iPhase), iPhase)<0, phPos = ~phPos; end % tricky! in image ref end %% subfunction: extract useful fields for multiframe dicom function s = multiFrameFields(s) if isfield(s, 'MRVFrameSequence') % not real multi-frame dicom try s.ImagePositionPatient = s.MRVFrameSequence.Item_1.ImagePositionPatient; s.AcquisitionDateTime = s.MRVFrameSequence.Item_1.AcquisitionDateTime; item = sprintf('Item_%g', s.LocationsInAcquisition); s.LastFile.ImagePositionPatient = s.MRVFrameSequence.(item).ImagePositionPatient; end return; end pffgs = 'PerFrameFunctionalGroupsSequence'; sfgs = 'SharedFunctionalGroupsSequence'; if any(~isfield(s, {sfgs pffgs})), return; end try nFrame = s.NumberOfFrames; catch, nFrame = numel(s.(pffgs).FrameStart); end % check slice ordering (Philips often needs SortFrames) n = numel(MF_val('DimensionIndexValues', s, 1)); if n>0 && nFrame>1 s2 = struct('InStackPositionNumber', nan(1, nFrame), ... 'TemporalPositionIndex', nan(1, nFrame), ... 'DimensionIndexValues', nan(n, nFrame), ... 'B_value', zeros(1, nFrame)); s2 = dicm_hdr(s, s2, 1:nFrame); if ~isnan(s2.InStackPositionNumber(1)) SL = s2.InStackPositionNumber'; VL = [s2.TemporalPositionIndex' s2.DimensionIndexValues([3:end 1],:)']; else % use DimensionIndexValues as backup (seen in GE) SL = s2.DimensionIndexValues(2,:)'; % Bruker slice dim in (3,:)? VL = s2.DimensionIndexValues([3:end 1],:)'; end [ind, nSL] = sort_frames([SL s2.B_value'], VL); if ~isequal(ind, 1:nFrame) % && strncmpi(s.Manufacturer, 'Philips', 7) if ind(1) ~= 1 || ind(end) ~= nFrame s = dicm_hdr(s.Filename, [], ind([1 end])); % re-read new frames [1 end] end s.SortFrames = ind; % will use to sort img and get iVol/iSL for PerFrameSQ end if ~isfield(s, 'LocationsInAcquisition'), s.LocationsInAcquisition = nSL; end end % copy important fields into s flds = {'EchoTime' 'PixelSpacing' 'SpacingBetweenSlices' 'SliceThickness' ... 'RepetitionTime' 'FlipAngle' 'RescaleIntercept' 'RescaleSlope' ... 'ImageOrientationPatient' 'ImagePositionPatient' ... 'InPlanePhaseEncodingDirection' 'MRScaleSlope' 'CardiacTriggerDelayTime'}; iF = 1; if isfield(s, 'SortFrames'), iF = s.SortFrames(1); end for i = 1:numel(flds) if isfield(s, flds{i}), continue; end a = MF_val(flds{i}, s, iF); if ~isempty(a), s.(flds{i}) = a; end end if ~isfield(s, 'EchoTime') a = MF_val('EffectiveEchoTime', s, iF); if ~isempty(a), s.EchoTime = a; else, try s.EchoTime = str2double(s.EchoTimeDisplay); end end end % for Siemens: the redundant copy makes non-Siemens code faster if isfield(s.(sfgs).Item_1, 'CSASeriesHeaderInfo') s.CSASeriesHeaderInfo = s.(sfgs).Item_1.CSASeriesHeaderInfo.Item_1; end fld = 'CSAImageHeaderInfo'; if isfield(s.(pffgs).Item_1, fld) s.(fld) = s.(pffgs).(sprintf('Item_%g', iF)).(fld).Item_1; end % check ImageOrientationPatient consistency for 1st and last frame only if nFrame<2, return; end iF = nFrame; if isfield(s, 'SortFrames'), iF = s.SortFrames(iF); end a = MF_val('ImagePositionPatient', s, iF); if ~isempty(a), s.LastFile.ImagePositionPatient = a; end fld = 'ImageOrientationPatient'; val = MF_val(fld, s, iF); if ~isempty(val) && isfield(s, fld) && any(abs(val-s.(fld))>1e-4) s = []; return; % inconsistent orientation, skip end %% subfunction: return value from Shared or PerFrame FunctionalGroupsSequence function val = MF_val(fld, s, iFrame) pffgs = 'PerFrameFunctionalGroupsSequence'; switch fld case 'EffectiveEchoTime' sq = 'MREchoSequence'; case {'DiffusionDirectionality' 'B_value'} sq = 'MRDiffusionSequence'; case 'ComplexImageComponent' sq = 'MRImageFrameTypeSequence'; case {'DimensionIndexValues' 'InStackPositionNumber' 'TemporalPositionIndex' ... 'FrameReferenceDatetime' 'FrameAcquisitionDatetime'} sq = 'FrameContentSequence'; case {'RepetitionTime' 'FlipAngle'} sq = 'MRTimingAndRelatedParametersSequence'; case 'ImagePositionPatient' sq = 'PlanePositionSequence'; case 'ImageOrientationPatient' sq = 'PlaneOrientationSequence'; case {'PixelSpacing' 'SpacingBetweenSlices' 'SliceThickness'} sq = 'PixelMeasuresSequence'; case {'RescaleIntercept' 'RescaleSlope' 'RescaleType'} sq = 'PixelValueTransformationSequence'; case {'InPlanePhaseEncodingDirection' 'MRAcquisitionFrequencyEncodingSteps' ... 'MRAcquisitionPhaseEncodingStepsInPlane'} sq = 'MRFOVGeometrySequence'; case 'CardiacTriggerDelayTime' sq = 'CardiacTriggerSequence'; case {'SliceNumberMR' 'EchoTime' 'MRScaleSlope'} sq = 'PrivatePerFrameSq'; % Philips case 'DiffusionGradientDirection' % sq = 'MRDiffusionSequence'; try s2 = s.(pffgs).(sprintf('Item_%g', iFrame)).(sq).Item_1; val = s2.DiffusionGradientDirectionSequence.Item_1.(fld); catch, val = [0 0 0]'; end if nargin>1, return; end otherwise error('Sequence for %s not set.', fld); end if nargin<2 val = {'SharedFunctionalGroupsSequence' pffgs sq fld 'NumberOfFrames'}; return; end try val = s.SharedFunctionalGroupsSequence.Item_1.(sq).Item_1.(fld); catch try val = s.(pffgs).(sprintf('Item_%g', iFrame)).(sq).Item_1.(fld); catch val = []; end end %% subfunction: split nii components into multiple nii function nii = split_components(nii, s) fld = 'ComplexImageComponent'; if ~strcmp(tryGetField(s, fld, ''), 'MIXED'), return; end if ~isfield(s, 'Volumes') % PAR file and single-frame file have this nSL = nii.hdr.dim(4); nVol = nii.hdr.dim(5); iFrames = 1:nSL:nSL*nVol; if isfield(s, 'SortFrames'), iFrames = s.SortFrames(iFrames); end s1 = struct(fld, {cell(1, nVol)}, 'MRScaleSlope', nan(1,nVol), ... 'RescaleSlope', nan(1,nVol), 'RescaleIntercept', nan(1,nVol)); s.Volumes = dicm_hdr(s, s1, iFrames); end if ~isfield(s, 'Volumes'), return; end % suppose scl not applied in set_nii_hdr, since MRScaleSlope is not integer flds = {'EchoTimes' 'CardiacTriggerDelayTimes'}; % to split s1 = s.Volumes; nii0 = nii; % [c, ia] = unique(s.Volumes.(fld), 'stable'); % since 2013a? [~, ia] = unique(s1.(fld)); ia = sort(ia); c = s1.(fld)(ia); for i = 1:numel(c) nii(i) = nii0; ind = strcmp(c{i}, s1.(fld)); nii(i).img = nii0.img(:,:,:,ind); slope = s1.RescaleSlope(ia(i)); if isnan(slope), slope = 1; end inter = s1.RescaleIntercept(ia(i)); if isnan(inter), inter = 0; end if ~isnan(s1.MRScaleSlope(ia(i))) inter = inter / (slope * s1.MRScaleSlope(ia(i))); slope = 1 / s1.MRScaleSlope(ia(i)); end nii(i).hdr.scl_inter = inter; nii(i).hdr.scl_slope = slope; nii(i).hdr.file_name = [s.NiftiName '_' lower(c{i})]; nii(i) = nii_tool('update', nii(i)); for j = 1:numel(flds) if ~isfield(nii(i).json, flds{j}), continue; end nii(i).json.(flds{j}) = nii(i).json.(flds{j})(ind); end end %% Write error info to a file in case user ignores Command Window output function firstTime = errorLog(errInfo, folder) persistent niiFolder; if nargin>1, firstTime = isempty(niiFolder); niiFolder = folder; end if isempty(errInfo), return; end fprintf(2, ' %s\n', errInfo); % red text in Command Window fid = fopen([niiFolder 'dicm2nii_warningMsg.txt'], 'a'); fseek(fid, 0, -1); fprintf(fid, '%s\n', errInfo); fclose(fid); %% Ger version in from file: version yyyy.mm.dd function dStr = getVersion(str) dStr = '20130101'; if nargin<1 || isempty(str) pth = fileparts(mfilename('fullpath')); fname = fullfile(pth, 'README.md'); if ~exist(fname, 'file'), return; end str = fileread(fullfile(pth, 'README.md')); end a = regexp(str, 'version\s(\d{4}\.\d{2}\.\d{2})', 'tokens', 'once'); if ~isempty(a), dStr = a{1}([1:4 6:7 9:10]); end %% Get position info from Siemens CSA ASCII header % The only case this is useful for now is for DTI_ColFA, where Siemens omit % ImageOrientationPatient, ImagePositionPatient, PixelSpacing. % This shows how to get info from Siemens CSA header. function s = csa2pos(s, nSL) ori = {'Sag' 'Cor' 'Tra'}; % 1/2/3 sNormal = zeros(3,1); for i = 1:3 a = asc_header(s, ['sSliceArray.asSlice[0].sNormal.d' ori{i}]); if ~isempty(a), sNormal(i) = a; end end if all(sNormal==0); return; end % likely no useful info, give up isMos = tryGetField(s, 'isMos', false); revNum = ~isempty(asc_header(s, 'sSliceArray.ucImageNumb')); [cosSL, iSL] = max(abs(sNormal)); if isMos && (~isfield(s, 'CSAImageHeaderInfo') || ... ~isfield(s.CSAImageHeaderInfo, 'SliceNormalVector')) a = sNormal; if revNum, a = -a; end s.CSAImageHeaderInfo.SliceNormalVector = a; end pos = zeros(3,2); sl = [0 nSL-1]; for j = 1:2 key = sprintf('sSliceArray.asSlice[%g].sPosition.d', sl(j)); for i = 1:3 a = asc_header(s, [key ori{i}]); if ~isempty(a), pos(i,j) = a; end end end if ~isfield(s, 'SpacingBetweenSlices') if all(pos(:,2)==0) % like Mprage: dThickness & sPosition for volume a = asc_header(s, 'sSliceArray.asSlice[0].dThickness') ./ nSL; if ~isempty(a), s.SpacingBetweenSlices = a; end else s.SpacingBetweenSlices = abs(diff(pos(iSL,:))) / (nSL-1) / cosSL; end end if ~isfield(s, 'PixelSpacing') a = asc_header(s, 'sSliceArray.asSlice[0].dReadoutFOV'); a = a ./ asc_header(s, 'sKSpace.lBaseResolution'); interp = asc_header(s, 'sKSpace.uc2DInterpolation'); if interp, a = a ./ 2; end if ~isempty(a), s.PixelSpacing = a * [1 1]'; end end R(:,3) = sNormal; % ignore revNum for now if isfield(s, 'ImageOrientationPatient') R(:, 1:2) = reshape(s.ImageOrientationPatient, 3, 2); else if iSL==3 R(:,2) = [0 R(3,3) -R(2,3)] / norm(R(2:3,3)); R(:,1) = cross(R(:,2), R(:,3)); elseif iSL==2 R(:,1) = [R(2,3) -R(1,3) 0] / norm(R(1:2,3)); R(:,2) = cross(R(:,3), R(:,1)); elseif iSL==1 R(:,1) = [-R(2,3) R(1,3) 0] / norm(R(1:2,3)); R(:,2) = cross(R(:,1), R(:,3)); end rot = asc_header(s, 'sSliceArray.asSlice[0].dInPlaneRot'); if isempty(rot), rot = 0; end rot = rot - round(rot/pi*2)*pi/2; % -45 to 45 deg, is this right? ca = cos(rot); sa = sin(rot); R = R * [ca sa 0; -sa ca 0; 0 0 1]; s.ImageOrientationPatient = R(1:6)'; end if ~isfield(s, 'ImagePositionPatient') dim = double([s.Columns s.Rows]'); if all(pos(:,2) == 0) % pos(:,1) for volume center if any(~isfield(s,{'PixelSpacing' 'SpacingBetweenSlices'})), return; end R = R * diag([s.PixelSpacing([2 1]); s.SpacingBetweenSlices]); x = [-dim/2*[1 1]; (nSL-1)/2*[-1 1]]; pos = R * x + pos(:,1) * [1 1]; % volume center to slice 1&nSL position else % this may be how Siemens sets unusual mosaic ImagePositionPatient if ~isfield(s, 'PixelSpacing'), return; end R = R(:,1:2) * diag(s.PixelSpacing([2 1])); pos = pos - R * dim/2 * [1 1]; % slice centers to slice position end if revNum, pos = pos(:, [2 1]); end if isMos, pos(:,2) = pos(:,1); end % set LastFile same as first for mosaic s.ImagePositionPatient = pos(:,1); s.LastFile.ImagePositionPatient = pos(:,2); end %% subfuction: check whether parpool is available % Return true if it is already open, or open it if available function doParal = useParTool doParal = usejava('jvm'); if ~doParal, return; end if isempty(which('parpool')) % for early matlab versions try if matlabpool('size')<1 %#ok<*DPOOL> try matlabpool; catch me fprintf(2, '%s\n', me.message); doParal = false; end end catch doParal = false; end return; end % Following for later matlab with parpool try if isempty(gcp('nocreate')) try parpool; catch me fprintf(2, '%s\n', me.message); doParal = false; end end catch doParal = false; end %% subfunction: return nii ext from dicom struct % The txt extension is in format of: name = parameter; % Each parameter ends with [';' char(0 10)]. Examples: % Modality = 'MR'; % str parameter enclosed in single quotation marks % FlipAngle = 72; % single numeric value, brackets may be used, but optional % SliceTiming = [0.5 0.1 ... ]; % vector parameter enclosed in brackets % bvec = [0 -0 0 % -0.25444411 0.52460458 -0.81243353 % ... % 0.9836791 0.17571079 0.038744]; % matrix rows separated by char(10) and/or ';' function ext = set_nii_ext(s) flds = fieldnames(s); ext.ecode = 6; % text ext ext.edata = ''; for i = 1:numel(flds) try val = s.(flds{i}); catch, continue; end if ischar(val) str = sprintf('''%s''', val); elseif numel(val) == 1 % single numeric str = sprintf('%.8g', val); elseif isvector(val) % row or column str = sprintf('%.8g ', val); str = sprintf('[%s]', str(1:end-1)); % drop last space elseif isnumeric(val) % matrix, like DTI bvec fmt = repmat('%.8g ', 1, size(val, 2)); str = sprintf([fmt char(10)], val'); str = sprintf('[%s]', str(1:end-2)); % drop last space and char(10) else % in case of struct etc, skip continue; end ext.edata = [ext.edata flds{i} ' = ' str ';' char([0 10])]; end % % Matlab ext: ecode = 40 % fname = [tempname '.mat']; % save(fname, '-struct', 's', '-v7'); % field as variable % fid = fopen(fname); % b = fread(fid, inf, '*uint8'); % data bytes % fclose(fid); % delete(fname); % % % first 4 bytes (int32) encode real data length, endian-dependent % if exist('ext', 'var'), n = numel(ext)+1; else n = 1; end % ext(n).edata = [typecast(int32(numel(b)), 'uint8')'; b]; % ext(n).ecode = 40; % Matlab % % Dicom ext: ecode = 2 % if isfield(s, 'SOPInstanceUID') % make sure it is dicom % if exist('ext', 'var'), n = numel(ext)+1; else n = 1; end % ext(n).ecode = 2; % dicom % fid = fopen(s.Filename); % ext(n).edata = fread(fid, s.PixelData.Start, '*uint8'); % fclose(fid); % end %% Fix some broken multiband sliceTiming. Hope this won't be needed in future. % Odd number of nShot is fine, but some even nShot may have problem. % This gives inconsistent result to the following example in PDF doc, but I % would rather believe the example is wrong: % nSL=20; mb=2; nShot=nSL/mb; % inc=3 % In PDF: 0,10 - 3,13 - 6,16 - 9,19 - 1,11 - 4,14 - 7,17 - 2,12 - 5,15 - 8,18 % result: 0,10 - 3,13 - 6,16 - 9,19 - 2,12 - 5,15 - 8,18 - 1,11 - 4,14 - 7,17 function t = mb_slicetiming(s, TA) dict = dicm_dict(s.Manufacturer, 'MosaicRefAcqTimes'); s2 = dicm_hdr(s.LastFile.Filename, dict); t = s2.MosaicRefAcqTimes; % try last volume first % No SL acc factor. Not even multiband flag. This is UGLY nSL = double(s.LocationsInAcquisition); mb = ceil((max(t) - min(t)) ./ TA); % based on the wrong timing pattern if isempty(mb) || mb==1 || mod(nSL,mb)>0, return; end % not MB or wrong mb guess nShot = nSL / mb; ucMode = asc_header(s, 'sSliceArray.ucMode'); % 1/2/4: Asc/Desc/Inter if isempty(ucMode), return; end t = linspace(0, TA, nShot+1)'; t(end) = []; t = repmat(t, mb, 1); % ascending, ucMode==1 if ucMode == 2 % descending t = t(nSL:-1:1); elseif ucMode == 4 % interleaved if mod(nShot,2) % odd number of shots inc = 2; else inc = nShot / 2 - 1; if mod(inc,2) == 0, inc = inc - 1; end errorLog([s.NiftiName ': multiband interleaved order, even' ... ' number of shots.\nThe SliceTiming information may be wrong.']); end % % This gives the result in the PDF doc for example above % ind = nan(nShot, 1); j = 0; i = 1; k = 0; % while 1 % ind(i) = j + k*inc; % if ind(i)+(mb-1)*nShot > nSL-1 % j = j + 1; k = 0; % else % i = i + 1; k = k + 1; % end % if i>nShot, break; end % end ind = mod((0:nShot-1)*inc, nShot)'; % my guess based on chris data if nShot==6, ind = [0 2 4 1 5 3]'; end % special case ind = bsxfun(@plus, ind*ones(1,mb), (0:mb-1)*nShot); ind = ind + 1; t = zeros(nSL, 1); for i = 1:nShot t(ind(i,:)) = (i-1) / nShot; end t = t * TA; end if csa_header(s, 'ProtocolSliceNumber')>0, t = t(nSL:-1:1); end % rev-num %% subfunction: check ImagePostionPatient from multiple slices/volumes function [err, nSL, sliceN, isTZ] = checkImagePosition(ipp, gantryTilt) a = diff(sort(ipp)); tol = max(a)/100; % max(a) close to SliceThichness. 1% arbituary if nargin>1 && gantryTilt, tol = tol * 10; end % arbituary nSL = sum(a > tol) + 1; err = ''; sliceN = []; isTZ = false; nVol = numel(ipp) / nSL; if mod(nVol,1), err = 'Missing file(s) detected'; return; end if nSL<2, return; end isTZ = nVol>1 && all(abs(diff(ipp(1:nVol))) < tol); if isTZ % Philips XYTZ a = ipp(1:nVol:end); b = reshape(ipp, nVol, nSL); else a = ipp(1:nSL); b = reshape(ipp, nSL, nVol)'; end [~, sliceN] = sort(a); % no descend since wrong for PAR/singleDicom if any(abs(diff(a,2))>tol), err = 'Inconsistent slice spacing'; return; end if nVol>1 b = diff(b); if any(abs(b(:))>tol), err = 'Irregular slice order'; return; end end %% Save JSON file, proposed by Chris G % matlab.internal.webservices.toJSON(s) function save_json(s, fname) flds = fieldnames(s); fid = fopen([fname '.json'], 'w'); % overwrite silently if exist fprintf(fid, '{\n'); for i = 1:numel(flds) nam = flds{i}; if ~isfield(s, nam), continue; end val = s.(nam); % this if-elseif block takes care of name/val change for BIDS json if any(strcmp(nam, {'RepetitionTime' 'InversionTime' 'EchoTimes' 'CardiacTriggerDelayTimes'})) val = val / 1000; % in sec now elseif strcmp(nam, 'UnwarpDirection') nam = 'PhaseEncodingDirection'; if val(1) == '-' || val(1) == '?', val = val([2 1]); end if val(1) == 'x', val(1) = 'i'; % BIDS spec elseif val(1) == 'y', val(1) = 'j'; elseif val(1) == 'z', val(1) = 'k'; end elseif strcmp(nam, 'EffectiveEPIEchoSpacing') nam = 'EffectiveEchoSpacing'; val = val / 1000; elseif strcmp(nam, 'ReadoutSeconds') nam = 'TotalReadoutTime'; elseif strcmp(nam, 'SliceTiming') val = (0.5 - val) * s.RepetitionTime / 1000; % FSL style to secs elseif strcmp(nam, 'SecondEchoTime') nam = 'EchoTime2'; val = val / 1000; elseif strcmp(nam, 'EchoTime') % if there are two TEs we are dealing with a fieldmap if isfield(s, 'SecondEchoTime') nam = 'EchoTime1'; end val = val / 1000; elseif strcmp(nam, 'bval') nam = 'DiffusionBValue'; elseif strcmp(nam, 'bvec') nam = 'DiffusionGradientOrientation'; elseif strcmp(nam, 'DelayTimeInTR') nam = 'DelayTime'; val = val / 1000; % secs elseif strcmp(nam, 'ImageType') val = regexp(val, '\\', 'split'); end fprintf(fid, '\t"%s": ', nam); if isempty(val) fprintf(fid, 'null,\n'); elseif ischar(val) fprintf(fid, '"%s",\n', strrep(val, '\', '\\')); elseif iscellstr(val) fprintf(fid, '['); fprintf(fid, '"%s", ', val{:}); fseek(fid, -2, 'cof'); % remove trailing comma and space fprintf(fid, '],\n'); elseif numel(val) == 1 % scalar numeric fprintf(fid, '%.8g,\n', val); elseif isvector(val) % row or column fprintf(fid, '[\n'); fprintf(fid, '\t\t%.8g,\n', val); fseek(fid, -2, 'cof'); fprintf(fid, '\t],\n'); elseif isnumeric(val) % matrix fprintf(fid, '[\n'); fmt = repmat('%.8g ', 1, size(val, 2)); fprintf(fid, ['\t\t[' fmt(1:end-1) '],\n'], val'); fseek(fid, -2, 'cof'); fprintf(fid, '\n\t],\n'); else % in case of struct etc, skip fprintf(2, 'Unknown type of data for %s.\n', nam); fprintf(fid, 'null,\n'); end end fseek(fid, -2, 'cof'); % remove trailing comma and \n fprintf(fid, '\n}\n'); fclose(fid); %% Check for newer version for 42997 at Matlab Central % Simplified from checkVersion in findjobj.m by Yair Altman function checkUpdate(mfile) verLink = 'https://github.com/xiangruili/dicm2nii/blob/master/README.md'; webUrl = 'https://www.mathworks.com/matlabcentral/fileexchange/42997'; try str = webread(verLink); catch me try str = urlread(verLink); %#ok catch str = sprintf('%s.\n\nPlease download manually.', me.message); errordlg(str, 'Web access error'); web(webUrl, '-browser'); return; end end latestStr = getVersion(str); if datenum(getVersion(), 'yyyymmdd') >= datenum(latestStr, 'yyyymmdd') msgbox([mfile ' and the package are up to date.'], 'Check update'); return; end msg = ['Update to the newer version (' latestStr ')?']; answer = questdlg(msg, ['Update ' mfile], 'Yes', 'Later', 'Yes'); if ~strcmp(answer, 'Yes'), return; end url = ['https://www.mathworks.com/matlabcentral/mlc-downloads/'... 'downloads/e5a13851-4a80-11e4-9553-005056977bd0/' ... '80e748a3-0ae1-48a5-a2cb-b8380dac0232/packages/zip']; tmp = tempdir; try fname = websave('dicm2nii_github.zip', url); % 2014a unzip(fname, tmp); delete(fname); a = dir([tmp 'xiangruili*']); if isempty(a), tdir = tmp; else, tdir = [tmp a(1).name '/']; end catch % system('git clone https://github.com/xiangruili/dicm2nii.git') url = 'https://github.com/xiangruili/dicm2nii/archive/master.zip'; try fname = [tmp 'dicm2nii_github.zip']; urlwrite(url, fname); %#ok unzip(fname, tmp); delete(fname); tdir = [tmp 'dicm2nii-master/']; catch me errordlg(['Error in updating: ' me.message], mfile); web(webUrl, '-browser'); return; end end movefile([tdir '*.*'], [fileparts(which(mfile)) '/.'], 'f'); rmdir(tdir, 's'); rehash; warndlg(['Package updated successfully. Please restart ' mfile ... ', otherwise it may give error.'], 'Check update'); %% Subfunction: return NumberOfImagesInMosaic if Siemens mosaic, or [] otherwise. % If NumberOfImagesInMosaic in CSA is >1, it is mosaic, and we are done. % If not exists, it may still be mosaic due to Siemens bug seen in syngo MR % 2004A 4VA25A phase image. Then we check EchoColumnPosition in CSA, and if it % is smaller than half of the slice dim, sSliceArray.lSize is used as nMos. If % no CSA at all, the better way may be to peek into img to get nMos. Then the % first attempt is to check whether there are padded zeros. If so we count zeros % either at top or bottom of the img to decide real slice dim. In case there is % no padded zeros, we use the single zero lines along row or col seen in most % (not all, for example some phase img, derived data like moco series or tmap % etc) mosaic. If the lines are equally spaced, and nMos is divisible by mosaic % dim, we accept nMos. Otherwise, we fall back to NumberOfPhaseEncodingSteps, % which is used by dcm2nii, but is not reliable for most mosaic due to partial % fourier or less 100% phase fov. function nMos = nMosaic(s) nMos = csa_header(s, 'NumberOfImagesInMosaic'); % healthy mosaic dicom if ~isempty(nMos), return; end % seen 0 for GLM Design file and others % The next fix detects mosaic which is not labeled as MOSAIC in ImageType, nor % NumberOfImagesInMosaic exists, seen in syngo MR 2004A 4VA25A phase image. res = csa_header(s, 'EchoColumnPosition'); % half or full of slice dim if ~isempty(res) dim = max([s.Columns s.Rows]); interp = asc_header(s, 'sKSpace.uc2DInterpolation'); if ~isempty(interp) && interp, dim = dim / 2; end if dim/res/2 >= 2 % nTiles>=2 nMos = asc_header(s, 'sSliceArray.lSize'); % mprage lSize=1 end return; % Siemens non-mosaic returns here end % The fix below is for dicom labeled as \MOSAIC in ImageType, but no CSA. if ~isType(s, '\MOSAIC') && ~isType(s, '\VFRAME'), return; end % non-mosaic try nMos = s.LocationsInAcquisition; return; end % try Siemens/UIH private tag try nMos = numel(fieldnames(s.MRVFrameSequence)); return; end % UIH dim = double([s.Columns s.Rows]); % slice or mosaic dim img = dicm_img(s, 0) ~= 0; % peek into img to figure out nMos nP = tryGetField(s, 'NumberOfPhaseEncodingSteps', 4); % sliceDim >= phase steps c = img(dim(1)-nP:end, dim(2)-nP:end); % corner at bottom-right done = false; if all(~c(:)) % at least 1 padded slice: not 100% safe c = img(1:nP+1, dim(2)-nP:end); % top-right if all(~c(:)) % all right tiles padded: use all to determine ln = sum(img); else % use several rows at bottom to determine: not as safe as all ln = sum(img(dim(1)-nP:end, :)); end z = find(ln~=0, 1, 'last'); nMos = dim(2) / (dim(2) - z); done = mod(nMos,1)==0 && mod(dim(1),nMos)==0; end if ~done % this relies on zeros along row or col seen in most mosaic ln = sum(img, 2) == 0; if sum(ln)<2 ln = sum(img) == 0; % likely PhaseEncodingDirectionPositive=0 i = find(~ln, 1, 'last'); % last non-zero column in img ln(i+2:end) = []; % leave only 1 true for padded zeros end nMos = sum(ln); done = nMos>1 && all(mod(dim,nMos)==0) && all(diff(find(ln),2)==0); end if ~done && isfield(s, 'NumberOfPhaseEncodingSteps') nMos = min(dim) / nP; done = nMos>1 && mod(nMos,1)==0 && all(mod(dim,nMos)==0); end if ~done errorLog([ProtocolName(s) ': NumberOfImagesInMosaic not available.']); nMos = []; % keep mosaic as it is return; end nMos = nMos * nMos; % not work for UIH img = mos2vol(uint8(img), nMos, 0); % find padded slices: useful for STC while 1 a = img(:,:,nMos); if any(a(:)), break; end nMos = nMos - 1; end %% Get sorting index for multi-frame and PAR/XML (also called by dicm_hdr) function [ind, nSL] = sort_frames(sl, ic) % sl is for slice index, and has B_value as 2nd column for DTI. % ic contains other possible identifiers which will be converted into index. % The ic column order is important. nSL = max(sl(:, 1)); nFrame = size(sl, 1); if nSL==nFrame, ind = 1:nSL; ind(sl(:,1)) = ind; return; end % single vol nVol = floor(nFrame / nSL); badVol = nVol*nSL < nFrame; % incomplete volume id = zeros(size(ic)); for i = 1:size(ic,2) [~, ~, id(:,i)] = unique(ic(:,i)); % entries to index end n = max(id); id = id(:, n>1); n = n(n>1); i = find(n == nVol+badVol, 1); if ~isempty(i) % most fMRI/DTI id = id(:, i); % use a single column for sorting elseif ~badVol && numel(n)>1 [j, i] = find(tril(n' * n, -1) == nVol, 1); % need to ignore diag if ~isempty(i) id = id(:, [i j]); % 2 columns make nVol elseif numel(n)>2 i = find(cumprod(n) == nVol, 1); if ~isempty(i), id = id(:, 1:i); end % first i columns make nVol end end [~, ind] = sortrows([sl id]); % this sort idea is from julienbesle if badVol % only seen in Philips try lastV = id(ind,1) > nVol; catch, lastV = []; end if sum(lastV) == nFrame-nSL*nVol ind(lastV) = []; % remove incomplete volume else % suppose extra later slices are from bad volume for i = 1:nSL a = ind==i; if sum(a) <= nVol, continue; end % shoule be == ind(find(a, 'last')) = []; % remove last extra one if numel(ind) == nSL*nVol, break; end end end end ind = reshape(ind, [], nSL)'; % XYTZ to XYZT ind = ind(:)'; %% this can be removed for matlab 2013b+ function y = flip(varargin) if exist('flip', 'builtin') y = builtin('flip', varargin{:}); else if nargin<2, varargin{2} = find(size(varargin{1})>1, 1); end y = flipdim(varargin); %#ok end %% return all file names in a folder, including in sub-folders function files = filesInDir(folder) dirs = genpath(folder); dirs = regexp(dirs, pathsep, 'split'); files = {}; for i = 1:numel(dirs) if isempty(dirs{i}), continue; end curFolder = [dirs{i} filesep]; a = dir(curFolder); % all files and folders a([a.isdir]) = []; % remove folders a = strcat(curFolder, {a.name}); files = [files a]; %#ok<*AGROW> end %% Select both folders and files function out = jFileChooser(folder, prompt, multi, button) if nargin<4 || isempty(button), button = 'Select'; end if nargin<3 || isempty(multi), multi = true; end if nargin<2 || isempty(prompt) if multi, prompt = 'Choose files and/or folders'; else, prompt = 'Choose file or folder'; end end if nargin<1 || isempty(folder), folder = pwd; end jFC = javax.swing.JFileChooser(folder); jFC.setFileSelectionMode(jFC.FILES_AND_DIRECTORIES); set(jFC, 'MultiSelectionEnabled', logical(multi)); set(jFC, 'ApproveButtonText', button); set(jFC, 'DialogTitle', prompt); returnVal = jFC.showOpenDialog([]); if returnVal ~= jFC.APPROVE_OPTION, out = returnVal; return; end % numeric if multi files = jFC.getSelectedFiles(); n = numel(files); out = cell(1, n); for i = 1:n, out{i} = char(files(i)); end else out = char(jFC.getSelectedFile()); end %% function v = normc(M) den = sqrt(sum(M .* M)); den(den==0) = 1; v = bsxfun(@rdivide, M, den); %% function BtnModalityTable(h,TT,TS) if all(any(ismember(TT.Data{:,2:3},'skip'),2)) warndlg('All images are skipped... Please select the type and modality for all scans','No scan selected'); return; end setappdata(0,'ModalityTable',TT.Data) setappdata(0,'SubjectTable',TS.Data) delete(h)
github
cocoanlab/humanfmri_preproc_bids-master
dicm_hdr.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/dicm_hdr.m
62,090
utf_8
b5094a6d10aab8edfae3dea1bff32612
function [s, info, dict] = dicm_hdr(fname, dict, iFrames) % Return header of a dicom file in a struct. % % [s, err] = DICM_HDR(dicomFileName, dict, iFrames); % % The mandatory 1st input is the dicom file name. % % The optional 2nd input is a dicom dictionary returned by dicm_dict. It may % have only part of the full dictionary, which can speed up header read % considerably. See rename_dicm for example. % % The optional 3rd intput is useful for multi-frame dicom. When there are many % frames, it may be slow to read all frames in PerFrameFunctionalGroupsSequence. % The 3rd input specifies the frames to read. By default, items for only 1st, % 2nd and last frames are read. % % The optional 2nd output contains information in case of error, and will be % empty if there is no error. % % The optional 3rd output is rarely needed. It returns the dicom dictionary % which may be updated from the input dict if the dicom vendor is different from % that in the input dict. % % DICM_HDR is like Matlab dicominfo, but is independent of Image Processing % Toolbox. The advantage is that it decodes most private and shadow tags for % Siemens, GE and Philips dicom, and runs faster, especially for partial header % and multi-frame dicom. % % DICM_HDR can also read Philips PAR/XML file, AFNI HEAD file, Freesurfer MGH % file and some BrainVoyager files, and return needed fields for dicm2nii to % convert into nifti. % % See also DICM_DICT, DICM2NII, DICM_IMG, RENAME_DICM, SORT_DICM, ANONYMIZE_DICM % History (yymmdd): % 130823 Write it for dicm2nii.m ([email protected]). % 130912 Extend private tags, automatically detect vendor. % 130923 Call philips_par, so make dicm2nii easier. % 131001 Decode SQ, useful for multiframe dicom and Philips Stack. % 131008 Load then typecast. Faster than multiple fread. % 131009 Work for implicit VR. % 131010 Decode Siemens CSA header (slow), so it is human readable. % 131019 PAR file: read image col labels, and use it for indexing. % 131023 Implement afni_hdr. % 131102 Use last tag for partial hdr, so return if it is non-exist fld. % 131107 Search tags if only a few fields: faster than regular way. % 131114 Add 3rd input: only 1,2,last frames hdr read. 0.4 vs 38 seconds! % Store needed fields in LastFile for PAR MIXED image type. % 140123 Support dicom without meta info (thanks Paul). % 140213 afni_head: IJK_TO_DICOM_REAL replaces IJK_TO_DICOM. % 140502 philips_par: don't use FOV for PixelSpacing and SpacingBetweenSlices. % 140506 philips_par: use PAR file name as SeriesDescription. % 140512 decode GE ProtocolDataBlock (gz compressed). % 140611 No re-do if there are <16 extra bytes after image data. % 140724 Ignore PAR/HEAD ext case; fix philips_par: Patient Position. % 140924 Use dict VR if VR==OB/UN (thx Macro R). Could be bad in theory. % 141006 philips_par: take care of char(13 10) issue (thx Hye). % 141021 Store fields in dict, so it can be used for changed vendor. % 141023 checkManufacturer for fast search approach too. % 141128 Minor tweaks (len-1 in read_csa) for Octave 3.8.1. % 150114 Siemens CSA str is not always len=1. Fix it (runs slower). % 150128 Use memory gunzip for GE ProtocolDataBlock (0.5 vs 43 ms). % 150222 Avoid repeatedly reading .REC .BRIK file for hdr. % 150227 Avoid error due to empty file (thx Kushal). % 150316 Avoid error due to empty item dat for search method (thx VG). % 150324 philips_par/afni_head: make up SeriesInstanceUID for dicm2nii. % 150405 Implement bv_file to read non-transformed BV fmr/vmr/dmr. % 150504 bv_file: fix multiple STCdata; bug fix for VMRData. % 150513 return dict as 3rd output for dicm2nii in case of vendor change. % 150517 fix manufacturer check problem for Octave: no re-read. % 150522 PerFrameSQ ind: fix the case if numel(ind)~=nFrame. % 150526 read_sq: use ItemDelimitationItem instead of empty dat1 as SQ end. % 150924 philips_par: store SliceNumber if not acsending/decending order. % 151001 check Manufacturer in advance for 'search' method. % 160105 Bug fix for b just missing iPixelData (Thx Andrew S). % 160127 Support big endian dicom; Always return TransferSyntaxUID for dicm_img. % 160310 Fix problem of failing to update allRead with Inf bytes read. % 160410 philips_par: check IndexInREC, and minor improvement. % 160412 add read_val() for search method, but speed benefit is minor. % 160414 Skip GEIIS SQ: not dicom compliant. % 160418 Add search_MF_val(); need FrameStart in PerFrameSQ. % 160422 Performance: avoid nestedFunc (big), use uint8, avoid typecast (minor). % 160527 philips_par: center of slice 1 for slice dir; (dim-1)/2 for vol center. % 160608 read_sq: n=nEnd (j>2) with PerFrameSQ (needed if length is not inf). % 160825 can read dcm without PixelData, by faking p.iPixelData=fSize+1. % 160829 no make-up SeriesNumber/InstanceUID in afni_head/philips_par/bv_file. % 160928 philips_par: fix para table ind; treat type 17 as phase img. Thx SS. % 161130 check i+n-1<=p.iPixelData in search method to avoid error. Thx xLei. % 170127 Implement mgh_file: read FreeSurfer mgh or mgz. % 170618 philips_par(): use regexp (less error prone); ignore keyname case. % 170618 afni_head(): make MSB_FIRST (BE) BRIK work; fix negative PixelSpacing. % 170625 read_ProtocolDataBlock(): decompress only to avoid datatype guess. % 170803 par_key(): bug fix introduced on 170618. % 170910 regexp tweak to work for Octave. % 170921 read_ProtocolDataBlock: decode into struct with better performance. % 171228 philips_par: bug fix for possible slice flip. thx ShereifH. % 170309 philips_par: take care of incomplete volume if not XYTZ. thx YiL. % 180507 read_val: keep bytes if typecast fails. thx JillM. % 180528 remove reversed search so allow to get item from 1st PerFrame. % 180531 philips_par: use SortFrames to solve XYTZ and incomplete volume. % 180605 philips_xml: much faster than xml2par; % philips_par: start to support V3 (thx ChrisR); fix (ap,fh,rl) issue. % 180612 philips_par & xml: take care of IndexInREC (may never be tested). % 180615 Avoid error for dicm without PixelData for search method (thx LucaT). % 180620 philips_xml: bug fix to convert str to num for sort_frames. % 180712 bug fix for implict VR in search method (thx LorenaF). persistent dict_full; s = []; info = ''; if nargin<2 || isempty(dict) if isempty(dict_full), dict_full = dicm_dict; end p.fullHdr = true; p.dict = dict_full; else p.fullHdr = false; % p updated in main func p.dict = dict; end if nargin==3 && isstruct(fname) % wrapper s = search_MF_val(fname, dict, iFrames); % s, s1, iFrames return; end if nargin<3, iFrames = []; end p.iFrames = iFrames; fid = fopen(fname, 'r', 'l'); if fid<0, info = ['File not exists: ' fname]; return; end closeFile = onCleanup(@() fclose(fid)); % auto close when done or error fseek(fid, 0, 1); fSize = ftell(fid); fseek(fid, 0, -1); if fSize<140 % 132 + one empty tag, ignore truncated info = ['Invalid file: ' fname]; return; end b8 = fread(fid, 130000, 'uint8=>uint8')'; % enough for most dicom iTagStart = 132; % start of first tag isDicm = isequal(b8(129:132), 'DICM'); if ~isDicm % truncated dicom: is first group 2 or 8? not safe group = ch2int16(b8(1:2), 0); isDicm = group==2 || group==8; % truncated dicm always LE iTagStart = 0; end if ~isDicm % may be PAR/HEAD/BV file [~, ~, ext] = fileparts(fname); try if strcmpi(ext, '.PAR') [s, info] = philips_par(fname); elseif strcmpi(ext, '.xml') [s, info] = philips_xml(fname); elseif strcmpi(ext, '.HEAD') % || strcmpi(ext, '.BRIK') [s, info] = afni_head(fname); elseif any(strcmpi(ext, {'.mgh' '.mgz'})) [s, info] = mgh_file(fname); elseif any(strcmpi(ext, {'.vmr' '.fmr' '.dmr'})) % BrainVoyager [s, info] = bv_file(fname); else info = ['Unknown file type: ' fname]; end catch me info = me.message; end return; end p.expl = false; % default for truncated dicom p.be = false; % little endian by default % Get TransferSyntaxUID first, so find PixelData i = strfind(char(b8), [char([2 0 16 0]) 'UI']); % always explicit LE tsUID = ''; if ~isempty(i) % empty for truncated i = i(1) + 6; n = ch2int16(b8(i+(0:1)), 0); tsUID = deblank(char(b8(i+1+(1:n)))); p.expl = ~strcmp(tsUID, '1.2.840.10008.1.2'); % may be wrong for some p.be = strcmp(tsUID, '1.2.840.10008.1.2.2'); end % find s.PixelData.Start so avoid search in img % We verify iPixelData+bytes=fSize. If bytes=2^32-1, read all and use last tag tg = char([224 127 16 0]); % PixelData, VR can be OW/OB even if expl if p.be, tg = tg([2 1 4 3]); end found = false; for nb = [0 2e6 20e6 fSize] % if not enough, read more till all read b8 = [b8 fread(fid, nb, 'uint8=>uint8')']; %#ok i = strfind(char(b8), tg); i = i(mod(i,2)==1); % must be odd number if isempty(i) && feof(fid) tg = char([00 86 32 0]); % SpectroscopyData, VR = 'OF' if p.be, tg = tg([2 1 4 3]); end i = strfind(char(b8), tg); i = i(mod(i,2)==1); end for k = i(end:-1:1) % last is likely real PixelData if p.expl, p.VR = char(b8(k+(4:5))); end p.iPixelData = k + p.expl*4 + 7; % s.PixelData.Start: 0-based if numel(b8)<p.iPixelData, b8 = [b8 fread(fid, 12, '*uint8')']; end %#ok p.bytes = ch2int32(b8(p.iPixelData+(-3:0)), p.be); if p.bytes==4294967295 && feof(fid), break; end % 2^32-1 compressed d = fSize - p.iPixelData - p.bytes; % d=0 most of time if d>=0 && d<16, found = true; break; end % real PixelData end if found, break; end if feof(fid) if isempty(i), p.iPixelData = fSize+1; end % fake it: no PixelData break; end end s.Filename = fopen(fid); s.FileSize = fSize; nTag = numel(p.dict.tag); % always search if only one tag: can find it in any SQ toSearch = nTag<2 || (nTag<30 && ~any(strcmp(p.dict.vr, 'SQ')) && p.iPixelData<1e6); if toSearch % search each tag if header is short and not many tags asked if ~isempty(tsUID), s.TransferSyntaxUID = tsUID; end % hope it is 1st tag bc = char(b8(1:min(end, p.iPixelData))); if ~isempty(p.dict.vendor) && any(mod(p.dict.group, 2)) % private group tg = char([8 0 112 0]); % Manufacturer if p.be, tg = tg([2 1 4 3]); end if p.expl, tg = [tg 'LO']; end i = strfind(bc, tg); i = i(mod(i,2)==1); if ~isempty(i) i = i(1) + 4 + p.expl*2; % Manufacturer should be the earliest one [n, nvr] = val_len('LO', b8(i+(0:5)), p.expl, p.be); i = i + nvr; if i+n<p.iPixelData dat = deblank(bc(i+(0:n-1))); [p, dict] = updateVendor(p, dat); end end end tg = char([40 0 8 0]); % NumberOfFrames if p.be, tg = tg([2 1 4 3]); end if p.expl, tg = [tg 'IS']; end i = strfind(bc, tg); i = i(mod(i,2)==1); if ~isempty(i) i = i(1) + 4 + p.expl*2; % take 1st [n, nvr] = val_len('IS', b8(i+(0:5)), p.expl, p.be); i = i + nvr; if i+n<p.iPixelData, p.nFrames = str2double(bc(i+(0:n-1))); end end for k = 1:numel(p.dict.tag) group = p.dict.group(k); swap = p.be && group~=2; hasVR = p.expl || group==2; tg = char(typecast([group p.dict.element(k)], 'uint8')); if swap, tg = tg([2 1 4 3]); end i = strfind(bc, tg); i = i(mod(i,2)==1); if isempty(i), continue; % no this tag, next elseif isfield(p, 'nFrames') && mod(numel(i), p.nFrames)<2, i = i(1); % elseif strcmp('SeriesInstanceUID', p.dict.name{k}), i = i(end); elseif numel(i)>1 % +1 tags found, add vr to try again if expl if hasVR tg = [tg p.dict.vr{k}]; %#ok i = strfind(bc, tg); i = i(mod(i,2)==1); if numel(i)~=1, toSearch = false; break; end else toSearch = false; break; % switch to regular way end end i = i + 4; % tag if hasVR vr = bc(i+(0:1)); i = i+2; if any(vr>'Z') || any(vr<'A'), toSearch = false; break; end if strcmp(vr, 'UN') || strcmp(vr, 'OB'), vr = p.dict.vr{k}; end else vr = p.dict.vr{k}; end [n, nvr] = val_len(vr, b8(i+(0:5)), hasVR, swap); i = i+nvr; if n<1 || mod(n,2) || i+n-1>p.iPixelData, continue; end % skip this tag [dat, info] = read_val(b8(i+(0:n-1)), vr, swap); if ~isempty(info), toSearch = false; break; end % re-do in regular way if ~isempty(dat), s.(p.dict.name{k}) = dat; end end end i = iTagStart + 1; while ~toSearch if i >= p.iPixelData if strcmp(name, 'PixelData') % iPixelData might be in img p.iPixelData = iPre + p.expl*4 + 7; % overwrite previous p.bytes = ch2int32(b8(p.iPixelData+(-3:0)), p.be); elseif p.iPixelData < fSize % has PixelData info = ['End of file reached: likely error: ' s.Filename]; end break; % done or give up end iPre = i; % back it up for PixelData [dat, name, info, i, tg] = read_item(b8, i, p); if ~isempty(info), break; end if ~p.fullHdr && tg>p.dict.tag(end), break; end % done for partial hdr if isempty(dat) || isnumeric(name), continue; end s.(name) = dat; if strcmp(name, 'Manufacturer') [p, dict] = updateVendor(p, dat); elseif tg>=2621697 && ~isfield(p, 'nFrames') % BitsAllocated p = get_nFrames(s, p, b8); % only make code here cleaner end end if p.iPixelData < fSize+1 s.PixelData.Start = p.iPixelData; s.PixelData.Bytes = p.bytes; if isfield(p, 'VR'), s.PixelData.Format = vr2fmt(p.VR); end end if isfield(s, 'CSAImageHeaderInfo') % Siemens CSA image header s.CSAImageHeaderInfo = read_csa(s.CSAImageHeaderInfo); end if isfield(s, 'CSASeriesHeaderInfo') % series header s.CSASeriesHeaderInfo = read_csa(s.CSASeriesHeaderInfo); end if isfield(s, 'ProtocolDataBlock') % GE s.ProtocolDataBlock = read_ProtocolDataBlock(s.ProtocolDataBlock); end %% nested function: update Manufacturer function [p, dict] = updateVendor(p, vendor) if ~isempty(p.dict.vendor) && strncmpi(vendor, p.dict.vendor, 2) dict = p.dict; % in case dicm_hdr asks 3rd output return; end dict_full = dicm_dict(vendor); if ~p.fullHdr && isfield(p.dict, 'fields') dict = dicm_dict(vendor, p.dict.fields); else dict = dict_full; end p.dict = dict; end end % main func %% subfunction: read dicom item. Called by dicm_hdr and read_sq function [dat, name, info, i, tag] = read_item(b8, i, p) dat = []; name = nan; info = ''; vr = 'CS'; % vr may be used if implicit group = b8(i+(0:1)); i=i+2; swap = p.be && ~isequal(group, [2 0]); % good news: no 0x0200 group group = ch2int16(group, swap); elmnt = ch2int16(b8(i+(0:1)), swap); i=i+2; tag = group*65536 + elmnt; if tag == 4294893581 % || tag == 4294893789 % FFFEE00D or FFFEE0DD i = i+4; % skip length return; % return in case n is not 0 end swap = p.be && group~=2; hasVR = p.expl || group==2; if hasVR, vr = char(b8(i+(0:1))); i = i+2; end % 2-byte VR [n, nvr] = val_len(vr, b8(i+(0:5)), hasVR, swap); i = i + nvr; if n==0, return; end % empty val % Look up item name in dictionary ind = find(p.dict.tag == tag, 1); if ~isempty(ind) name = p.dict.name{ind}; if strcmp(vr, 'UN') || strcmp(vr, 'OB') || ~hasVR, vr = p.dict.vr{ind}; end elseif tag==524400 % in case not in dict name = 'Manufacturer'; elseif tag==131088 % need TransferSyntaxUID even if not in dict name = 'TransferSyntaxUID'; elseif tag==593936 % 0x0009 0010 GEIIS not dicom compliant i = i+n; return; % seems n is not 0xffffffff elseif p.fullHdr if elmnt==0, i = i+n; return; end % skip GroupLength if mod(group,2), name = sprintf('Private_%04x_%04x', group, elmnt); else, name = sprintf('Unknown_%04x_%04x', group, elmnt); end if ~hasVR, vr = 'UN'; end % not in dict, will leave as uint8 elseif n<4294967295 % no skip for SQ with length 0xffffffff i = i+n; return; end % compressed PixelData, n can be 0xffffffff if ~hasVR && n==4294967295, vr = 'SQ'; end % best guess if n+i>p.iPixelData && ~strcmp(vr, 'SQ'), i = i+n; return; end % PixelData or err % fprintf('(%04x %04x) %s %6.0f %s\n', group, elmnt, vr, n, name); if strcmp(vr, 'SQ') nEnd = min(i+n, p.iPixelData); % n is likely 0xffff ffff [dat, info, i] = read_sq(b8, i, nEnd, p, tag==1375769136); % isPerFrameSQ? else [dat, info] = read_val(b8(i+(0:n-1)), vr, swap); i=i+n; end % if group==33 % fprintf('\t''%04X'' ''%04X'' ''%s'' ''%s'' ', group, elmnt, vr, name); % if numel(dat)>99, fprintf('''%s ...''', dat(1:9)); % elseif ischar(dat), fprintf('''%s''', dat); % elseif isnumeric(dat), fprintf('%g ', dat); % else, fprintf('''SQ'''); % end % fprintf('\n'); % end end %% Subfunction: decode SQ, called by read_item (recursively) % SQ structure: % while isItem (FFFE E000, Item) % Item_1, Item_2, ... % loop tags under the Item till FFFE E00D, ItemDelimitationItem % return if FFFE E0DD SequenceDelimitationItem (not checked) function [rst, info, i] = read_sq(b8, i, nEnd, p, isPerFrameSQ) rst = []; info = ''; tag1 = []; j = 0; % j is SQ Item index while i<nEnd % loop through multi Item under the SQ tag = b8(i+([2 3 0 1])); i = i+4; if p.be, tag = tag([2 1 3 4]); end tag = ch2int32(tag, 0); if tag ~= 4294893568, i = i+4; return; end % only do FFFE E000, Item n = ch2int32(b8(i+(0:3)), p.be); i = i+4; % n may be 0xffff ffff n = min(i+n, nEnd); j = j + 1; % This 'if' block deals with partial PerFrameSQ: j and i jump to a frame. % The 1/2/nf frame scheme will have problem in case that tag1 in 1st frame % is not the first tag in other frames. Then the tags before tag1 in other % frames will be treated as for previous frame. This is very unlikely since % the 1st tag is almost always a SQ, like MREchoSequence if isPerFrameSQ if ischar(p.iFrames) % 'all' frames if j==1 && ~isnan(p.nFrames), rst.FrameStart = nan(1, p.nFrames); end rst.FrameStart(j) = i-9; elseif j==1 % always read 1st frame, save i0 in case of re-do i0 = i-8; rst.FrameStart = i-9; elseif j==2 % always read 2nd frame, and find start ind for all frames if isnan(p.nFrames) || isempty(tag1) % 1st frame has no asked tag p.iFrames = 'all'; rst = []; j = 0; i = i0; % re-do the SQ continue; % re-do end tag1 = char(typecast(uint32(tag1), 'uint8')); tag1 = tag1([3 4 1 2]); if p.be && ~isequal(tag1(1:2),[2 0]), tag1 = tag1([2 1 4 3]); end ind = strfind(char(b8(i0:p.iPixelData)), tag1) + i0 - 1; ind = ind(mod(ind,2)==1); nInd = numel(ind); if nInd ~= p.nFrames tag1PerF = nInd / p.nFrames; if mod(tag1PerF, 1) > 0 % not integer, read all frames p.iFrames = 'all'; rst = []; j = 0; i = i0; % re-do SQ fprintf(2, ['Failed to determine indice for frames. ' ... 'Reading all frames. Maybe slow ...\n']); continue; elseif tag1PerF>1 % more than one ind for each frame ind = ind(1:tag1PerF:nInd); nInd = p.nFrames; end end rst.FrameStart = ind-9; % 0-based iItem = 2; % initialize here. Increase when j>2 iFrame = unique([1 2 round(p.iFrames) nInd]); else % overwrite j with asked iFrame, overwrite i with start ind iItem = iItem + 1; j = iFrame(iItem); i = ind(j); % start of tag1 for asked frame n = nEnd; % use very end of the sq end end Item_n = sprintf('Item_%g', j); while i<n % loop through multi tags under one Item [dat, name, info, i, tag] = read_item(b8, i, p); if tag == 4294893581, break; end % FFFE E00D ItemDelimitationItem if isempty(tag1), tag1 = tag; end % first detected tag for PerFrameSQ if isempty(dat) || isnumeric(name), continue; end % 0-length or skipped rst.(Item_n).(name) = dat; end end end %% subfunction: cast uint8/char to double. Better performance than typecast function d = ch2int32(u8, swap) if swap, u8 = u8([4 3 2 1]); end d = double(u8); d = d(1) + d(2)*256 + d(3)*65536 + d(4)*16777216; % d = d * 256.^(0:3)'; end function d = ch2int16(u8, swap) if swap, u8 = u8([2 1]); end d = double(u8); d = d(1) + d(2)*256; end %% subfunction: return value length, numel(b)=6 function [n, nvr] = val_len(vr, b, expl, swap) len16 = 'AE AS AT CS DA DS DT FD FL IS LO LT PN SH SL SS ST TM UI UL US'; if ~expl % implicit, length irrevalent to vr (faked as CS) n = ch2int32(b(1:4), swap); nvr = 4; % bytes of VR elseif ~isempty(strfind(len16, vr)) %#ok<*STREMP> % length in uint16 n = ch2int16(b(1:2), swap); nvr = 2; else % length in uint32 and skip 2 bytes n = ch2int32(b(3:6), swap); nvr = 6; end if n==13, n = 10; end % ugly bug fix for some old dicom file end %% subfunction: read value, called by search method and read_item function [dat, info] = read_val(b, vr, swap) if strcmp(vr, 'DS') || strcmp(vr, 'IS') dat = sscanf(char(b), '%f\\'); % like 1\2\3 elseif ~isempty(strfind('AE AS CS DA DT LO LT PN SH ST TM UI UT', vr)) % char dat = deblank(char(b)); else % numeric data, UN. SQ taken care of fmt = vr2fmt(vr); if isempty(fmt) dat = []; info = sprintf('Given up: Invalid VR (%d %d)', vr); return; end dat = b'; % keep as bytes in case typecast fails try dat = typecast(dat, fmt); end if swap, dat = swapbytes(dat); end end info = ''; end %% subfunction: numeric format str from VR function fmt = vr2fmt(vr) switch vr case 'US', fmt = 'uint16'; case 'OB', fmt = 'uint8'; case 'FD', fmt = 'double'; case 'SS', fmt = 'int16'; case 'UL', fmt = 'uint32'; case 'SL', fmt = 'int32'; case 'FL', fmt = 'single'; case 'AT', fmt = 'uint16'; case 'OW', fmt = 'uint16'; case 'OF', fmt = 'single'; case 'OD', fmt = 'double'; case 'UN', fmt = 'uint8'; otherwise, fmt = ''; end end %% subfunction: get nFrames into p.nFrames function p = get_nFrames(s, p, ch) if isfield(s, 'NumberOfFrames') p.nFrames = s.NumberOfFrames; % useful for PerFrameSQ elseif all(isfield(s, {'Columns' 'Rows' 'BitsAllocated'})) && p.bytes<4294967295 if isfield(s, 'SamplesPerPixel'), spp = double(s.SamplesPerPixel); else, spp = 1; end n = p.bytes * 8 / double(s.BitsAllocated); p.nFrames = n / (spp * double(s.Columns) * double(s.Rows)); else % FFFE E0DD, 4-byte len (zeros), 0020 9111 (FrameContentSequence) % GE has no FFFE E0DD 0000 0000. Only FrameContentSequence tag is not safe tg = char([254 255 221 224 0 0 0 0 32 0 17 145]); if p.be, tg = tg([2 1 4 3 5:8 10 9 12 11]); end if p.expl, tg = [tg 'SQ']; end p.nFrames = numel(strfind(char(ch), tg)); if p.nFrames<1, p.nFrames = nan; end end end %% subfunction: decode Siemens CSA image and series header function csa = read_csa(csa) b = csa'; if numel(b)<4 || ~strcmp(char(b(1:4)), 'SV10'), return; end % no op if not SV10 chDat = 'AE AS CS DA DT LO LT PN SH ST TM UI UN UT'; i = 8; % 'SV10' 4 3 2 1 try % in case of error, we return the original csa nField = ch2int32(b(i+(1:4)), 0); i=i+8; for j = 1:nField i=i+68; % name(64) and vm(4) vr = char(b(i+(1:2))); i=i+8; % vr(4), syngodt(4) n = ch2int32(b(i+(1:4)), 0); i=i+8; if n<1, continue; end % skip name decoding, faster nam = regexp(char(b(i-84+(1:64))), '\w+', 'match', 'once'); isNum = isempty(strfind(chDat, vr)); % fprintf('%s %3g %s\n', vr, n, nam); dat = []; for k = 1:n % n is often 6, but often only the first contains value len = ch2int32(b(i+(1:4)), 0); i=i+16; if len<1, i = i+(n-k)*16; break; end % rest are empty too foo = char(b(i+(1:len-1))); % exclude nul, need for Octave i = i + ceil(len/4)*4; % multiple 4-byte if isNum tmp = sscanf(foo, '%f', 1); % numeric to double if ~isempty(tmp), dat(k,1) = tmp; end %#ok else dat{k} = deblank(foo); %#ok end end if ~isNum dat(cellfun(@isempty, dat)) = []; %#ok if isempty(dat), continue; end if numel(dat)==1, dat = dat{1}; end end rst.(nam) = dat; end csa = rst; end end %% subfunction: decode GE ProtocolDataBlock function ch = read_ProtocolDataBlock(ch) n = typecast(ch(1:4), 'int32') + 4; % nBytes, zeros may be padded to make 4x if ~all(ch(5:6) == [31 139]') || n>numel(ch), return; end % gz signature ch = nii_tool('LocalFunc', 'gunzip_mem', ch(5:n))'; ch = regexp(char(ch), '(\w*)\s+"(.*?)"\n', 'tokens'); ch = [ch{:}]; ch = struct(ch{:}); end %% subfunction: get fields for multiframe dicom function s1 = search_MF_val(s, s1, iFrame) % s1 = search_MF_val(s, s1, iFrame); % Arg 1: the struct returned by dicm_hdr for a multiframe dicom % Arg 2: a struct with fields to search, and with initial value, such as % zeros or nans. The number of rows indicates the number of values for the % tag, and columns for frames indicated by iFrame, Arg 3. % Arg 3: frame indice, length consistent with columns of s1 field values. % Example: % s = dicm_hdr('multiFrameFile.dcm'); % read only 1,2 and last frame by default % s1 = struct('ImagePositionPatient', nan(3, s.NumberOfFrames)); % define size % s1 = search_MF_val(s, s1, 1:s.NumberOfFrames); % get values % This is MUCH faster than asking all frames by dicm_hdr, and avoid to get into % annoying SQ levels under PerFrameFuntionalGroupSequence. In case a tag is not % found in PerFrameSQ, the code will search SharedSQ and common tags, and will % ignore the 3th arg and duplicate the same value for all frames. if ~isfield(s, 'PerFrameFunctionalGroupsSequence'), return; end expl = false; be = false; if isfield(s, 'TransferSyntaxUID') expl = ~strcmp(s.TransferSyntaxUID, '1.2.840.10008.1.2'); be = strcmp(s.TransferSyntaxUID, '1.2.840.10008.1.2.2'); end fStart = s.PerFrameFunctionalGroupsSequence.FrameStart; % error if no FrameStart fid = fopen(s.Filename); b0 = fread(fid, fStart(1), 'uint8=>char')'; % before 1st frame in PerFrameSQ b = fread(fid, s.PixelData.Start-fStart(1), 'uint8=>char')'; % within PerFrameSQ fclose(fid); fStart(end+1) = s.PixelData.Start; % for later ind search fStart = fStart - fStart(1) + 1; % 1-based index in b flds = fieldnames(s1); dict = dicm_dict(s.Manufacturer, flds); len16 = 'AE AS AT CS DA DS DT FD FL IS LO LT PN SH SL SS ST TM UI UL US'; chDat = 'AE AS CS DA DT LO LT PN SH ST TM UI UT'; nf = numel(iFrame); for i = 1:numel(flds) k = find(strcmp(dict.name, flds{i}), 1, 'last'); % GE has another ipp tag if isempty(k), continue; end % likely private tag for another vendor vr = dict.vr{k}; group = dict.group(k); isBE = be && group~=2; isEX = expl || group==2; tg = char(typecast([group dict.element(k)], 'uint8')); if isBE, tg = tg([2 1 4 3]); end if isEX, tg = [tg vr]; end %#ok ind = strfind(b, tg); ind = ind(mod(ind,2)>0); % indice is odd if isempty(ind) % no tag in PerFrameSQ, try tag before PerFrameSQ ind = strfind(b0, tg); ind = ind(mod(ind,2)>0); if ~isempty(ind) k = ind(1) + numel(tg); % take 1st in case of multiple [n, nvr] = val_len(vr, uint8(b0(k+(0:5))), isEX, isBE); k = k + nvr; a = read_val(uint8(b0(k+(0:n-1))), vr, isBE); if ischar(a), a = {a}; end s1.(flds{i}) = repmat(a, 1, nf); % all frames have the same value end continue; end len = 4; % bytes of tag value length (uint32) if ~isEX % implicit, length irrevalent to VR ind = ind + 4; % tg(4) elseif ~isempty(strfind(len16, vr)) % data length in uint16 ind = ind + 6; % tg(4), vr(2) len = 2; else % length in uint32: skip 2 bytes ind = ind + 8; % tg(4), vr(2), skip(2) end isCH = ~isempty(strfind(chDat, vr)); % char data isDS = strcmp(vr, 'DS') || strcmp(vr, 'IS'); if ~isCH && ~isDS % numeric data, UN or SQ fmt = vr2fmt(vr); if isempty(fmt), continue; end % skip SQ end for k = 1:nf j = iFrame(k); % asked frame index j = find(ind>fStart(j) & ind<fStart(j+1), 1); % index in ind if isempty(j), continue; end % no tag for this frame if len==2, n = ch2int16(b(ind(j)+(0:1)), isBE); else, n = ch2int32(b(ind(j)+(0:3)), isBE); end a = b(ind(j)+len+(0:n-1)); if isDS a = sscanf(a, '%f\\'); % like 1\2\3 try s1.(flds{i})(:,k) = a; end %#ok<*TRYNC> ignore in case of error elseif isCH try s1.(flds{i}){k} = deblank(a); end else a = typecast(uint8(a), fmt)'; if isBE, a = swapbytes(a); end try s1.(flds{i})(:,k) = a; end end end end end %% subfunction: read PAR file, return struct like that from dicm_hdr. function [s, err] = philips_par(fname) err = ''; fid = fopen(fname); if fid<0, s = []; err = ['File not exist: ' fname]; return; end fullName = fopen(fid); % name with full path [pth, nam] = fileparts(fullName); str = fread(fid, inf, '*char')'; % read all as char fclose(fid); str = strrep(str, char([13 10]), char(10)); % remove char(13) ch = regexp(str, '.*?(?=IMAGE INFORMATION DEFINITION)', 'match', 'once'); V = regexpi(ch, 'image export tool\s*(V[\d\.]+)', 'tokens', 'once'); if isempty(V), err = 'Not PAR file'; s = []; return; end V = V{1}; s.SoftwareVersion = [V '\PAR']; s.PatientName = par_attr(ch, 'Patient name', 0); s.StudyDescription = par_attr(ch, 'Examination name', 0); s.SeriesDescription = nam; s.ProtocolName = par_attr(ch, 'Protocol name', 0); a = par_attr(ch, 'Examination date/time', 0); s.AcquisitionDateTime = a(isstrprop(a, 'digit')); s.SeriesNumber = par_attr(ch, 'Acquisition nr'); % s.ReconstructionNumberMR = par_attr(ch, 'Reconstruction nr'); % s.MRSeriesScanDuration = par_attr(ch, 'Scan Duration'); s.NumberOfEchoes = par_attr(ch, 'Max. number of echoes'); a = par_attr(ch, 'Patient position', 0); if isempty(a), a = par_attr(ch, 'Patient Position', 0); end if ~isempty(a) if numel(a)>4, s.PatientPosition = a(regexp(a, '\<.')); else, s.PatientPosition = a; end end s.MRAcquisitionType = par_attr(ch, 'Scan mode', 0); s.ScanningSequence = par_attr(ch, 'Technique', 0); % ScanningTechnique typ = par_attr(ch, 'Series Type', 0); typ(isspace(typ)) = ''; s.ImageType = ['PhilipsPAR\' typ '\' s.ScanningSequence]; s.RepetitionTime = par_attr(ch, 'Repetition time'); s.WaterFatShift = par_attr(ch, 'Water Fat shift'); s.EPIFactor = par_attr(ch, 'EPI factor'); % s.DynamicSeries = par_key(ch, 'Dynamic scan'); % 0 or 1 % Get list of para meaning for the table, and col index of each para i1 = regexpi(str, 'IMAGE INFORMATION DEFINITION', 'once'); i2 = regexpi(str, '= IMAGE INFORMATION ='); i2 = i2(end); ind = regexp(str(i1:i2), '\n#') + i1; colLabel = {}; iColumn = []; for i = 1:numel(ind)-1 a = str(ind(i)+1:ind(i+1)-2); % a line i1 = regexp(a, '[<(]{1}'); % need first '<' or '(', and last '(' if isempty(i1), continue; end nCol = sscanf(a(i1(end)+1:end), '%g'); if isempty(nCol), nCol = 1; end colLabel{end+1} = strtrim(a(1:i1(1)-1)); %#ok para name iColumn(end+1) = nCol; %#ok number of columns in the table for this para end iColumn = cumsum([1 iColumn]); % col start ind for corresponding colLabel keyInLabel = @(key)strcmpi(colLabel, key); colIndex = @(key)iColumn(keyInLabel(key)); i1 = regexp(str(i2:end), '\n\s*\d+', 'once') + i2; n = iColumn(end)-1; % number of items each row, 41 for V4 para = sscanf(str(i1:end), '%g'); % read all numbers nFrame = floor(numel(para) / n); para = reshape(para(1:n*nFrame), n, nFrame)'; % whole table now % SortFrames solves XYTZ, unusual slice order, incomplete volume etc keys = {'dynamic scan number' 'gradient orientation number' 'echo number' ... 'cardiac phase number' 'image_type_mr' 'label type' 'scanning sequence'}; ic = []; for i = 1:numel(keys), ic = [ic colIndex(keys{i})]; end %#ok sort_frames = dicm2nii('', 'sort_frames', 'func_handle'); sl = [para(:, colIndex('slice number')) para(:, colIndex('diffusion_b_factor'))]; [ind_sort, nSL] = sort_frames(sl, para(:, ic)); a = par_val('index in REC file', 1:nFrame); % always 0:nFrame-1 ? a(a+1) = 1:nFrame; % [~, a] = sort(a); a = a(ind_sort)'; if ~isequal(a, 1:nFrame), s.SortFrames = a; end % used only in dicm2nii para = para(ind_sort, :); % XYZT order s.LocationsInAcquisition = nSL; s.NumberOfFrames = numel(ind_sort); % may be smaller than nFrame s.NumberOfTemporalPositions = s.NumberOfFrames/nSL; iVol = (0:s.NumberOfTemporalPositions-1)*nSL + 1; % already XYZT fld = 'ComplexImageComponent'; typ = {'MAGNITUDE' 'REAL' 'IMAGINARY' 'PHASE'}; imgType = para(iVol, colIndex('image_type_mr')); imgType(imgType==16) = 0; imgType(imgType==17) = 3; imgType(imgType==18) = 1; ind = imgType + 1; a = unique(imgType(imgType>3)); % unknown type for i = 1:numel(a) ind(imgType==a(i)) = i+4; typ{i+4} = sprintf('image_type%g', a(i)); end if numel(iVol) == 1 s.ComplexImageComponent = typ{ind(1)}; elseif any(diff(ind) ~= 0) % more than 1 type of image s.(fld) = 'MIXED'; s.Volumes.(fld) = typ(ind); % one for each vol s.Volumes.RescaleIntercept = para(iVol, colIndex('rescale intercept')); s.Volumes.RescaleSlope = para(iVol, colIndex('rescale slope')); s.Volumes.MRScaleSlope = para(iVol, colIndex('scale slope')); else s.ComplexImageComponent = typ(ind(1)); % cellstr end % These columns should be the same for nifti-convertible images: cols = {'image pixel size' 'recon resolution' 'image angulation' ... 'slice thickness' 'slice gap' 'slice orientation' 'pixel spacing'}; if ~strcmp(s.((fld)), 'MIXED') cols = [cols {'rescale intercept' 'rescale slope' 'scale slope'}]; end ind = []; for i = 1:numel(cols) j = find(keyInLabel(cols{i})); if isempty(j), continue; end % some not in V3 ind = [ind iColumn(j):iColumn(j+1)-1]; %#ok end a = para(:, ind); a = abs(diff(a)); if any(a(:) > 1e-5) err = sprintf('Inconsistent image size, bits etc: %s', fullName); fprintf(2, ' %s. \n', err); s = []; return; end % s.EchoNumber = getTableVal('echo number', 1:s.NumberOfFrames); % 'pixel spacing' and 'slice gap' have poor precision for v<=4? % It may be wrong to use FOV, maybe due to partial Fourier? if strncmp(V, 'V3', 2) s.BitsAllocated = par_attr(ch, 'Image pixel size', 1); res = par_attr(ch, 'Recon resolution', 1); s.SliceThickness = par_attr(ch, 'Slice thickness', 1); gap = par_attr(ch, 'Slice gap', 1); s.TurboFactor = par_attr('TURBO factor', 1); s.NumberOfAverages = par_attr(ch, 'Number of averages', 1); else s.BitsAllocated = par_val('image pixel size'); res = par_val('recon resolution'); s.SliceThickness = par_val('slice thickness'); gap = par_val('slice gap'); s.TurboFactor = par_val('TURBO factor'); s.NumberOfAverages = par_val('number of averages'); end s.Columns = res(1); s.Rows = res(2); if gap < 0, gap = 0; end s.SpacingBetweenSlices = gap + s.SliceThickness; a = par_val('pixel spacing'); s.PixelSpacing = a(:); s.RescaleIntercept = par_val('rescale intercept'); s.RescaleSlope = par_val('rescale slope'); s.MRScaleSlope = par_val('scale slope'); s.EchoTimes = par_val('echo_time', iVol); s.EchoTime = s.EchoTimes(1); s.FlipAngle = par_val('image_flip_angle'); s.CardiacTriggerDelayTimes = par_val('trigger_time', iVol); % s.TimeOfAcquisition = par_val('dyn_scan_begin_time', 1:s.NumberOfFrames); posMid = par_attr(ch, 'Off Centre midslice'); % (ap,fh,rl) [mm] posMid = posMid([3 1 2]); % better precision than those in the table rotAngle = par_attr(ch, 'Angulation midslice'); % (ap,fh,rl) deg a = rotAngle([3 1 2]) /180*pi; % always this order? R = makehgtform('xrotate', a(1), 'yrotate', a(2), 'zrotate', a(3)); R = R(1:3, :); iOri = par_val('slice orientation'); % 1/2/3 for TRA/SAG/COR iOri = mod(iOri+1, 3) + 1; a = {'SAGITTAL' 'CORONAL' 'TRANSVERSAL'}; s.SliceOrientation = a{iOri}; if iOri == 1 R(:,[1 3]) = -R(:,[1 3]); R = R(:, [2 3 1 4]); elseif iOri == 2 R(:,3) = -R(:,3); R = R(:, [1 3 2 4]); end a = par_attr(ch, 'Preparation direction', 0); % Anterior-Posterior if ~isempty(a) a = a(regexp(a, '\<.')); % 'AP' s.Stack.Item_1.MRStackPreparationDirection = a; iPhase = strfind('LRAPFH', a(1)); iPhase = ceil(iPhase/2); % 1/2/3 if iPhase == (iOri==1)+1, a = 'ROW'; else, a = 'COL'; end s.InPlanePhaseEncodingDirection = a; end s.ImageOrientationPatient = R(1:6)'; R = R * diag([s.PixelSpacing([2 1]); s.SpacingBetweenSlices; 1]); R(:,4) = posMid; % 4th col is mid slice center position a = par_val('image offcentre', [1 nSL]); % Take axis with largest 'image offcentre' range as slice axis. This can be % wrong in theory, but the fix based on PAR version do not work [~, ind] = max(max(a)-min(a)); if ind==iOri, ax_order = 1:3; else, ax_order = [3 1 2]; end s.SliceLocation = a(1, ax_order(iOri)); % center loc for 1st slice if sign(R(iOri,3)) ~= sign(posMid(iOri)-s.SliceLocation) R(:,3) = -R(:,3); end if par_attr(ch, 'Diffusion')>0 % DTI s.ImageType = [s.ImageType '\DIFFUSION\']; s.DiffusionEchoTime = par_attr(ch, 'Diffusion echo time'); % ms s.B_value = par_val('diffusion_b_factor', iVol); a = par_val('diffusion', iVol); if ~isempty(a), s.bvec_original = a(:, ax_order); end end R(:,4) = R * [-([s.Columns s.Rows nSL]-1)/2 1]'; % vol center to corner of 1st s.ImagePositionPatient = R(:,4); s.LastFile.ImagePositionPatient = R * [0 0 nSL-1 1]'; % last slice s.Manufacturer = 'Philips'; s.Filename = fullfile(pth, [nam '.REC']); % rest for dicm_img s.PixelData.Start = 0; s.PixelData.Bytes = s.Rows * s.Columns * nFrame * s.BitsAllocated / 8; % nested function: set field if the key is in colTable function val = par_val(key, iRow) if nargin<2, iRow = 1; end iCol = find(keyInLabel(key)); val = para(iRow, iColumn(iCol):iColumn(iCol+1)-1); end % subfunction: return value specified by key in PAR file function val = par_attr(ch, key, isNum) expr = ['\n.\s*' key '.*?:(.*?)\n']; % \n. key ... : val \n val = strtrim(regexp(ch, expr, 'tokens', 'once')); if isempty(val), val = ''; else, val = val{1}; end if nargin<3 || isNum, val = sscanf(val, '%g'); end end end %% subfunction: read AFNI HEAD file, return struct like that from dicm_hdr. function [s, err] = afni_head(fname) err = ''; fid = fopen(fname); if fid<0, s = []; err = ['File not exist: ' fname]; return; end str = fread(fid, inf, '*char')'; fname = fopen(fid); fclose(fid); i = strfind(str, 'DATASET_DIMENSIONS'); if isempty(i), s = []; err = 'Not brik header file'; return; end % these make dicm_nii.m happy [~, foo] = fileparts(fname); % s.IsAFNIHEAD = true; s.ProtocolName = foo; s.ImageType = ['AFNIHEAD\' afni_key('TYPESTRING')]; foo = afni_key('BYTEORDER_STRING'); % "LSB_FIRST" or "MSB_FIRST". if strcmpi(foo, 'MSB_FIRST'), s.TransferSyntaxUID = '1.2.840.10008.1.2.2'; end foo = afni_key('BRICK_FLOAT_FACS'); if any(diff(foo)~=0), err = 'Inconsistent BRICK_FLOAT_FACS'; s = []; return; end if foo(1)==0, foo = 1; end s.RescaleSlope = foo(1); s.RescaleIntercept = 0; foo = afni_key('BRICK_TYPES'); if any(diff(foo)~=0), err = 'Inconsistent DataType'; s = []; return; end foo = foo(1); if foo == 0 bpp = 8; s.PixelData.Format = '*uint8'; elseif foo == 1 bpp = 16; s.PixelData.Format = '*int16'; elseif foo == 3 bpp = 32; s.PixelData.Format = '*single'; else error('Unsupported BRICK_TYPES: %g', foo); end hist = afni_key('HISTORY_NOTE'); i = strfind(hist, 'Time:') + 6; if ~isempty(i) dat = sscanf(hist(i:end), '%11c', 1); % Mar 1 2010 dat = datenum(dat, 'mmm dd yyyy'); s.AcquisitionDateTime = datestr(dat, 'yyyymmdd'); end i = strfind(hist, 'Sequence:') + 9; if ~isempty(i), s.ScanningSequence = strtok(hist(i:end), ' '); end i = strfind(hist, 'Studyid:') + 8; if ~isempty(i), s.StudyID = strtok(hist(i:end), ' '); end % i = strfind(hist, 'Dimensions:') + 11; % if ~isempty(i) % dimStr = strtok(hist(i:end), ' ') % 64x64x35x92 % end % i = strfind(hist, 'Orientation:') + 12; % if ~isempty(i) % oriStr = strtok(hist(i:end), ' ') % LAI % end i = strfind(hist, 'TE:') + 3; if ~isempty(i), s.EchoTime = sscanf(hist(i:end), '%g', 1) * 1000; end % foo = afni_key('TEMPLATE_SPACE'); % ORIG/TLRC % INT_CMAP foo = afni_key('SCENE_DATA'); s.TemplateSpace = foo(1)+1; %[0] 0=+orig, 1=+acpc, 2=+tlrc if foo(2)==9, s.ImageType = [s.ImageType '\DIFFUSION\']; end % ori = afni_key('ORIENT_SPECIFIC')+1; % orients = [1 -1 -2 2 3 -3]; % RL LR PA AP IS SI % ori = orients(ori) % in dicom/afni LPS, % seems always [1 2 3], meaning AFNI re-oriented the volome % no read/phase/slice dim info, so following 3D info are meaningless dim = afni_key('DATASET_DIMENSIONS'); s.Columns = dim(1); s.Rows = dim(2); s.LocationsInAcquisition = dim(3); R = afni_key('IJK_TO_DICOM_REAL'); % IJK_TO_DICOM is always straight? if isempty(R), R = afni_key('IJK_TO_DICOM'); end R = reshape(R, [4 3])'; s.ImagePositionPatient = R(:,4); % afni_key('ORIGIN') can be wrong s.LastFile.ImagePositionPatient = R * [0 0 dim(3)-1 1]'; % last slice R = R(1:3, 1:3); R = bsxfun(@rdivide, R, sqrt(sum(R.^2))); s.ImageOrientationPatient = R(1:6)'; foo = afni_key('DELTA'); s.PixelSpacing = abs(foo([2 1])); % s.SpacingBetweenSlices = foo(3); s.SliceThickness = abs(foo(3)); foo = afni_key('BRICK_STATS'); foo = reshape(foo, 2, []); mn = min(foo(1,:)); mx = max(foo(2,:)); s.WindowCenter = (mx+mn)/2; s.WindowWidth = mx-mn; foo = afni_key('TAXIS_FLOATS'); %[0]:0; if ~isempty(foo), s.RepetitionTime = foo(2)*1000; end foo = afni_key('TAXIS_NUMS'); % [0]:nvals; [1]: 0 or nSL normally if ~isempty(foo) inMS = foo(3)==77001; foo = afni_key('TAXIS_OFFSETS'); if inMS, foo = foo/1000; end if ~isempty(foo), s.MosaicRefAcqTimes = foo; end end foo = afni_key('DATASET_RANK'); % [3 nvals] dim(4) = foo(2); s.NumberOfTemporalPositions = dim(4); % s.NumberOfFrames = dim(4)*dim(3); s.Manufacturer = ''; s.Filename = strrep(fname, '.HEAD', '.BRIK'); s.PixelData.Start = 0; % make it work for dicm_img.m s.PixelData.Bytes = prod(dim(1:4)) * bpp / 8; % subfunction: return value specified by key in afni header str function val = afni_key(key) i1 = regexp(str, ['\nname\s*=\s*' key '\n']); % line 'name = key' if isempty(i1), val = []; return; end i1 = i1(1) + 1; typ = regexp(str(1:i1), 'type\s*=\s*(\w*)-attribute\n', 'tokens'); [n, i2] = regexp(str(i1:end), 'count\s*=\s*(\d+)', 'tokens', 'end', 'once'); n = sscanf(n{1}, '%g'); if strcmpi(typ{end}{1}, 'string') val = regexp(str(i1:end), '(?<='').*?(?=~?\n)', 'match', 'once'); else val = sscanf(str(i2+i1:end), '%g', n); end end end %% Subfunction: read BrainVoyager vmr/fmr/dmr. Call BVQXfile function [s, err] = bv_file(fname) s = []; err = ''; try bv = BVQXfile(fname); catch me err = me.message; if strfind(me.identifier, 'UndefinedFunction') fprintf(2, 'Please download BVQXtools at \n%s\n', ... 'http://support.brainvoyager.com/available-tools/52-matlab-tools-bvxqtools.html'); end return; end if ~isempty(bv.Trf) for i = 1:numel(bv.Trf) if ~isequal(diag(bv.Trf(i).TransformationValues), [1 1 1 1]') err = 'Data has been transformed: skipped.'; return; end end end persistent subj folder % folder is used to update subj if isempty(subj), subj = ''; folder = ''; end s.Filename = bv.FilenameOnDisk; fType = bv.filetype; s.ImageType = ['BrainVoyagerFile\' fType]; % Find a fmr/dmr, and get subj based on dicom file name in BV format. % Suppose BV files in the folder are for the same subj [pth, nam] = fileparts(s.Filename); s.SeriesDescription = nam; if isempty(folder) || ~strcmp(folder, pth) folder = pth; subj = ''; if strcmp(fType, 'fmr') || strcmp(fType, 'dmr') [~, nam] = fileparts(bv.FirstDataSourceFile); nam = strtok(nam, '-'); if ~isempty(nam), subj = nam; end else fnames = dir([pth '/*.fmr']); if isempty(fnames), fnames = dir([pth '/*.dmr']); end if ~isempty(fnames) bv1 = BVQXfile(fullfile(pth, fnames(1).name)); [~, nam] = fileparts(bv1.FirstDataSourceFile); bv1.ClearObject; nam = strtok(nam, '-'); if ~isempty(nam), subj = nam; end end end end if ~isempty(subj), s.PatientName = subj; end s.SoftwareVersion = sprintf('%g/BV_FileVersion', bv.FileVersion); s.Columns = bv.NCols; s.Rows = bv.NRows; s.SliceThickness = bv.SliceThickness; R = [bv.RowDirX bv.RowDirY bv.RowDirZ; bv.ColDirX bv.ColDirY bv.ColDirZ]'; s.ImageOrientationPatient = R(:); R(:,3) = cross(R(:,1), R(:,2)); [~, ixyz] = max(abs(R)); iSL =ixyz(3); try s.TemplateSpace = bv.ReferenceSpace; % 0/2/3: Scanner/ACPC/TAL if s.TemplateSpace==0, s.TemplateSpace = 1; end catch s.TemplateSpace = 1; end pos = [bv.Slice1CenterX bv.Slice1CenterY bv.Slice1CenterZ bv.SliceNCenterX bv.SliceNCenterY bv.SliceNCenterZ]'; % for real slices if strcmpi(fType, 'vmr') s.SpacingBetweenSlices = s.SliceThickness + bv.GapThickness; s.PixelSpacing = [bv.VoxResX bv.VoxResY]'; % order correct? if ~isempty(bv.VMRData16) nSL = bv.DimZ; s.PixelData = bv.VMRData16; % no padded zeros else v16 = [s.Filename(1:end-3) 'v16']; if exist(v16, 'file') bv16 = BVQXfile(v16); nSL = bv16.DimZ; s.PixelData = bv16.VMRData; % no padded zeros bv16.ClearObject; else % fall back the 8-bit data, and deal with padded zeros ix = floor((bv.DimX - s.Columns)/2); iy = floor((bv.DimY - s.Rows)/2); R3 = abs(R(iSL,3)) * s.SpacingBetweenSlices; nSL = round(abs(diff(pos(iSL,:))) / R3) + 1; iz = floor((bv.DimZ - nSL)/2); s.PixelData = bv.VMRData(ix+(1:s.Columns), iy+(1:s.Rows), iz+(1:nSL), :); end end s.LocationsInAcquisition = nSL; s.MRAcquisitionType = '3D'; % for dicm2nii to re-orient elseif strcmpi(fType, 'fmr') || strcmpi(fType, 'dmr') s.SpacingBetweenSlices = s.SliceThickness + bv.SliceGap; s.PixelSpacing = [bv.InplaneResolutionX bv.InplaneResolutionY]'; % order? nSL = bv.NrOfSlices; s.LocationsInAcquisition = nSL; s.NumberOfTemporalPositions = bv.NrOfVolumes; s.RepetitionTime = bv.TR; s.EchoTime = bv.TE; if bv.TimeResolutionVerified switch bv.SliceAcquisitionOrder % the same as NIfTI? case 1, ind = 1:nSL; case 2, ind = nSL:-1:1; case 3, ind = [1:2:nSL 2:2:nSL]; case 4, ind = [nSL:-2:1 nSL-1:-2:1]; case 5, ind = [2:2:nSL 1:2:nSL]; case 6, ind = [nSL-1:-2:1 nSL:-2:1]; otherwise, ind = []; err = 'Unknown SliceAcquisitionOrder'; end if ~isempty(ind) t = (0:s.LocationsInAcquisition-1)' * bv.InterSliceTime; % ms t(ind) = t; s.SliceTiming = t; end end if strcmpi(fType, 'fmr') bv.LoadSTC; s.PixelData = permute(bv.Slice(1).STCData , [1 2 4 3]); for i = 2:numel(bv.Slice) s.PixelData(:,:,i,:) = permute(bv.Slice(i).STCData , [1 2 4 3]); end else % dmr s.ImageType = [s.ImageType '\DIFFUSION\']; bv.LoadDWI; s.PixelData = bv.DWIData; if strncmpi(bv.GradientInformationAvailable, 'Y', 1) a = bv.GradientInformation; % nDir by 4 s.B_value = a(:,4); a = a(:,1:3); % bvec % Following should be right in theory, but I would trust the grd % table which should be in dicom coodinate system, rather than the % confusing Gradient?DirInterpretation % % 1:6 for LR RL AP PA IS SI. Default [2 3 5] by dicom LPS % i1_6 = [bv.GradientXDirInterpretation ... % bv.GradientYDirInterpretation ... % bv.GradientZDirInterpretation]; % [xyz, ind] = sort(i1_6); % if isequal(ceil(xyz/2), 1:3) % perm of 1/2/3 % a = a(:,ind); % flip = xyz == [1 4 6]; % negative by dicom % a(:,flip) = -a(:,flip); % else % str = sprintf(['Wrong Interpretation of gradient found: %s\n' ... % 'Please check bvec and its sign.\n'], fname); % fprintf(2, str); % err = [err str]; % end s.bvec_original = a; end end % fmr/dmr are normally converted from uint16 to single if isfloat(s.PixelData) && isequal(floor(s.PixelData), s.PixelData) ... && max(s.PixelData(:))<32768 && min(s.PixelData(:))>=-32768 s.PixelData = int16(s.PixelData); end else err = ['Unknown BV file type: ' fType]; s = []; return; end pos = pos - R(:,1:2) * diag(s.PixelSpacing([2 1])) * [s.Columns s.Rows]'/2 * [1 1]; s.ImagePositionPatient = pos(:,1); s.LastFile.ImagePositionPatient = pos(:,2); % Following make dicm2nii happy s.SeriesInstanceUID = sprintf('%s_%03x', datestr(now, 'yymmddHHMMSSfff'), randi(999)); end %% subfunction: read Freesurfer mgh or mgz file, return dicm info dicm_hdr. function [s, err] = mgh_file(fname) err = ''; s = []; [~, ~, ext] = fileparts(fname); isGZ = strcmpi(ext, '.mgz'); % .mgz = .mgh.gz if isGZ nam = nii_tool('LocalFunc', 'gunzipOS', fname); fid = fopen(nam, 'r', 'b'); else fid = fopen(fname, 'r', 'b'); % always big endian? end if fid<0, err = sprintf('File not exists: %s', fname); return; end cln = onCleanup(@() close_mgh(fid, isGZ)); % close file, delete if isGZ v = fread(fid, 1, 'int32'); if v ~= 1, err = sprintf('Not mgh file: %s', fname); return; end dim = fread(fid, 4, 'int32')'; typ = fread(fid, 1, 'int32'); dof = fread(fid, 1, 'int32'); %#ok not used s.Filename = fname; s.Columns = dim(1); s.Rows = dim(2); s.LocationsInAcquisition = dim(3); if dim(4)>1, s.NumberOfTemporalPositions = dim(4); end have_ras = fread(fid, 1, 'int16'); if have_ras % 3+9+3=15 single pixdim = fread(fid, 3, 'single'); R = fread(fid, [3 3], 'single'); % direction cosine matrix c = fread(fid, 3, 'single'); % center xyz R(1:2,:) = -R(1:2,:); c(1:2) = -c(1:2); % RAS to dicom LPS s.PixelSpacing = pixdim([2 1]); s.SliceThickness = pixdim(3); s.ImageOrientationPatient = R(1:6)'; R = R * diag(pixdim); s.ImagePositionPatient = R * -dim(1:3)'/2 + c; s.LastFile.ImagePositionPatient = R * [-(dim(1:2))/2 dim(3)/2-1]' + c; else s.ImageOrientationPatient = [1 0 0 0 0 -1]'; % coronal end switch typ case 0, fmt = 'uint8'; % MRI_UCHAR case 1, fmt = 'int32'; % MRI_INT case 2, fmt = 'int32'; % MRI_LONG case 3, fmt = 'single'; % MRI_FLOAT case 4, fmt = 'int16'; % MRI_SHORT % case 5, fmt = 'uint8'; % MRI_BITMAP *3? % case 6, fmt = 'uint8'; % MRI_TENSOR *5? otherwise err = sprintf('Unknown datatype: %s', fname); s = []; return; end fseek(fid, 284, 'bof'); % start of img data nv = prod(dim); img = fread(fid, nv, ['*' fmt]); if numel(img) ~= nv err = ['Not enough data in file: ' fname]; s = []; return; end flds = {'RepetitionTime' 'FlipAngle' 'EchoTime' 'InversionTime'}; parms4 = fread(fid, 4, 'single'); for i = 1:numel(parms4), s.(flds{i}) = parms4(i); end if isfield(s, 'FlipAngle'), s.FlipAngle = s.FlipAngle/pi*180; end % to deg s.PixelData = reshape(img, dim); function close_mgh(fid, isGZ) if isGZ uzip_nam = fopen(fid); fclose(fid); delete(uzip_nam); else fclose(fid); end end end %% similar to philips_par, inspired by Julien's xml2par function [s, err] = philips_xml(fname) err = ''; fid = fopen(fname); if fid<0, s = []; err = ['File not exist: ' fname]; return; end fullName = fopen(fid); % name with full path ch = fread(fid, inf, '*char')'; % read all as char fclose(fid); [pth, nam] = fileparts(fullName); i = regexp(ch, '</Series_Info>', 'once'); if isempty(i), s = []; err = 'Not valid Philips xml file'; return; end ch1 = ch(1:i); ch = ch(i:end); s.SoftwareVersion = regexp(ch1, '(?<=<)PRIDE.*?(?=>)', 'match', 'once'); s.PatientName = xml_attr(ch1, 'Patient Name'); s.StudyDescription = xml_attr(ch1, 'Examination Name'); s.SeriesDescription = nam; s.ProtocolName = xml_attr(ch1, 'Protocol Name'); d = xml_attr(ch1, 'Examination Date'); d = d(isstrprop(d, 'digit')); t = xml_attr(ch1, 'Examination Time'); t = t(isstrprop(t, 'digit')); s.AcquisitionDateTime = [d t]; s.SeriesNumber = xml_attr(ch1, 'Ac?quisition Number', 1); % s.ReconstructionNumberMR = xml_attr(ch1, 'Reconstruction Number', 1); % s.MRSeriesScanDuration = xml_attr(ch1, 'Scan Duration', 1); s.NumberOfEchoes = xml_attr(ch1, 'Max No Echoes', 1); s.LocationsInAcquisition = xml_attr(ch1, 'Max No Slices', 1); s.PatientPosition = xml_attr(ch1, 'Patient Position'); s.MRAcquisitionType = xml_attr(ch1, 'Scan Mode'); s.ScanningSequence = xml_attr(ch1, 'Technique'); % ScanningTechnique typ = xml_attr(ch1, 'Series Data Type'); typ(isspace(typ)) = ''; s.ImageType = ['PhilipsXML\' typ '\' s.ScanningSequence]; s.RepetitionTime = xml_attr(ch1, 'Repetition Times?', 1); if numel(s.RepetitionTime)>1, s.RepetitionTime = s.RepetitionTime(1); end s.WaterFatShift = xml_attr(ch1, 'Water Fat Shift', 1); s.EPIFactor = xml_attr(ch1, 'EPI factor', 1); % s.DynamicSeries = xml_attr(ch1, 'Dynamic Scan', 1); % 0 or 1 isDTI = strncmpi(xml_attr(ch1, 'Diffusion'), 'Y', 1); if isDTI s.ImageType = [s.ImageType '\DIFFUSION\']; s.DiffusionEchoTime = xml_attr(ch1, 'Diffusion echo time', 1); % ms end % SortFrames solves XYTZ, unusual slice order, incomplete volume etc keys = {'Dynamic' 'Grad Orient' 'Echo' 'Phase' 'Type' 'Label Type' 'Sequence'}; id = []; for i = 1:numel(keys) [aa, ~, a] = unique(xml_raw(ch, keys{i}, i<5)); if numel(aa)>1, id = [id a]; end %#ok end sort_frames = dicm2nii('', 'sort_frames', 'func_handle'); sl = xml_raw(ch, 'Slice'); if isDTI, sl(:,2) = xml_raw(ch, 'Diffusion B Factor'); end [ind_sort, nSL] = sort_frames(sl, id); nFrame = size(sl, 1); a = xml_raw(ch, 'Index'); % always 0:nFrame-1 ? a(a+1) = 1:nFrame; % [~, a] = sort(a); a = a(ind_sort)'; if ~isequal(a, 1:nFrame), s.SortFrames = a; end % used only in dicm2nii s.NumberOfFrames = numel(ind_sort); % may be smaller than nFrame s.NumberOfTemporalPositions = s.NumberOfFrames/nSL; iVol = ind_sort((0:s.NumberOfTemporalPositions-1)*nSL + 1); % already XYZT typ = {'MAGNITUDE' 'REAL' 'IMAGINARY' 'PHASE'}; imgType = xml_val(ch, 'Type', 0, iVol); % 'M' for i = 1:numel(imgType), imgType{i} = find(strncmpi(typ, imgType{i}, 1), 1); end imgType = cell2mat(imgType); if numel(iVol) == 1 s.ComplexImageComponent = typ{imgType(1)}; elseif any(diff(imgType) ~= 0) % more than 1 type of image s.ComplexImageComponent = 'MIXED'; s.Volumes.ComplexImageComponent = typ(imgType); % one for each vol s.Volumes.RescaleIntercept = xml_val(ch, 'Rescale Intercept', 1, iVol); s.Volumes.RescaleSlope = xml_val(ch, 'Rescale Slope', 1, iVol); s.Volumes.MRScaleSlope = xml_val(ch, 'Scale Slope', 1, iVol); else s.ComplexImageComponent = typ(imgType(1)); end % These columns should be the same for nifti-convertible images: keys = {'Pixel Size' 'Resolution X' 'Resolution Y' 'Slice Orientation' ... 'Angulation AP' 'Angulation FH' 'Angulation RL' ... 'Slice Thickness' 'Slice Gap' 'Pixel Spacing'}; if ~strcmp(s.ComplexImageComponent, 'MIXED') keys = [keys {'Rescale Intercept' 'Rescale Slope' 'Scale Slope'}]; end for i = 1:numel(keys) if numel(unique(xml_raw(ch, keys{i}, 0))) > 1 err = sprintf('Inconsistent %s for %s', keys{i}, fullName); fprintf(2, ' %s. \n', err); s = []; return; end end v1 = ind_sort(1); s.BitsAllocated = xml_val(ch, 'Pixel Size'); s.Columns = xml_val(ch, 'Resolution X'); s.Rows = xml_val(ch, 'Resolution Y'); s.RescaleIntercept = xml_val(ch, 'Rescale Intercept', 1, v1); s.RescaleSlope = xml_val(ch, 'Rescale Slope', 1, v1); s.MRScaleSlope = xml_val(ch, 'Scale Slope', 1, v1); s.SliceThickness = xml_val(ch, 'Slice Thickness'); s.EchoTimes = xml_val(ch, 'Echo Time', 1, iVol); s.EchoTime = s.EchoTimes(1); s.FlipAngle = xml_val(ch, 'Image Flip Angle'); s.NumberOfAverages = xml_val(ch, 'No Averages'); s.CardiacTriggerDelayTimes = xml_val(ch, 'Trigger Time', 1, iVol); if isDTI s.B_value = xml_val(ch, 'Diffusion B Factor', 1, iVol); s.bvec_original = [xml_val(ch, 'Diffusion RL', 1, iVol) ... xml_val(ch, 'Diffusion AP', 1, iVol) ... xml_val(ch, 'Diffusion FH', 1, iVol)]; end s.TurboFactor = xml_val(ch, 'TURBO Factor'); a = [xml_attr(ch1, 'Angulation RL', 1) xml_attr(ch1, 'Angulation AP', 1) xml_attr(ch1, 'Angulation FH', 1)] /180*pi; % deg to radians R = makehgtform('xrotate', a(1), 'yrotate', a(2), 'zrotate', a(3)); R = R(1:3, :); s.SliceOrientation = upper(xml_val(ch, 'Slice Orientation', 0)); iOri = find(strncmp({'SAG' 'COR' 'TRA'}, s.SliceOrientation, 3)); if iOri == 1 R(:,[1 3]) = -R(:,[1 3]); R = R(:, [2 3 1 4]); elseif iOri == 2 R(:,3) = -R(:,3); R = R(:, [1 3 2 4]); end s.PixelSpacing = xml_val(ch, 'Pixel Spacing')'; s.SpacingBetweenSlices = xml_val(ch, 'Slice Gap') + s.SliceThickness; a = xml_attr(ch1, 'Preparation Direction'); % AP s.Stack.Item_1.MRStackPreparationDirection = a; iPhase = strfind('LRAPFH', a(1)); iPhase = ceil(iPhase/2); % 1/2/3 if iPhase == (iOri==1)+1, a = 'ROW'; else, a = 'COL'; end s.InPlanePhaseEncodingDirection = a; s.ImageOrientationPatient = R(1:6)'; R = R * diag([s.PixelSpacing([2 1]); s.SpacingBetweenSlices; 1]); R(:,4) = [xml_attr(ch1, 'Off Center RL', 1) xml_attr(ch1, 'Off Center AP', 1) xml_attr(ch1, 'Off Center FH', 1)]; % vol center for now ori = {'RL' 'AP' 'FH'}; ori = ori{iOri}; s.SliceLocation = xml_val(ch, ['Offcenter ' ori], 1, v1); if sign(R(iOri,3)) ~= sign(R(iOri,4)-s.SliceLocation) R(:,3) = -R(:,3); end R(:,4) = R * [-([s.Columns s.Rows nSL]-1)/2 1]'; % vol center to corner of 1st s.ImagePositionPatient = R(:,4); s.LastFile.ImagePositionPatient = R * [0 0 nSL-1 1]'; % last slice s.Manufacturer = 'Philips'; s.Filename = fullfile(pth, [nam '.REC']); % rest for dicm_img s.PixelData.Start = 0; s.PixelData.Bytes = s.Rows * s.Columns * nFrame * s.BitsAllocated / 8; % Return xml attribute value for key in Series_Info function val = xml_attr(ch1, key, isnum) expr = ['<Attribute\s+Name="' key '".*?>(.*?)</Attribute>']; val = regexp(ch1, expr, 'tokens', 'once'); if isempty(val), val = ''; else, val = val{1}; end if nargin>2 && isnum, val = str2num(val); end %#ok<*ST2NM> end % Return all values for key with original order in Image_Info function val = xml_raw(ch, key, isnum) expr = ['<Attribute\s+Name="' key '".*?>(.*?)</Attribute>']; val = regexp(ch, expr, 'tokens'); val = [val{:}]'; if nargin<3 || isnum, val = str2num(char(val)); end end % Return values for key in Image_Info for volumes iVol function val = xml_val(ch, key, isnum, iVol) if nargin<3 || isempty(isnum), isnum = true; end if nargin<4 || isempty(iVol), iVol = 1; end expr = ['<Attribute\s+Name="' key '".*?>(.*?)</Attribute>']; if isequal(iVol, 1), val = regexpi(ch, expr, 'tokens', 'once'); else, val = regexp(ch, expr, 'tokens'); val = [val{iVol}]'; end if isnum, val = str2num(char(val)); elseif nargin<4, val = val{1}; end end end
github
cocoanlab/humanfmri_preproc_bids-master
nii_viewer.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/nii_viewer.m
147,002
utf_8
9704a0e67438819449f6d0f5a1dc4334
function varargout = nii_viewer(fname, varargin) % Basic tool to visualize NIfTI images. % % NII_VIEWER('/data/subj2/fileName.nii.gz') % NII_VIEWER('background.nii', 'overlay.nii') % NII_VIEWER('background.nii', {'overlay1.nii' 'overlay2.nii'}) % % If no input is provided, the viewer will load included MNI_2mm brain as % background NIfTI. Although the preferred format is NIfTI, NII_VIEWER accepts % any files that can be converted into NIfTI by dicm2nii, including NIfTI, % dicom, PAR/REC, etc. In case of CIfTI file, it will show the volume view, as % well as surface view if GIfTI is available. % % Here are some features and usage. % % The basic use is to open a NIfTI file to view. When a NIfTI (background) is % open, the display always uses the image plane close to xyz axes (voxel space) % even for oblique acquisition. The possible confusion arises if the acquisition % was tilted with a large angle, and then the orientation labels will be less % accurate. The benefit is that no interpolation is needed for the background % image, and there is no need to switch coordinate system when images with % different systems are overlaid. The display is always in correct scale at % three axes even with non-isotropic voxels. The displayed IJK always correspond % to left -> right, posterior -> anterior and inferior -> superior directions, % while the NIfTI data may not be saved in this order or along these directions. % The I-index is increasing from left to right even when the display is flipped % as radiological convention (right on left side). % % Navigation in 4D can be by mouse click, dialing IJK and volume numbers, or % using keys (arrow keys and [ ] for 3D, and < > for volume). % % After the viewer is open, one can drag-and-drop a NIfTI file into the viewer % to open as background, or drop a NIfTI with Control key down to add it as % overlay. % % By default, the viewer shows full view of the background image data. The % zoom-in always applies to three views together, and enlarges around the % location of the crosshair. To zoom around a different location, set the % crosshair to the interested location, and apply zoom again either by View -> % Zoom in, or pressing Ctrl (Cmd) and +/-. View -> Set crosshair at -> center of % view (or pressing key C) can set the crosshair to the center of display for % all three views. % % Overlays are always mapped onto the coordinate of background image, so % interpolation (nearest/linear/cubic/spline) is usually involved. The overlay % makes sense only when it has the same coordinate system as the background % image, while the resolution and dimension can be different. The viewer tries % to match any of sform and qform between the images. If there is no match, a % warning message will show up. % % A special overlay feature "Add aligned overlay" can be used to check the % effect of registration, or overlay an image to a different coordinate system % without creating a transformed file. It will ask for two files. The first is % the overlay NIfTI file, and the second is either a transformation matrix file % which aligns the overlay to the background image, or a warp file which % transforms the overlay into the background reference. % % Here is an example to check FSL alignment. From a .feat/reg folder, Open % "highres" as background image. "Add overlay" for "example_func". If there is % head movement between the highres and the functional scans, the overlap will % be off. Now "Add aligned overlay" for "example_func", and use % example_func2highres.mat as the matrix. The two dataset should overlap well if % the alignment matrix is accurate. % % Here is another example to overlay to a different coordinate system for FSL % result. Open .feat/reg/standard.nii.gz as background. If an image like % .feat/stats/zstat1.nii.gz is added as an overlay, a warning message will say % inconsistent coordinate system since the zstat image is in Scanner Anat. The % correct way is to "Add aligned overlay" for zstat1, and either use % .feat/reg/example_func2standard.mat for linear transformation or better use % .feat/reg/example_func2standard_warp.nii.gz if available for alignment. % % When the mouse pointer is moved onto a voxel, the x/y/z coordinates and voxel % value will show on the panel. If there is an overlay, the overlay voxel value % will also show up, unless its display is off. When the pointer moves onto the % panel or out of an image, the information for the voxel at crosshair will be % displayed. The display format is as following with val of the top image % displayed first: % (x,y,z): val_1 val_2 val_3 ... % % Note that although the x/y/z coordinates are shared by background and overlay % images, IJK indices are always for background image (name shown on title bar). % % The mouse-over display can be turned on/off from Help -> Preferences ... % % If there is a .txt label file in the same folder as the NIfTI file, like for % AAL, the labels will be shown instead of voxel value. The txt file should have % a voxel value and ROI label pair per line, like % 1 Precentral_L % 2 Precentral_R % 3 ... % % Image display can be smoothed in 3D (default is off). The smooth is slow when % the image dimension is large, even when the current implementation of smooth % does not consider voxel size. % % Background image and overlays are listed at the top-left of the panel. All % parameters of the bottom row of the panel are for the selected image. This % feature is indicated by a frame grouping these parameters. Each NIfTI file has % its own set of parameters (display min and max value, LUT, alpha, whether to % smooth, interpolation method, and volume number) to control its display. % Moving the mouse onto a parameter will show the meaning of the parameter. % % The lastly added overlay is on the top of display and top of the file list. % This also applies in case there is surface figure for CIfTI files. The % background and overlay order can be changed by the two small arrows next to % the list, or from Overlay -> Move selected image ... % % Each NIfTI display can be turned on/off by clicking the small checkbox at the % left side of the file (or pressing spacebar for the selected NIfTI). This % provides a way to turn on/off an overlay to view the overlap. Most operations % are applied to the selected NIfTI in the list, such as Show NIfTI hdr/ext % under Window menu, Move/Close overlay under Overlay menu, and most operations % under File menu. % % A NIfTI mask can be applied to the selected image. Ideally, the mask should be % binary, and the image corresponding to the non-zero part of the mask will be % displayed. If non-binary mask is detected, a threshold to binarize will be % asked. If the effect is not satisfied with the threshold, one can apply the % mask with a different threshold without re-loading image. The way to remove a % mask is to Remove, then Add overlay again. In case one likes to modulate the % selected image with another NIfTI image (multiply two images), File -> Apply % modulation will do it. If the mask image is not within 0 and 1, the lower and % upper bound will be asked to normalize the range to [0 1]. A practical use of % modulation is to use dti_FA map as weight for dti_V1 RGB image. % % For multi-volume data, one can change the Volume Number (the parameter at % rightmost of the panel) to check the head motion. Click in the number dialer % and or press < or > key, to simulate movie play. It is better to open the 4D % data as background, since it may be slower to map it to the background image. % % Popular LUT options are implemented. Custom LUT can be added by Overlay -> % Load LUT for selected overlay. The custom LUT file can be in text format (each % line represents an RGB triplet, while the first line corresponds to the value % 0 in the image data), or binary format (uint8 for all red, then green then % blue). The color coding can be shown by View -> Show colorbar. There are % several special LUTs. The "two-sided" allows to show both positive and % negative data in one view. For example, if the display range is 3 to 10 for a % t-map, positive T above 3 will be coded as red-yellow, and T below -3 will be % coded as blue-green. This means the absolute display range values are used. % % One of the special LUT is "lines" in red text. This is for normalized vector % display, e.g. for diffusion vector. The viewer will refuse the LUT selection % if the data is not normalized vector. Under this LUT, all other parameters for % the display are ignored. The color of the "lines" is the max color of previous % LUT. For example, if one likes to show blue vector lines, choose LUT "blue" % first, then change it to "lines". % % In case of complex image, most LUTs will display only the magnitude of the % data, except the following three phase LUTs, where the magnitude is used as % mask. Here is how the 3 phase LUTs encodes phase from 0 to 360 degree: % phase: red-yellow monotonically, % phase3: red-yellow-green-yellow-red circularly, and % phase6: red-yellow-green/violet-blue-cyan, with sharp change at 180 degree. % These LUTs are useful to visualize activation of periodic stimulus, such as % those by expanding/shrinking ring or rotating wedge for retinotopy. To use % this feature, one can save an complex NIfTI storing the Fourier component at % the stimulus frequency. % % Note that, for RGB NIfTI, the viewer always displays the data as color % regardless of the LUT option. The display min and max value also have no % effect on RGB image. There is a special LUT, RGB, which is designed to display % non-RGB NIfTI data as RGB, e.g. FSL-style 3-volome data. % % The viewer figure can be copied into clipboard (not available for Linux) or % saved as variety of image format. For high quality picture, one can increase % the output resolution by Help -> Preferences -> Resolution. Higher resolution % will take longer time to copy or save, and result in larger file. If needed, % one can change to white background for picture output. With white background, % the threshold for the background image needs to be carefully selected to avoid % strange effect with some background images. For this reason, white background % is intended only for picture output. % % The selected NIfTI can also be saved as different format from File -> Save % NIfTI as. For example, a file can be saved as a different resolution. With a % transformation matrix, a file can also be saved into a different template. The % latter is needed for FSLview since it won't allow overlay with different % resolution or dimension at least till version 5.0.8. % % See also NII_TOOL DICM2NII NII_XFORM %% By Xiangrui Li (xiangrui.li at gmail.com) % History(yymmdd): % 151021 Almost ready to publish. % 151104 Include drag&drop by Maarten van der Seijs. % 151105 Bug fix for Show NIfTI hdr/ext. % 151106 Use p.interp to avoid unnecessary interp for overlay; % Use check mark for colorbar/crosshair/background menu items. % 151111 Take care of slope/inter of img; mask applies to DTI lines. % 151114 Avoid see-thu for white background. % 151119 Make smooth faster by using only 3 slices; Allow flip L/R. % 151120 Implement key navigation and zoom in/out. % 151121 Implement erode for white background; Add 'Show NIfTI essentials'. % 151122 Bug fix for background img with sform=0. % 151123 Show coordinate system in fig title; show masked/aligned in file list; % Bug fix for alpha (0/1 only); Bug fix for background image R change. % 151125 Avoid recursion for white background (failed under Linux). % 151128 Change checkbox to radiobutton: looks better; % Fix the bug in reorient dim(perm), introduced in last revision. % 151129 Correct Center crosshair (was off by 0.5); Use evt.Key & add A/C/X/F1. % 151201 Keep fig location & pref when 'open' & dnd: more user friendly. % 151202 java robot trick allows to add overlay by Ctrl-dnd. % 151207 Implement 'Add modulation'. % 151208 Add xyz display for each view. % 151217 Callback uses subfunc directly, and include fh as input. % 151222 Show ROI labels (eg AAL) if .txt file with same name exists. % 151224 Implement more matlab LUTs and custom LUT. % 151230 Use listbox for files; Add stack buttons; file order reversed. % 160102 Store p.R0 if need interp; No coordinate change for background. % 160104 set_cdata: avoid indexing for single vol img: may be much faster! % jscroll_handle from findjobj.m to set vertical scoll bar as needed. % 160107 Rename XYZ label to IJK, implement "Set crosshair at XYZ". % 160108 Fix the case of 2-form_code for background and addMask. % 160109 Allow to turn off mouse-over display from Preferences; % Implement Help -> Check update for easy update; % Use Matlab built-in pref method for all files in the package. % 160111 Use image ButtonDownFcn; Mouse down&move now is same as mouse move. % 160112 Change back to line for crosshair: quiver is slow; % Bug fix for white backgrnd & saveas backgrnd due to list order reverse. % 160113 Implement time course for a cube. % 160114 Figure visible avoids weird hanging problem for some matlab versions. % 160119 Allow adding multiple overlays with cellstr as 2nd input. % 160131 set_file: bug fix for cb(j); dnd: restore mouse location. % 160208 Allow moving background image in stack. % 160209 RGBA data supported; Background image can use lut "lines". % 160218 "lines": Fix non-isovoxel display; Same-dim background not required. % 160402 nii_xform_mat: make up R for possible Analyze file. % 160506 phase LUT to map complex img: useful for retinotopy. % 160509 Have 3 phase LUTs; Implement 'Open in new window'. % 160512 KeyPressFcn bug fix: use the smallest axis dim when zoom in. % 160517 KeyPressFcn: avoid double-dlg by Ctrl-A; phase6: bug fix for blue b3. % 160531 use handle() for fh & others: allow dot convention for early matlab. % 160601 Add cog and to image center, re-organize 'Set crosshair at' menu. % 160602 bug fix for 'closeAll' files.String(ib); COG uses abs and excludes NaN. % 160605 Add 'RGB' LUT to force RGB display: DTI_V1 or fsl style RGB file. % 160608 javaDropFcn: 2 more method for ctlDn; bug fix for fh.xxx in Resize. % 160620 Use JIDE CheckBoxList; Simplify KeyFcn by not focusing on active items. % 160627 javaDropFcn: robot-click drop loc to avoid problem with vnc display. % 160701 Implement hist for current volume; hs.value show top overlay first. % 160703 bug fix for 'Add aligned' complex img: set p.phase after re-orient. % 160710 Implement 'Create ROI file'; Time coure is for sphere, not cube. % 160713 javaDropFnc for Linux: Robot key press replaces mouse click; % Implement 'Set crosshair at' 'Smoothed maximum'. % 160715 lut2img: bug fix for custom LUT; custom LUT uses rg [0 255]; add gap=0. % 160721 Implement 'Set crosshair at' & 'a point with value of'. % 160730 Allow to load single volume for large dataset. % 161003 Add aligned overlay: accept FSL warp file as transformation. % 161010 Implement 'Save volume as'; xyzr2roi: use valid q/sform. % 161018 Take care of issue converting long file name to var name. % 161103 Fix qform-only overlay, too long fig title, overlay w/o valid formCode. % 161108 Implement "Crop below crosshair" to remove excessive neck tissue. % 161115 Use .mat file for early spm Analyze file. % 161216 Show more useful 4x4 R for both s/q form in nii essentials. % 170109 bug fix: add .phase for background nifti. % 170130 get_range: use nii as input, so always take care of slope/inter. % 170210 Use flip for flipdim if available (in multiple files). % 170212 Can open nifti-convertible files; Add Save NIfTI as -> a copy. % 170421 java_dnd() changed as func, ControlDown OS independent by ACTION_LINK. % 170515 Use area to normalize histogram. % 171031 Implement layout. axes replace subplot to avoid overlap problem. % 171129 bug fix save_nii_as(): undo img scale for no_save_nii. % 171214 Try to convert back to volume in case of CIfTI (need anatomical gii). % 171226 Store all info into sag img handle (fix it while it aint broke :) % 171228 Surface view for gii (include HCP gii template). % 171229 combine into one overlay for surface view. % 180103 Allow inflated surface while mapping to correct location in volume. % 180108 set_file back to nii_viewer_cb for cii_view_cb convenience. % 180128 Preference stays for current window, and applies to new window only. % 180228 'Add overlay' check nii struct in base workspace first. % 180309 Implement 'Standard deviation' like for 'time course'. % 180522 set_xyz: bug fix for display val >2^15. % Later update history can be found at github. %% if nargin==2 && ischar(fname) && strcmp(fname, 'func_handle') varargout{1} = str2func(varargin{1}); return; elseif nargin>0 && ischar(fname) && strcmp(fname, 'LocalFunc') [varargout{1:nargout}] = feval(varargin{:}); return; end if nargin<1 || isempty(fname) % open the included standard_2mm fname = fullfile(fileparts(mfilename('fullpath')), 'example_data.mat'); fname = load(fname, 'nii'); fname = fname.nii; end nii = get_nii(fname); [p, hs.form_code, rg, dim] = read_nii(nii); % re-oriented p.Ri = inv(p.R); nVol = size(p.nii.img, 4); hs.bg.R = p.R; hs.bg.Ri = p.Ri; hs.bg.hdr = p.hdr0; if ~isreal(p.nii.img) p.phase = angle(p.nii.img); % -pi to pi p.phase = mod(p.phase/(2*pi), 1); % 0~1 p.nii.img = abs(p.nii.img); % real now end hs.dim = single(dim); % single saves memory for ndgrid hs.pixdim = p.pixdim; hs.gap = min(hs.pixdim) ./ hs.pixdim * 3; % in unit of smallest pixdim p.lb = rg(1); p.ub = rg(2); p = dispPara(p); [pName, niiName, ext] = fileparts(p.nii.hdr.file_name); if strcmpi(ext, '.gz'), [~, niiName] = fileparts(niiName); end if nargin>1 && any(ishandle(varargin{1})) % called by Open or dnd fh = varargin{1}; hsN = guidata(fh); pf = hsN.pref.UserData; % use the current pref for unless new figure fn = get(fh, 'Number'); close(fh); else pf = getpref('nii_viewer_para'); if isempty(pf) || ~isfield(pf, 'layout') % check lastly-added field pf = struct('openPath', pwd, 'addPath', pwd, 'interp', 'linear', ... 'extraV', NaN, 'dpi', '0', 'rightOnLeft', false, ... 'mouseOver', true, 'layout', 2); setpref('nii_viewer_para', fieldnames(pf), struct2cell(pf)); end set(0, 'ShowHiddenHandles', 'on'); a = handle(findobj('Type', 'figure', 'Tag', 'nii_viewer')); set(0, 'ShowHiddenHandles', 'off'); if isempty(a) fn = 'ni' * 256.^(1:2)'; % start with a big number for figure elseif numel(a) == 1 fn = get(a, 'Number') + 1; % this needs handle() to work else fn = max(cell2mat(get(a, 'Number'))) + 1; end end [siz, axPos, figPos] = plot_pos(dim.*hs.pixdim, pf.layout); fh = figure(fn); hs.fig = handle(fh); % have to use numeric for uipanel for older matlab figNam = p.nii.hdr.file_name; if numel(figNam)>40, figNam = [figNam(1:40) '...']; end figNam = ['nii_viewer - ' figNam ' (' formcode2str(hs.form_code(1)) ')']; set(fh, 'Toolbar', 'none', 'Menubar', 'none', 'Renderer', 'opengl', ... 'NumberTitle', 'off', 'Tag', 'nii_viewer', 'DockControls', 'off', ... 'Position', [figPos siz+[0 64]], 'Name', figNam); cb = @(cmd) {@nii_viewer_cb cmd hs.fig}; % callback shortcut xyz = [0 0 0]; % start cursor location c = round(p.Ri * [xyz 1]'); c = c(1:3)' + 1; % ind = c<=1 | c>=dim; c(ind) = round(dim(ind)/2); % c = round(dim/2); % start cursor at the center of images xyz = round(p.R * [c-1 1]'); % take care of rounding error %% control panel pos = getpixelposition(fh); pos = [1 pos(4)-64 pos(3) 64]; hs.panel = uipanel(fh, 'Units', 'pixels', 'Position', pos, 'BorderType', 'none'); hs.focus = uicontrol(hs.panel, 'Style', 'text'); % dummy uicontrol for focus % file list by JIDE CheckBoxList: check/selection independent mdl = handle(javax.swing.DefaultListModel, 'CallbackProperties'); % dynamic item mdl.add(0, niiName); mdl.IntervalAddedCallback = cb('width'); mdl.IntervalRemovedCallback = cb('width'); mdl.ContentsChangedCallback = cb('width'); % add '(mask)' etc h = handle(com.jidesoft.swing.CheckBoxList(mdl), 'CallbackProperties'); h.setFont(java.awt.Font('Tahoma', 0, 11)); % h.ClickInCheckBoxOnly = true; % it's default h.setSelectionMode(0); % single selection h.setSelectedIndex(0); % 1st highlighted h.addCheckBoxListSelectedIndex(0); % check it h.ValueChangedCallback = cb('file'); % selection change h.MouseReleasedCallback = @(~,~)uicontrol(hs.focus); % move focus away % h.Focusable = false; h.setToolTipText(['<html>Select image to show/modify its display ' ... 'parameters.<br>Click checkbox to turn on/off image']); jScroll = com.mathworks.mwswing.MJScrollPane(h); width = h.getPreferredScrollableViewportSize.getWidth; width = max(60, min(width+20, pos(3)-408)); % 20 pixels for vertical scrollbar [~, hs.scroll] = javacomponent(jScroll, [2 4 width 60], hs.panel); hCB = handle(h.getCheckBoxListSelectionModel, 'CallbackProperties'); hCB.ValueChangedCallback = cb('toggle'); % check/uncheck hs.files = javaObjectEDT(h); % trick to avoid java error by Yair % panel for controls except hs.files pos = [width 1 pos(3)-width pos(4)]; ph = uipanel(hs.panel, 'Units', 'pixels', 'Position', pos, 'BorderType', 'none'); clr = get(ph, 'BackgroundColor'); hs.params = ph; feature('DefaultCharacterSet', 'UTF-8'); % for old matlab to show triangles hs.overlay(1) = uicontrol(ph, 'Style', 'pushbutton', 'FontSize', 7, ... 'Callback', cb('stack'), 'Enable', 'off', 'SelectionHighlight', 'off', ... 'String', char(9660), 'Position', [1 36 16 15], 'Tag', 'down', ... 'TooltipString', 'Move selected image one level down'); hs.overlay(2) = copyobj(hs.overlay(1), ph); set(hs.overlay(2), 'Callback', cb('stack'), ... 'String', char(9650), 'Position', [1 50 16 15], 'Tag', 'up', ... 'TooltipString', 'Move selected image one level up'); hs.value = uicontrol(ph, 'Style', 'text', 'Position', [208 38 pos(3)-208 20], ... 'BackgroundColor', clr, 'FontSize', 8+(~ispc && ~ismac), ... 'TooltipString', '(x,y,z): top ... bottom'); % IJK java spinners labls = 'IJK'; str = {'Left to Right' 'Posterior to Anterior' 'Inferior to Superior'}; pos = [38 44 22]; posTxt = [36 10 20]; for i = 1:3 loc = [(i-1)*64+34 pos]; txt = sprintf('%s, 1:%g', str{i}, dim(i)); hs.ijk(i) = java_spinner(loc, [c(i) 1 dim(i) 1], ph, cb('ijk'), '#', txt); uicontrol(ph, 'Style', 'text', 'String', labls(i), 'BackgroundColor', clr, ... 'Position', [loc(1)-11 posTxt], 'TooltipString', txt, 'FontWeight', 'bold'); end % Controls for each file uipanel('Parent', ph, 'Units', 'pixels', 'Position', [1 2 412 34], ... 'BorderType', 'etchedin', 'BorderWidth', 2); hs.lb = java_spinner([7 8 48 22], [p.lb -inf inf p.lb_step], ph, ... cb('lb'), '#.##', 'min value (threshold)'); hs.ub = java_spinner([59 8 56 22], [p.ub -inf inf p.ub_step], ph, ... cb('ub'), '#.##', 'max value (clipped)'); hs.lutStr = {'grayscale' 'red' 'green' 'blue' 'violet' 'yellow' 'cyan' ... 'red-yellow' 'blue-green' 'two-sided' '<html><font color="red">lines' ... 'parula' 'jet' 'hsv' 'hot' 'cool' 'spring' 'summer' 'autumn' 'winter' ... 'bone' 'copper' 'pink' 'prism' 'flag' 'phase' 'phase3' 'phase6' 'RGB' 'custom'}; hs.lut = uicontrol(ph, 'Style', 'popup', 'Position', [113 8 74 22], ... 'String', hs.lutStr, 'BackgroundColor', 'w', 'Callback', cb('lut'), ... 'Value', p.lut, 'TooltipString', 'Lookup table options for non-RGB data'); if p.lut==numel(hs.lutStr), set(hs.lut, 'Enable', 'off'); end hs.alpha = java_spinner([187 8 44 22], [1 0 1 0.1], ph, cb('alpha'), '#.#', ... 'Alpha: 0 transparent, 1 opaque'); hs.smooth = uicontrol(ph, 'Style', 'checkbox', 'Value', p.smooth, ... 'Position', [231 8 60 22], 'String', 'smooth', 'BackgroundColor', clr, ... 'Callback', cb('smooth'), 'TooltipString', 'Smooth image in 3D'); hs.interp = uicontrol(ph, 'Style', 'popup', 'Position', [291 8 68 22], ... 'String', {'nearest' 'linear' 'cubic' 'spline'}, 'Value', p.interp, ... 'Callback', cb('interp'), 'Enable', 'off', 'BackgroundColor', 'w', ... 'TooltipString', 'Interpolation method for overlay'); hs.volume = java_spinner([361 8 44 22], [1 1 nVol 1], ph, cb('volume'), '#', ... ['Volume number, 1:' num2str(nVol)]); hs.volume.setEnabled(nVol>1); %% Three views: sag, cor, tra % this panel makes resize easy: axes relative to panel hs.frame = uipanel(fh, 'Units', 'pixels', 'Position', [1 1 siz], ... 'BorderType', 'none', 'BackgroundColor', 'k'); for i = 1:3 j = 1:3; j(j==i) = []; hs.ax(i) = axes('Position', axPos(i,:), 'Parent', hs.frame); hs.hsI(i) = handle(image(zeros(dim(j([2 1])), 'single'))); hold(hs.ax(i), 'on'); x = [c(j(1))+[-1 1 0 0]*hs.gap(j(1)); 0 dim(j(1))+1 c(j(1))*[1 1]]; y = [c(j(2))+[0 0 -1 1]*hs.gap(j(2)); c(j(2))*[1 1] 0 dim(j(2))+1]; hs.cross(i,:) = line(x, y); hs.xyz(i) = text(0.02, 0.96, num2str(xyz(i)), 'Units', 'normalized', ... 'Parent', hs.ax(i), 'FontSize', 12); end set(hs.hsI, 'ButtonDownFcn', cb('mousedown')); p.hsI = hs.hsI; % background img p.hsI(1).UserData = p; % store everything in sag img UserData labls='ASLSLP'; pos = [0.95 0.5; 0.47 0.96; 0 0.5; 0.47 0.96; 0 0.5; 0.47 0.05]; for i = 1:numel(labls) hs.ras(i) = text(pos(i,1), pos(i,2), labls(i), 'Units', 'normalized', ... 'Parent', hs.ax(ceil(i/2)), 'FontSize', 12, 'FontWeight', 'bold'); end % early matlab's colormap works only for axis, so ax(4) is needed. hs.ax(4) = axes('Position', axPos(4,:), 'Parent', hs.frame); try hs.colorbar = colorbar(hs.ax(4), 'YTicks', [0 0.5 1], 'Color', [1 1 1], ... 'Location', 'West', 'PickableParts', 'none', 'Visible', 'off'); catch % for early matlab colorbar('peer', hs.ax(4), 'Location', 'West', 'Units', 'Normalized'); hs.colorbar = findobj(fh, 'Tag', 'Colorbar'); set(hs.colorbar, 'Visible', 'off', 'HitTest', 'off', 'EdgeColor', [1 1 1]); end % image() reverses YDir. Turn off ax and ticks set(hs.ax, 'YDir', 'normal', 'Visible', 'off'); set([hs.ras hs.cross(:)' hs.xyz], 'Color', 'b', 'UIContextMenu', ''); try set([hs.ras hs.cross(:)' hs.xyz], 'PickableParts', 'none'); % new matlab catch, set([hs.ras hs.cross(:)' hs.xyz], 'HitTest', 'off'); % old ones end %% menus h = uimenu(fh, 'Label', '&File'); uimenu(h, 'Label', 'Open', 'Accelerator', 'O', 'UserData', pName, 'Callback', cb('open')); uimenu(h, 'Label', 'Open in new window', 'Callback', cb('open')); uimenu(h, 'Label', 'Apply mask', 'Callback', @addMask); uimenu(h, 'Label', 'Apply modulation', 'Callback', @addMask); h_savefig = uimenu(h, 'Label', 'Save figure as'); h_saveas = uimenu(h, 'Label', 'Save NIfTI as'); uimenu(h, 'Label', 'Save volume as ...', 'Callback', cb('saveVolume')); uimenu(h, 'Label', 'Crop below crosshair', 'Callback', cb('cropNeck')); uimenu(h, 'Label', 'Create ROI file ...', 'Callback', cb('ROI')); uimenu(h, 'Label', 'Close window', 'Accelerator', 'W', 'Callback', 'close gcf'); uimenu(h_saveas, 'Label', 'SPM 3D NIfTI (one file/pair per volume)', 'Callback', @save_nii_as); uimenu(h_saveas, 'Label', 'NIfTI standard RGB (for AFNI, later mricron)', ... 'Callback', @save_nii_as, 'Separator', 'on'); uimenu(h_saveas, 'Label', 'FSL style RGB (RGB saved in dim 4)', 'Callback', @save_nii_as); uimenu(h_saveas, 'Label', 'Old mricron style RGB (RGB saved in dim 3)', 'Callback', @save_nii_as); uimenu(h_saveas, 'Label', 'a copy', 'Callback', @save_nii_as, 'Separator', 'on'); uimenu(h_saveas, 'Label', 'file with a new resolution', 'Callback', @save_nii_as); uimenu(h_saveas, 'Label', 'file matching background', 'Callback', @save_nii_as); uimenu(h_saveas, 'Label', 'file in aligned template space', 'Callback', @save_nii_as); fmt = {'png' 'jpg' 'tif' 'bmp' 'pdf' 'eps'}; if ispc, fmt = [fmt 'emf']; end for i = 1:numel(fmt) uimenu(h_savefig, 'Label', fmt{i}, 'Callback', cb('save')); end if ispc || ismac h = uimenu(fh, 'Label', '&Edit'); uimenu(h, 'Label', 'Copy figure', 'Callback', cb('copy')); end h_over = uimenu(fh, 'Label', '&Overlay'); uimenu(h_over, 'Label', 'Add overlay', 'Accelerator', 'A', 'Callback', cb('add')); uimenu(h_over, 'Label', 'Add aligned overlay', 'Callback', cb('add')); h = uimenu(h_over, 'Label', 'Move selected image', 'Enable', 'off'); uimenu(h, 'Label', 'to top', 'Callback', cb('stack'), 'Tag', 'top'); uimenu(h, 'Label', 'to bottom', 'Callback', cb('stack'), 'Tag', 'bottom'); uimenu(h, 'Label', 'one level up', 'Callback', cb('stack'), 'Tag', 'up'); uimenu(h, 'Label', 'one level down', 'Callback', cb('stack'), 'Tag', 'down'); hs.overlay(3) = h; hs.overlay(5) = uimenu(h_over, 'Label', 'Remove overlay', 'Accelerator', 'R', ... 'Callback', cb('close'), 'Enable', 'off'); hs.overlay(4) = uimenu(h_over, 'Label', 'Remove overlays', ... 'Callback', cb('closeAll'), 'Enable', 'off'); uimenu(h_over, 'Label', 'Load LUT for current overlay', 'Callback', cb('custom')); h_view = uimenu(fh, 'Label', '&View'); h = uimenu(h_view, 'Label', 'Zoom in by'); for i = [1 1.2 1.5 2 3 4 5 8 10 20] uimenu(h, 'Label', num2str(i), 'Callback', cb('zoom')); end h = uimenu(h_view, 'Label', 'Layout', 'UserData', pf.layout); uimenu(h, 'Label', 'one-row', 'Callback', cb('layout')); uimenu(h, 'Label', 'two-row sag on right', 'Callback', cb('layout')); uimenu(h, 'Label', 'two-row sag on left', 'Callback', cb('layout')); uimenu(h_view, 'Label', 'White background', 'Callback', cb('background')); hLR = uimenu(h_view, 'Label', 'Right on left side', 'Callback', cb('flipLR')); uimenu(h_view, 'Label', 'Show colorbar', 'Callback', cb('colorbar')); uimenu(h_view, 'Label', 'Show crosshair', 'Separator', 'on', ... 'Checked', 'on', 'Callback', cb('cross')); h = uimenu(h_view, 'Label', 'Set crosshair at'); uimenu(h, 'Label', 'center of view', 'Callback', cb('viewCenter')); uimenu(h, 'Label', 'center of image', 'Callback', cb('center')); uimenu(h, 'Label', 'COG of image', 'Callback', cb('cog')); uimenu(h, 'Label', 'Smoothed maximum', 'Callback', cb('maximum')); uimenu(h, 'Label', 'a point [x y z] ...', 'Callback', cb('toXYZ')); uimenu(h, 'Label', 'a point with value of ...', 'Callback', cb('toValue')); uimenu(h_view, 'Label', 'Crosshair color', 'Callback', cb('color')); h = uimenu(h_view, 'Label', 'Crosshair gap'); for i = [0 1 2 3 4 5 6 8 10 20 40] str = num2str(i); if i==6, str = [str ' (default)']; end %#ok uimenu(h, 'Label', str, 'Callback', cb('gap')); end h = uimenu(h_view, 'Label', 'Crosshair thickness'); uimenu(h, 'Label', '0.5 (default)', 'Callback', cb('thickness')); for i = [0.75 1 2 4 8] uimenu(h, 'Label', num2str(i), 'Callback', cb('thickness')); end h = uimenu(fh, 'Label', '&Window'); uimenu(h, 'Label', 'Show NIfTI essentials', 'Callback', cb('essential')); uimenu(h, 'Label', 'Show NIfTI hdr', 'Callback', cb('hdr')); uimenu(h, 'Label', 'Show NIfTI ext', 'Callback', cb('ext')); uimenu(h, 'Label', 'DICOM to NIfTI converter', 'Callback', 'dicm2nii', 'Separator', 'on'); th = uimenu(h, 'Label', 'Time course ...', 'Callback', cb('tc'), 'Separator', 'on'); setappdata(th, 'radius', 6); th = uimenu(h, 'Label', 'Standard deviation ...', 'Callback', cb('tc')); setappdata(th, 'radius', 6); uimenu(h, 'Label', 'Histogram', 'Callback', cb('hist')); h = uimenu(fh, 'Label', '&Help'); hs.pref = uimenu(h, 'Label', 'Preferences', 'UserData', pf, 'Callback', @pref_dialog); uimenu(h, 'Label', 'Key shortcut', 'Callback', cb('keyHelp')); uimenu(h, 'Label', 'Show help text', 'Callback', 'doc nii_viewer'); checkUpdate = dicm2nii('', 'checkUpdate', 'func_handle'); uimenu(h, 'Label', 'Check update', 'Callback', @(~,~)checkUpdate('nii_viewer')); uimenu(h, 'Label', 'About', 'Callback', cb('about')); %% finalize gui if isnumeric(fh) % for older matlab fh = handle(fh); schema.prop(fh, 'Number', 'mxArray'); fh.Number = fn; hs.lut = handle(hs.lut); hs.frame = handle(hs.frame); hs.value = handle(hs.value); hs.panel = handle(hs.panel); hs.params = handle(hs.params); hs.scroll = handle(hs.scroll); hs.pref = handle(hs.pref); end guidata(fh, hs); % store handles and data %% java_dnd based on dndcontrol at matlabcentral/fileexchange/53511 try % panel has JavaFrame in later matlab jFrame = handle(hs.frame.JavaFrame.getGUIDEView, 'CallbackProperties'); catch warning('off', 'MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); jFrame = fh.JavaFrame.getAxisComponent; end try java_dnd(jFrame, cb('drop')); catch me, disp(me.message); end set(fh, 'ResizeFcn', cb('resize'), ... % 'SizeChangedFcn' for later matlab 'WindowKeyPressFcn', @KeyPressFcn, 'CloseRequestFcn', cb('closeFig'), ... 'PaperPositionMode', 'auto', 'InvertHardcopy', 'off', 'HandleVisibility', 'Callback'); nii_viewer_cb(fh, [], 'resize', fh); % avoid some weird problem if pf.mouseOver, set(fh, 'WindowButtonMotionFcn', cb('mousemove')); end if pf.rightOnLeft, nii_viewer_cb(hLR, [], 'flipLR', fh); end set_cdata(hs); set_xyz(hs); if nargin>1 if ischar(varargin{1}) addOverlay(varargin{1}, fh); elseif iscellstr(varargin{1}) for i=1:numel(varargin{1}), addOverlay(varargin{1}{i}, fh); end end end if hs.form_code(1)<1 warndlg(['There is no valid form code in NIfTI. The orientation ' ... 'labeling is likely meaningless.']); end if isfield(p.nii, 'cii'), cii_view(hs); end %% Get info from sag img UserData function p = get_para(hs, iFile) if nargin<2, iFile = hs.files.getSelectedIndex + 1; end hsI = findobj(hs.ax(1), 'Type', 'image', '-or', 'Type', 'quiver'); p = get(hsI(iFile), 'UserData'); %% callbacks function nii_viewer_cb(h, evt, cmd, fh) hs = guidata(fh); switch cmd case 'ijk' % IJK spinner ix = find(h == hs.ijk); set_cdata(hs, ix); set_cross(hs, ix); xyz = set_xyz(hs); for i = 1:3, set(hs.xyz(i), 'String', xyz(i)); end % need 3 if oblique case 'mousedown' % image clicked % if ~strcmp(get(fh, 'SelectionType'), 'normal'), return; end ax = gca; c = get(ax, 'CurrentPoint'); c = round(c(1, 1:2)); i = 1:3; i(ax==hs.ax(1:3)) = []; hs.ijk(i(1)).setValue(c(1)); hs.ijk(i(2)).setValue(c(2)); case {'lb' 'ub' 'lut' 'alpha' 'smooth' 'interp' 'volume'} if ~strcmp(cmd, 'volume'), uicontrol(hs.focus); end % move away focus p = get_para(hs); val = get(h, 'Value'); if val == 11 && val~=p.lut hs.lut.UserData = p.lut; % remember old lut end if strcmp(cmd, 'smooth') if val==1 && numel(p.nii.img(:,:,:,1))<2 set(h, 'Value', 0); return; end elseif strcmp(cmd, 'lut') err = false; if val == 11 % error check for vector lines err = true; if size(p.nii.img,4)~=3 errordlg('Not valid vector data: dim4 is not 3'); else a = sum(p.nii.img.^2, 4); a = a(a(:)>1e-4); if any(abs(a-1)>0.1) errordlg('Not valid vector data: squared sum is not 1'); else, err = false; % passed all checks end end elseif any(val == 26:28) % error check for phase img err = ~isfield(p, 'phase'); if err, warndlg('Seleced image is not complex data.'); end elseif val == 29 % RGB err = size(p.nii.img,4)~=3; if err, errordlg('RGB LUT requres 3-volume data.'); end elseif val == numel(hs.lutStr) err = true; errordlg('Custom LUT is used be NIfTI itself'); end if err, hs.lut.Value = p.lut; return; end % undo selection end p.hsI(1).UserData.(cmd) = val; if any(strcmp(cmd, {'lut' 'lb' 'ub' 'volume'})), set_colorbar(hs); end if strcmp(cmd, 'volume'), set_xyz(hs); end set_cdata(hs); case 'resize' if isempty(hs), return; end cb = fh.ResizeFcn; fh.ResizeFcn = []; drawnow; % avoid weird effect clnObj = onCleanup(@() set(fh, 'ResizeFcn', cb)); % restore func posP = getpixelposition(hs.panel); % get old height in pixels posF = getpixelposition(fh); % asked position by user posI = getpixelposition(hs.frame); % old size siz = hs.frame.Position(3:4); res = screen_pixels(1); oldF = round([posI(3) posI(4)+posP(4)]); % previous fig size if isequal(oldF, posF(3:4)), return; end % moving without size change if all(posF(3:4) >= oldF) % enlarge a = max([posF(3) posF(4)-posP(4)] ./ siz) * siz; a(1) = min(a(1), res(1)-30); % leave space for MAC dock etc a(2) = min(a(2), res(2)-92-posP(4)); % leave space for title bar etc a = min(a ./ siz) * siz; elseif all(posF(3:4) <= oldF) % shrink a = min([posF(3) posF(4)-posP(4)] ./ siz) * siz; else % one side enlarge, another side shrink: use old size a = posI(3:4); end d = posF(1)+a(1)-res(1); if d>0, posF(1) = posF(1) - d; end d = posF(2)+a(2)+posP(4)+92-res(2); if d>0, posF(2) = posF(2) - d; end posF(1) = max(posF(1), 10); posF(2) = max(posF(2), 50); posF(3:4) = [a(1) a(2)+posP(4)]; % final figure size fh.Position = posF; % done for fig posP(2) = posF(4)-posP(4)+1; posP(3) = posF(3); hs.panel.Position = posP; % done for control panel hs.frame.Position = [1 1 a]; % done for image panel nii_viewer_cb([], [], 'width', fh); case 'toggle' % turn on/off NIfTI i = h.getAnchorSelectionIndex+1; if i<1, return; end checked = hs.files.getCheckBoxListSelectedIndices+1; p = get_para(hs, i); if p.show == any(checked==i), return; end % no change p.show = ~p.show; p.hsI(1).UserData = p; states = {'off' 'on'}; try %#ok<*TRYNC> set(p.hsI, 'Visible', states{p.show+1}); if p.show, set_cdata(hs); end set_xyz(hs); end case 'mousemove' % if ~strcmp(get(fh, 'SelectionType'), 'normal'), return; end c = cell2mat(get(hs.ax(1:3), 'CurrentPoint')); c = c([1 3 5], 1:2); % 3x2 x = cell2mat(get(hs.ax(1:3), 'XLim')); y = cell2mat(get(hs.ax(1:3), 'YLim')); I = cell2mat(get(hs.ijk, 'Value'))'; if c(1,1)>x(1,1) && c(1,1)<x(1,2) && c(1,2)>y(1,1) && c(1,2)<y(1,2)%sag I = [I(1) c(1,:)]; elseif c(2,1)>x(2,1) && c(2,1)<x(2,2) && c(2,2)>y(2,1) && c(2,2)<y(2,2)%cor I = [c(2,1) I(2) c(2,2)]; elseif c(3,1)>x(3,1) && c(3,1)<x(3,2) && c(3,2)>y(3,1) && c(3,2)<y(3,2)%tra I = [c(3,:) I(3)]; end set_xyz(hs, I); case 'open' % open on current fig or new fig pName = hs.pref.UserData.openPath; [fname, pName] = uigetfile([pName '/*.nii; *.hdr;*.nii.gz; *.hdr.gz'], ... 'Select a NIfTI to view', 'MultiSelect', 'on'); if isnumeric(fname), return; end fname = strcat([pName '/'], fname); if strcmp(get(h, 'Label'), 'Open in new window'), nii_viewer(fname); else, nii_viewer(fname, fh); end return; case 'add' % add overlay vars = evalin('base', 'who'); is_nii = @(v)evalin('base', ... sprintf('isstruct(%s) && all(isfield(%s,{''hdr'',''img''}))', v, v)); for i = numel(vars):-1:1, if ~is_nii(vars{i}), vars(i) = []; end; end if ~isempty(vars) a = listdlg('SelectionMode', 'single', 'ListString', vars, ... 'ListSize', [300 100], 'CancelString', 'File dialog', ... 'Name', 'Select a NIfTI in the list or click File dialog'); if ~isempty(a), fname = evalin('base', vars{a}); end end pName = hs.pref.UserData.addPath; label = get(h, 'Label'); if strcmp(label, 'Add aligned overlay') if ~exist('fname', 'var') [fname, pName] = uigetfile([pName '/*.nii; *.hdr;*.nii.gz;' ... '*.hdr.gz'], 'Select overlay NIfTI'); if ~ischar(fname), return; end fname = fullfile(pName, fname); end [mtx, pName] = uigetfile([pName '/*.mat;*_warp.nii;*_warp.nii.gz'], ... 'Select FSL mat file or warp file transforming the nii to background'); if ~ischar(mtx), return; end mtx = fullfile(pName, mtx); addOverlay(fname, fh, mtx); else if ~exist('fname', 'var') [fname, pName] = uigetfile([pName '/*.nii; *.hdr;*.nii.gz;' ... '*.hdr.gz'], 'Select overlay NIfTI', 'MultiSelect', 'on'); if ~ischar(fname) && ~iscell(fname), return; end fname = get_nii(strcat([pName filesep], fname)); end addOverlay(fname, fh); end setpref('nii_viewer_para', 'addPath', pName); case 'closeAll' % close all overlays for j = hs.files.getModel.size:-1:1 p = get_para(hs, j); if p.hsI(1) == hs.hsI(1), continue; end delete(p.hsI); % remove image hs.files.getModel.remove(j-1); end hs.files.setSelectedIndex(0); set_xyz(hs); case 'close' % close selected overlay jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); if p.hsI(1) == hs.hsI(1), return; end % no touch to background delete(p.hsI); % 3 view hs.files.getModel.remove(jf-1); hs.files.setSelectedIndex(max(0, jf-2)); set_xyz(hs); case {'hdr' 'ext' 'essential'} % show hdr ext or essential jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); if strcmp(cmd, 'hdr') hdr = p.hdr0; elseif strcmp(cmd, 'ext') if ~isfield(p.nii, 'ext') errordlg('No extension for the selected NIfTI'); return; end hdr = {}; for i = 1:numel(p.nii.ext) if ~isfield(p.nii.ext(i), 'edata_decoded'), continue; end hdr{end+1} = p.nii.ext(i).edata_decoded; %#ok end if isempty(hdr) errordlg('No known extension for the selected NIfTI'); return; elseif numel(hdr) == 1, hdr = hdr{1}; end elseif strcmp(cmd, 'essential') hdr = nii_essential(p); end nam = hs.files.getModel.get(jf-1); if ~isstrprop(nam(1), 'alpha'), nam = ['x' nam]; end % like genvarname nam(~isstrprop(nam, 'alphanum')) = '_'; % make it valid for var name nam = [nam '_' cmd]; nam = strrep(nam, '__', '_'); n = numel(nam); nm = namelengthmax; if n>nm, nam(nm-4:n-4) = ''; end assignin('base', nam, hdr); evalin('base', ['openvar ' nam]); case 'cross' % show/hide crosshairs and RAS labels if strcmp(get(h, 'Checked'), 'on') set(h, 'Checked', 'off'); set([hs.cross(:)' hs.ras hs.xyz], 'Visible', 'off'); else set(h, 'Checked', 'on'); set([hs.cross(:)' hs.ras hs.xyz], 'Visible', 'on'); end case 'color' % crosshair color c = uisetcolor(get(hs.ras(1), 'Color'), 'Pick crosshair color'); if numel(c) ~= 3, return; end set([hs.cross(:)' hs.ras hs.xyz], 'Color', c); case 'thickness' % crosshair thickness c = strtok(get(h, 'Label')); set(hs.cross(:)', 'LineWidth', str2double(c)); case 'gap' % crosshair gap c = str2double(strtok(get(h, 'Label'))); hs.gap = min(hs.pixdim) ./ hs.pixdim * c / 2; guidata(fh, hs); set_cross(hs, 1:3); case 'copy' % copy figure into clipboard fh1 = ancestor(h, 'figure'); if strncmp(get(fh1, 'Name'), 'nii_viewer', 10) set(hs.panel, 'Visible', 'off'); clnObj = onCleanup(@() set(hs.panel, 'Visible', 'on')); end print(fh1, '-dbitmap', '-noui', ['-r' hs.pref.UserData.dpi]); % print('-dmeta', '-painters'); case 'save' % save figure as picture ext = get(h, 'Label'); fmt = ext; if strcmp(ext, 'jpg'), fmt = 'jpeg'; elseif strcmp(ext, 'tif'), fmt = 'tiff'; elseif strcmp(ext, 'eps'), fmt = 'epsc'; elseif strcmp(ext, 'emf'), fmt = 'meta'; end [fname, pName] = uiputfile(['*.' ext], 'Input file name to save figure'); if ~ischar(fname), return; end fname = fullfile(pName, fname); if any(strcmp(ext, {'eps' 'pdf' 'emf'})), render = '-painters'; else, render = '-opengl'; end fh1 = ancestor(h, 'figure'); if strncmp(get(fh1, 'Name'), 'nii_viewer', 10) set(hs.panel, 'Visible', 'off'); clnObj = onCleanup(@() set(hs.panel, 'Visible', 'on')); end print(fh1, fname, render, '-noui', ['-d' fmt], ['-r' hs.pref.UserData.dpi], '-cmyk'); case 'colorbar' % colorbar on/off if strcmpi(get(hs.colorbar, 'Visible'), 'on') set(hs.colorbar, 'Visible', 'off'); set(h, 'Checked', 'off'); else set(hs.colorbar, 'Visible', 'on'); set(h, 'Checked', 'on'); set_colorbar(hs); end case 'about' getVersion = dicm2nii('', 'getVersion', 'func_handle'); str = sprintf(['nii_viewer.m by Xiangrui Li\n\n' ... 'Last updated on %s\n\n', ... 'Feedback to: [email protected]\n'], getVersion()); helpdlg(str, 'About nii_viewer') case 'stack' uicontrol(hs.focus); % move focus out of buttons jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); n = hs.files.getModel.size; switch get(h, 'Tag') % for both uimenu and pushbutton case 'up' % one level up if jf==1, return; end for j = 1:3, uistack(p.hsI(j)); end ind = [1:jf-2 jf jf-1 jf+1:n]; jf = jf-1; case 'down' % one level down if jf==n, return; end for j = 1:3, uistack(p.hsI(j), 'down'); end ind = [1:jf-1 jf+1 jf jf+2:n]; jf = jf+1; case 'top' if jf==1, return; end for j = 1:3, uistack(p.hsI(j), 'up', jf-1); end ind = [jf 1:jf-1 jf+1:n]; jf = 1; case 'bottom' if jf==n, return; end for j = 1:3, uistack(p.hsI(j), 'down', n-jf); end ind = [1:jf-1 jf+1:n jf]; jf = n; otherwise error('Unknown stack level: %s', get(h, 'Tag')); end str = cell(hs.files.getModel.toArray); str = str(ind); for j = 1:n, hs.files.getModel.set(j-1, str{j}); end chk = false(1,n); chk(hs.files.getCheckBoxListSelectedIndices+1) = true; chk = find(chk(ind)) - 1; if ~isempty(chk), hs.files.setCheckBoxListSelectedIndices(chk); end hs.files.setSelectedIndex(jf-1); set_xyz(hs); case 'zoom' m = str2double(get(h, 'Label')); a = min(hs.dim) / m; if a<1, m = min(hs.dim); end set_zoom(m, hs); case 'background' if strcmp(get(h, 'Checked'), 'on') set(h, 'Checked', 'off'); hs.frame.BackgroundColor = [0 0 0]; set(hs.colorbar, 'EdgeColor', [1 1 1]); else set(h, 'Checked', 'on'); hs.frame.BackgroundColor = [1 1 1]; set(hs.colorbar, 'EdgeColor', [0 0 0]); end set_cdata(hs); case 'flipLR' hs.pref.UserData.rightOnLeft = strcmp(get(h, 'Checked'), 'on'); if hs.pref.UserData.rightOnLeft set(h, 'Checked', 'off'); set(hs.ax([2 3]), 'XDir', 'normal'); set(hs.ras([3 5]), 'String', 'L'); else set(h, 'Checked', 'on'); set(hs.ax([2 3]), 'XDir', 'reverse'); set(hs.ras([3 5]), 'String', 'R'); end case 'layout' submenu = {'one-row' 'two-row sag on right' 'two-row sag on left'}; layout = find(strcmp(get(h, 'Label'), submenu)); if hs.pref.UserData.layout == layout, return; end cb = hs.fig.ResizeFcn; hs.fig.ResizeFcn = ''; drawnow; clnObj = onCleanup(@() set(hs.fig, 'ResizeFcn', cb)); [siz, axPos, figPos] = plot_pos(hs.dim.*hs.pixdim, layout); hs.fig.Position = [figPos siz+[0 64]]; hs.frame.Position(3:4) = siz; hs.panel.Position(2) = hs.fig.Position(4) - 64; for i = 1:4, set(hs.ax(i), 'Position', axPos(i,:)); end hs.pref.UserData.layout = layout; case 'keyHelp' str = sprintf([ ... 'Key press available when focus is not in a number dialer:\n\n' ... 'Left or Right arrow key: Move crosshair left or right.\n\n' ... 'Up or Down arrow key: Move crosshair superior or inferior.\n\n' ... '[ or ] key: Move crosshair posterior or anterior.\n\n' ... '< or > key: Decrease or increase volume number.\n\n' ... 'Ctrl + or - key: Zoom in or out by 10%% around crosshair.\n\n' ... 'A: Toggle on/off crosshair.\n\n' ... 'C: Crosshair to view center.\n\n' ... 'Space: Toggle on/off selected image.\n\n' ... 'F1: Show help text.\n']); helpdlg(str, 'Key Shortcut'); case 'center' % image center p = get_para(hs); dim = p.nii.hdr.dim(2:4); c = round(hs.bg.Ri * (p.R * [dim/2-1 1]')) + 1; for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'viewCenter' c(1) = mean(get(hs.ax(2), 'XLim')); c(2) = mean(get(hs.ax(1), 'XLim')); c(3) = mean(get(hs.ax(1), 'YLim')); c = round(c-0.5); for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'toXYZ' c0 = cell2mat(get(hs.ijk, 'Value')); c0 = hs.bg.R * [c0-1; 1]; c0 = sprintf('%g %g %g', round(c0(1:3))); str = 'X Y Z coordinates in mm'; while 1 a = inputdlg(str, 'Crosshair to xyz', 1, {c0}); if isempty(a), return; end c = sscanf(a{1}, '%g %g %g'); if numel(c) == 3, break; end end c = round(hs.bg.Ri * [c(:); 1]) + 1; for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'toValue' def = getappdata(h, 'Value'); if isempty(def), def = 1; end def = num2str(def); str = 'Input the voxel value'; while 1 a = inputdlg(str, 'Crosshair to a value', 1, {def}); if isempty(a), return; end val = sscanf(a{1}, '%g'); if ~isnan(val), break; end end setappdata(h, 'Value', val); jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); img = p.nii.img(:,:,:, hs.volume.getValue); c = find(img(:)==val, 1); if isempty(c) nam = strtok(hs.files.getModel.get(jf-1), '('); errordlg(sprintf('No value of %g found in %s', val, nam)); return; end dim = size(img); dim(numel(dim)+1:3) = 1; [c(1), c(2), c(3)] = ind2sub(dim, c); % ijk+1 c = round(hs.bg.Ri * (p.R * [c(:)-1; 1])) + 1; for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'cog' % crosshair to img COG p = get_para(hs); img = p.nii.img(:,:,:, hs.volume.getValue); c = img_cog(img); if any(isnan(c)), errordlg('No valid COG found'); return; end c = round(hs.bg.Ri * (p.R * [c-1; 1])) + 1; for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'maximum' % crosshair to img max p = get_para(hs); img = p.nii.img(:,:,:,hs.volume.getValue); if sum(img(:)~=0) < 1 errordlg('All value are the same. No maximum!'); return; end img = smooth23(img, 'gaussian', 5); img(isnan(img)) = 0; img = abs(img); [~, I] = max(img(:)); dim = size(img); dim(end+1:3) = 1; c = zeros(3, 1); [c(1), c(2), c(3)] = ind2sub(dim, I); c = round(hs.bg.Ri * (p.R * [c-1; 1])) + 1; for i = 1:3, hs.ijk(i).setValue(c(i)); end case 'custom' % add custom lut p = get_para(hs); pName = fileparts(p.nii.hdr.file_name); [fname, pName] = uigetfile([pName '/*.lut'], 'Select LUT file for current overlay'); if ~ischar(fname), return; end fid = fopen(fullfile(pName, fname)); p.map = fread(fid, '*uint8'); fclose(fid); if mod(numel(p.map),3)>0 || sum(p.map<8)<3 % guess text file try, p.map = str2num(char(p.map')); catch, errordlg('Unrecognized LUT file'); return; end if max(p.map(:)>1), p.map = single(p.map) / 255; end else p.map = reshape(p.map, [], 3); p.map = single(p.map) / 255; end if isequal(p.nii.img, round(p.nii.img)) try, p.map = p.map(1:max(p.nii.img(:))+1, :); end end p.lut = numel(hs.lutStr); p.hsI(1).UserData = p; set(hs.lut, 'Value', p.lut, 'Enable', 'off'); set_cdata(hs); set_colorbar(hs); case 'tc' % time course or std jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); nam = strtok(hs.files.getModel.get(jf-1), '('); labl = strrep(get(h, 'Label'), ' ...', ''); r = num2str(getappdata(h, 'radius')); r = inputdlg('Radius around crosshair (mm):', labl, 1, {r}); if isempty(r), return; end r = str2double(r{1}); setappdata(h, 'radius', r); for j = 3:-1:1, c(j) = get(hs.ijk(j), 'Value'); end % ijk for background c = hs.bg.R * [c-1 1]'; % in mm now c = c(1:3); b = xyzr2roi(c, r, p.nii.hdr); % overlay space img = p.nii.img; dim = size(img); img = reshape(img, [], prod(dim(4:end)))'; img = img(:, b(:)); fh1 = figure(mod(fh.Number,10)+jf); if strcmp(labl, 'Time course') img = mean(single(img), 2); else img = std(single(img), [], 2); end plot(img); xlabel('Volume number'); c = sprintf('(%g,%g,%g)', round(c)); set(fh1, 'Name', [nam ' ' lower(labl) ' around voxel ' c]); case 'hist' % plot histgram jf =hs.files.getSelectedIndex+1; if jf<1, return; end p = get_para(hs, jf); img = p.nii.img(:,:,:, hs.volume.getValue); img = sort(img(:)); img(isnan(img)) = []; img(img<hs.lb.getValue) = []; img(img>hs.ub.getValue) = []; nv = numel(img); img0 = unique(img); nu = numel(img0); n = max([nv/2000 nu/20 10]); n = min(round(n), nu); if n == nu, edges = img0; else, edges = linspace(0,1,n)*double(img(end)-img(1)) + double(img(1)); end nam = strtok(hs.files.getModel.get(jf-1), '('); fh1 = figure(mod(fh.Number,10)+jf); set(fh1, 'NumberTitle', 'off', 'Name', nam); [y, x] = hist(img, edges); bar(x, y/sum(y)/(x(2)-x(1)), 'hist'); % probability density xlabel('Voxel values'); ylabel('Probability density'); title('Histogram between min and max values'); case 'width' % adjust hs.scroll width hs.files.updateUI; width = hs.panel.Position(3); x = hs.files.getPreferredScrollableViewportSize.getWidth; x = max(60, min(x+20, width-408)); % 408 width of the little panel hs.scroll.Position(3) = x; hs.params.Position([1 3]) = [x+2 width-x-2]; hs.value.Position(3) = max(1, width-x-hs.value.Position(1)); case 'saveVolume' % save 1 or more volumes as a nifti p = get_para(hs); nam = p.nii.hdr.file_name; t = p.volume; while 1 a = inputdlg('Volume indice to save (2:4 for example)', ... 'Save Volume', 1, {num2str(t)}); if isempty(a), return; end try t = eval(['[' a{1} '];']); break; end end pName = fileparts(nam); [fname, pName] = uiputfile([pName '/*.nii;*.nii.gz'], ... 'Input name to save volume as'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii = nii_tool('load', nam); % re-load to be safe nii.img = nii.img(:,:,:,t); nii_tool('save', nii, fname); case 'ROI' % save sphere c0 = cell2mat(get(hs.ijk, 'Value')); c0 = hs.bg.R * [c0-1; 1]; c0 = sprintf('%g %g %g', round(c0(1:3))); str = {'X Y Z coordinates in mm' 'Radius in mm'}; while 1 a = inputdlg(str, 'Sphere ROI', 1, {c0 '6'}); if isempty(a), return; end c = sscanf(a{1}, '%g %g %g'); r = sscanf(a{2}, '%g'); if numel(c) == 3, break; end end p = get_para(hs); pName = fileparts(p.nii.hdr.file_name); [fname, pName] = uiputfile([pName '/*.nii;*.nii.gz'], ... 'Input file name to save ROI into'); if ~ischar(fname), return; end fname = fullfile(pName, fname); b = xyzr2roi(c, r, p.nii.hdr); p.nii.img = single(b); % single better supported by FSL nii_tool('save', p.nii, fname); case 'cropNeck' k0 = get(hs.ijk(3), 'Value') - 1; p = get_para(hs); nam = p.nii.hdr.file_name; pName = fileparts(nam); [fname, pName] = uiputfile([pName '/*.nii;*.nii.gz'], ... 'Input file name to save cropped image'); if ~ischar(fname), return; end fname = fullfile(pName, fname); d = single(p.hdr0.dim(2:4)); I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); % ijk in 4 by nVox R = nii_xform_mat(p.hdr0, hs.form_code); % original R k = hs.bg.Ri * R * I; % background ijk nii = nii_tool('load', nam); d = size(nii.img); nii.img = reshape(nii.img, prod(d(1:3)), []); nii.img(k(3,:)<k0, :) = -nii.hdr.scl_inter / nii.hdr.scl_slope; nii.img = reshape(nii.img, d); nii_tool('save', nii, fname); case 'closeFig' try close(fh.UserData); end % cii_view delete(fh); return; case 'file' if ~isempty(evt) && evt.getValueIsAdjusting, return; end p = get_para(hs); nam = {'lb' 'ub' 'alpha' 'volume' 'lut' 'smooth' 'interp' }; cb = cell(4,1); for j = 1:4 % avoid firing spinner callback cb{j} = hs.(nam{j}).StateChangedCallback; hs.(nam{j}).StateChangedCallback = ''; end for j = 1:numel(nam) set(hs.(nam{j}), 'Value', p.(nam{j})); end set(hs.lb.Model, 'StepSize', p.lb_step); set(hs.ub.Model, 'StepSize', p.ub_step); nVol = size(p.nii.img, 4); str = sprintf('Volume number, 1:%g', nVol); set(hs.volume, 'Enable', nVol>1, 'ToolTipText', str); set(hs.volume.Model, 'Maximum', nVol); for j = 1:4 % restore spinner callback hs.(nam{j}).StateChangedCallback = cb{j}; end set_colorbar(hs); off_on = {'off' 'on'}; set(hs.interp, 'Enable', off_on{isfield(p, 'R0')+1}); set(hs.overlay(1:4), 'Enable', off_on{(hs.files.getModel.size>1)+1}); % stack & Close overlays set(hs.overlay(5), 'Enable', off_on{(p.hsI(1) ~= hs.hsI(1))+1}); % Close overlay set(hs.lut, 'Enable', off_on{2-(p.lut==numel(hs.lutStr))}); case 'drop' try nii = get_nii(evt.Data); if evt.ControlDown, addOverlay(nii, fh); % overlay else, nii_viewer(nii, fh); return; % background end catch me errordlg(me.message); end otherwise error('Unknown Callback: %s', cmd); end try, cii_view_cb(fh.UserData, [], cmd); end %% zoom in/out with a factor function set_zoom(m, hs) c = hs.dim(:) / 2; if m <= 1, I = c; % full view regardless of crosshair location else, I = cell2mat(get(hs.ijk, 'Value')); end lim = round([I I] + c/m*[-1 1]) + 0.5; axis(hs.ax(1), [lim(2,:) lim(3,:)]); axis(hs.ax(2), [lim(1,:) lim(3,:)]); axis(hs.ax(3), [lim(1,:) lim(2,:)]); %% KeyPressFcn for figure function KeyPressFcn(fh, evt) if any(strcmp(evt.Key, evt.Modifier)), return; end % only modifier hs = guidata(fh); if ~isempty(intersect({'control' 'command'}, evt.Modifier)) switch evt.Key case {'add' 'equal'} [dim, i] = min(hs.dim); if i==1, d = get(hs.ax(2), 'XLim'); elseif i==2, d = get(hs.ax(1), 'XLim'); else, d = get(hs.ax(1), 'YLim'); end d = abs(diff(d')); if d<=3, return; end % ignore m = dim / d * 1.1; if round(dim/2/m)==d/2, m = dim / (d-1); end set_zoom(m, hs); case {'subtract' 'hyphen'} d = abs(diff(get(hs.ax(2), 'XLim'))); m = hs.dim(1) / d; if m<=1, return; end m = m / 1.1; if round(hs.dim(1)/2/m)==d/2, m = hs.dim(1) / (d+1); end if m<1.01, m = 1; end set_zoom(m, hs); end return; end switch evt.Key case 'leftarrow' val = max(get(hs.ijk(1), 'Value')-1, 1); hs.ijk(1).setValue(val); case 'rightarrow' val = min(get(hs.ijk(1), 'Value')+1, hs.dim(1)); hs.ijk(1).setValue(val); case 'uparrow' val = min(get(hs.ijk(3),'Value')+1, hs.dim(3)); hs.ijk(3).setValue(val); case 'downarrow' val = max(get(hs.ijk(3),'Value')-1, 1); hs.ijk(3).setValue(val); case 'rightbracket' % ] val = min(get(hs.ijk(2),'Value')+1, hs.dim(2)); hs.ijk(2).setValue(val); case 'leftbracket' % [ val = max(get(hs.ijk(2),'Value')-1, 1); hs.ijk(2).setValue(val); case 'period' % . or > val = min(get(hs.volume,'Value')+1, get(hs.volume.Model,'Maximum')); hs.volume.setValue(val); case 'comma' % , or < val = max(get(hs.volume,'Value')-1, 1); hs.volume.setValue(val); case 'c' nii_viewer_cb([], [], 'viewCenter', hs.fig); case {'x' 'space'} i = hs.files.getSelectedIndex; checked = hs.files.getCheckBoxListSelectedIndices; if any(i == checked) hs.files.removeCheckBoxListSelectedIndex(i); else hs.files.addCheckBoxListSelectedIndex(i); end case 'a' h = findobj(hs.fig, 'Type', 'uimenu', 'Label', 'Show crosshair'); nii_viewer_cb(h, [], 'cross', hs.fig); case 'f1' doc nii_viewer; case 'tab' % prevent tab from cycling uicontrol mousexy = get(0, 'PointerLocation'); % for later restore posF = getpixelposition(fh); posA = getpixelposition(hs.ax(4), true); % relative to figure c = posF(1:2) + posA(1:2) + posA(3:4)/2; % ax(4) center xy res = screen_pixels; rob = java.awt.Robot(); rob.mouseMove(c(1), res(2)-c(2)); rob.mousePress(16); rob.mouseRelease(16); % BUTTON1 set(0, 'PointerLocation', mousexy); % restore mouse location end %% update CData/AlphaData for 1 or 3 of the sag/cor/tra views function set_cdata(hs, iaxis) if nargin<2, iaxis = 1:3; end interStr = get(hs.interp, 'String'); for i = 1:hs.files.getModel.size p = get_para(hs, i); if ~p.show, continue; end % save time, but need to update when enabled lut = p.lut; if lut == 11 % "lines" special case: do it separately vector_lines(hs, i, iaxis); continue; elseif ~strcmpi(p.hsI(1).Type, 'image') % was "lines" delete(p.hsI); % delete quiver p.hsI = copyimg(hs); p.hsI(1).UserData = p; % update whole UserData if i>1, for j=1:3; uistack(p.hsI(j), 'down', i-1); end; end end t = round(p.volume); img = p.nii.img; isRGB = size(img, 8)>2; if isRGB % avoid indexing for single vol img: could speed up a lot img = permute(img(:,:,:,t,:,:,:,:), [1:3 8 4:7]); elseif size(img,4)>1 && lut~=29 img = img(:,:,:,t); end if ~isfloat(img) img = single(img); if isfield(p, 'scl_slope') img = img * p.scl_slope + p.scl_inter; end end if isfield(p, 'mask') img = bsxfun(@times, img, p.mask); end if isfield(p, 'modulation') img = bsxfun(@times, img, p.modulation); end if any(lut == 26:28) % interp/smooth both mag and phase img(:,:,:,2) = p.phase(:,:,:,t); end dim4 = size(img,4); for ix = iaxis ind = get(hs.ijk(ix), 'Value'); % faster than hs.ijk(ix).getValue ind = round(ind); if ind<1 || ind>hs.dim(ix), continue; end ii = {':' ':' ':'}; io = ii; d = hs.dim; d(ix) = 1; % 1 slice at dim ix im = zeros([d dim4], 'single'); if isfield(p, 'R0') % interp, maybe smooth I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); % ijk grids of background img I(ix,:) = ind-1; if isfield(p, 'warp') iw = {':' ':' ':' ':'}; iw{ix} = ind; warp = p.warp(iw{:}); warp = reshape(warp, [], 3)'; warp(4,:) = 0; I = p.Ri * (p.R0 * I + warp) + 1; else I = p.Ri * p.R0 * I + 1; % ijk+1 for overlay img end for j = 1:dim4 if p.smooth ns = 3; % number of voxels (odd) used for smooth d3 = d; d3(ix) = ns; % e.g. 3 slices b = zeros(d3, 'single'); I0 = I(1:3,:); for k = 1:ns % interp for each slice I0(ix,:) = I(ix,:) - (ns+1)/2 + k; a = interp3a(img(:,:,:,j), I0, interStr{p.interp}); ii{ix} = k; b(ii{:}) = reshape(a, d); end b = smooth23(b, 'gaussian', ns); io{ix} = (ns+1)/2; im(:,:,:,j) = b(io{:}); % middle one else a = interp3a(img(:,:,:,j), I, interStr{p.interp}); im(:,:,:,j) = reshape(a, d); end end elseif p.smooth % smooth only ns = 3; % odd number of slices to smooth ind1 = ind - (ns+1)/2 + (1:ns); % like ind+(-1:1) if any(ind1<1 | ind1>hs.dim(ix)), ind1 = ind; end % 2D ii{ix} = ind1; io{ix} = mean(1:numel(ind1)); % middle slice for j = 1:dim4 a = smooth23(img(ii{:},j), 'gaussian', ns); im(:,:,:,j) = a(io{:}); end else % no interp or smooth io{ix} = ind; im(:) = img(io{:}, :); end if ix == 1, im = permute(im, [3 2 4 1]); elseif ix == 2, im = permute(im, [3 1 4 2]); elseif ix == 3, im = permute(im, [2 1 4 3]); end if ~isRGB % not NIfTI RGB [im, alfa] = lut2img(im, p, hs.lutStr{p.lut}); elseif dim4 == 3 % NIfTI RGB if max(im(:))>2, im = im / 255; end % guess uint8 im(im>1) = 1; im(im<0) = 0; alfa = sum(im,3) / dim4; % avoid mean elseif dim4 == 4 % NIfTI RGBA if max(im(:))>2, im = im / 255; end % guess uint8 im(im>1) = 1; im(im<0) = 0; alfa = im(:,:,4); im = im(:,:,1:3); else error('Unknown data type: %s', p.nii.hdr.file_name); end if p.hsI(1) == hs.hsI(1) && isequal(hs.frame.BackgroundColor, [1 1 1]) alfa = img2mask(alfa); elseif dim4 ~= 4 alfa = alfa > 0; end alfa = p.alpha * alfa; set(p.hsI(ix), 'CData', im, 'AlphaData', alfa); end end %% Add an overlay function addOverlay(fname, fh, mtx) hs = guidata(fh); frm = hs.form_code; aligned = nargin>2; R_back = hs.bg.R; R0 = nii_xform_mat(hs.bg.hdr, frm(1)); % original background R [~, perm, flp] = reorient(R0, hs.bg.hdr.dim(2:4), 0); if aligned % aligned mtx: do it in special way [p, ~, rg, dim] = read_nii(fname, frm, 0); % no re-orient try if any(regexpi(mtx, '\.mat$')) R = load(mtx, '-ascii'); if ~isequal(size(R), [4 4]) error('Invalid transformation matrix file: %s', mtx); end else % see nii_xform R = eye(4); warp = nii_tool('img', mtx); % FSL warp nifti if ~isequal(size(warp), [hs.bg.hdr.dim(2:4) 3]) error('warp file and template file img size don''t match.'); end if det(R0(1:3,1:3))<0, warp(:,:,:,1) = -warp(:,:,:,1); end if ~isequal(perm, 1:3) warp = permute(warp, [perm 4]); end for j = 1:3 if flp(j), warp = flip(warp, j); end end p.warp = warp; p.R0 = R_back; % always interp end catch me errordlg(me.message); return; end % see nii_xform for more comment on following method R = R0 / diag([hs.bg.hdr.pixdim(2:4) 1]) * R * diag([p.pixdim 1]); [~, i1] = max(abs(p.R(1:3,1:3))); [~, i0] = max(abs(R(1:3,1:3))); flp = sign(R(i0+[0 4 8])) ~= sign(p.R(i1+[0 4 8])); if any(flp) rotM = diag([1-flp*2 1]); rotM(1:3,4) = (dim-1).* flp; R = R / rotM; end [p.R, perm, p.flip] = reorient(R, dim); % in case we apply mask to it if ~isequal(perm, 1:3) dim = dim(perm); p.pixdim = p.pixdim(perm); p.nii.img = permute(p.nii.img, [perm 4:8]); end for j = 1:3 if p.flip(j), p.nii.img = flip(p.nii.img, j); end end p.alignMtx = mtx; % info only for NIfTI essentials else % regular overlay [p, frm, rg, dim] = read_nii(fname, frm); % Silently use another background R_back matching overlay: very rare if frm>0 && frm ~= hs.form_code(1) && any(frm == hs.form_code) R = nii_xform_mat(hs.bg.hdr, frm); % img alreay re-oriented R_back = reorient(R, hs.bg.hdr.dim(2:4)); elseif frm==0 && isequal(p.hdr0.dim(2:4), hs.bg.hdr.dim(2:4)) p.R = hs.bg.R; % best guess: use background xform p.perm = perm; p.nii.img = permute(p.nii.img, [p.perm 4:8]); for i = 1:3 if p.flip(i) ~= flp(i) p.nii.img = flip(p.nii.img, i); end end p.flip = flp; warndlg(['There is no valid coordinate system for the overlay. ' ... 'The viewer supposes the same coordinate as the background.'], ... 'Missing valid tranformation'); elseif frm ~= 2 && ~any(frm == hs.form_code) warndlg(['There is no matching coordinate system between the overlay ' ... 'image and the background image. The overlay is likely meaningless.'], ... 'Transform Inconsistent'); end end singleVol = 0; nv = size(p.nii.img, 4); if nv>1 && numel(p.nii.img)>1e7 % load all or a single volume if isfield(p.nii, 'NamedMap') nams = cell(1, numel(p.nii.NamedMap)); for i = 1:numel(nams), nams{i} = p.nii.NamedMap{i}.MapName; end a = listdlg('PromptString', 'Load "All" or one of the map:', ... 'SelectionMode', 'single', 'ListString', ['All' nams]); if a==1, a = 'All'; else, a = a - 1; end else str = ['Input ''all'' or a number from 1 to ' num2str(nv)]; while 1 a = inputdlg(str, 'Volumes to load', 1, {'all'}); if isempty(a), return; end a = strtrim(a{1}); if ~isstrprop(a, 'digit'), break; end a = str2num(a); if isequal(a,1:nv) || (numel(a)==1 && a>=1 && a<=nv && mod(a,1)==0) break; end end end if isnumeric(a) && numel(a)==1 singleVol = a; p.nii.img = p.nii.img(:,:,:,a); if isfield(p.nii, 'cii') p.nii.cii{1} = p.nii.cii{1}(:,a); p.nii.cii{2} = p.nii.cii{2}(:,a); end if isfield(p.nii, 'NamedMap') try, p.nii.NamedMap = p.nii.NamedMap(a); %#ok<*NOCOM> catch, p.nii.NamedMap = p.nii.NamedMap(1); end try, p.map = p.nii.NamedMap{1}.map; end end rg = get_range(p.nii); end end ii = [1 6 11 13:15]; % diag and offset: avoid large ratio due to small value if ~isequal(hs.dim, dim) || any(abs(R_back(ii)./p.R(ii)-1) > 0.01) p.R0 = R_back; end p.Ri = inv(p.R); if ~isreal(p.nii.img) p.phase = angle(p.nii.img); % -pi to pi p.phase = mod(p.phase/(2*pi), 1); % 0~1 p.nii.img = abs(p.nii.img); % real now end mdl = hs.files.getModel; luts = zeros(1, mdl.size); for i = 1:mdl.size % overlay added p0 = get_para(hs, i); luts(i) = p0.lut; end p.hsI = copyimg(hs); % duplicate image obj for overlay: will be at top p.lb = rg(1); p.ub = rg(2); p = dispPara(p, luts); p.hsI(1).UserData = p; [pName, niiName, ext] = fileparts(p.nii.hdr.file_name); if strcmpi(ext, '.gz'), [~, niiName] = fileparts(niiName); end if aligned, niiName = [niiName '(aligned)']; end if singleVol, niiName = [niiName '(' num2str(singleVol) ')']; end try checked = [0; hs.files.getCheckBoxListSelectedIndices+1]; mdl.insertElementAt(niiName, 0); hs.files.setCheckBoxListSelectedIndices(checked); hs.files.setSelectedIndex(0); hs.files.updateUI; catch me delete(p.hsI); errordlg(me.message); return; end hs.pref.UserData.addPath = pName; set_cdata(hs); set_xyz(hs); if isfield(p.nii, 'cii'), cii_view(hs); end %% Reorient 4x4 R function [R, perm, flp] = reorient(R, dim, leftHand) % [R, perm, flip] = reorient(R, dim, leftHand) % Re-orient transformation matrix R (4x4), so it will be diagonal major and % positive at diagonal, unless the optional third input is true, which requires % left-handed matrix, where R(1,1) will be negative. % The second input is the img space dimension (1x3). % The perm output, like [1 2 3] or a permutation of it, indicates if input R was % permuted for 3 axis. The third output, flip (1x3 logical), indicates an axis % (AFTER perm) is flipped if true. a = abs(R(1:3,1:3)); [~, ixyz] = max(a); if ixyz(2) == ixyz(1), a(ixyz(2),2) = 0; [~, ixyz(2)] = max(a(:,2)); end if any(ixyz(3) == ixyz(1:2)), ixyz(3) = setdiff(1:3, ixyz(1:2)); end [~, perm] = sort(ixyz); R(:,1:3) = R(:,perm); flp = R([1 6 11]) < 0; % diag(R(1:3, 1:3)) if nargin>2 && leftHand, flp(1) = ~flp(1); end rotM = diag([1-flp*2 1]); rotM(1:3, 4) = (dim(perm)-1) .* flp; % 0 or dim-1 R = R / rotM; % xform matrix after flip %% Load, re-orient nii, extract essential nii stuff % nifti may be re-oriented, p.hdr0 stores original nii.hdr function [p, frm, rg, dim] = read_nii(fname, ask_code, reOri) if nargin<2, ask_code = []; end if ischar(fname), p.nii = nii_tool('load', fname); else, p.nii = fname; fname = p.nii.hdr.file_name; end p.hdr0 = p.nii.hdr; % original hdr c = p.nii.hdr.intent_code; if c>=3000 && c<=3099 && isfield(p.nii, 'ext') && any([p.nii.ext.ecode] == 32) p.nii = cii2nii(p.nii); end if nargin<3 || reOri [p.nii, p.perm, p.flip] = nii_reorient(p.nii, 0); else p.perm = 1:3; p.flip = false(1,3); end dim = p.nii.hdr.dim(2:8); dim(dim<1 | mod(dim,1)~=0) = 1; if p.nii.hdr.dim(1)>4 % 4+ dim, put all into dim4 if sum(dim(4:7)>1)>1 warndlg([fname ' has 5 or more dimension. Dimension above 4 are ' ... 'all treated as volumes for visualization']); end dim(4) = prod(dim(4:7)); dim(5:7) = 1; p.nii.img = reshape(p.nii.img, [dim size(p.nii.img, 8)]); end [p.R, frm] = nii_xform_mat(p.nii.hdr, ask_code); dim = dim(1:3); p.pixdim = p.nii.hdr.pixdim(2:4); if size(p.nii.img,4)<4 && ~isfloat(p.nii.img) p.nii.img = single(p.nii.img); end if p.nii.hdr.scl_slope==0, p.nii.hdr.scl_slope = 1; end if p.nii.hdr.scl_slope~=1 || p.nii.hdr.scl_inter~=0 if isfloat(p.nii.img) p.nii.img = p.nii.img * p.nii.hdr.scl_slope + p.nii.hdr.scl_inter; else p.scl_slope = p.nii.hdr.scl_slope; p.scl_inter = p.nii.hdr.scl_inter; end end % check if ROI labels available: the same file name with .txt extension if c == 1002 % Label [pth, nam, ext] = fileparts(p.nii.hdr.file_name); nam1 = fullfile(pth, [nam '.txt']); if strcmpi(ext, '.gz') && ~exist(nam1, 'file') [~, nam] = fileparts(nam); nam1 = fullfile(pth, [nam '.txt']); end if exist(nam1, 'file') % each line format: 1 ROI_1 fid = fopen(nam1); while 1 ln = fgetl(fid); if ~ischar(ln), break; end [ind, a] = strtok(ln); ind = str2double(ind); try p.labels{ind} = strtrim(a); catch, end end fclose(fid); end end rg = get_range(p.nii, isfield(p, 'labels')); if isfield(p.nii, 'NamedMap') try, p.map = p.nii.NamedMap{1}.map; end end %% Return xform mat and form_code: form_code may have two if not to ask_code function [R, frm] = nii_xform_mat(hdr, ask_code) % [R, form] = nii_xform_mat(hdr, asked_code); % Return the transformation matrix from a NIfTI hdr. By default, this returns % the sform if available. If the optional second input, required form code, is % provided, this will try to return matrix for that form code. The second % optional output is the form code of the actually returned matrix. fs = [hdr.sform_code hdr.qform_code]; % sform preferred if fs(1)==fs(2), fs = fs(1); end % sform if both are the same f = fs(fs>=1 & fs<=4); % 1/2/3/4 only if isempty(f) || ~strncmp(hdr.magic, 'n', 1) % treat it as Analyze frm = 0; try % try spm style Analyze [pth, nam, ext] = fileparts(hdr.file_name); if strcmpi(ext, '.gz'), [~, nam] = fileparts(nam); end R = load(fullfile(pth, [nam '.mat'])); R = R.M; catch % make up R for Analyze: suppose xyz order with left storage R = [diag(hdr.pixdim(2:4)) -(hdr.dim(2:4).*hdr.pixdim(2:4)/2)'; 0 0 0 1]; R(1,:) = -R(1,:); % use left handed end return; end if numel(f)==1 || nargin<2 || isempty(ask_code) % only 1 avail or no ask_code frm = f; else % numel(f) is 2, numel(ask_code) can be 1 or 2 frm = f(f == ask_code(1)); if isempty(frm) && numel(ask_code)>1, frm = f(f == ask_code(2)); end if isempty(frm) && any(f==2), frm = 2; end % use confusing code 2 if isempty(frm), frm = f(1); end % no match to ask_code, use sform end if frm(1) == fs(1) % match sform_code or no match R = [hdr.srow_x; hdr.srow_y; hdr.srow_z; 0 0 0 1]; else % match qform_code R = quat2R(hdr); end %% function R = quat2R(hdr) % Return 4x4 qform transformation matrix from nii hdr. b = hdr.quatern_b; c = hdr.quatern_c; d = hdr.quatern_d; a = sqrt(1-b*b-c*c-d*d); if ~isreal(a), a = 0; end % avoid complex due to precision R = [1-2*(c*c+d*d) 2*(b*c-d*a) 2*(b*d+c*a); 2*(b*c+d*a) 1-2*(b*b+d*d) 2*(c*d-b*a); 2*(b*d-c*a ) 2*(c*d+b*a) 1-2*(b*b+c*c)]; if hdr.pixdim(1)<0, R(:,3) = -R(:,3); end % qfac R = R * diag(hdr.pixdim(2:4)); R = [R [hdr.qoffset_x hdr.qoffset_y hdr.qoffset_z]'; 0 0 0 1]; %% Create java SpinnerNumber function h = java_spinner(pos, val, parent, callback, fmt, helpTxt) % h = java_spinner(pos, val, parent, callback, fmt, helpTxt) % pos: [left bottom width height] % val: [curVal min max step] % parent: figure or panel % fmt: '#' for integer, or '#.#', '#.##' mdl = javax.swing.SpinnerNumberModel(val(1), val(2), val(3), val(4)); % jSpinner = javax.swing.JSpinner(mdl); jSpinner = com.mathworks.mwswing.MJSpinner(mdl); h = javacomponent(jSpinner, pos, parent); set(h, 'StateChangedCallback', callback, 'ToolTipText', helpTxt); jEditor = javaObject('javax.swing.JSpinner$NumberEditor', h, fmt); h.setEditor(jEditor); h.setFont(java.awt.Font('Tahoma', 0, 11)); %% Estimate lower and upper bound of img display function rg = get_range(nii, isLabel) if size(nii.img, 8)>2 || any(nii.hdr.datatype == [128 511 2304]) % RGB / RGBA if max(nii.img(:))>2, rg = [0 255]; else, rg = [0 1]; end return; elseif nii.hdr.cal_max~=0 && nii.hdr.cal_max>min(nii.img(:)) rg = [nii.hdr.cal_min nii.hdr.cal_max]; return; end img = nii.img(:,:,:,1); img = img(:); img(isnan(img) | isinf(img)) = []; if ~isreal(img), img = abs(img); end if ~isfloat(img) slope = nii.hdr.scl_slope; if slope==0, slope = 1; end img = single(img) * slope + nii.hdr.scl_inter; end mi = min(img); ma = max(img); if nii.hdr.intent_code > 1000 || (nargin>1 && isLabel) rg = [mi ma]; return; end ind = abs(img)>50; if sum(ind)<numel(img)/10, ind = abs(img)>std(img)/2; end im = img(ind); mu = mean(im); sd = std(im); rg = mu + [-2 2]*sd; if rg(1)<=0 && mu-sd>0, rg(1) = sd/5; end if rg(1)<mi || isnan(rg(1)), rg(1) = mi; end if rg(2)>ma || isnan(rg(2)), rg(2) = ma; end if rg(1)==rg(2), rg(1) = mi; if rg(1)==rg(2), rg(1) = 0; end; end % rg = round(rg, 2, 'significant'); % since 2014b rg = str2num(sprintf('%.2g ', rg)); %#ok<*ST2NM> if rg(1)==rg(2), rg(1) = mi; end if abs(rg(1))>10, rg(1) = floor(rg(1)/2)*2; end % even number if abs(rg(2))>10, rg(2) = ceil(rg(2)/2)*2; end % even number %% Draw vector lines, called by set_cdata function vector_lines(hs, i, iaxis) p = get_para(hs, i); d = single(size(p.nii.img)); pixdim = hs.bg.hdr.pixdim(2:4); % before reorient if strcmpi(get(p.hsI(1), 'Type'), 'image') % just switched to "lines" delete(p.hsI); lut = hs.lut.UserData; % last lut if isempty(lut), lut = 2; end % default red clr = lut2map(p, hs.lutStr{lut}); clr = clr(end,:); cb = get(hs.hsI(1), 'ButtonDownFcn'); for j = 1:3 p.hsI(j) = quiver(hs.ax(j), 1, 1, 0, 0, 'Color', clr, ... 'ShowArrowHead', 'off', 'AutoScale', 'off', 'ButtonDownFcn', cb); end crossFront(hs); % to be safe before next if i>1, for j = 1:3, uistack(p.hsI(j), 'down', i-1); end; end if isfield(p, 'R0') && ~isfield(p, 'ivec') I = ones([d(1:3) 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); I = p.R0 \ (p.R * I) + 1; p.ivec = reshape(I(1:3,:)', d); R0 = normc(p.R0(1:3, 1:3)); R = normc(p.R(1:3, 1:3)); [pd, j] = min(p.pixdim); p.Rvec = R0 / R * pd / pixdim(j); end p.hsI(1).UserData = p; end img = p.nii.img; % This is needed since vec is in image ref, at least for fsl img(:,:,:,p.flip) = -img(:,:,:,p.flip); if isfield(p, 'mask') % ignore modulation img = bsxfun(@times, img, p.mask); end if any(abs(diff(pixdim))>1e-4) % non isovoxel background pd = pixdim / min(pixdim); for j = 1:3, img(:,:,:,j) = img(:,:,:,j) / pd(j); end end if isfield(p, 'Rvec') img = reshape(img, [], d(4)); img = img * p.Rvec; img = reshape(img, d); end for ix = iaxis I = round(get(hs.ijk(ix), 'Value')); j = 1:3; j(ix) = []; if isfield(p, 'ivec') I = abs(p.ivec(:,:,:,ix) - I); [~, I] = min(I, [], ix); ii = {1:d(1) 1:d(2) 1:d(3)}; ii{ix} = single(1); [ii{1}, ii{2}, ii{3}] = ndgrid(ii{:}); ii{ix} = single(I); io = {':' ':' ':' ':'}; io{ix} = 1; im = img(io{:}); for k = 1:2 im(:,:,:,k) = interp3(img(:,:,:,j(k)), ii{[2 1 3]}, 'nearest'); end ind = sub2ind(d(1:3), ii{:}); X = p.ivec(:,:,:,j(1)); X = permute(X(ind), [j([2 1]) ix]); Y = p.ivec(:,:,:,j(2)); Y = permute(Y(ind), [j([2 1]) ix]); else ii = {':' ':' ':'}; ii{ix} = I; im = img(ii{:}, j); [Y, X] = ndgrid(1:d(j(2)), 1:d(j(1))); end im = permute(im, [j([2 1]) 4 ix]); im(im==0) = nan; % avoid dots in emf and eps X = X - im(:,:,1)/2; Y = Y - im(:,:,2)/2; set(p.hsI(ix), 'XData', X, 'YData', Y, 'UData', im(:,:,1), 'VData', im(:,:,2)); end %% Bring cross and label to front function crossFront(hs) for i = 1:3 txt = allchild(hs.ax(i)); ind = strcmpi(get(txt, 'Type'), 'text'); txt = txt(ind); % a number, two letters, plus junk text with matlab 2010b uistack([txt' hs.cross(i,:)], 'top'); end %% Compute color map for LUT function map = lut2map(p, lutStr) persistent parula64; if isfield(p, 'map') if isfield(p.nii, 'NamedMap') try, map = p.nii.NamedMap{p.volume}.map; end else, map = p.map; end return; end lut = p.lut; map = linspace(0,1,64)'*[1 1 1]; % gray if lut == 1, return; % gray elseif lut == 2, map(:,2:3) = 0; % red elseif lut == 3, map(:,[1 3]) = 0; % green elseif lut == 4, map(:,1:2) = 0; % blue elseif lut == 5, map(:,2) = 0; % violet elseif lut == 6, map(:,3) = 0; % yellow elseif lut == 7, map(:,1) = 0; % cyan elseif any(lut == [8 19 26]), map(:,3) = 0; map(:,1) = 1; % red_yellow elseif lut == 9, map(:,1) = 0; map(:,3) = flip(map(:,3)); % blue_green elseif lut == 10 % two-sided map = map(1:2:end,:); % half map_neg = map; map(:,3) = 0; map(:,1) = 1; % red_yellow map_neg(:,1) = 0; map_neg(:,3) = flip(map_neg(:,3)); % blue_green map = [flip(map_neg,1); map]; elseif lut == 11, map(:,2:3) = 0; % vector lines elseif lut == 12 % parula not in old matlab, otherwise this can be omitted if isempty(parula64) fname = fullfile(fileparts(mfilename('fullpath')), 'example_data.mat'); a = load(fname, 'parula'); parula64 = a.parula; end map = parula64; elseif lut < 26 % matlab LUT map = feval(lutStr, 64); elseif lut == 27 % phase3: red-yellow-green-yellow-red a = map(:,1); map(1:32,3) = 0; map(1:16,1) = 1; map(17:32,2) = 1; map(1:16,2) = a(1:4:64); map(17:32,1) = a(64:-4:1); map(33:64,:) = map(32:-1:1,:); elseif lut == 28 % phase6: red-yellow-green/violet-blue-cyan a = map(:,1); map(1:32,3) = 0; map(1:16,1) = 1; map(17:32,2) = 1; map(1:16,2) = a(1:4:64); map(17:32,1) = a(64:-4:1); map(33:48,2) = 0; map(33:48,3) = 1; map(33:48,1) = a(64:-4:1); map(49:64,1) = 0; map(49:64,3) = 1; map(49:64,2) = a(1:4:64); elseif lut == 29 % RGB end %% Preference dialog function pref_dialog(h, ~) pf = getpref('nii_viewer_para'); d = dialog('Name', 'Preferences', 'Visible', 'off'); pos = getpixelposition(d); pos(3:4) = [396 332]; hs.fig = ancestor(h, 'figure'); uicontrol(d, 'Style', 'text', 'Position', [8 306 300 22], ... 'String', 'Background (template) image folder:', 'HorizontalAlignment', 'left'); hs.openPath = uicontrol(d, 'Style', 'edit', 'String', pf.openPath, ... 'Position', [8 288 350 22], 'BackgroundColor', 'w', 'HorizontalAlignment', 'left', ... 'TooltipString', 'nii_viewer will point to this folder when you "Open" image'); uicontrol('Parent', d, 'Position', [358 289 30 22], 'Tag', 'browse', ... 'String', '...', 'Callback', @pref_dialog_cb); hs.rightOnLeft = uicontrol(d, 'Style', 'popup', 'BackgroundColor', 'w', ... 'Position', [8 252 380 22], 'Value', pf.rightOnLeft+1, ... 'String', {'Neurological orientation (left on left side)' ... 'Radiological orientation (right on left side)'}, ... 'TooltipString', 'Display convention also applies to future use'); uicontrol(d, 'Style', 'text', 'Position', [8 210 40 22], ... 'String', 'Layout', 'HorizontalAlignment', 'left', ... 'TooltipString', 'Layout for three views'); % iconsFolder = fullfile(matlabroot,'/toolbox/matlab/icons/'); % iconUrl = strrep(['file:/' iconsFolder 'matlabicon.gif'],'\','/'); % str = ['<html><img src="' iconUrl '"/></html>']; hs.layout = uicontrol(d, 'Style', 'popup', 'BackgroundColor', 'w', ... 'Position', [50 214 338 22], 'Value', pf.layout, ... 'String', {'one-row' 'two-row sag on right' 'two-row sag on left'}, ... 'TooltipString', 'Layout for three views'); hs.mouseOver = uicontrol(d, 'Style', 'checkbox', ... 'Position', [8 182 380 22], 'Value', pf.mouseOver, ... 'String', 'Show coordinates and intensity when mouse moves over image', ... 'TooltipString', 'Also apply to future use'); uipanel(d, 'Units', 'Pixels', 'Position', [4 110 390 56], 'BorderType', 'etchedin', ... 'BorderWidth', 2, 'Title', 'For "Save NIfTI as" if interpolation is applicable'); str = {'nearest' 'linear' 'cubic' 'spline'}; val = find(strcmp(str, pf.interp)); uicontrol('Parent', d, 'Style', 'text', 'Position', [8 116 140 22], ... 'String', 'Interpolation method:', 'HorizontalAlignment', 'right'); hs.interp = uicontrol(d, 'Style', 'popup', 'String', str, ... 'Position', [150 120 68 22], 'Value', val, 'BackgroundColor', 'w'); uicontrol('Parent', d, 'Style', 'text', 'Position', [230 116 90 22], ... 'String', 'Missing value:', 'HorizontalAlignment', 'right'); hs.extraV = uicontrol(d, 'Style', 'edit', 'String', num2str(pf.extraV), ... 'Position', [324 120 60 22], 'BackgroundColor', 'w', ... 'TooltipString', 'NaN or 0 is typical, but can be any number'); str = strtrim(cellstr(num2str([0 120 150 200 300 600 1200]'))); val = find(strcmp(str, pf.dpi)); uipanel(d, 'Units', 'Pixels', 'Position', [4 40 390 56], 'BorderType', 'etchedin', ... 'BorderWidth', 2, 'Title', 'For "Save figure as" and "Copy figure"'); uicontrol('Parent', d, 'Style', 'text', 'Position', [8 46 90 22], ... 'String', 'Resolution:', 'HorizontalAlignment', 'right'); hs.dpi = uicontrol(d, 'Style', 'popup', 'String', str, ... 'Position', [110 50 50 22], 'Value', val, 'BackgroundColor', 'w', ... 'TooltipString', 'in DPI (0 means screen resolution)'); uicontrol('Parent', d, 'Position', [300 10 70 24], 'Tag', 'OK', ... 'String', 'OK', 'Callback', @pref_dialog_cb); uicontrol('Parent', d, 'Position',[200 10 70 24], ... 'String', 'Cancel', 'Callback', 'delete(gcf)'); set(d, 'Position', pos, 'Visible', 'on'); guidata(d, hs); %% Preference dialog callback function pref_dialog_cb(h, ~) hs = guidata(h); if strcmp(get(h, 'Tag'), 'OK') % done fh = hs.fig; pf = getpref('nii_viewer_para'); pf.layout = get(hs.layout, 'Value'); % 1:3 pf.rightOnLeft = get(hs.rightOnLeft, 'Value')==2; pf.mouseOver = get(hs.mouseOver, 'Value'); if pf.mouseOver % this is the only one we update current fig set(fh, 'WindowButtonMotionFcn', {@nii_viewer_cb 'mousemove' fh}); else set(fh, 'WindowButtonMotionFcn', ''); end i = get(hs.interp, 'Value'); str = get(hs.interp, 'String'); pf.interp = str{i}; pf.extraV = str2double(get(hs.extraV, 'String')); pf.openPath = get(hs.openPath, 'String'); i = get(hs.dpi, 'Value'); str = get(hs.dpi, 'String'); pf.dpi = str{i}; setpref('nii_viewer_para', fieldnames(pf), struct2cell(pf)); delete(get(h, 'Parent')); elseif strcmp(get(h, 'Tag'), 'browse') % set openPath pth = uigetdir(pwd, 'Select folder for background image'); if ~ischar(pth), return; end set(hs.openPath, 'String', pth); end %% Simple version of interp3 function V = interp3a(V, I, method) % V = interp3a(V, I, 'linear'); % This is similar to interp3 from Matlab, but takes care of the Matlab version % issue, and the input is simplified for coordinate. The coordinate input are in % this way: I(1,:), I(2,:) and I(3,:) are for x, y and z. persistent v; if isempty(v) try griddedInterpolant(ones(3,3,3), 'nearest', 'none'); v = 2014; catch try griddedInterpolant(ones(3,3,3), 'nearest'); v = 2013; catch v = 2011; end end end if strcmp(method, 'nearest') || any(size(V)<2), I = round(I); end if size(V,1)<2, V(2,:,:) = nan; end if size(V,2)<2, V(:,2,:) = nan; end if size(V,3)<2, V(:,:,2) = nan; end if v > 2011 if v > 2013 F = griddedInterpolant(V, method, 'none'); else F = griddedInterpolant(V, method); end V = F(I(1,:), I(2,:), I(3,:)); % interpolate else % earlier matlab V = interp3(V, I(2,:), I(1,:), I(3,:), method, nan); end %% 2D/3D smooth wrapper: no input check for 2D function im = smooth23(im, varargin) % out = smooth23(in, varargin) % This works the same as smooth3 from Matlab, but takes care of 2D input. is2D = size(im,3) == 1; if is2D, im = repmat(im, [1 1 2]); end im = smooth3(im, varargin{:}); if is2D, im = im(:,:,1); end %% Show xyz and value function xyz = set_xyz(hs, I) if nargin<2 for i=3:-1:1, I(i) = get(hs.ijk(i), 'Value'); end end I = round(I); xyz = round(hs.bg.R * [I-1 1]'); xyz = xyz(1:3); str = sprintf('(%i,%i,%i): ', xyz); for i = 1:hs.files.getModel.size % show top one first p = get_para(hs, i); if p.show == 0, continue; end t = round(p.volume); if isfield(p, 'R0') % need interpolation if isfield(p, 'warp') warp = p.warp(I(1), I(2), I(3), :); I0 = p.Ri * (p.R0 * [I-1 1]' + [warp(:); 0]); else I0 = p.Ri * p.R0 * [I-1 1]'; % overlay ijk end I0 = round(I0(1:3)+1); else, I0 = I; end try val = p.nii.img(I0(1), I0(2), I0(3), t, :); if isfield(p, 'scl_slope') val = single(val) * p.scl_slope + p.scl_inter; end catch val = nan; % out of range end if isfield(p, 'labels') try labl = p.labels{val}; str = sprintf('%s %s', str, labl); continue; % skip numeric val assignment end end if isfield(p.nii, 'NamedMap') try labl = p.nii.NamedMap{p.volume}.labels{val}; str = sprintf('%s %s', str, labl); continue; end end fmtstr = '%.4g '; if numel(val)>1 fmtstr = repmat(fmtstr, 1, numel(val)); fmtstr = ['[' fmtstr]; fmtstr(end) = ']'; %#ok end str = sprintf(['%s ' fmtstr], str, val); end hs.value.String = str; %% nii essentials function s = nii_essential(hdr) % info = nii_essential(hdr); % Decode important NIfTI hdr into struct info, which is human readable. if isfield(hdr, 'nii') % input by nii_viewer s.FileName = hdr.nii.hdr.file_name; if isfield(hdr, 'mask_info'), s.MaskedBy = hdr.mask_info; end if isfield(hdr, 'modulation_info'), s.ModulatdBy = hdr.modulation_info; end if isfield(hdr, 'alignMtx'), s.AlignMatrix = hdr.alignMtx; end hdr = hdr.nii.hdr; else s.FileName = hdr.file_name; end switch hdr.intent_code case 2, s.intent = 'Correlation'; s.DoF = hdr.intent_p1; case 3, s.intent = 'T-test'; s.DoF = hdr.intent_p1; case 4, s.intent = 'F-test'; s.DoF = [hdr.intent_p1 hdr.intent_p2]; case 5, s.intent = 'Z-score'; case 6, s.intent = 'Chi squared'; s.DoF = hdr.intent_p1; % several non-statistical intent_code case 1002, s.intent = 'Label'; % e.g. AAL labels case 2003, s.intent = 'RGB'; % triplet in the 5th dimension case 2004, s.intent = 'RGBA'; % quadruplet in the 5th dimension end switch hdr.datatype case 0 case 1, s.DataType = 'logical'; case 2, s.DataType = 'uint8'; case 4, s.DataType = 'int16'; case 8, s.DataType = 'int32'; case 16, s.DataType = 'single'; case 32, s.DataType = 'single complex'; case 64, s.DataType = 'double'; case 128, s.DataType = 'uint8 RGB'; case 256, s.DataType = 'int8'; case 511, s.DataType = 'single RGB'; case 512, s.DataType = 'uint16'; case 768, s.DataType = 'uint32'; case 1024, s.DataType = 'int64'; case 1280, s.DataType = 'uint64'; case 1792, s.DataType = 'double complex'; case 2304, s.DataType = 'uint8 RGBA'; otherwise, s.DataType = 'unknown'; end s.Dimension = hdr.dim(2:hdr.dim(1)+1); switch bitand(hdr.xyzt_units, 7) case 1, s.VoxelUnit = 'meters'; case 2, s.VoxelUnit = 'millimeters'; case 3, s.VoxelUnit = 'micrometers'; end s.VoxelSize = hdr.pixdim(2:4); switch bitand(hdr.xyzt_units, 56) case 8, s.TemporalUnit = 'seconds'; case 16, s.TemporalUnit = 'milliseconds'; case 24, s.TemporalUnit = 'microseconds'; case 32, s.TemporalUnit = 'Hertz'; case 40, s.TemporalUnit = 'ppm'; case 48, s.TemporalUnit = 'radians per second'; end if isfield(s, 'TemporalUnit') && strfind(s.TemporalUnit, 'seconds') s.TR = hdr.pixdim(5); end if hdr.dim_info>0 s.FreqPhaseSliceDim = bitand(hdr.dim_info, [3 12 48]) ./ [1 4 16]; a = bitand(hdr.dim_info, 192) / 64; if a>0 && s.FreqPhaseSliceDim(2)>0 ax = 'xyz'; % ijk to be accurate pm = ''; if a == 2, pm = '-'; end s.PhaseEncodingDirection = [pm ax(s.FreqPhaseSliceDim(2))]; end end switch hdr.slice_code case 0 case 1, s.SliceOrder = 'Sequential Increasing'; case 2, s.SliceOrder = 'Sequential Decreasing'; case 3, s.SliceOrder = 'Alternating Increasing 1'; case 4, s.SliceOrder = 'Alternating Decreasing 1'; case 5, s.SliceOrder = 'Alternating Increasing 2'; case 6, s.SliceOrder = 'Alternating Decreasing 2'; otherwise, s.SliceOrder = 'Multiband?'; end if ~isempty(hdr.descrip), s.Notes = hdr.descrip; end str = formcode2str(hdr.qform_code); if ~isempty(str), s.qform = str; end if hdr.qform_code>0, s.qform_mat = quat2R(hdr); end str = formcode2str(hdr.sform_code); if ~isempty(str), s.sform = str; end if hdr.sform_code>0 s.sform_mat = [hdr.srow_x; hdr.srow_y; hdr.srow_z; 0 0 0 1]; end %% decode NIfTI form_code function str = formcode2str(code) switch code case 0, str = ''; case 1, str = 'Scanner Anat'; case 2, str = 'Aligned Anat'; case 3, str = 'Talairach'; case 4, str = 'mni_152'; otherwise, str = 'Unknown'; end %% Get a mask based on image intensity, but with inside brain filled function r = img2mask(img) mn = mean(img(img(:)>0)); r = smooth23(img, 'box', 5) > mn/8; % smooth, binarize if sum(r(:))==0, return; end try C = contourc(double(r), [1 1]); i = 1; c = {}; while size(C,2)>2 % split C into contours k = C(2,1) + 1; c{i} = C(:, 2:k); C(:,1:k) = []; %#ok i = i+1; end nc = numel(c); rg = nan(nc, 4); % minX minY maxX maxY for i = 1:nc rg(i,:) = [min(c{i},[],2)' max(c{i},[],2)']; end ind = false(nc,1); foo = min(rg(:,1)); ind = ind | foo==rg(:,1); foo = min(rg(:,2)); ind = ind | foo==rg(:,2); foo = max(rg(:,3)); ind = ind | foo==rg(:,3); foo = max(rg(:,4)); ind = ind | foo==rg(:,4); c = c(ind); % outmost contour(s) len = cellfun(@(x) size(x,2), c); [~, ind] = sort(len, 'descend'); c = c(ind); C = c{1}; if isequal(C(:,1), C(:,end)), c(2:end) = []; end % only 1st if closed nc = numel(c); for i = nc:-1:2 % remove closed contours except one with max len if isequal(c{i}(:,1), c{i}(:,end)), c(i) = []; end end nc = numel(c); while nc>1 % +1 contours, put all into 1st d2 = nan(nc-1, 2); % distance^2 from C(:,end) to other start/endpoint for i = 2:nc d2(i-1,:) = sum((C(:,end)*[1 1] - c{i}(:,[1 end])).^2); end [i, j] = find(d2 == min(d2(:))); i = i + 1; % start with 2nd if j == 1, C = [C c{i}]; %#ok C(:,1) connect to c{i}(:,1) else C = [C c{i}(:,end:-1:1)]; %#ok C(:,end) to c{i}(:,end) end c(i) = []; nc = nc-1; end if ~isequal(C(:,1), C(:,end)), C(:,end+1) = C(:,1); end % close the contour x = C(1, :); y = C(2, :); [m, n] = size(r); % following is the method in Octave poly2mask xe = [x(1:numel(x)-1); x(1, 2:numel(x))]; % edge x ye = [y(1:numel(y)-1); y(1, 2:numel(y))]; % edge y ind = ye(1,:) == ye(2,:); xe(:,ind) = []; ye(:, ind) = []; % reomve horizontal edges minye = min(ye); maxye = max(ye); t = (ye == [minye; minye]); exminy = xe(:); exminy = exminy(t); exmaxy = xe(:); exmaxy = exmaxy(~t); maxye = maxye'; minye = minye'; m_inv = (exmaxy - exminy) ./ (maxye - minye); ge = [maxye minye exmaxy m_inv]; ge = sortrows(ge, [1 3]); ge = [-Inf -Inf -Inf -Inf; ge]; gei = size(ge, 1); sl = ge(gei, 1); ae = []; % active edge while (sl == ge(gei, 1)) ae = [ge(gei, 2:4); ae]; %#ok gei = gei - 1; end miny = min(y); if miny < 1, miny = 1; end while (sl >= miny) if (sl <= m) % check vert clipping ie = round(reshape(ae(:, 2), 2, size(ae, 1)/2)); ie(1, :) = ie(1, :) + (ie(1, :) ~= ie(2, :)); ie(1, (ie(1, :) < 1)) = 1; ie(2, (ie(2, :) > n)) = n; ie = ie(:, (ie(1, :) <= n)); ie = ie(:, (ie(2, :) >= 1)); for i = 1:size(ie,2) r(sl, ie(1, i):ie(2, i)) = true; end end sl = sl - 1; ae = ae((ae(:, 1) ~= sl), :); ae(:, 2) = ae(:, 2) - ae(:, 3); while (sl == ge(gei, 1)) ae = [ae; ge(gei, 2:4)]; %#ok gei = gei - 1; end if size(ae,1) > 0 ae = sortrows(ae, 2); end end catch %me, fprintf(2, '%s\n', me.message); assignin('base', 'me', me); end %% update colorbar label function set_colorbar(hs) if strcmpi(get(hs.colorbar, 'Visible'), 'off'), return; end p = get_para(hs); map = lut2map(p, hs.lutStr{p.lut}); rg = sort([p.lb p.ub]); tickLoc = [0 0.5 1]; if any(p.lut == 26:28) labls = [0 180 360]; elseif p.lut==10 rg = sort(abs(rg)); labls = {num2str(-rg(2),'%.2g') num2str(rg(1),'+/-%.2g') num2str(rg(2),'%.2g')}; elseif p.lut==numel(hs.lutStr) % custom im = p.nii.img(:,:,:,p.volume); im(isnan(im) | im==0) = []; im = unique(im); if max(im)<=size(map,1) && isequal(im, round(im)) % integer try, map = map(im+1, :); rg = [im(1) im(end)]; end end labls = [rg(1) rg(2)]; tickLoc = [0 1]; else if rg(2)<0, rg = rg([2 1]); end mn = str2double(num2str(mean(rg), '%.4g')); labls = [rg(1) mn rg(2)]; end % colormap in earlier matlab version changes values in colorbar. % So we have to set those values each time. colormap(hs.ax(end), map); % map must be double for old matlab % set(hs.colorbar, 'YTickLabel', labls); % new matlab set(get(hs.colorbar, 'Children'), 'YData', [0 1]); % Trick for old matlab set(hs.colorbar, 'YTickLabel', labls, 'YTick', tickLoc, 'Ylim', [0 1]); fh = hs.fig.UserData; if isempty(fh) || ~ishandle(fh) || ~isfield(p.nii, 'cii'), return; end hs = guidata(fh); colormap(hs.ax(end), map); set(get(hs.colorbar, 'Children'), 'YData', [0 1]); set(hs.colorbar, 'YTickLabel', labls, 'YTick', tickLoc, 'Ylim', [0 1]); %% return screen size in pixels function res = screen_pixels(id) res = get(0, 'MonitorPositions'); if size(res,1)<2, res = res(1, 3:4); return; end % single/duplicate monitor if nargin, res = res(id,3:4); return; end res = sortrows(res); res = res(end,1:2) + res(end,3:4) - res(1,1:2); %% add mask or modulation function addMask(h, ~) hs = guidata(h); jf = hs.files.getSelectedIndex+1; p = get_para(hs, jf); pName = fileparts(p.nii.hdr.file_name); [fname, pName] = uigetfile([pName '/*.nii;*.hdr;*.nii.gz;*.hdr.gz'], ... 'Select mask NIfTI'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii = nii_tool('load', fname); hdr = p.nii.hdr; codes = [hdr.sform_code hdr.qform_code]; [R, frm] = nii_xform_mat(nii.hdr, codes); if ~any(frm == codes) str = ['There is no matching coordinate system between the selected ' ... 'image and the mask image. Do you want to apply the mask anyway?']; btn = questdlg(str, 'Apply mask?', 'Cancel', 'Apply', 'Cancel'); if isempty(btn) || strcmp(btn, 'Cancel'), return; end R0 = nii_xform_mat(hdr, codes(1)); else R0 = nii_xform_mat(hdr, frm); % may be the same as p.R end % R0 = reorient(R0, hdr.dim(2:4)); % do this since img was done when loaded % if isfield(p, 'alignMtx'), R = R0 / p.R * R; end % inverse % this wont work if lines is background & Mprage is overlay if all(isfield(p, {'R0' 'alignMtx'})) % target as mask R1 = reorient(R, nii.hdr.dim(2:4)); if all(abs(R1(:)-p.R0(:))<1e-4), R0 = p.R; end % not 100% safe end d = single(size(p.nii.img)); % dim for reoriented img d(numel(d)+1:3) = 1; d = d(1:3); I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); % ijk grids of target img I = inv(R) * R0 * I + 1; %#ok ijk+1 for mask I = round(I * 100) / 100; im = single(nii.img(:,:,:,1)); % first mask volume slope = nii.hdr.scl_slope; if slope==0, slope = 1; end im = im * slope + nii.hdr.scl_inter; im = interp3a(im, I, 'nearest'); im1 = im(~isnan(im)); % for threshold computation im = reshape(im, d); if strcmp(get(h, 'Label'), 'Apply mask') % binary mask if numel(unique(im1))<3 thre = min(im1); else a = get_range(nii); str = sprintf('Threshold for non-binary mask (%.3g to %.4g)', ... min(im1), max(im1)); a = inputdlg(str, 'Input mask threshold', 1, {num2str(a(1), '%.3g')}); if isempty(a), return; end thre = str2double(a{1}); fname = [fname ' (threshold = ' a{1} ')']; % info only end p.mask = ones(size(im), 'single'); p.mask(abs(im)<=thre) = nan; p.mask_info = fname; noteStr = '(masked)'; else % modulation mi = min(im1); ma = max(im1); if mi<0 || ma>1 str = {sprintf('Lower bound to clip to 0 (image min = %.2g)', mi) ... sprintf('Upper bound to clip to 1 (image max = %.2g)', ma)}; def = strtrim(cellstr(num2str([mi;ma], '%.2g'))'); a = inputdlg(str, 'Input modulation range', 1, def); if isempty(a), return; end mi = str2double(a{1}); ma = str2double(a{2}); fname = [fname ' (range [' a{1} ' ' a{2} '])']; end im(im<mi) = mi; im(im>ma) = ma; p.modulation = (im-mi) / (ma-mi); p.modulation_info = fname; noteStr = '(modulated)'; end p.hsI(1).UserData = p; set_cdata(hs); str = hs.files.getModel.get(jf-1); if ~any(regexp(str, [regexptranslate('escape', noteStr) '$'])) hs.files.getModel.set(jf-1, [str noteStr]); end %% update crosshair: ix correspond to one of the three spinners, not views function set_cross(hs, ix) h = hs.cross; for i = ix c = get(hs.ijk(i), 'Value'); g = hs.gap(i); if i == 1 % I changed set([h(2,3:4) h(3,3:4)], 'XData', [c c]); set([h(2,1) h(3,1)], 'XData', [0 c-g]); set([h(2,2) h(3,2)], 'XData', [c+g hs.dim(1)+1]); elseif i == 2 % J set(h(1,3:4), 'XData', [c c]); set(h(1,1), 'XData', [0 c-g]); set(h(1,2), 'XData', [c+g hs.dim(2)+1]); set(h(3,1:2), 'YData', [c c]); set(h(3,3), 'YData', [0 c-g]); set(h(3,4), 'YData', [c+g hs.dim(2)+1]); else % K set([h(1,1:2) h(2,1:2)], 'YData', [c c]); set([h(1,3) h(2,3)], 'YData', [0 c-g]); set([h(1,4) h(2,4)], 'YData', [c+g hs.dim(3)+1]); end end %% Duplicate image handles, inlcuding ButtonDownFcn for new matlab function h = copyimg(hs) h = hs.hsI; for i = 1:3, h(i) = handle(copyobj(hs.hsI(i), hs.ax(i))); end cb = get(hs.hsI(1), 'ButtonDownFcn'); set(h, 'Visible', 'on', 'ButtonDownFcn', cb); % cb needed for 2014b+ crossFront(hs); %% Save selected nii as another file function save_nii_as(h, ~) hs = guidata(h); c = get(h, 'Label'); p = get_para(hs); nam = p.nii.hdr.file_name; pName = fileparts(nam); if isempty(pName), pName = pwd; end try nii = nii_tool('load', nam); % re-load to be safe catch % restore reoriented img nii = p.nii; for k = 1:3, if p.flip(k), nii.img = flip(nii.img, k); end; end nii.img = permute(nii.img, [p.perm 4:8]); % all vol in dim(4) slope = nii.hdr.scl_slope; if slope==0, slope = 1; end nii.img = (single(nii.img) - nii.hdr.scl_inter) / slope; % undo scale if nii.hdr.datatype == 4 % leave others as it is or single nii.img = int16(nii.img); elseif nii.hdr.datatype == 512 nii.img = uint16(nii.img); elseif any(nii.hdr.datatype == [2 128 2304]) nii.img = uint8(nii.img); end end if ~isempty(strfind(c, 'a copy')) %#ok<*STREMP> % a copy [fname, pName] = uiputfile([pName '/*.nii'], 'Input name for FSL RGB file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_tool('save', nii, fname); elseif ~isempty(strfind(c, 'dim 4')) % fsl RGB if any(size(nii.img,8) == 3:4) nii.img = permute(nii.img, [1:3 8 4:7]); elseif ~any(nii.hdr.dim(5) == 3:4) errordlg('Selected image is not RGB data.'); return; end [fname, pName] = uiputfile([pName '/*.nii'], 'Input name for FSL RGB file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_tool('save', nii, fname); elseif ~isempty(strfind(c, 'dim 3')) % old mricron RGB if any(nii.hdr.dim(5) == 3:4) nii.img = permute(nii.img, [1:3 5:7 4]); elseif ~any(size(nii.img,8) == 3:4) errordlg('Selected image is not RGB data'); return; end [fname, pName] = uiputfile([pName '/*.nii'], 'Input name for old mricrom styte file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); old = nii_tool('RGBStyle', 'mricron'); nii_tool('save', nii, fname); nii_tool('RGBStyle', old); elseif ~isempty(strfind(c, 'AFNI')) % NIfTI RGB if any(nii.hdr.dim(5) == 3:4) nii.img = permute(nii.img, [1:3 5:8 4]); elseif ~any(size(nii.img,8) == 3:4) errordlg('Selected image is not RGB data'); return; end nii.img = abs(nii.img); [fname, pName] = uiputfile([pName '/*.nii'], ... 'Input name for NIfTI standard RGB file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); old = nii_tool('RGBStyle', 'afni'); nii_tool('save', nii, fname); nii_tool('RGBStyle', old); elseif ~isempty(strfind(c, '3D')) % SPM 3D if nii.hdr.dim(5)<2 errordlg('Selected image is not multi-volume data'); return; end [fname, pName] = uiputfile([pName '/*.nii'], 'Input base name for SPM 3D file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_tool('save', nii, fname, 1); % force 3D elseif ~isempty(strfind(c, 'new resolution')) str = 'Resolution for three dimension in mm'; a = inputdlg(str, 'Input spatial resolution', 1, {'3 3 3'}); if isempty(a), return; end res = sscanf(a{1}, '%g %g %g'); if numel(res) ~= 3 errordlg('Invalid spatial resolution'); return; end if isequal(res, p.nii.hdr.pixdim(2:4)) warndlg('The input resolution is the same as current one'); return; end [fname, pName] = uiputfile([pName '/*.nii;nii.gz'], ... 'Input result name for the new resolution file'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_xform(nii, res, fname, hs.pref.UserData.interp, hs.pref.UserData.extraV) elseif ~isempty(strfind(c, 'matching background')) if p.hsI(1) == hs.hsI(1) errordlg('You selected background image'); return; end [fname, pName] = uiputfile([pName '/*.nii;*.nii.gz'], ... 'Input result file name'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_xform(nii, hs.bg.hdr, fname, hs.pref.UserData.interp, hs.pref.UserData.extraV) elseif ~isempty(strfind(c, 'aligned template')) [temp, pName] = uigetfile([pName '/*.nii;*.nii.gz'], ... 'Select the aligned template file'); if ~ischar(temp), return; end temp = fullfile(pName, temp); [mtx, pName] = uigetfile([pName '/*.mat'], ['Select the text ' ... 'matrix file which aligns the nii to the template']); if ~ischar(mtx), return; end mtx = fullfile(pName, mtx); [fname, pName] = uiputfile([pName '/*.nii;*.nii.gz'], ... 'Input result file name'); if ~ischar(fname), return; end fname = fullfile(pName, fname); nii_xform(nii, {temp mtx}, fname, hs.pref.UserData.interp, hs.pref.UserData.extraV) else errordlg(sprintf('%s not implemented yet.', c)); end %% Return 3-layer RGB, called by set_cdata function [im, alfa] = lut2img(im, p, lutStr) rg = sort([p.lb p.ub]); if isfield(p.nii, 'NamedMap') try, p.map = p.nii.NamedMap{p.volume}.map; end end if any(p.lut == 26:28) im = im(:,:,2) .* single(im(:,:,1)>min(abs(rg))); % mag as mask end if rg(2)<0 % asking for negative data rg = -rg([2 1]); if p.lut~=10, im = -im; end end alfa = single(0); % override for lut=10 if p.lut == 10 % two-sided, store negative value rg = sort(abs(rg)); im_neg = -single(im) .* (im<0); im_neg = (im_neg-rg(1)) / (rg(2)-rg(1)); im_neg(im_neg>1) = 1; im_neg(im_neg<0) = 0; alfa = im_neg; % add positive part later im_neg = repmat(im_neg, [1 1 3]); % gray now end if p.lut < 26 % no scaling for 3 phase LUTs, RGB, custom im = (im-rg(1)) / (rg(2)-rg(1)); im(im>1) = 1; im(im<0) = 0; end alfa = im + alfa; if p.lut ~= 29, im = repmat(im, [1 1 3]); end % gray now switch p.lut case 1 % gray do nothing case 2, im(:,:,2:3) = 0; % red case 3, im(:,:,[1 3]) = 0; % green case 4, im(:,:,1:2) = 0; % blue case 5, im(:,:,2) = 0; % violet case 6, im(:,:,3) = 0; % yellow case 7, im(:,:,1) = 0; % cyan case {8 19} % red_yellow, autumn a = im(:,:,1); a(a>0) = 1; im(:,:,1) = a; im(:,:,3) = 0; case 9 % blue_green im(:,:,1) = 0; a = im(:,:,3); a(a==0) = 1; a = 1 - a; im(:,:,3) = a; case 10 % two-sided: combine red_yellow & blue_green im(:,:,3) = 0; a = im(:,:,1); a(a>0) = 1; im(:,:,1) = a; im_neg(:,:,1) = 0; a = im_neg(:,:,3); a(a==0) = 1; a = 1 - a; im_neg(:,:,3) = a; im = im + im_neg; case 15 % hot, Matlab colormap can be omitted, but faster than mapping a = im(:,:,1); a = a/0.375; a(a>1) = 1; im(:,:,1) = a; a = im(:,:,2); a = a/0.375-1; a(a<0) = 0; a(a>1) = 1; im(:,:,2) = a; a = im(:,:,3); a = a*4-3; a(a<0) = 0; im(:,:,3) = a; case 16 % cool a = im(:,:,2); a(a==0) = 1; a = 1 - a; im(:,:,2) = a; a = im(:,:,3); a(a>0) = 1; im(:,:,3) = a; case 17 % spring a = im(:,:,1); a(a>0) = 1; im(:,:,1) = a; a = im(:,:,3); a(a==0) = 1; a = 1 - a; im(:,:,3) = a; case 18 % summer a = im(:,:,2); a(a==0) = -1; a = a/2+0.5; im(:,:,2) = a; a = im(:,:,3); a(a>0) = 0.4; im(:,:,3) = a; case 20 % winter im(:,:,1) = 0; a = im(:,:,3); a(a==0) = 2; a = 1-a/2; im(:,:,3) = a; case 22 % copper a = im(:,:,1); a = a*1.25; a(a>1) = 1; im(:,:,1) = a; im(:,:,2) = im(:,:,2) * 0.7812; im(:,:,3) = im(:,:,3) * 0.5; case 26 % phase, like red_yellow im(:,:,1) = 1; im(:,:,3) = 0; case 27 % phase3, red-yellow-green-yellow-red a = im(:,:,1); b1 = a<=0.25; b2 = a>0.25 & a<=0.5; b3 = a>0.5 & a<=0.75; b4 = a>0.75; a(b1 | b4) = 1; a(b2) = (0.5-a(b2))*4; a(b3) = (a(b3)-0.5)*4; im(:,:,1) = a; a = im(:,:,2); a(b2 | b3) = 1; a(b1) = a(b1)*4; a(b4) = (1-a(b4))*4; im(:,:,2) = a; im(:,:,3) = 0; case 28 % phase6, red-yellow-green/violet-blue-cyan a = im(:,:,1); b1 = a<=0.25; b2 = a>0.25 & a<=0.5; b3 = a>0.5 & a<=0.75; b4 = a>0.75; a(b2) = (0.5-a(b2))*4; a(b1) = 1; a(b3) = (0.75-a(b3))*4; a(b4) = 0; im(:,:,1) = a; a = im(:,:,2); a(b1) = a(b1)*4; a(b2) = 1; a(b3) = 0; a(b4) = (a(b4)-0.75)*4; im(:,:,2) = a; a = im(:,:,3); a(b1 | b2) = 0; a(b3 | b4) = 1; im(:,:,3) = a; case 29 % disp non-NIfTI RGB as RGB im = abs(im); % e.g. DTI V1 if max(im(:)) > 1, im = im / 255; end % it should be unit8 alfa = sum(im,3)/3; otherwise % parula(12), jet(13), hsv(14), bone(21), pink(23), custom if isfield(p, 'map') % custom map = p.map; else try, map = feval(lutStr, 256); catch me if p.lut == 12, map = lut2map(p); % parula for old matlab else, rethrow(me); end end end if p.lut ~= 30 % normalized previously a = floor(im(:,:,1) * (size(map,1)-1)) + 1; % 1st for bkgrnd elseif max(p.nii.img(:)) <= size(map,1) alfa = alfa / max(alfa(:)); a = round(im(:,:,1)) + 1; % custom or uint8, round to be safe else a = (im(:,:,1) - rg(1)) / (rg(2)-rg(1)); a(a<0) = 0 ; a(a>1) = 1; alfa = a; a = round(a * (size(map,1)-1)) + 1; end a(isnan(a)) = 1; aa = a; for i = 1:3 aa(:) = map(a, i); im(:,:,i) = aa; end end %% Return binary sphere ROI from xyz and r (mm) function b = xyzr2roi(c, r, hdr) % ROI_img = xyzr2roi(center, radius, hdr) % Return an ROI img based on the dim info in NIfTI hdr. The center and radius % are in unit of mm. d = single(hdr.dim(2:4)); I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); % ijk in 4 by nVox R = nii_xform_mat(hdr); I = R * I; % xyz in 4 by nVox b = bsxfun(@minus, I(1:3,:), c(:)); % dist in x y z direction from center b = sum(b .* b); % dist to center squared, 1 by nVox b = b <= r*r; % within sphere b = reshape(b, d); %% Return center of gravity of an image function c = img_cog(img) % center_ijk = img_cog(img) % Return the index of center of gravity in img (must be 3D). img(isnan(img)) = 0; img = double(abs(img)); gs = sum(img(:)); c = ones(3,1); for i = 1:3 if size(img,i)==1, continue; end a = shiftdim(img, i-1); a = sum(sum(a,3),2); c(i) = (1:size(img,i)) * a / gs; end %% set up disp parameter for new nifti function p = dispPara(p, luts) if nargin<2, luts = []; end p.show = true; % img on if isfield(p, 'map') p.lut = 30; % numel(hs.lutStr) elseif any(p.nii.hdr.datatype == [32 1792]) % complex p.lut = 26; % phase p.lb = str2double(sprintf('%.2g', p.ub/2)); elseif any(p.nii.hdr.intent_code == [1002 3007]) % Label p.lut = 24; % prism elseif p.nii.hdr.intent_code > 0 % some stats if p.lb < 0 p.lut = 10; % two-sided p.lb = str2double(sprintf('%.2g', p.ub/2)); else a = setdiff(8:9, luts); % red-yellow & blue-green if isempty(a), a = 8; end % red-yellow p.lut = a(1); end elseif isempty(luts) p.lut = 1; % gray else a = setdiff(2:7, luts); % use smallest unused mono-color lut if isempty(a), a = 2; end % red p.lut = a(1); end p.lb_step = stepSize(p.lb); p.ub_step = stepSize(p.ub); p.alpha = 1; % opaque p.smooth = false; p.interp = 1; % nearest p.volume = 1; % first volume %% estimate StepSize for java spinner function d = stepSize(val) d = abs(val/10); % d = round(d, 1, 'significant'); d = str2double(sprintf('%.1g', d)); d = max(d, 0.01); if d>4, d = round(d/2)*2; end %% Return nii struct from nii struct, nii fname or other convertible files function nii = get_nii(fname) if isstruct(fname), nii = fname; return; elseif iscellstr(fname), nam = fname{1}; else, nam = fname; end try nii = nii_tool('load', strtrim(nam)); catch me try, nii = dicm2nii(fname, pwd, 'no_save'); catch, rethrow(me); end end %% Get figure/plot position from FoV for layout % siz is in pixels, while pos is normalized. function [siz, axPos, figPos] = plot_pos(mm, layout) if layout==1 % 1x3 siz = [sum(mm([2 1 1]))+mm(1)/4 max(mm(2:3))]; % image area width/height y0 = mm(2) / siz(1); % normalized width of sag images x0 = mm(1) / siz(1); % normalized width of cor/tra image z0 = mm(3) / siz(2); % normalized height of sag/cor images y1 = mm(2) / siz(2); % normalized height of tra image if y1>z0, y3 = 0; y12 = (y1-z0)/2; else, y3 = (z0-y1)/2; y12 = 0; end axPos = [0 y12 y0 z0; y0 y12 x0 z0; y0+x0 y3 x0 y1; y0+x0*2 0 mm(1)/4/siz(1) min(z0,y1)]; elseif layout==2 || layout==3 % 2x2 siz = [sum(mm(1:2)) sum(mm(2:3))]; % image area width/height x0 = mm(1) / siz(1); % normalized width of cor/tra images y0 = mm(2) / siz(2); % normalized height of tra image z0 = mm(3) / siz(2); % normalized height of sag/cor images if layout == 2 % 2x2 sag at (1,2) axPos = [x0 y0 1-x0 z0; 0 y0 x0 z0; 0 0 x0 y0; x0 0 1-x0 y0]; else % ==3: 2x2 sag at (1,2) axPos = [0 y0 1-x0 z0; 1-x0 y0 x0 z0; 1-x0 0 x0 y0; 0 0 1-x0 y0]; end else error('Unknown layout parameter'); end siz = siz / max(siz) * 800; res = screen_pixels(1); % use 1st screen maxH = res(2) - 160; maxW = res(1) - 100; if siz(1)>maxW, siz = siz / siz(1) * maxW; end if siz(2)>maxH, siz = siz / siz(2) * maxH; end figPos = round((res-siz)/2); if figPos(1)+siz(1) > res(1), figPos(1) = res(1)-siz(1)-10; end if figPos(2)+siz(2) > res(2)-130, figPos(2) = min(figPos(2), 50); end %% Return nii struct from cii and gii function nii = cii2nii(nii) persistent gii; % Anatomical surface if nargin<1, nii = gii; return; end ind = find([nii.ext.ecode]==32, 1); xml = nii.ext(ind).edata_decoded; expr = '(?<=((SurfaceNumberOfVertices)|(SurfaceNumberOfNodes))=").*?(?=")'; nVer = str2double(regexp(xml, expr, 'match', 'once')); if isempty(nVer), error('SurfaceNumberOfVertices not found'); end if isempty(gii), gii = get_surfaces(nVer, 'Anatomical'); end if isempty(gii) || numel(gii.Vertices) ~=2, error('Not valid GIfTI'); end if nVer ~= size(gii.Vertices{1},1), error('GIfTI and CIfTI don''t match'); end if gii_attr(xml, 'CIFTI Version', 1) == 1 dim = size(nii.img); nii.img = reshape(nii.img, dim([1:4 6 5])); end dim = gii_attr(xml, 'VolumeDimensions', 1); if isempty(dim), dim = [91 109 91]; end % HCP 2x2x2 mm TR = gii_attr(xml, 'SeriesStep', 1); if ~isempty(TR), nii.hdr.pixdim(5) = TR; end mat = gii_element(xml, 'TransformationMatrixVoxelIndicesIJKtoXYZ', 1); if isempty(mat) % some cii miss 'mat' and 'dim' mat = [-2 0 0 90; 0 2 0 -126; 0 0 2 -72; 0 0 0 1]; % best guess from HCP else pow = gii_attr(xml, 'MeterExponent', 1); mat(1:3,:) = mat(1:3,:) / 10^(3+pow); end nii.hdr.sform_code = gii.DataSpace; nii.hdr.srow_x = mat(1,:); nii.hdr.srow_y = mat(2,:); nii.hdr.srow_z = mat(3,:); nii.hdr.pixdim(2:4) = sqrt(sum(mat(1:3,1:3).^2)); nVol = size(nii.img, 5); imgG = permute(nii.img, [6 5 1:4]); nii.img = zeros([prod(dim) nVol], class(imgG)); iMdl = regexp(xml, '<BrainModel[\s>]'); iMdl(end+1) = numel(xml); for j = 1:numel(iMdl)-1 c = xml(iMdl(j):iMdl(j+1)); offset = gii_attr(c, 'IndexOffset', 1); typ = gii_attr(c, 'ModelType'); if strcmp(typ, 'CIFTI_MODEL_TYPE_SURFACE') a = gii_attr(c, 'BrainStructure'); ig = find(strcmp(a, {'CIFTI_STRUCTURE_CORTEX_LEFT' 'CIFTI_STRUCTURE_CORTEX_RIGHT'})); if isempty(ig), warning('Unknown BrainStructure: %s', a); continue; end ind = gii_element(c, 'VertexIndices', 1) + 1; if isempty(ind), ind = 1:gii_attr(c, 'IndexCount', 1); end nii.cii{ig} = zeros(nVer, nVol, 'single'); nii.cii{ig}(ind,:) = imgG((1:numel(ind))+offset, :); elseif strcmp(typ, 'CIFTI_MODEL_TYPE_VOXELS') a = gii_element(c, 'VoxelIndicesIJK', 1) + 1; a = sub2ind(dim, a(:,1), a(:,2), a(:,3)); nii.img(a, :) = imgG((1:numel(a))+offset, :); end end for ig = 1:2 % map surface back to volume v = gii.Vertices{ig}'; v(4,:) = 1; v = round(mat \ v) + 1; % ijk 1-based ind = sub2ind(dim, v(1,:), v(2,:), v(3,:)); nii.img(ind, :) = nii.cii{ig}; end nii.img = reshape(nii.img, [dim nVol]); nii = nii_tool('update', nii); expr = '<Label\s+Key="(.*?)"\s+Red="(.*?)"\s+Green="(.*?)"\s+Blue="(.*?)".*?>(.*?)</Label>'; ind = regexp(xml, '<NamedMap'); ind(end+1) = numel(xml); for k = 1:numel(ind)-1 nii.NamedMap{k}.MapName = gii_element(xml(ind(k):ind(k+1)), 'MapName'); tok = regexp(xml(ind(k):ind(k+1)), expr, 'tokens'); if numel(tok)<2, continue; end tok = reshape([tok{:}], 5, [])'; % Key R G B nam a = str2double(tok(:, 1:4)); nii.NamedMap{k}.map(a(:,1)+1, :) = a(:,2:4); if a(1,1) == 0 % key="0" nii.NamedMap{k}.labels(a(2:end, 1)) = tok(2:end, 5); % drop Key="0" else nii.NamedMap{k}.map = [0 0 0; nii.NamedMap{k}.map]; nii.NamedMap{k}.labels(a(:, 1)) = tok(:, 5); end end %% Return gii for both hemesperes function gii = get_surfaces(nVer, surfType) persistent pth; if nargin>1 && strcmpi(surfType, 'Anatomical') && nVer == 32492 % HCP 2mm surface fname = fullfile(fileparts(mfilename('fullpath')), 'example_data.mat'); a = load(fname, 'gii'); gii = a.gii; return; end if nargin>1, surfType = [surfType ' ']; else, surfType = ''; end prompt = ['Select ' surfType 'GIfTI surface files for both hemispheres']; if isempty(pth), pth = pwd; end [nam, pth] = uigetfile([pth '/*.surf.gii'], prompt, 'MultiSelect', 'on'); if isnumeric(nam), gii = []; return; end nam = cellstr(strcat([pth '/'], nam)); for i = 1:numel(nam) a = read_gii(nam{i}); if ~isempty(surfType) && ~strcmpi(surfType, a.GeometryType) error('Surface is not of required type: %s', surfType); end gii.DataSpace = a.DataSpace; if all(a.Vertices(:,3)==0), a.Vertices = a.Vertices(:,[3 1 2]); end % flat if strcmp(a.AnatomicalStructurePrimary, 'CortexLeft') gii.Vertices{1} = a.Vertices; gii.Faces{1} = a.Faces; elseif strcmp(a.AnatomicalStructurePrimary, 'CortexRight') gii.Vertices{2} = a.Vertices; gii.Faces{2} = a.Faces; end end %% Return gii struct with DataSpace, Vertices and Faces. function gii = read_gii(fname) xml = fileread(fname); % text file basically for i = regexp(xml, '<DataArray[\s>]') % often 2 of them c = regexp(xml(i:end), '.*?</DataArray>', 'match', 'once'); [Data, i0] = gii_element(c, 'Data'); % suppose '<Data' is last element c = regexprep(c(1:i0-1), '<!\[CDATA\[(.*?)\]\]>', '$1'); % rm CDADA thing a = gii_attr(c, 'DataType'); if strcmp(a, 'NIFTI_TYPE_FLOAT32'), dType = 'single'; elseif strcmp(a, 'NIFTI_TYPE_INT32'), dType = 'int32'; elseif strcmp(a, 'NIFTI_TYPE_UINT8'), dType = 'uint8'; else, error('Unknown GIfTI DataType: %s', a); end nDim = gii_attr(c, 'Dimensionality', 1); dim = ones(1, nDim); for j = 1:nDim, dim(j) = gii_attr(c, sprintf('Dim%g', j-1), 1); end Endian = gii_attr(c, 'Endian'); % LittleEndian or BigEndian Endian = lower(Endian(1)); Encoding = gii_attr(c, 'Encoding'); if any(strcmp(Encoding, {'Base64Binary' 'GZipBase64Binary'})) % Data = matlab.net.base64decode(Data); % since 2016b Data = javax.xml.bind.DatatypeConverter.parseBase64Binary(Data); Data = typecast(Data, 'uint8'); if strcmp(Encoding, 'GZipBase64Binary') % HCP uses this Data = nii_tool('LocalFunc', 'gunzip_mem', Data); end Data = typecast(Data, dType); if Endian == 'b', Data = swapbytes(Data); end elseif strcmp(Encoding, 'ASCII') % untested Data = str2num(Data); elseif strcmp(Encoding, 'ExternalFileBinary') % untested nam = gii_attr(c, 'ExternalFileName'); if isempty(fileparts(nam)), nam = fullfile(fileparts(fname), nam); end fid = fopen(nam, 'r', Endian); if fid==-1, error('ExternalFileName %s not exists'); end fseek(fid, gii_attr(c, 'ExternalFileOffset', 1), 'bof'); Data = fread(fid, prod(dim), ['*' dType]); fclose(fid); else, error('Unknown Encoding: %s', Encoding); end if nDim>1 if strcmp(gii_attr(c, 'ArrayIndexingOrder'), 'RowMajorOrder') Data = reshape(Data, dim(nDim:-1:1)); Data = permute(Data, nDim:-1:1); else Data = reshape(Data, dim); end end Intent = gii_attr(c, 'Intent'); if strcmp(Intent, 'NIFTI_INTENT_TRIANGLE') gii.Faces = Data; % 0-based continue; elseif ~strcmp(Intent, 'NIFTI_INTENT_POINTSET') % store Data only for now if ~isfield(gii, 'Data'), gii.Data = []; gii.Intent = []; end gii.Intent{end+1} = Intent; gii.Data{end+1} = Data; continue; end % now only for NIFTI_INTENT_POINTSET gii.AnatomicalStructurePrimary = gii_meta(c, 'AnatomicalStructurePrimary'); gii.AnatomicalStructureSecondary = gii_meta(c, 'AnatomicalStructureSecondary'); gii.GeometricType = gii_meta(c, 'GeometricType'); frms = {'NIFTI_XFORM_UNKNOWN' 'NIFTI_XFORM_SCANNER_ANAT' ... 'NIFTI_XFORM_ALIGNED_ANAT' 'NIFTI_XFORM_TALAIRACH' 'NIFTI_XFORM_MNI_152'}; gii.DataSpace = find(strcmp(gii_element(c, 'DataSpace'), frms)) - 1; gii.TransformedSpace = find(strcmp(gii_element(c, 'TransformedSpace'), frms)) - 1; gii.MatrixData = gii_element(c, 'MatrixData', 1); gii.Vertices = Data; end %% Return cii/gii attribute function val = gii_attr(ch, key, isnum) val = regexp(ch, ['(?<=' key '=").*?(?=")'], 'match', 'once'); if nargin>2 && isnum, val = str2num(val); end %#ok<*ST2NM> %% Return cii/gii element function [val, i0] = gii_element(ch, key, isnum) i0 = regexp(ch, ['<' key '[\s>]'], 'once'); val = regexp(ch(i0:end), ['(?<=<' key '.*?>).*?(?=</' key '>)'], 'match', 'once'); if nargin>2 && isnum, val = str2num(val); end %% Return MetaData value for cii/gii 'Name' function val = gii_meta(ch, key) val = regexp(ch, ['(?<=>' key '<.*?<Value>).*?(?=</Value>)'], 'match', 'once'); %% Open surface view or add cii to it function cii_view(hsN) fh = hsN.fig.UserData; if isempty(fh) || ~ishandle(fh) % create surface figure fh = figure(hsN.fig.Number+100); set(fh, 'NumberTitle', 'off', 'MenuBar', 'none', 'Renderer', 'opengl', ... 'Color', 'k', 'HandleVisibility', 'Callback', 'InvertHardcopy', 'off'); if isnumeric(fh), fh = handle(fh); end cMenu = uicontextmenu('Parent', fh); uimenu(cMenu, 'Label', 'Reset view', 'Callback', {@cii_view_cb 'reset'}); uimenu(cMenu, 'Label', 'Zoom in' , 'Callback', {@cii_view_cb 'zoomG'}); uimenu(cMenu, 'Label', 'Zoom out', 'Callback', {@cii_view_cb 'zoomG'}); uimenu(cMenu, 'Label', 'Change cortex color', ... 'Callback', {@cii_view_cb 'cortexColor'}, 'Separator', 'on'); uimenu(cMenu, 'Label', 'Change surface', 'Callback', {@cii_view_cb 'changeSurface'}); saveAs = findobj(hsN.fig, 'Type', 'uimenu', 'Label', 'Save figure as'); m = copyobj(saveAs, cMenu); set(m, 'Separator', 'on'); m = get(m, 'Children'); delete(m(1:3)); m = m(4:end); % pdf/eps etc too slow set(m, 'Callback', {@nii_viewer_cb 'save' hsN.fig}); if ispc || ismac uimenu(cMenu, 'Label', 'Copy figure', 'Callback', {@nii_viewer_cb 'copy' hsN.fig}); end set(fh, 'UIContextMenu', cMenu); r = 0.96; % width of two columns, remaining for colorbar pos = [0 1 r 1; 0 0 r 1; r 1 r 1; r 0 r 1] / 2; gii = cii2nii(); % get buffered Anatomical gii for ig = 1:2 v = gii.Vertices{ig}; lim = [min(v)' max(v)']; im = ones(size(v,1), 3, 'single') * 0.667; for i = ig*2+[-1 0] hs.ax(i) = axes('Parent', fh, 'Position', pos(i,:), 'CameraViewAngle', 6.8); axis vis3d; axis equal; axis off; set(hs.ax(i), 'XLim', lim(1,:), 'YLim', lim(2,:), 'ZLim', lim(3,:)); hs.patch(i) = patch('Parent', hs.ax(i), 'EdgeColor', 'none', ... 'Faces', gii.Faces{ig}+1, 'Vertices', v, ... 'FaceVertexCData', im, 'FaceColor', 'interp', 'FaceLighting', 'gouraud'); hs.light(i) = camlight('infinite'); material dull; end end set(hs.patch, 'ButtonDownFcn', {@cii_view_cb 'buttonDownPatch'}, 'UIContextMenu', cMenu); hs.ax(5) = axes('Position', [r 0.1 1-r 0.8], 'Visible', 'off', 'Parent', fh); try hs.colorbar = colorbar(hs.ax(5), 'PickableParts', 'none'); catch % for early matlab colorbar('peer', hs.ax(5), 'Units', 'Normalized', 'HitTest', 'off'); hs.colorbar = findobj(fh, 'Tag', 'Colorbar'); end set(hs.colorbar, 'Location', 'East', 'Visible', get(hsN.colorbar, 'Visible')); fh.Position(3:4) = [1/r diff(lim(3,:))/diff(lim(2,:))] * 600; srn = get(0, 'MonitorPositions'); dz = srn(1,4)- 60 - sum(fh.Position([2 4])); if dz<0, fh.Position(2) = fh.Position(2) + dz; end fh.ResizeFcn = {@cii_view_cb 'resizeG'}; fh.WindowButtonUpFcn = {@cii_view_cb 'buttonUp'}; fh.WindowButtonDownFcn = {@cii_view_cb 'buttonDown'}; fh.WindowButtonMotionFcn={@cii_view_cb 'buttonMotion'}; fh.WindowKeyPressFcn = {@cii_view_cb 'keyFcn'}; fh.UserData = struct('xy', [], 'xyz', [], 'hemi', [], 'deg', [-90 0], ... 'color', [1 1 1]*0.667); hsN.fig.UserData = fh; hs.gii = gii.Vertices; hs.fig = fh; hs.hsN = hsN; guidata(fh, hs); set_cii_view(hs, [-90 0]); try % drawnow then set manual, not exist for earlier Matlab set(hs.patch, 'VertexNormalsMode', 'auto'); drawnow; set(hs.patch, 'VertexNormalsMode', 'manual'); % faster update end end set_colorbar(hsN); cii_view_cb(fh, [], 'volume'); cii_view_cb(fh, [], 'background'); %% cii_view callbacks function cii_view_cb(h, ev, cmd) if isempty(h) || ~ishandle(h), return; end hs = guidata(h); switch cmd case 'buttonMotion' % Rotate gii and set light direction if isempty(hs.fig.UserData.xy), return; end % button not down d = get(hs.fig, 'CurrentPoint') - hs.fig.UserData.xy; % location change d = hs.fig.UserData.deg - d; % new azimuth and elevation set_cii_view(hs, d); hs.fig.UserData.xyz = []; % so not set cursor in nii_viewer case 'buttonDownPatch' % get button xyz if ~strcmpi(hs.fig.SelectionType, 'normal') % button 1 only hs.fig.UserData.xyz = []; return; end hs.fig.UserData.hemi = 1 + any(get(h, 'Parent') == hs.ax(3:4)); try, hs.fig.UserData.xyz = ev.IntersectionPoint; catch, hs.fig.UserData.xyz = get(gca, 'CurrentPoint'); % old Matlab end case 'buttonDown' % figure button down: prepare for rotation if ~strcmpi(hs.fig.SelectionType, 'normal'), return; end % not button 1 hs.fig.UserData.xy = get(hs.fig, 'CurrentPoint'); hs.fig.UserData.deg = get(hs.ax(1), 'View'); case 'buttonUp' % set cursor in nii_viewer hs.fig.UserData.xy = []; % disable buttonMotion xyz = hs.fig.UserData.xyz; if isempty(xyz), return; end ig = hs.fig.UserData.hemi; v = get(hs.patch(ig*2), 'Vertices'); % xyz = get(gca, 'CurrentPoint'); % test if size(xyz,1) > 1 % for Matlab without IntersectionPoint ln = [linspace(xyz(1,1), xyz(2,1), 200); linspace(xyz(1,2), xyz(2,2), 200); linspace(xyz(1,3), xyz(2,3), 200)]; % line between box edges ln = permute(ln, [3 1 2]); d = sum(bsxfun(@minus, v, ln) .^ 2, 2); % distance squared a = permute(min(d), [3 1 2]); % min along the line a = sum([a a([2:end end]) a([1 1:end-1])], 2) / 3; % smooth i = find((diff(a)>0) & (a(1:end-1)<8), 1); % find 1st valley i = max(1, i-1); d = d(:,:, i:i+3); % use a couple of samples along the line [~, ind] = min(d(:)); [iv, ~, ~] = ind2sub(size(d), ind); xyz = v(iv,:); % may find 2nd intersection for Anatomical surface % disp(xyz-hs.fig.UserData.xyz); if ~isequal(v, hs.gii{ig}), xyz = hs.gii{ig}(iv,:); end elseif ~isequal(v, hs.gii{ig}) v = bsxfun(@minus, v, xyz); [~, iv] = min(sum(v.^2, 2)); xyz = hs.gii{ig}(iv,:); end c = round(hs.hsN.bg.Ri * [xyz(:); 1]) + 1; for i = 1:3, hs.hsN.ijk(i).setValue(c(i)); end case 'reset' set_cii_view(hs, [-90 0]); case 'cortexColor' c = uisetcolor(hs.fig.UserData.color, 'Set cortical surface color'); if numel(c) ~= 3, return; end hs.fig.UserData.color = c; set_cdata_cii(hs); case 'changeSurface' gii = get_surfaces(size(hs.gii{1}, 1)); if isempty(gii), return; end if size(gii.Vertices{1},1) ~= size(hs.gii{1},1) errordlg('GIfTI has different number of vertices from CIfTI'); return; end ind = [isequal(gii.Vertices{1}, get(hs.patch(1), 'Vertices')) ... isequal(gii.Vertices{2}, get(hs.patch(3), 'Vertices'))]; if all(ind), return; end % no change for i = find(~ind) ip = i*2+(-1:0); set(hs.patch(ip), 'Vertices', gii.Vertices{i}, 'Faces', gii.Faces{i}+1); lim = [min(gii.Vertices{i})' max(gii.Vertices{i})']; set(hs.ax(ip), 'ZLim', lim(3,:), 'YLim', lim(2,:)); try, set(hs.ax(ip), 'XLim', lim(1,:)); end % avoid error for flat end set_cdata_cii(hs); try set(hs.patch, 'VertexNormalsMode', 'auto'); drawnow; set(hs.patch, 'VertexNormalsMode', 'manual'); end case 'resizeG' sz = getpixelposition(h); % asked position cb = hs.fig.ResizeFcn; hs.fig.ResizeFcn = []; drawnow; % avoid weird effect r = get(hs.ax(5), 'Position'); r = diff(get(hs.ax(1), 'ZLim')) / diff(get(hs.ax(1), 'YLim')) * r(1); if sz(3)/sz(4) < r, sz = sz(3) * [1 r]; else, sz = sz(4) * [1/r 1]; end hs.fig.Position(3:4) = sz; hs.fig.ResizeFcn = cb; case 'zoomG' va = get(hs.ax(1), 'CameraViewAngle'); if strcmp(get(h, 'Label'), 'Zoom in'), va = va * 0.9; else, va = va * 1.1; end set(hs.ax(1:4), 'CameraViewAngle', va); case 'keyFcn' if any(strcmp(ev.Key, ev.Modifier)), return; end % only modifier figure(hs.fig); % avoid focus to Command Window if ~isempty(intersect({'control' 'command'}, ev.Modifier)) if any(strcmp(ev.Key, {'add' 'equal'})) h = findobj(hs.fig, 'Type', 'uimenu', 'Label', 'Zoom in'); cii_view_cb(h, [], 'zoomG'); elseif any(strcmp(ev.Key, {'subtract' 'hyphen'})) h = findobj(hs.fig, 'Type', 'uimenu', 'Label', 'Zoom out'); cii_view_cb(h, [], 'zoomG'); elseif any(strcmp(ev.Key, {'a' 'r'})) figure(hs.hsN.fig); key = java.awt.event.KeyEvent.(['VK_' upper(ev.Key)]); java.awt.Robot().keyPress(key); java.awt.Robot().keyRelease(key); end elseif any(strcmp(ev.Key, {'space' 'comma' 'period'})) KeyPressFcn(hs.hsN.fig, ev); end % Rest cases not called by surface callback, but from nii_viewer_cb case {'lb' 'ub' 'lut' 'toggle' 'alpha' 'volume' 'stack' 'close' 'closeAll'} set_cdata_cii(hs); if strcmp(cmd, 'volume'), cii_view_cb(h, [], 'file'); end case 'file' % update MapName if available p = get_para(hs.hsN); try, mName = p.nii.NamedMap{p.volume}.MapName; catch, mName = ''; end frm = formcode2str(p.nii.hdr.sform_code); hs.fig.Name = ['cii_view - ' mName ' (' frm ')']; case 'background' clr = hs.hsN.frame.BackgroundColor; hs.fig.Color = clr; set(hs.colorbar, 'EdgeColor', 1-clr); case 'colorbar' % colorbar on/off set(hs.colorbar, 'Visible', get(hs.hsN.colorbar, 'Visible')); otherwise, return; % ignore other nii_viewer_cb cmd end %% set surface FaceVertexCData function set_cdata_cii(hs) imP{1} = ones(size(hs.gii{1},1), 1, 'single') * hs.fig.UserData.color; imP{2} = ones(size(hs.gii{2},1), 1, 'single') * hs.fig.UserData.color; for j = hs.hsN.files.getModel.size:-1:1 p = get_para(hs.hsN, j); if ~p.show || ~isfield(p.nii, 'cii'), continue; end for i = 1:2 % hemispheres [im, alfa] = lut2img(p.nii.cii{i}(:, p.volume), p, hs.hsN.lutStr{p.lut}); alfa = p.alpha * single(alfa>0); im = permute(im, [1 3 2]); % nVertices x 3 im = bsxfun(@times, im, alfa); imP{i} = bsxfun(@times, imP{i}, 1-alfa) + im; end end set(hs.patch(1:2), 'FaceVertexCData', imP{1}); set(hs.patch(3:4), 'FaceVertexCData', imP{2}); % tic; drawnow; toc %% set surface view function set_cii_view(hs, ae) ae = [ae; ae(1)+180 -ae(2); -ae(1) ae(2); -ae(1)-180 -ae(2)]; for i = 1:4 set(hs.ax(i), 'View', ae(i,:)); camlight(hs.light(i), 'headlight'); end %% this can be removed for matlab 2013b+ function y = flip(varargin) if exist('flip', 'builtin') y = builtin('flip', varargin{:}); else if nargin<2, varargin{2} = find(size(varargin{1})>1, 1); end y = flipdim(varargin{:}); %#ok end %% normalize columns function v = normc(M) v = bsxfun(@rdivide, M, sqrt(sum(M .* M))); % v = M ./ sqrt(sum(M .* M)); % since 2016b %% reorient nii to diagnal major function [nii, perm, flp] = nii_reorient(nii, leftHand) [R, frm] = nii_xform_mat(nii.hdr); dim = nii.hdr.dim(2:4); pixdim = nii.hdr.pixdim(2:4); [R, perm, flp] = reorient(R, dim, leftHand); if ~isequal(perm, 1:3) nii.hdr.dim(2:4) = dim(perm); nii.hdr.pixdim(2:4) = pixdim(perm); fps = bitand(nii.hdr.dim_info, [3 12 48]) ./ [1 4 16]; nii.hdr.dim_info = [1 4 16] * fps(perm)' + bitand(nii.hdr.dim_info, 192); nii.img = permute(nii.img, [perm 4:8]); end sc = nii.hdr.slice_code; if sc>0 && perm(3)~=3 && flp(perm==3) nii.hdr.slice_code = sc+mod(sc,2)*2-1; % 1<->2, 3<->4, 5<->6 end if ~isequal(perm, 1:3) || any(flp) if frm(1) == nii.hdr.sform_code % only update matching form nii.hdr.srow_x = R(1,:); nii.hdr.srow_y = R(2,:); nii.hdr.srow_z = R(3,:); end if frm(1) == nii.hdr.qform_code nii.hdr.qoffset_x = R(1,4); nii.hdr.qoffset_y = R(2,4); nii.hdr.qoffset_z = R(3,4); R0 = normc(R(1:3, 1:3)); dcm2quat = dicm2nii('', 'dcm2quat', 'func_handle'); [q, nii.hdr.pixdim(1)] = dcm2quat(R0); nii.hdr.quatern_b = q(2); nii.hdr.quatern_c = q(3); nii.hdr.quatern_d = q(4); end end for i = 1:3, if flp(i), nii.img = flip(nii.img, i); end; end %% flip slice dir for nii hdr % function hdr = flip_slices(hdr) % if hdr.sform_code<1 && hdr.sform_code<1, error('No valid form_code'); end % R = nii_xform_mat(hdr); % [~, iSL] = max(abs(R(1:3,1:3))); iSL = find(iSL==3); % if hdr.sform_code % hdr.srow_x(iSL) = -hdr.srow_x(iSL); % hdr.srow_y(iSL) = -hdr.srow_y(iSL); % hdr.srow_z(iSL) = -hdr.srow_z(iSL); % end % if hdr.qform_code<1, return; end % R = quat2R(hdr); % R(:, iSL) = -R(:,iSL); % R = normc(R(1:3, 1:3)); % dcm2quat = dicm2nii('', 'dcm2quat', 'func_handle'); % [q, hdr.pixdim(1)] = dcm2quat(R); % hdr.quatern_b = q(2); % hdr.quatern_c = q(3); % hdr.quatern_d = q(4); %%
github
cocoanlab/humanfmri_preproc_bids-master
nii_moco.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/nii_moco.m
10,422
utf_8
4b02f2199b90d3823468dba1a430723e
function varargout = nii_moco(nii, out, ref) % Perform motion correction to the input NIfTI data. % % Syntax: % p = NII_MOCO(filename_in); % return correction parameter only % NII_MOCO(filename_in, filename_out); % save corrected image file % [p, nii_out] = NII_MOCO(nii_in); % also return correct NIfTI without saving % [p, nii_out] = NII_MOCO(nii_in, fileName_out); % [...] = NII_MOCO(nii_in, fileName_out, ref); % % The mandatory first input is a NIfTI file name or a struct returned by % nii_tool('load'). % % If the second optional input, the result NIfTI file name, is provided, the % corrected data will be saved into the file (overwrite if exists). A .mat file % with the same name is also saved for the correction parameters (see first % output argument below for meaning of the parameters). If no reference volume % is provided (see 3rd input below), a NIfTI file, with name in format of % fileName_out_ref.nii, will also be saved. % % The third optional input is the reference to align to. It can be: % omitted or empty: NII_MOCO will choose a good reference volume in the data; % a single number: volume index to align to; % nii struct or file name: its first volume will be used as reference. % This argument is useful if one likes to align multiple runs to the same % referece img. For example align all 3 runs to run1: % p = NII_MOCO('run1.nii', 'run1_moco.nii'); % return ref info for run1 % NII_MOCO('run2.nii', 'run2_moco.nii', p.ref); % align run2 to ref vol of run1 % NII_MOCO('run3.nii', 'run3_moco.nii', p.ref); % align run3 % Then run1_moco_ref.nii can be used to align to structural image. % % The first optional output, if requested, returns the parameters of motion. It % is a struct with following fields: % ref: reference NIfTI name, or struct if no corrected img is saved. % R: rigid xform matrix to correct the motion to ref volume, 4 by 4 by nVol % mss: sum of squared diff between vol and ref img % trans: translation in mm, nVol by 3 % rot: rotation in radian, nVol by 3 % FD: frame-wise displacement in mm, nVol by 1 % % The second optional output is nii struct after motion correction. % % See also NII_STC, NII_VIEWER, NII_TOOL % Xiangrui Li ([email protected]) % 161127 Wrote it by peeking into spm_realign.m. % 170120 Use later ref vol: p.ref=p.ref+1 toSave = nargin>1 && ~isempty(out); if toSave && ~ischar(out) error('Second input must be nii file name to save data.'); end if ~toSave && nargout<1 [out, pth] = uiputfile('*.nii;*.nii.gz', 'Input file name to save result'); if ~ischar(out), varargout(1:nargout) = {}; return; end out = fullfile(pth, out); toSave = true; end if ischar(nii), nii = nii_tool('load', nii); end % file name if ~isstruct(nii) || ~all(isfield(nii, {'hdr' 'img'})) error('Input must be nii struct or nii file name.'); end d = nii.hdr.dim(2:7); d(d<1 | d>32768 | mod(d,1)) = 1; nVol = prod(d(4:end)); if nVol<2, error('Not multi-volume NIfTI: %s', nii.hdr.file_name); end d = d(1:3); Rm = nii_viewer('LocalFunc', 'nii_xform_mat', nii.hdr, 1); % moving img R sz = nii.hdr.pixdim(2:4); if all(abs(diff(sz)/sz(1)))<0.05 && sz(1)>2 && sz(1)<4 % 6~12mm sz = 3; % iso-voxel, 2~4mm res, simple fast smooth else sz = 9 ./ sz; % 9 mm seems good end % Deal with ref vol options if nargin<3 || isempty(ref) % pick a good vol as ref: similar to next vol n = min(10, nVol); mss = double(nii.img(:,:,:,1:n)); mss = diff(mss, 1, 4) .^ 2; mss = reshape(mss, [], n-1); mss = sum(mss); [~, p.ref] = min(mss); p.ref = p.ref + 1; % later one less affected by spin history? refV.hdr = nii.hdr; refV.img = nii.img(:,:,:,p.ref); elseif isnumeric(ref) && numel(ref)==1 % ref vol index in moving nii refV.hdr = nii.hdr; refV.img = nii.img(:,:,:,ref); p.ref = ref; else % ref NIfTI file or struct if isstruct(ref) && isfield(ref, 'ref'), ref = ref.ref; end % p input if ischar(ref) && exist(ref, 'file') % NIfTI file as ref refV = nii_tool('load', ref); elseif isstruct(ref) && isfield(ref, 'img') && isfield(ref, 'hdr') refV = ref; else error('Invalid reference input: %s', inputname(3)); end p.ref = ref; % simply pass the ref input end R0 = nii_viewer('LocalFunc', 'nii_xform_mat', refV.hdr, 1); % resample ref vol to isovoxel (often lower-res) res = 4; % use 4 mm grid for alignment d0 = size(refV.img); d0 = [d0 1]; d0 = d0(1:3); d0 = d0-1; ind = find(d0<4, 1); if ~isempty(ind), res = refV.hdr.pixdim(ind+1); end % untested dd = res ./ refV.hdr.pixdim(2:4); [i, j, k] = ndgrid(0:dd(1):d0(1)-0.5, 0:dd(2):d0(2)-0.5, 0:dd(3):d0(3)-0.5); I = [i(:) j(:) k(:)]'; clear i j k; a = rng('default'); I = I + rand(size(I))*0.5; rng(a); % used by spm sz1 = sz .* nii.hdr.pixdim(2:4) ./ refV.hdr.pixdim(2:4); V = smooth_mc(refV.img(:,:,:,1), sz1); F = griddedInterpolant({0:d0(1), 0:d0(2), 0:d0(3)}, V, 'linear', 'none'); V0 = F(I(1,:), I(2,:), I(3,:)); % ref: 1 by nVox I(4,:) = 1; % 0-based ijk: 4 by nVox I = R0 * I; % xyz of ref voxels % compute derivative to each motion parameter in ref vol dG = zeros(6, numel(V0)); dd = 1e-6; % delta of motion parameter, value won't affect dG much R0i = inv(R0); % speed up a little for i = 1:6 p6 = zeros(6,1); p6(i) = dd; % change only 1 of 6 J = R0i * rigid_mat(p6) * I; %#ok<*MINV> dG(i,:) = F(J(1,:), J(2,:), J(3,:)) - V0; % diff now end dG = dG / dd; % derivative % choose voxels with larger derivative for alignment: much faster a = sum(dG.^2); % 6 derivatives has similar range ind = a > std(a(~isnan(a)))/10; % arbituray threshold. Also exclude NaN dG = dG(:, ind); V0 = V0(ind); I = I(:, ind); F.GridVectors = {0:d(1)-1, 0:d(2)-1, 0:d(3)-1}; p.R = repmat(inv(Rm), [1 1 nVol]); % inv(R_rst) for i = 1:nVol % R = p.R(:,:,i); if i>1, R = p.R(:,:,i-1); else, R = p.R(:,:,i); end % start w/ previous vol F.Values = smooth_mc(nii.img(:,:,:,i), sz); mss0 = inf; for iter = 1:64 J = R * I; % R_rst*J -> R0*ijk V = F(J(1,:), J(2,:), J(3,:)); ind = ~isnan(V); % NaN means out of range V = V(ind); dV = V0(ind); % ref dV = dV - V * (sum(dV)/sum(V)); % diff now, sign affects p6 sign mss = dV*dV' / numel(dV); % mean(dV.^2) % % watch mss change over iterations % if iter==1 % figure(33); pause(1*(i>1)); % hPlot = plot(nan(1,64), 'o-', 'MarkerFaceColor', 'r'); % title(['Volume ' num2str(i)]); set(gca, 'xtick', 1:64); % xlabel('Iterations'); ylabel('mss'); % end % try hPlot.YData(iter) = mss; drawnow; end %#ok if mss > mss0, break; end % give up and use previous R p.R(:,:,i) = R; % accecpt only if improving p.mss(i) = mss; if 1-mss/mss0 < 1e-6, break; end % little effect, stop a = dG(:, ind); p6 = (a * a') \ (a * dV'); % dG(:,ind)'\dV' estimate p6 from current R R = R * rigid_mat(p6); % inv(inv(rigid_mat(p6)) * inv(R_rst)) mss0 = mss; end if iter==64 warning('Max iterations reached: %s, vol %g', nii.hdr.file_name, i); end end doXform = toSave || nargout>1; if doXform nii.img = single(nii.img); % single for result nii nii.hdr.sform_code = 2; % Aligned Anat nii.hdr.descrip = ['nii_moco.m: orig ' nii.hdr.file_name]; F.Method = 'spline'; % much slower than linear F.ExtrapolationMethod = 'nearest'; I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, 4, []); % ijk in 4 by nVox for original dim I = Rm * I; % xyz now end % Compute p.trans and p.rot, then p.FD, and xform nii if needed p.trans = zeros(nVol,3); p.rot = zeros(nVol,3); for i = 1:nVol if doXform % create xfrom 'ed nii J = p.R(:,:,i) * I; % R_rst \ (Rm * ijk) F.Values = nii.img(:,:,:,i); a = F(J(1,:), J(2,:), J(3,:)); nii.img(:,:,:,i) = reshape(a, d(1:3)); end R = Rm * p.R(:,:,i); % inv(R_rst / Rref) p.trans(i,:) = -R(1:3, 4); R = bsxfun(@rdivide, R, sqrt(sum(R.^2))); % to be safe p.rot(i,:) = -[atan2(R(2,3), R(3,3)) asin(R(1,3)) atan2(R(1,2), R(1,1))]; p.R(:,:,i) = inv(p.R(:,:,i)); end p.FD = diff([p.trans p.rot*50]); % 50 mm is radius of head p.FD = [0; sum(abs(p.FD), 2)]; % Power et al method % Update p.ref in case it is needed for other runs if isnumeric(p.ref) % need to store p.ref refV.hdr.descrip = sprintf('Ref: vol %g of %s', p.ref, nii.hdr.file_name); if toSave [pth, nam, ext] = fileparts(out); if strcmpi(ext, '.gz'), [~, nam, e0] = fileparts(nam); ext = [e0 ext]; end p.ref = fullfile(pth, [nam '_ref' ext]); nii_tool('save', refV, p.ref); else % store nii struct as ref in p: result large p refV.hdr.file_name = ''; % just avoid overwrite accident p.ref = nii_tool('update', refV); % override iRef for single vol nii end end if ischar(p.ref) % file name, make it full name in case of relative path [~, a] = fileattrib(p.ref); p.ref = a.Name; end if toSave % save corrected nii and p nii_tool('save', nii, out); [pth, nam, ext] = fileparts(out); if strcmpi(ext, '.gz'), [~, nam] = fileparts(nam); end nam = fullfile(pth, [nam '.mat']); save(nam, 'p'); % save a mat file with the same name as NIfTI end if nargout>0, varargout{1} = p; end if nargout>1, varargout{2} = nii_tool('update', nii); end %% Translation (mm) and rotation (deg) to 4x4 R. Order: ZYXT function R = rigid_mat(p6) ca = cosd(p6(4:6)); sa = sind(p6(4:6)); rx = [1 0 0; 0 ca(1) -sa(1); 0 sa(1) ca(1)]; % 3D rotation ry = [ca(2) 0 sa(2); 0 1 0; -sa(2) 0 ca(2)]; rz = [ca(3) -sa(3) 0; sa(3) ca(3) 0; 0 0 1]; R = rx * ry * rz; R = [R p6(1:3); 0 0 0 1]; %% Simple gaussian smooth for motion correction, sz in unit of voxels function out = smooth_mc(in, sz) out = double(in); if all(abs(diff(sz)/sz(1))<0.05) && abs(sz(1)-round(sz(1)))<0.05 ... && mod(round(sz(1)),2)==1 out = smooth3(out, 'gaussian', round(sz)); % sz odd integer return; % save time for special case end d = size(in); I = {1:d(1) 1:d(2) 1:d(3)}; n = sz/3; if numel(n)==1, n = n*[1 1 1]; end J = {1:n(1):d(1) 1:n(2):d(2) 1:n(3):d(3)}; intp = 'linear'; F = griddedInterpolant(I, out, intp); out = smooth3(F(J), 'gaussian'); % sz=3 F = griddedInterpolant(J, out, intp); out = F(I);
github
cocoanlab/humanfmri_preproc_bids-master
java_dnd.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/java_dnd.m
2,820
utf_8
b72dadc83df5d9f523b72cf084b3e056
function java_dnd(jObj, dropFcn) % Set Matlab dropFcn for java object, like JavaFrame or JTextField. % 170421 Xiangrui Li adapted from dndcontrol class by Maarten van der Seijs: % https://www.mathworks.com/matlabcentral/fileexchange/53511 % Required: MLDropTarget.class under the same folder if ~exist('MLDropTarget', 'class') pth = fileparts(mfilename('fullpath')); javaaddpath(pth); % dynamic for this session fid = fopen(fullfile(prefdir, 'javaclasspath.txt'), 'a+'); if fid>0 % static path for later sessions: work for 2013+? cln = onCleanup(@() fclose(fid)); fseek(fid, 0, 'bof'); classpth = fread(fid, inf, '*char')'; if isempty(strfind(classpth, pth)) %#ok<*STREMP> % avoid multiple write fseek(fid, 0, 'bof'); fprintf(fid, '%s\n', pth); end end end dropTarget = handle(javaObjectEDT('MLDropTarget'), 'CallbackProperties'); set(dropTarget, 'DragEnterCallback', @DragEnterCallback, ... 'DragExitCallback', @DragExitCallback, ... 'DropCallback', {@DropCallback, dropFcn}); jObj.setDropTarget(dropTarget); %% function DropCallback(jSource, jEvent, dropFcn) setComplete = onCleanup(@()jEvent.dropComplete(true)); % Following DropAction is for ~jEvent.isLocalTransfer, such as dropping file. % For LocalTransfer, Linux seems consistent with other OS. % DropAction: Neither ctrl nor shift Dn, PC/MAC 2, Linux 1 % All OS: ctrlDn 1, shiftDn 2, both Dn 1073741824 (2^30) if ispc || ismac evt.ControlDown = jEvent.getDropAction() ~= 2; else % fails to report CtrlDn if user releases shift between DragEnter and Drop evt.ControlDown = bitget(jEvent.getDropAction,31)>0; % ACTION_LINK 1<<30 java.awt.Robot().keyRelease(16); % shift up end % evt.Location = [jEvent.getLocation.x jEvent.getLocation.y]; % top-left [0 0] if jSource.getDropType() == 1 % String dropped evt.DropType = 'string'; evt.Data = char(jSource.getTransferData()); if strncmp(evt.Data, 'file://', 7) % files identified as string evt.DropType = 'file'; evt.Data = regexp(evt.Data, '(?<=file://).*?(?=\r?\n)', 'match')'; end elseif jSource.getDropType() == 2 % file(s) dropped evt.DropType = 'file'; evt.Data = cell(jSource.getTransferData()); else, return; % No success end if iscell(dropFcn), feval(dropFcn{1}, jSource, evt, dropFcn{2:end}); else, feval(dropFcn, jSource, evt); end %% function DragEnterCallback(~, jEvent) try jEvent.acceptDrag(1); catch, return; end % ACTION_COPY if ~ispc && ~ismac, java.awt.Robot().keyPress(16); end % shift down %% function DragExitCallback(~, jEvent) if ~ispc && ~ismac, java.awt.Robot().keyRelease(16); end % shift up try jEvent.rejectDrag(1); catch, end % ACTION_COPY %%
github
cocoanlab/humanfmri_preproc_bids-master
nii_xform.m
.m
humanfmri_preproc_bids-master/external/dicm2nii/nii_xform.m
9,448
utf_8
f1220c195ff9723fdad045a1477dbf77
function varargout = nii_xform(src, target, rst, intrp, missVal) % Transform a NIfTI into different resolution, or into a template space. % % NII_XFORM('source.nii', 'template.nii', 'result.nii') % NII_XFORM(nii, 'template.nii', 'result.nii') % NII_XFORM('source.nii', [1 1 1], 'result.nii') % nii = NII_XFORM('source.nii', 'template.nii'); % NII_XFORM('source.nii', {'template.nii' 'source2template.mat'}, 'result.nii') % NII_XFORM('source.nii', {'template.nii' 'source2template_warp.nii.gz'}, 'result.nii') % NII_XFORM('source.nii', 'template.nii', 'result.nii', 'nearest', 0) % % NII_XFORM transforms the source NIfTI, so it has the requested resolution or % has the same dimension and resolution as the template NIfTI. % % Input (first two mandatory): % 1. source file (nii, hdr/img or gz versions) or nii struct to be transformed. % 2. The second input determines how to transform the source file: % (1) If it is numeric and length is 1 or 3, [2 2 2] for example, it will be % treated as requested resolution in millimeter. The result will be in % the same coordinate system as the source file. % (2) If it is a nii file name, a nii struct, or nii hdr struct, it will be % used as the template. The result will have the same dimension and % resolution as the template. The source file and the template must have % at least one common coordinate system, otherwise the transformation % doesn't make sense, and it will err out. With different coordinate % systems, a transformation to align the two dataset is needed, which is % the next case. % (3) If the input is a cell containing two file names, it will be % interpreted as a template nii file and a transformation. The % transformation can be a FSL-style .mat file with 4x4 transformation % matrix which aligns the source data to the template, in format of: % 0.9983 -0.0432 -0.0385 -17.75 % 0.0476 0.9914 0.1216 -14.84 % 0.0329 -0.1232 0.9918 111.12 % 0 0 0 1 % The transformation can also be a FSL-style warp nii file incorporating % both linear and no-linear transformation from the source to template. % 3. result file name. If not provided or empty, nii struct will be returned. % This allows to use the returned nii in script without saving to a file. % 4. interpolation method, default 'linear'. It can also be one of 'nearest', % 'cubic' and 'spline'. % 5. value for missing data, default NaN. This is the value assigned to the % location in template where no data is available in the source file. % % Output (optional): nii struct. % NII_XFORM will return the struct if the output is requested or result file % name is not provided. % % Please note that, once the transformation is applied to functional data, it is % normally invalid to perform slice timing correction. Also the data type is % changed to single unless the interpolation is 'nearest'. % % See also NII_VIEWER, NII_TOOL, DICM2NII % By Xiangrui Li ([email protected]) % History(yymmdd): % 151024 Write it. % 160531 Remove narginchk so work for early matlab. % 160907 allow src to be nii struct. % 160923 allow target to be nii struct or hdr; Take care of logical src img. % 161002 target can also be {tempFile warpFile}. % 170119 resolution can be singular. % 180219 treat formcode 3 and 4 the same. if nargin<2 || nargin>5, help('nii_xform'); error('Wrong number of input.'); end if nargin<3, rst = []; end if nargin<4 || isempty(intrp), intrp = 'linear'; end if nargin<5 || isempty(missVal), missVal = nan; else, missVal = missVal(1); end intrp = lower(intrp); quat2R = nii_viewer('func_handle', 'quat2R'); if isstruct(src), nii = src; else, nii = nii_tool('load', src); end if isstruct(target) || ischar(target) || (iscell(target) && numel(target)==1) hdr = get_hdr(target); elseif iscell(target) hdr = get_hdr(target{1}); if hdr.sform_code>0, R0 = [hdr.srow_x; hdr.srow_y; hdr.srow_z; 0 0 0 1]; elseif hdr.qform_code>0, R0 = quat2R(hdr); end [~, ~, ext] = fileparts(target{2}); if strcmpi(ext, '.mat') % template and xform file names R = load(target{2}, '-ascii'); if ~isequal(size(R), [4 4]), error('Invalid transformation file.'); end else % template and warp file names warp_img_fsl = nii_tool('img', target{2}); if ~isequal(size(warp_img_fsl), [hdr.dim(2:4) 3]) error('warp file and template file img size don''t match.'); end R = eye(4); end if nii.hdr.sform_code>0 R1 = [nii.hdr.srow_x; nii.hdr.srow_y; nii.hdr.srow_z; 0 0 0 1]; elseif nii.hdr.qform_code>0 R1 = quat2R(nii.hdr); end % I thought it is something like R = R0 \ R * R1; but it is way off. It % seems the transform info in src nii is irrevelant, but direction must be % used: Left/right-handed storage of both src and target img won't affect % FSL alignment R. Alignment R may not be diag-major, and can be negative % for major axes (e.g. cor/sag slices). % Following works for tested FSL .mat and warp.nii files: Any better way? % R0: target; R1: source; R: xform; result is also R R = R0 / diag([hdr.pixdim(2:4) 1]) * R * diag([nii.hdr.pixdim(2:4) 1]); [~, i1] = max(abs(R1(1:3,1:3))); [~, i0] = max(abs(R(1:3,1:3))); flp = sign(R(i0+[0 4 8])) ~= sign(R1(i1+[0 4 8])); if any(flp) rotM = diag([1-flp*2 1]); rotM(1:3,4) = (nii.hdr.dim(2:4)-1) .* flp; R = R / rotM; end elseif isnumeric(target) && any(numel(target)==[1 3]) % new resolution in mm if numel(target)==1, target = target * [1 1 1]; end hdr = nii.hdr; ratio = target(:)' ./ hdr.pixdim(2:4); hdr.pixdim(2:4) = target; hdr.dim(2:4) = round(hdr.dim(2:4) ./ ratio); if hdr.sform_code>0 hdr.srow_x(1:3) = hdr.srow_x(1:3) .* ratio; hdr.srow_y(1:3) = hdr.srow_y(1:3) .* ratio; hdr.srow_z(1:3) = hdr.srow_z(1:3) .* ratio; end else error('Invalid template or resolution input.'); end if ~iscell(target) s = hdr.sform_code; q = hdr.sform_code; sq = [nii.hdr.sform_code nii.hdr.qform_code]; if s>0 && (any(s == sq) || (s>2 && (any(sq==3) || any(sq==4)))) R0 = [hdr.srow_x; hdr.srow_y; hdr.srow_z; 0 0 0 1]; frm = s; elseif any(q == sq) || (q>2 && (any(sq==3) || any(sq==4))) R0 = quat2R(hdr); frm = q; else error('No matching transformation between source and template.'); end if sq(1) == frm || (sq(1)>2 && frm>2) || sq(2)<1 R = [nii.hdr.srow_x; nii.hdr.srow_y; nii.hdr.srow_z; 0 0 0 1]; else R = quat2R(nii.hdr); end end d = single(hdr.dim(2:4)); I = ones([d 4], 'single'); [I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)] = ndgrid(0:d(1)-1, 0:d(2)-1, 0:d(3)-1); I = permute(I, [4 1 2 3]); I = reshape(I, [4 prod(d)]); % template ijk if exist('warp_img_fsl', 'var') warp_img_fsl = reshape(warp_img_fsl, [prod(d) 3])'; if det(R0(1:3,1:3))<0, warp_img_fsl(1,:) = -warp_img_fsl(1,:); end % correct? warp_img_fsl(4,:) = 0; I = R \ (R0 * I + warp_img_fsl) + 1; % ijk+1 (fraction) in source else I = R \ (R0 * I) + 1; % ijk+1 (fraction) in source end I = reshape(I(1:3,:)', [d 3]); V = nii.img; isbin = islogical(V); if any(size(V)<2) && ~strcmpi(intrp, 'nearest') intrp = 'nearest'; warning('nii_xform:NotEnoughPoints', 'Not enough data. Switch to "nearest".'); end d48 = size(V); % in case of RGB d48(numel(d48)+1:4) = 1; d48(1:3) = []; if isbin intrp = 'nearest'; missVal = false; nii.img = zeros([d d48], 'uint8'); elseif isinteger(V) nii.img = zeros([d d48], 'single'); else nii.img = zeros([d d48], class(V)); end if ~isfloat(V), V = single(V); end if strcmpi(intrp, 'nearest'), I = round(I); end % needed for edge voxels if size(V,1)<2, V(2,:,:) = missVal; end if size(V,2)<2, V(:,2,:) = missVal; end if size(V,3)<2, V(:,:,2) = missVal; end try F = griddedInterpolant(V(:,:,:,1), intrp, 'none'); % since 2014? for i = 1:prod(d48) F.Values = V(:,:,:,i); nii.img(:,:,:,i) = F(I(:,:,:,1), I(:,:,:,2), I(:,:,:,3)); end if ~isnan(missVal), nii.img(isnan(nii.img)) = missVal; end catch for i = 1:prod(d48) nii.img(:,:,:,i) = interp3(V(:,:,:,i), I(:,:,:,2), I(:,:,:,1), I(:,:,:,3), intrp, missVal); end end if isbin, nii.img = logical(nii.img); end % copy xform info from template to rst nii nii.hdr.pixdim(1:4) = hdr.pixdim(1:4); flds = {'qform_code' 'sform_code' 'srow_x' 'srow_y' 'srow_z' ... 'quatern_b' 'quatern_c' 'quatern_d' 'qoffset_x' 'qoffset_y' 'qoffset_z'}; for i = 1:numel(flds), nii.hdr.(flds{i}) = hdr.(flds{i}); end if ~isempty(rst), nii_tool('save', nii, rst); end if nargout || isempty(rst), varargout{1} = nii_tool('update', nii); end %% function hdr = get_hdr(in) if iscell(in), in = in{1}; end if isstruct(in) if isfield(in, 'hdr') % nii input hdr = in.hdr; elseif isfield(in, 'sform_code') % hdr input hdr = in; else error('Invalid input: %s', inputname(1)); end else % template file name hdr = nii_tool('hdr', in); end
github
TREE-Ind/speaker-rec-skill-test-master
estimate_x_and_u.m
.m
speaker-rec-skill-test-master/jfa/estimate_x_and_u.m
5,477
utf_8
1f30c33b7f0eecda4b7fa1266a4b23ba
function [x u]=estimate_x_and_u(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % ESTIMATE_X_AND_U estimates channel factors and eigenchannels for % joint factor analysis model % % % [x u]=estimate_x_and_u(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % provides new estimates of channel factors, x, and 'eigenchannels', u, % given zeroth and first order sufficient statistics (N. F), current % hyper-parameters of joint factor analysis model (m, E, d, u, v) and % current estimates of speaker and channel factors (x, y, z) % % F - matrix of first order statistics (not centered). The rows correspond % to training segments. Number of columns is given by the supervector % dimensionality. The first n collums correspond to the n dimensions % of the first Gaussian component, the second n collums to second % component, and so on. % N - matrix of zero order statistics (occupation counts of Gaussian % components). The rows correspond to training segments. The collums % correspond to Gaussian components. % S - NOT USED by this function; reserved for second order statistics % m - speaker and channel independent mean supervector (e.g. concatenated % UBM mean vectors) % E - speaker and channel independent variance supervector (e.g. concatenated % UBM variance vectors) % d - Row vector that is the diagonal from the diagonal matrix describing the % remaining speaker variability (not described by eigenvoices). Number of % columns is given by the supervector dimensionality. % v - The rows of matrix v are 'eigenvoices'. (The number of rows must be the % same as the number of columns of matrix y). Number of columns is given % by the supervector dimensionality. % u - The rows of matrix u are 'eigenchannels'. (The number of rows must be % the same as the number of columns of matrix x) Number of columns is % given by the supervector dimensionality. % y - matrix of speaker factors corresponding to eigenvoices. The rows % correspond to speakers (values in vector spk_ids are the indices of the % rows, therfore the number of the rows must be (at least) the highest % value in spk_ids). The columns correspond to eigenvoices (The number % of columns must the same as the number of rows of matrix v). % z - matrix of speaker factors corresponding to matrix d. The rows % correspond to speakers (values in vector spk_ids are the indices of the % rows, therfore the number of the rows must be (at least) the highest % value in spk_ids). Number of columns is given by the supervector % dimensionality. % x - NOT USED by this function; used by other JFA function as % matrix of channel factors. The rows correspond to training % segments. The columns correspond to eigenchannels (The number of columns % must be the same as the number of rows of matrix u) % spk_ids - column vector with rows corresponding to training segments and % integer values identifying a speaker. Rows having same values identifies % segments spoken by same speakers. The values are indices of rows in % y and z matrices containing corresponding speaker factors. % % % x=estimate_x_and_u(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % only the channels factors are estimated % % % [x A C]=estimate_x_and_u(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % estimates channels factors and acumulators A and C. A is cell array of MxM % matrices, where M is number of eigenchannels. Number of elements in the % cell array is given by number of Gaussian components. C is of the same size % at the matrix u. % % % u=estimate_x_and_u(A, C) % % updates eigenchannels from accumulators A and C. Using F and N statistics % corresponding to subsets of training segments, multiple sets of accumulators % can be collected (possibly in parallel) and summed before the update. Note % that segments of one speaker must not be split into different subsets. if nargin == 2 && nargout == 1 % update u from acumulators A and C x=update_u(F, N); return end % this will just create a index map, so that we can copy the counts n-times (n=dimensionality) dim = size(F,2)/size(N,2); index_map = reshape(repmat(1:size(N,2), dim,1),size(F,2),1); x = zeros(size(spk_ids,1), size(u,1)); if nargout > 1 for c=1:size(N,2) A{c} = zeros(size(u,1)); end C = zeros(size(u,1), size(F,2)); end for c=1:size(N,2) c_elements = ((c-1)*dim+1):(c*dim); uEuT{c} = u(:,c_elements) .* repmat(1./E(c_elements), size(u,1), 1) * u(:,c_elements)'; end for ii = unique(spk_ids)' speakers_sessions = find(spk_ids == ii); spk_shift = m + y(ii,:) * v + z(ii,:) .* d; for jj = speakers_sessions' Nh = N(jj, index_map); Fh = F(jj,:) - Nh .* spk_shift; % L = eye(size(u,1)) + u * diag(Nh./E) * u'; L = eye(size(u,1)); for c=1:size(N,2) L = L + uEuT{c} * N(jj,c); end invL = inv(L); x(jj,:) = ((Fh./E) * u') * invL; if nargout > 1 invL = invL + x(jj,:)' * x(jj,:); for c=1:size(N,2) A{c} = A{c} + invL * N(jj,c); end C = C + x(jj,:)' * Fh; end end end if nargout == 3 % output new estimates of x and accumulators A and C u = A; elseif nargout == 2 % output new estimates of x and u u=update_u(A, C); end %------------------------------------------------- function u=update_u(A, C) u = zeros(size(C)); dim = size(C,2)/length(A); for c=1:length(A) c_elements = ((c-1)*dim+1):(c*dim); u(:,c_elements) = inv(A{c}) * C(:,c_elements); end
github
TREE-Ind/speaker-rec-skill-test-master
estimate_y_and_v.m
.m
speaker-rec-skill-test-master/jfa/estimate_y_and_v.m
5,502
utf_8
1e4d706f8060302120ad648461d7a943
function [y v C]=estimate_y_and_v(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % ESTIMATE_Y_AND_V estimates speaker factors and eigenvoices for % joint factor analysis model % % % [y v]=estimate_y_and_v(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % provides new estimates of channel factors, x, and 'eigenchannels', u, % given zeroth and first order sufficient statistics (N. F), current % hyper-parameters of joint factor analysis model (m, E, d, u, v) and % current estimates of speaker and channel factors (x, y, z) % % F - matrix of first order statistics (not centered). The rows correspond % to training segments. Number of columns is given by the supervector % dimensionality. The first n collums correspond to the n dimensions % of the first Gaussian component, the second n collums to second % component, and so on. % N - matrix of zero order statistics (occupation counts of Gaussian % components). The rows correspond to training segments. The collums % correspond to Gaussian components. % S - NOT USED by this function; reserved for second order statistics % m - speaker and channel independent mean supervector (e.g. concatenated % UBM mean vectors) % E - speaker and channel independent variance supervector (e.g. concatenated % UBM variance vectors) % d - Row vector that is the diagonal from the diagonal matrix describing the % remaining speaker variability (not described by eigenvoices). Number of % columns is given by the supervector dimensionality. % v - The rows of matrix v are 'eigenvoices'. (The number of rows must be the % same as the number of columns of matrix y). Number of columns is given % by the supervector dimensionality. % u - The rows of matrix u are 'eigenchannels'. (The number of rows must be % the same as the number of columns of matrix x) Number of columns is % given by the supervector dimensionality. % y - NOT USED by this function; used by other JFA function as % matrix of speaker factors corresponding to eigenvoices. The rows % correspond to speakers (values in vector spk_ids are the indices of the % rows, therfore the number of the rows must be (at least) the highest % value in spk_ids). The columns correspond to eigenvoices (The number % of columns must the same as the number of rows of matrix v). % z - matrix of speaker factors corresponding to matrix d. The rows % correspond to speakers (values in vector spk_ids are the indices of the % rows, therfore the number of the rows must be (at least) the highest % value in spk_ids). Number of columns is given by the supervector % dimensionality. % x - matrix of channel factors. The rows correspond to training % segments. The columns correspond to eigenchannels (The number of columns % must be the same as the number of rows of matrix u) % spk_ids - column vector with rows corresponding to training segments and % integer values identifying a speaker. Rows having same values identifies % segments spoken by same speakers. The values are indices of rows in % y and z matrices containing corresponding speaker factors. % % % y=estimate_y_and_v(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % only the speaker factors are estimated % % % [y A C]=estimate_y_and_v(F, N, S, m, E, d, v, u, z, y, x, spk_ids) % % estimates speaker factors and acumulators A and C. A is cell array of MxM % matrices, where M is number of eigenvoices. Number of elements in the % cell array is given by number of Gaussian components. C is of the same size % at the matrix v. % % % v=estimate_y_and_v(A, C) % % updates eigenvoices from accumulators A and C. Using F and N statistics % corresponding to subsets of training segments, multiple sets of accumulators % can be collected (possibly in parallel) and summed before the update. Note % that segments of one speaker must not be split into different subsets. if nargin == 2 && nargout == 1 % update v from acumulators A and C y=update_v(F, N); return end % this will just create a index map, so that we can copy the counts n-times (n=dimensionality) dim = size(F,2)/size(N,2); index_map = reshape(repmat(1:size(N,2), dim,1),size(F,2),1); y = zeros(max(spk_ids), size(v,1)); if nargout > 1 for c=1:size(N,2) A{c} = zeros(size(v,1)); end C = zeros(size(v,1), size(F,2)); end for c=1:size(N,2) c_elements = ((c-1)*dim+1):(c*dim); vEvT{c} = v(:,c_elements) .* repmat(1./E(c_elements), size(v, 1), 1) * v(:,c_elements)'; end for ii = unique(spk_ids)' speakers_sessions = find(spk_ids == ii); Fs = sum(F(speakers_sessions,:), 1); Nss = sum(N(speakers_sessions,:), 1); Ns = Nss(1,index_map); Fs = Fs - (m + z(ii,:) .* d) .* Ns; for jj = speakers_sessions' Fs = Fs - (x(jj,:) * u) .* N(jj, index_map); end % L = eye(size(v,1)) + v * diag(Ns./E) * v'; L = eye(size(v,1)); for c=1:size(N,2) L = L + vEvT{c} * Nss(c); end invL = inv(L); y(ii,:) = ((Fs ./ E) * v') * invL; if nargout > 1 invL = invL + y(ii,:)' * y(ii,:); for c=1:size(N,2) A{c} = A{c} + invL * Nss(c); end C = C + y(ii,:)' * Fs; end end if nargout == 3 % output new estimates of y and accumulators A and C v = A; elseif nargout == 2 % output new estimates of y and v v=update_v(A, C); end %------------------------------------------------- function C=update_v(A, C) dim = size(C,2)/length(A); for c=1:length(A) c_elements = ((c-1)*dim+1):(c*dim); C(:,c_elements) = inv(A{c}) * C(:,c_elements); end
github
nathanie/DataHack-2017-master
csv2kml.m
.m
DataHack-2017-master/visualiztion/csv2kml.m
3,175
utf_8
9c842c1e4597dfe89d1b5b200d7443bf
function csv2kml(mainDir,data2WorkOn,class2show,lines2show,nedOrigin,openFileWhenDone) %%%% % mainDir - Dir where train/test data is % data2WorkOn - Name of the data CSV file % class2show - Which class in CSV file to draw, or (-1) if using test set or lines2show parameter % lines2show - Which lines in CSV file to draw % nedOrigin - Geo coordinates where XYZ = 0 % openFileWhenDone - Open KML after it is ready (KML files have to be associated with Google Earth) %%%% if nargin == 0 mainDir = 'D:\DataHack2017\'; %data2WorkOn = 'test'; data2WorkOn = 'train'; class2show = -1; %for 'train' only lines2show = 1:300; %for 'test' (or 'train if class2show == -1) nedOrigin = [31.784491,35.214245,0]; openFileWhenDone = 1; end name = 'Rocket_Data_Science'; if class2show > 0 name = [name '_' num2str(class2show)]; end kmlStrHeader = ['<kml xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.opengis.net/kml/2.2"> \n' ... ' <Document> \n' ... ' <name>' name '</name> \n']; kmlStrFooter = ' </Document></kml>'; strUP = ''; strDN = ''; disp('Loading...'); csvSetTable = readtable([mainDir data2WorkOn '.csv']); csvSet = table2array(csvSetTable(:,1:211)); disp('Working...'); if strfind(data2WorkOn,'train') && class2show > 0 lines2show = find(csvSet(:,end) == class2show); end for lll = lines2show(:)' lla_str = ned2geodetic2String(csvSet,lll,nedOrigin); velVal = round((norm( csvSet(lll,6:8) )/1500) * 255 ); velColor = dec2hex(velVal,2); if csvSet(lll,8) > 0 clr_str = ['FF' velColor '0000']; strUP = addPlacemark(strUP,['line_' num2str(lll-1)],lla_str,clr_str); else clr_str = ['FF0000' velColor]; strDN = addPlacemark(strDN,['line_' num2str(lll-1)],lla_str,clr_str); end end finalStr = [kmlStrHeader '<Folder>\n <name>UP</name> \n' strUP ... '</Folder><Folder>\n <name>DOWN</name> \n' strDN '</Folder>' kmlStrFooter]; disp('Saving...'); fid = fopen([mainDir name '_MATLAB.kml'],'w'); fprintf(fid,finalStr); fclose(fid); disp('Done!'); if openFileWhenDone winopen( [mainDir name '_MATLAB.kml']); end end function str = addPlacemark(str,name,lla_str,clr_str) strTMP = [ ... ' <Placemark> \n' ... ' <name>' name '</name> \n' ... ' <Style> \n' ... ' <LineStyle> \n' ... ' <color>' clr_str '</color> \n' ... ' <width>4</width> \n' ... ' </LineStyle> \n' ... ' </Style> \n' ... ' <LineString> \n' ... ' <altitudeMode>absolute</altitudeMode> \n' ... ' <coordinates>' lla_str '</coordinates> \n' ... ' </LineString> \n' ... ' </Placemark> \n' ... ]; str = [str strTMP]; end function lla_str = ned2geodetic2String(csvSet,line,nedOrigin) lla_str = ''; for iii = 1:15 northCoor = csvSet(line,3+7*(iii-1)); eastCoor = csvSet(line,4+7*(iii-1)); downCoor = -csvSet(line,5+7*(iii-1)); if isnan(northCoor) continue end [lat,lon,h] = ned2geodetic(northCoor,eastCoor,downCoor,nedOrigin(1),nedOrigin(2),nedOrigin(3),referenceEllipsoid('GRS 80')); lla_str = [lla_str num2str([lon lat h],'%.10f,%.10f,%.10f') ' ']; end end
github
risetarnished/VehicleDetection-master
getBWratio.m
.m
VehicleDetection-master/Meng/getBWratio.m
1,609
utf_8
91fdec4a7183e0a15d6dc1b484eb2cc2
function features1 = getBWratio(img) % foregroundDetector = vision.ForegroundDetector('NumGaussians', 3, ... % 'NumTrainingFrames', 50); %foreground = step(foregroundDetector, img); foreground = rgb2gray(img); image=imresize(foreground, [256 256]); imwrite(image, 'temp.jpg'); blockCount = 1; xpixel = 1; ypixel = 1; blocksize = 16; yblockCount = 1; xblockCount = 1; features1 = zeros(1,256); while (blockCount <= blocksize*blocksize) whitepixel = 0; blackpixel = 0; originalypixel = ypixel; originalxpixel = xpixel; for i = ypixel:(blocksize*yblockCount) for j = xpixel:(blocksize*xblockCount) if( image(i,j) <= 128) blackpixel = blackpixel + 1; else whitepixel = whitepixel + 1; end end end if blackpixel == 0 blackpixel = 1; end if whitepixel == 0 whitepixel = 1; end features1(blockCount) = whitepixel / blackpixel; if xblockCount == blocksize xpixel = 1; ypixel = blocksize*yblockCount; xblockCount = 1; yblockCount = yblockCount + 1; elseif xblockCount < blocksize ypixel = originalypixel; xpixel = blocksize*xblockCount; xblockCount = xblockCount + 1; end blockCount = blockCount + 1; end %hist(features); end
github
rajaeipour/spatial-carrier-master
FTP10.m
.m
spatial-carrier-master/FTP10.m
47,519
utf_8
88ee2a3d9801c3ebcdbab29b2792bc10
function varargout = FTP10(varargin) % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @FTP10_OpeningFcn, ... 'gui_OutputFcn', @FTP10_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before FTP10 is made visible. function FTP10_OpeningFcn(hObject, eventdata, handles, varargin) % IMTEK Logo read logo_im = imread('imtek-logo.png','BackgroundColor',[0.93 0.93 0.93]); axes(handles.axes5); imshow(logo_im, []); % Define Zernike table size % set(handles.ZernFitTable,'Data',cell(10,1)); % Camera input setting handles.DepthVid = videoinput('linuxvideo', 1, 'RGB24_1920x1200');% 'YUY2_1920x1200'); % make object for depth camera set(handles.DepthVid,'FramesPerTrigger',1); % capture 1 frame every time DepthVid is trigered set(handles.DepthVid,'TriggerRepeat',Inf); % infinite amount of triggers %set(handles.DepthVid, 'ReturnedColorspace', 'RGB'); triggerconfig(handles.DepthVid, 'Manual');% trigger Depthvid manually within program % handles.DepthVid.LoggingMode = 'disk'; % diskLogger = VideoWriter('/home/pouya/Desktop/1.avi', 'Uncompressed AVI'); % handles.DepthVid.DiskLogger = diskLogger; % diskLogger.FrameRate = 1; % Define frame aquisition frequency handles.FrameAquiFreq = 1; writefreqtoedit = handles.FrameAquiFreq; set(handles.FrameFreq, 'String', num2str(writefreqtoedit)); % Define algorithm timers handles.t1 = timer('TimerFcn',{@FTP_MainFunc, gcf}, 'BusyMode', 'drop',... 'Period',1/handles.FrameAquiFreq,'executionMode','fixedRate'); handles.t2 = timer('TimerFcn',{@FTP_PlotFunc, gcf}, 'BusyMode', 'drop',... 'Period',1/handles.FrameAquiFreq,'executionMode','fixedRate'); % Define primary frequency filter diameter set(handles.FilterDiam,'Value',0.12); % Make axes1 units normalized set(handles.axes1,'Units','normalized'); % Set sliders step values set(handles.FilterDiam,'SliderStep',[0.001, 0.01]); set(handles.FilterX,'SliderStep',[0.0005, 0.01]); set(handles.FilterY,'SliderStep',[0.0005, 0.01]); % Set realtime sign off set(handles.realtime,'foregroundcolor',[1 1 1]); % set (handles.ZernFitTable,'ColumnWidth', {100,52}) % Choose default command line output for FTP10 handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes FTP10 wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = FTP10_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; handles.DepthVid.FramesAvailable function LightWaveLength_Callback(hObject, eventdata, handles) % hObject handle to LightWaveLength (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of LightWaveLength as text % str2double(get(hObject,'String')) returns contents of LightWaveLength as a double % --- Executes during object creation, after setting all properties. function LightWaveLength_CreateFcn(hObject, eventdata, handles) % hObject handle to LightWaveLength (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in SystemMode. function SystemMode_Callback(hObject, eventdata, handles) % hObject handle to SystemMode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns SystemMode contents as cell array % contents{get(hObject,'Value')} returns selected item from SystemMode % --- Executes during object creation, after setting all properties. function SystemMode_CreateFcn(hObject, eventdata, handles) % hObject handle to SystemMode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function FilterDiam_Callback(hObject, eventdata, handles) % hObject handle to FilterDiam (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function FilterDiam_CreateFcn(hObject, eventdata, handles) % hObject handle to FilterDiam (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function FilterX_Callback(hObject, eventdata, handles) % hObject handle to FilterX (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function FilterX_CreateFcn(hObject, eventdata, handles) % hObject handle to FilterX (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function FilterY_Callback(hObject, eventdata, handles) % hObject handle to FilterY (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function FilterY_CreateFcn(hObject, eventdata, handles) % hObject handle to FilterY (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function Crop4_Callback(hObject, eventdata, handles) % hObject handle to Crop4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop4 as text % str2double(get(hObject,'String')) returns contents of Crop4 as a double % --- Executes during object creation, after setting all properties. function Crop4_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop3_Callback(hObject, eventdata, handles) % hObject handle to Crop3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop3 as text % str2double(get(hObject,'String')) returns contents of Crop3 as a double % --- Executes during object creation, after setting all properties. function Crop3_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop1_Callback(hObject, eventdata, handles) % hObject handle to Crop1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop1 as text % str2double(get(hObject,'String')) returns contents of Crop1 as a double % --- Executes during object creation, after setting all properties. function Crop1_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop2_Callback(hObject, eventdata, handles) % hObject handle to Crop2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop2 as text % str2double(get(hObject,'String')) returns contents of Crop2 as a double % --- Executes during object creation, after setting all properties. function Crop2_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop7_Callback(hObject, eventdata, handles) % hObject handle to Crop7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop7 as text % str2double(get(hObject,'String')) returns contents of Crop7 as a double % --- Executes during object creation, after setting all properties. function Crop7_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop5_Callback(hObject, eventdata, handles) % hObject handle to Crop5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop5 as text % str2double(get(hObject,'String')) returns contents of Crop5 as a double % --- Executes during object creation, after setting all properties. function Crop5_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Crop6_Callback(hObject, eventdata, handles) % hObject handle to Crop6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop6 as text % str2double(get(hObject,'String')) returns contents of Crop6 as a double % --- Executes during object creation, after setting all properties. function Crop6_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in CropDone. function CropDone_Callback(hObject, eventdata, handles) % hObject handle to CropDone (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of CropDone function Crop8_Callback(hObject, eventdata, handles) % hObject handle to Crop8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of Crop8 as text % str2double(get(hObject,'String')) returns contents of Crop8 as a double % --- Executes during object creation, after setting all properties. function Crop8_CreateFcn(hObject, eventdata, handles) % hObject handle to Crop8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in Reset. function Reset_Callback(hObject, eventdata, handles) set(handles.Crop5,'String',num2str(0)); set(handles.Crop6,'String',num2str(0)); set(handles.Crop7,'String',num2str(1920)); set(handles.Crop8,'String',num2str(1200)); set(handles.CropDone,'Value',0); set(handles.CropDone,'backgroundcolor',[0.93 0.93 0.93]); set(handles.LoopTime,'String',''); set(handles.peak_valley,'String',''); set(handles.RMS,'String',''); % set(handles.ZernFitTable, 'Data', cell(size(get(handles.ZernFitTable,'Data')))); set(handles.uibuttongroup2,'selectedobject',handles.AutoFilter) set(handles.FourierPlot,'Value',0); set(handles.FilterPlot,'Value',0); set(handles.ReferencePlot,'Value',0); % set(handles.WUTPlot,'Value',0); set(handles.WrappedPlot,'Value',0); set(handles.D2Plot,'Value',0); set(handles.D3Plot,'Value',0); set(handles.ZernikeTable,'Value',0); cla(handles.axes2,'reset'); cla(handles.axes3,'reset'); cla(handles.axes4,'reset'); % --- Executes on button press in Apply. function Apply_Callback(hObject, eventdata, handles) stoppreview(handles.DepthVid) crop_x = str2double(get(handles.Crop5,'String')); crop_y = str2double(get(handles.Crop6,'String')); crop_width = str2double(get(handles.Crop7,'String')); crop_height = str2double(get(handles.Crop8,'String')); set(handles.DepthVid,'ROIPosition',[crop_x crop_y crop_width crop_height]); axes(handles.axes1) videoRes = get(handles.DepthVid, 'VideoResolution'); numberOfBands = get(handles.DepthVid, 'NumberOfBands'); handleToImageInAxes = image( zeros([videoRes(2), videoRes(1), numberOfBands], 'uint8') ); preview(handles.DepthVid,handleToImageInAxes) set(handles.axes1title,'String','Live View'); axis equal % --- Executes on button press in FourierPlot. function FourierPlot_Callback(hObject, eventdata, handles) % hObject handle to FourierPlot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of FourierPlot % --- Executes on button press in WrappedPlot. function WrappedPlot_Callback(hObject, eventdata, handles) % hObject handle to WrappedPlot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of WrappedPlot % --- Executes on button press in D2Plot. function D2Plot_Callback(hObject, eventdata, handles) % hObject handle to D2Plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of D2Plot % --- Executes on button press in D3Plot. function D3Plot_Callback(hObject, eventdata, handles) % hObject handle to D3Plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of D3Plot % --- Executes on button press in ZernikeTable. function ZernikeTable_Callback(hObject, eventdata, handles) % hObject handle to ZernikeTable (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ZernikeTable % % --- Executes on button press in WUTPlot. % function WUTPlot_Callback(hObject, eventdata, handles) % % hObject handle to WUTPlot (see GCBO) % % eventdata reserved - to be defined in a future version of MATLAB % % handles structure with handles and user data (see GUIDATA) % % % Hint: get(hObject,'Value') returns toggle state of WUTPlot % --- Executes on button press in FilterPlot. function FilterPlot_Callback(hObject, eventdata, handles) % hObject handle to FilterPlot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of FilterPlot % --- Executes on button press in ReferencePlot. function ReferencePlot_Callback(hObject, eventdata, handles) % hObject handle to ReferencePlot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ReferencePlot % --- Executes on button press in LiveView. function LiveView_Callback(hObject, eventdata, handles) crop_x = str2double(get(handles.Crop5,'String')); crop_y = str2double(get(handles.Crop6,'String')); crop_width = str2double(get(handles.Crop7,'String')); crop_height = str2double(get(handles.Crop8,'String')); set(handles.DepthVid,'ROIPosition',[crop_x crop_y crop_width crop_height]); axes(handles.axes1) videoRes = get(handles.DepthVid, 'VideoResolution'); numberOfBands = get(handles.DepthVid, 'NumberOfBands'); handleToImageInAxes = image( zeros([videoRes(2), videoRes(1), numberOfBands], 'uint8') ); preview(handles.DepthVid,handleToImageInAxes) set(handles.axes1title,'String','Live View'); axis equal % --- Executes on button press in Crop. function Crop_Callback(hObject, eventdata, handles) window1 = figure; window1.Units = 'pixels'; im_crop = getsnapshot(handles.DepthVid); figure(window1) imshow(im_crop) set(gca,'units','normalized','position',[0,0,1,1],'xtick',[],'ytick',[]); ROI_rect = imrect; ROI_crop = wait(ROI_rect); close(window1) ROI_crop = round(ROI_crop); ROI_crop_length = min([ROI_crop(3) ROI_crop(4)]); handles.ReferenceFringe_axes4 = imcrop(im_crop,[ROI_crop(1) ROI_crop(2) ROI_crop_length ROI_crop_length]); set(handles.Crop1, 'String', num2str(ROI_crop(1))); set(handles.Crop2, 'String', num2str(ROI_crop(2))); set(handles.Crop3, 'String', num2str(ROI_crop(3))); set(handles.Crop4, 'String', num2str(ROI_crop(4))); set(handles.Crop5, 'String', num2str(ROI_crop(1))); set(handles.Crop6, 'String', num2str(ROI_crop(2))); set(handles.Crop7, 'String', num2str(ROI_crop_length)); set(handles.Crop8, 'String', num2str(ROI_crop_length)); handles.reference_im = im_crop; handles.output = hObject; guidata(hObject, handles); % --- Executes on button press in Measure. function Measure_Callback(hObject, eventdata, handles) set(handles.DepthVid,'ROIPosition',[0 0 1920 1200]) %%%% Bring ROI to default for capturing start(handles.DepthVid); % Start Video start(handles.t1) % Start measurement function function realtime_Callback(hObject, eventdata, handles) % hObject handle to realtime (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of realtime as text % str2double(get(hObject,'String')) returns contents of realtime as a double % --- Executes during object creation, after setting all properties. function realtime_CreateFcn(hObject, eventdata, handles) % hObject handle to realtime (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in Capture. function Capture_Callback(hObject, eventdata, handles) % handles = guidata(fignum); check_timer1 = isvalid(handles.t1); if check_timer1 == 1 stop(handles.DepthVid); stop(handles.t1); set(handles.realtime,'foregroundcolor',[0.9 0.9 0.9],'backgroundcolor',[0.9 0.9 0.9]); end check_timer2 = isvalid(handles.t2); if check_timer2 == 1 stop(handles.t2); end % FTP_PlotFunc(hObject,eventdata,fignum) % Calling plot function axes(handles.axes4) colorbar colormap jet shading interp h=rotate3d; set(h,'Enable','on'); % assignin('base', 'Reference_fringe', handles.ReferenceFringe_axes4) assignin('base', 'Captured_frame', handles.im_axes1) % assignin('base', 'Fourier_Domain', handles.G_abs_axes2) assignin('base', 'Frequency_Filter', handles.lobe1_axes3) assignin('base', 'Wrapped_Phase', handles.Wrapped_axes3) assignin('base', 'Deformation', handles.Deformation2D_axes3) % --- Executes on button press in PLOT. function PLOT_Callback(hObject, eventdata, handles) start(handles.t2) % --- Executes on button press in STOP. function STOP_Callback(hObject, eventdata, handles) check_timer1 = isvalid(handles.t1); check_timer2 = isvalid(handles.t2); if check_timer2 == 1 stop(handles.t2) end if check_timer1 == 1 stop(handles.DepthVid); stop(handles.t1); set(handles.realtime,'foregroundcolor',[0.9 0.9 0.9],'backgroundcolor',[0.9 0.9 0.9]); set(handles.LoopTime, 'String', ' '); stoppreview(handles.DepthVid) else stoppreview(handles.DepthVid) end function LoopTime_Callback(hObject, eventdata, handles) % hObject handle to LoopTime (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of LoopTime as text % str2double(get(hObject,'String')) returns contents of LoopTime as a double % --- Executes during object creation, after setting all properties. function LoopTime_CreateFcn(hObject, eventdata, handles) % hObject handle to LoopTime (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function FrameFreq_Callback(hObject, eventdata, handles) % hObject handle to FrameFreq (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of FrameFreq as text % str2double(get(hObject,'String')) returns contents of FrameFreq as a double % --- Executes during object creation, after setting all properties. function FrameFreq_CreateFcn(hObject, eventdata, handles) % hObject handle to FrameFreq (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function FTP_MainFunc(hObject, evendata, fignum) tic; handles = guidata(fignum); set(handles.realtime,'foregroundcolor',[0 0 0],'backgroundcolor',[0 1 0]); trigger(handles.DepthVid)%trigger DepthVid to capture image im=getdata(handles.DepthVid,1);% crop_x = str2double(get(handles.Crop5,'String')); crop_y = str2double(get(handles.Crop6,'String')); crop_width = str2double(get(handles.Crop7,'String')); handles.ROI_P = [crop_x crop_y crop_width crop_width]; im = imcrop(im,[crop_x crop_y crop_width crop_width]); handles.im_axes1 = im; im = im(:,:,1); % reading only "red" values of the captured frame check_crop_done = get(handles.CropDone, 'Value'); if check_crop_done == 1 set(handles.CropDone,'backgroundcolor',[0.93 0.93 0.93]); K0 = get(handles.FilterDiam,'value'); % Radius of the filter as a fraction of pi wave_length = str2double(get(handles.LightWaveLength,'String'))*10^(-9); % Wavelength of the light used for illumination mode = get(handles.SystemMode,'Value'); % If the membrane is reflective: 'reflection' , if the membrane is transimissive: 'transmission' img1=im2double(im); [N,M]=size(img1); %[height, width] % Preparing for applying hamming window h_win=hamming(N); hamm = zeros(N,N); % Initialize windows along column direction for n=1:N hamm(:,n)=h_win; end % Apply windows along rows hamm=hamm.*hamm'; % Apply hamming window to the image img1=img1.*hamm; % Compute fft2 of the windowed image G=fft2(img1); G=fftshift(G); G_abs=abs(G); handles.G_abs_axes2 = G_abs; % making a copy of fourier transform for plotting % check for mode of finding the frequency filter position Filter_Position_Auto = get(handles.AutoFilter,'value'); K0 = K0*pi; dx = 1; dy = 1; if Filter_Position_Auto == 1 No_X_pixel = round(N/2); No_Y_pixel = round(M/2); G_abs_left = zeros(N,No_Y_pixel); G_abs_left(1:N,35:No_Y_pixel-5) = G_abs(1:N,35:No_Y_pixel-5); maxValue=max(G_abs_left(:)); [rowOfMax, colOfMax] = find(G_abs_left == maxValue); X_index = colOfMax; Y_index = rowOfMax; shift_x = -(1-X_index / No_X_pixel)*pi; % Shift of the origin of the filter in spatial domain as a fraction of pi (Should be equal to carrier frequency) shift_x_slider = shift_x/pi; set(handles.FilterX,'Value',shift_x_slider); shift_y = -(1-Y_index / No_Y_pixel)*pi; shift_y_slider = shift_y/pi; set(handles.FilterY,'Value',-shift_y_slider); else shift_x = get(handles.FilterX,'value'); shift_x = shift_x * pi; shift_y = get(handles.FilterY,'value'); shift_y = -shift_y * pi; end handles.Filter_X = shift_x/pi; handles.Filter_Y = shift_y/pi; handles.Filter_D = K0/pi; KX0 = (mod((1/2 + (0:(N-1))/N), 1) - 1/2); KX1 = KX0 * (2*pi/dx); KY0 = (mod((1/2 + (0:(M-1))/M), 1) - 1/2); KY1 = KY0 * (2*pi/dy); [KX,KY] = meshgrid(KX1,KY1); %Filter formulation lpf = ((KX-shift_x).^2 + (KY-shift_y).^2 < K0^2); lpf = fftshift(lpf); % Convoluting the filter with image G=lpf.*G; % Isolating the desired lobe % Finding horizontal and vertical elements by scaning in 4 directions help1=0; scan1=zeros(N,1); for kk=1:M if help1==0 scan1=G(:,kk); if mean(scan1) ~= 0 hor1=kk; help1=1; end end end help1=0; scan1=zeros(N,1); for kk=1:M if help1==0 scan1=G(:,M-kk); if mean(scan1) ~= 0 hor2=M-kk; help1=1; end end end help1=0; scan2=zeros(1,hor2-hor1); for kk=1:N if help1 == 0 scan2=G(kk,:); if mean(scan2) ~= 0 ver1=kk; help1=1; end end end help1=0; scan2=zeros(1,hor2-hor1); for kk=1:N if help1 == 0 scan2=G(N-kk,:); if mean(scan2) ~= 0 ver2=N-kk; help1=1; end end end lobe1_help=G(ver1:ver2,hor1:hor2); [xxx,yyy]=size(lobe1_help); zzz = min(xxx,yyy); lobe1=zeros(zzz,zzz); for ii=1:zzz for jj=1:zzz lobe1(ii,jj)=lobe1_help(ii,jj); end end handles.lobe1_axes3 = abs(lobe1); % Taking the inverse fourier transform of the lobe ifft2 lobe1 = fftshift(lobe1); ifft_lobe=ifft2(lobe1); % Extracting the imaginary part imag_ifft_lobe=imag(ifft_lobe); abs_lobe = abs(imag_ifft_lobe); % Wavefront under test handles.WUT_axes1 = abs_lobe; % Making a copy of the wavefront under test % Taking arc tan of the inverse Fourier transform of the 1st lobe % phase_lobe=2.*atan(real(ifft_lobe)./imag(ifft_lobe)); phase_lobe = angle(ifft_lobe); phase_lobe = mod(phase_lobe+pi,2*pi)-pi; handles.Wrapped_axes3 = phase_lobe; % Making a copy of the wrapped phase % Unwrapping [unwrapped] = cunwrap_nodisp(phase_lobe); switch mode case 2 unwrapped_phase = unwrapped / 2; % Compensating for reflection path difference case 1 unwrapped_phase = unwrapped; end Deformation = unwrapped_phase * (wave_length/(2*pi)) * 10^6; % Converting phase difference to deformations handles.Deformation2D_axes3 = Deformation; else % if crop is not done set(handles.CropDone,'backgroundcolor',[1 0 0]); end set(handles.realtime,'foregroundcolor',[0.9 0.9 0.9],'backgroundcolor',[0.9 0.9 0.9]); handles.TimeSpent = toc; guidata(fignum, handles); function FTP_PlotFunc(hObject,eventdata,fignum) handles = guidata(fignum); set(handles.LoopTime, 'String', num2str(handles.TimeSpent)); % Plotting the captured frame imshow(handles.im_axes1,'Parent',handles.axes1) set(handles.axes1title,'String','Captured Frame'); % Checking the output selection checkboxes Fourier_Plot = get(handles.FourierPlot, 'Value'); Filter_Plot = get(handles.FilterPlot, 'Value'); Reference_Plot = get(handles.ReferencePlot, 'Value'); % Wavefront_Plot = get(handles.WUTPlot, 'Value'); Fit_Plot = get(handles.Deformation_fit, 'Value'); Wrapped_Plot = get(handles.WrappedPlot, 'Value'); Deform2D_Plot = get(handles.D2Plot, 'Value'); Deform3D_Plot = get(handles.D3Plot, 'Value'); Zernike_Table = get(handles.ZernikeTable, 'Value'); % low =0; % high =50; % max_handles_G_abs_axes2=handles.G_abs_axes2/(max(max(handles.G_abs_axes2))); % max_handles_G_abs_axes2=max_handles_G_abs_axes2*255; if Fourier_Plot == 1 GG = mat2gray(log(handles.G_abs_axes2+1)); imshow(GG,'Parent',handles.axes2,'colormap',jet) set(handles.axes2title,'String','Fourier Transform'); end if Filter_Plot == 1 GG_lobe = mat2gray(log(handles.lobe1_axes3+1)); % max_handles_lobe1=handles.lobe1_axes3/(max(max(handles.G_abs_axes2))); % max_handles_lobe1=max_handles_lobe1*255; imshow(GG_lobe,'Parent',handles.axes3,'colormap',jet) set(handles.axes3title,'String','Frequency Filtered Area'); end if Reference_Plot == 1 imshow(handles.ReferenceFringe_axes4,'Parent',handles.axes4) set(handles.axes1title,'String','Reference Fringe'); end % if Wavefront_Plot == 1 % set(handles.FourierPlot,'Value',0); % set(handles.WrappedPlot,'Value',0); % min_wavefront=min(min(handles.WUT_axes1)); % wavefront_plot=handles.Wrapped_axes3+abs(min_wavefront); % wavefront_plot=wavefront_plot/max(max(wavefront_plot)); % imshow(wavefront_plot,'Parent',handles.axes2)%,'colormap',jet) % set(handles.axes2title,'String','Wavefront under test'); % end if Wrapped_Plot == 1 set(handles.FourierPlot,'Value',0); min_wrapped=min(min(handles.Wrapped_axes3)); wrapped_plot=handles.Wrapped_axes3+abs(min_wrapped); wrapped_plot=wrapped_plot/max(max(wrapped_plot)); imshow(wrapped_plot,'Parent',handles.axes2,'colormap',jet) set(handles.axes2title,'String','Wrapped Phase'); end if Deform2D_Plot == 1 set(handles.FilterPlot,'Value',0); min_deform2d = min(min(handles.Deformation2D_axes3)); deform2d_plot = handles.Deformation2D_axes3 + abs(min_deform2d); deform2d_plot = deform2d_plot/max(max(deform2d_plot)); imshow(deform2d_plot,'Parent',handles.axes3,'colormap',jet) % colorbar(handles.axes4) set(handles.axes3title,'String','Membrane Deformation 2D'); end if Deform3D_Plot == 1 set(handles.ReferencePlot,'Value',0); Deformation = handles.Deformation2D_axes3; [nnn,mmm] = size(Deformation); K0_unwrap_mask = pi/1.07; % Radius of circular area inside the square cropped frame KX0 = (mod((1/2 + (0:(nnn-1))/nnn), 1) - 1/2); KX1 = KX0 * (2*pi); KY0 = (mod(1/2 + (0:(mmm-1))/mmm, 1) - 1/2); KY1 = KY0 * (2*pi); [KX,KY] = meshgrid(KX1,KY1); % Unwrap mask formulation unwrap_mask = ((KX).^2 + (KY).^2 < K0_unwrap_mask^2); unwrap_mask = fftshift(unwrap_mask); Deformation_mask = unwrap_mask .* Deformation; X_UW = 1:nnn; Y_UW = 1:mmm; [AA,BB]=meshgrid(X_UW,Y_UW); % Applying the mask to X & Y coordinates AA = unwrap_mask .* AA; BB = unwrap_mask .* BB; length_x=nnn*mmm; length_y=nnn*mmm; length_z=nnn*mmm; X=zeros(1,length_x); Y=zeros(1,length_y); Z=zeros(1,length_z); PP=1; for ii=1:nnn X(1,PP:PP+mmm-1)=AA(ii,:); PP=PP+mmm; end PP=1; for ii=1:nnn Y(1,PP:PP+mmm-1)=BB(ii,:); PP=PP+mmm; end PP=1; for ii=1:nnn Z(1,PP:PP+mmm-1)=Deformation_mask(ii,:); PP=PP+mmm; end % Extracting X & Y & Z coordinates of only the membrane PP=1; for ii=1:length_x if X(ii) ~= 0 X_circ(PP) = X(ii); PP = PP + 1; end end PP=1; for ii=1:length_y if Y(ii) ~= 0 Y_circ(PP) = Y(ii); PP = PP + 1; end end PP=1; for ii=1:length_z if Z(ii) ~= 0 Z_circ(PP) = Z(ii); PP = PP + 1; end end mean_Z = mean(mean(Z_circ)); ZZ_circ = Z_circ-mean_Z; tri = delaunay(X_circ,Y_circ); plot(X_circ,Y_circ,'.', 'Parent',handles.axes4) % Plot it with TRISURF h = trisurf(tri, X_circ, Y_circ, ZZ_circ, 'Parent',handles.axes4); az = 0; el = 90; view(handles.axes4,az, el); colorbar(handles.axes4) colormap(handles.axes4,'jet') shading(handles.axes4,'flat') caxis(handles.axes4,[-1,1]) set(handles.axes4, 'ZLim', [-5,5]); set(handles.axes4title,'String','Membrane Deformation 3D [um]'); PeakValley = max(Z_circ) - min(Z_circ); PeakValley = roundn(PeakValley,-2); RMS_Z = rms(Z_circ); RMS_Z = roundn(RMS_Z,-2); set(handles.peak_valley, 'String', num2str(PeakValley)); set(handles.RMS, 'String', num2str(RMS_Z)); end if Fit_Plot == 1 set(handles.D3Plot,'Value',0); Deformation = handles.Deformation2D_axes3; [nnn,mmm] = size(Deformation); if mod(nnn,2) == 0 radious = nnn/2; [AA,BB]=meshgrid(-radious:radious-1,-radious:radious-1); else radious = floor(nnn/2); [AA,BB]=meshgrid(-radious:radious,-radious:radious); end % radious = round(nnn/2) - 1; [THETA_pix,Rad_Pix] = cart2pol(AA,BB); is_in_circle = Rad_Pix<=(radious); Rad = Rad_Pix(is_in_circle) ./ (radious); THETA = THETA_pix(is_in_circle); N = []; M = []; %make zernicke indexes m,n up to 4,4 for n = 0:8 N = [N n*ones(1,n+1)]; M = [M -n:2:n]; end zern_coeff = zernfun(N,M,Rad,THETA); %generate zernicke polynomial values at each pair of r,theta for each n,m index ZernikeCoeff = zern_coeff\Deformation(is_in_circle); %fit data to Zernicke to estimate coefficient of data ZernikeCoeff(1:3) = 0; fit_def = getFitted_mod3(ZernikeCoeff,THETA,Rad); %make fit data so we can visualize A = AA(is_in_circle); B = BB(is_in_circle); tri = delaunay(A,B); plot(A,B,'.', 'Parent',handles.axes4) h = trisurf(tri, A, B, fit_def, 'Parent',handles.axes4); az = 0; el = 90; view(handles.axes4,az, el); colorbar(handles.axes4) colormap(handles.axes4,'jet') shading(handles.axes4,'flat') caxis(handles.axes4,[-1,1]) set(handles.axes4, 'ZLim', [-5,5]); set(handles.axes4title,'String','Membrane Deformation Fit [um]'); PeakValley = max(fit_def) - min(fit_def); PeakValley = roundn(PeakValley,-2); RMS_Z = rms(fit_def); RMS_Z = roundn(RMS_Z,-2); set(handles.peak_valley, 'String', num2str(PeakValley)); set(handles.RMS, 'String', num2str(RMS_Z)); end if Zernike_Table == 1 if Fit_Plot == 1 Column1 = ZernikeCoeff(4:15); bar(Column1,0.5,'Parent',handles.axes6) set(handles.axes6, 'YLim', [-2,2]); set(handles.axes6,'XTickLabel',{'AST', 'DEF', 'AST', 'TFL','CMA','CMA','TFL','QUD','2AST','SPH','2AST','QUD'}) else Deformation = handles.Deformation2D_axes3; [nnn,mmm] = size(Deformation); if mod(nnn,2) == 0 radious = nnn/2; [AA,BB]=meshgrid(-radious:radious-1,-radious:radious-1); else radious = floor(nnn/2); [AA,BB]=meshgrid(-radious:radious,-radious:radious); end % radious = round(nnn/2) - 1; [THETA_pix,Rad_Pix] = cart2pol(AA,BB); is_in_circle = Rad_Pix<=(radious); Rad = Rad_Pix(is_in_circle) ./ (radious); THETA = THETA_pix(is_in_circle); N = []; M = []; %make zernicke indexes m,n up to 4,4 for n = 0:8 N = [N n*ones(1,n+1)]; M = [M -n:2:n]; end zern_coeff = zernfun(N,M,Rad,THETA); %generate zernicke polynomial values at each pair of r,theta for each n,m index ZernikeCoeff = zern_coeff\Deformation(is_in_circle); %fit data to Zernicke to estimate coefficient of data % Column1 = zeros(10,1); Column1 = ZernikeCoeff(4:15); bar(Column1,0.5,'Parent',handles.axes6) set(handles.axes6, 'YLim', [-2,2]); set(handles.axes6,'XTickLabel',{'AST', 'DEF', 'AST', 'TFL','CMA','CMA','TFL','QUD','2AST','SPH','2AST','QUD'}) end end function peak_valley_Callback(hObject, eventdata, handles) % hObject handle to peak_valley (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of peak_valley as text % str2double(get(hObject,'String')) returns contents of peak_valley as a double % --- Executes during object creation, after setting all properties. function peak_valley_CreateFcn(hObject, eventdata, handles) % hObject handle to peak_valley (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function RMS_Callback(hObject, eventdata, handles) % hObject handle to RMS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of RMS as text % str2double(get(hObject,'String')) returns contents of RMS as a double % --- Executes during object creation, after setting all properties. function RMS_CreateFcn(hObject, eventdata, handles) % hObject handle to RMS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in SAVE. function SAVE_Callback(hObject, eventdata, handles) % hObject handle to SAVE (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) Captured_frame = evalin('base', 'Captured_frame'); % Fourier_Domain = evalin('base', 'Fourier_Domain'); Frequency_Filter = evalin('base', 'Frequency_Filter'); Wrapped_Phase = evalin('base', 'Wrapped_Phase'); Deformation = evalin('base', 'Deformation'); uisave({'Captured_frame','Frequency_Filter','Wrapped_Phase','Deformation'}) % --- Executes on button press in loadandplot. function loadandplot_Callback(hObject, eventdata, handles) % hObject handle to loadandplot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) uiopen f = figure('Position',[200 200 1000 450]);; subplot(1,2,1) min_wrapped=min(min(Wrapped_Phase)); wrapped_plot=Wrapped_Phase+abs(min_wrapped); wrapped_plot=wrapped_plot/max(max(wrapped_plot)); imshow(wrapped_plot,'colormap',jet) title('Wrapped Phase') axis equal [nnn,mmm] = size(Deformation); K0_unwrap_mask = pi/1.07; % Radius of circular area inside the square cropped frame KX0 = (mod((1/2 + (0:(nnn-1))/nnn), 1) - 1/2); KX1 = KX0 * (2*pi); KY0 = (mod(1/2 + (0:(mmm-1))/mmm, 1) - 1/2); KY1 = KY0 * (2*pi); [KX,KY] = meshgrid(KX1,KY1); % Unwrap mask formulation unwrap_mask = ((KX).^2 + (KY).^2 < K0_unwrap_mask^2); unwrap_mask = fftshift(unwrap_mask); Deformation_mask = unwrap_mask .* Deformation; X_UW = 1:nnn; Y_UW = 1:mmm; [AA,BB]=meshgrid(X_UW,Y_UW); % Applying the mask to X & Y coordinates AA = unwrap_mask .* AA; BB = unwrap_mask .* BB; length_x=nnn*mmm; length_y=nnn*mmm; length_z=nnn*mmm; X=zeros(1,length_x); Y=zeros(1,length_y); Z=zeros(1,length_z); PP=1; for ii=1:nnn X(1,PP:PP+mmm-1)=AA(ii,:); PP=PP+mmm; end PP=1; for ii=1:nnn Y(1,PP:PP+mmm-1)=BB(ii,:); PP=PP+mmm; end PP=1; for ii=1:nnn Z(1,PP:PP+mmm-1)=Deformation_mask(ii,:); PP=PP+mmm; end % Extracting X & Y & Z coordinates of only the membrane PP=1; for ii=1:length_x if X(ii) ~= 0 X_circ(PP) = X(ii); PP = PP + 1; end end PP=1; for ii=1:length_y if Y(ii) ~= 0 Y_circ(PP) = Y(ii); PP = PP + 1; end end PP=1; for ii=1:length_z if Z(ii) ~= 0 Z_circ(PP) = Z(ii); PP = PP + 1; end end mean_Z = mean(mean(Z_circ)); ZZ_circ = Z_circ-mean_Z; tri = delaunay(X_circ,Y_circ); subplot(1,2,2) plot(X_circ,Y_circ,'.') % Plot it with TRISURF h = trisurf(tri, X_circ, Y_circ, ZZ_circ); title('Deformation [um]') az = 0; el = 90; view(az, el); colorbar colormap jet shading flat axis off caxis([-0.5,0.5]) colorbar('Ticks',[-2:0.5:2]) % create the data PeakValley = max(Z_circ) - min(Z_circ); PeakValley = roundn(PeakValley,-2); radious = round(nnn/2) - 1; [AA,BB]=meshgrid(-radious:radious,-radious:radious); [THETA,Rad_Pix] = cart2pol(AA,BB); is_in_circle = Rad_Pix<=(radious-1); Rad = Rad_Pix(is_in_circle) ./ (radious); N = []; M = []; %make zernicke indexes m,n up to 4,4 for n = 0:8 N = [N n*ones(1,n+1)]; M = [M -n:2:n]; end zern_coeff = zernfun(N,M,Rad,THETA(is_in_circle)); %generate zernicke polynomial values at each pair of r,theta for each n,m index ZernikeCoeff = zern_coeff\Deformation(is_in_circle); %fit data to Zernicke to estimate coefficient of data ZernikeCoeff(1:13); d = [PeakValley ZernikeCoeff(2) ZernikeCoeff(3) ZernikeCoeff(4) ZernikeCoeff(6) ZernikeCoeff(5) ZernikeCoeff(13)]; % Create the column and row names in cell arrays cnames = {'Peak to Valley','Tilt X','Tilt Y','O-Astigmatism','V-Astigmatism','Defocus','Spherical'}; rnames = {'Value [um]'}; % Create the uitable t = uitable(f,'Data',d,... 'ColumnName',cnames,... 'RowName',rnames); % Set width and height t.Position(3) = t.Extent(3); t.Position(4) = t.Extent(4); % --- Executes on button press in CharacData. function CharacData_Callback(hObject, eventdata, handles) % hObject handle to CharacData (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) assignin('base', 'Filter_X', handles.Filter_X) assignin('base', 'Filter_Y', handles.Filter_Y) assignin('base', 'Filter_D', handles.Filter_D) assignin('base', 'Crop_Pix', handles.ROI_P) Filter_X = evalin('base', 'Filter_X'); Filter_Y = evalin('base', 'Filter_Y'); Filter_D = evalin('base', 'Filter_D'); Crop_Pix = evalin('base', 'Crop_Pix'); % filename = fullfile('/home/pouya/meausre 31.05', 'Crop_and_Filter.mat'); uisave({'Filter_X','Filter_Y','Filter_D','Crop_Pix'},'Crop_and_Filter'); STOP_Callback(hObject, eventdata, handles) % --- Executes on button press in Deformation_fit. function Deformation_fit_Callback(hObject, eventdata, handles) % hObject handle to Deformation_fit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Deformation_fit
github
rajaeipour/spatial-carrier-master
cunwrap_nodisp.m
.m
spatial-carrier-master/cunwrap_nodisp.m
16,666
utf_8
f64eda6acf71fe85dfd64078206275c3
function PhiUnwrap = cunwrap_nodisp(Psi, options) % PhiUnwrap = cunwrap(Psi, options) % % Purpose: Costantini's 2D unwrapping based on Minimum Network Flow % % INPUTS: % - Psi: 2D-array wrapped phase (radian) % - options: optional structure used to modify the behavior of the % unwrapping algorithm. All fields are optional. % The fieldname does not need to exactly case-matched. % Weight: array of same dimension as the Psi, with is used as % the positive weight of the L1 norm of the residual (to be % minimized). For example user can provide WEIGHT as function % of the interference amplitude or function of phase % measurement quality (e.g., fringe contrast). % By default: all internal pixels have the same weight of 1, % 0.5 for edge-pixels, and 0.25 for corner-pixels. % CutSize: even integer scalar, default [4]: the width (in pixel) of % the Gaussian kernel use to lower the weight around pixels % that do not fulfill rotational relation. % If CutSize is 0, no rotational-based weighting will be % carried out. % RoundK: Boolean, [false] by default. When ROUNDK is true, CUNWRAP % forces the partial derivative residuals K1/K2 to be % integers. % MaxBlockSize: scalar default [125], target linear blocksize. % Set to Inf for single-block global unwrapping. % Note: network flow is costly in CPU for large size. % Overlap: scalar default [0.25], fractional overlapping between two % neighboring blocks. % Verbose: logical [true], control printout information. % LPoption: LINPROG option structure as return by OPTIMSET(...). % OUTPUT: % - Phi: 2D-array unwrapped phase (radian) % % Minimum network flow computation engine is Matlab LINPROG (optimization % toolbox is required) % % References: % - http://earth.esa.int/workshops/ers97/papers/costantini/ % - Costantini, M. (1998) A novel phase unwrapping method based on network % programming. IEEE Tran. on Geoscience and Remote Sensing, 36, 813-821. % % Author: Bruno Luong <[email protected]> % History: % Orginal: 27-Aug-2009 % 28-Aug-2009: modification in block splitting, default size changes % to 125 x 125 % 28-Aug-2009: correct a serious indexing bug if nargin<2 options = struct(); end if ndims(Psi)>2 error('CUNWRAP: input Psi must be 2D array.'); end [ny nx] = size(Psi); if nx<2 || ny<2 error('CUNWRAP: size of Psi must be larger than 2'); end roundK = getoption(options, 'roundk', false); verbose = getoption(options, 'verbose', true); % Default weight w1 = ones(ny,1); w1([1 end]) = 0.5; w2 = ones(1,nx); w2([1 end]) = 0.5; weight = w1*w2; % tensorial product weight = getoption(options, 'weight', weight); % Split in smaller block size blocksize = getoption(options, 'maxblocksize', 125); blocksize = max(blocksize,2); % Overlapping fraction p = getoption(options, 'overlap', 0.25); p = max(min(p,1),0); % Split the linear index for each dimension [ix blk_x] = splitidx(blocksize, nx, p); [iy blk_y] = splitidx(blocksize, ny, p); nbblk = length(iy)*length(ix); % Allocate arrays % negative/positive parts of wrapped partial derivatives x1p = nan(ny-1, nx, class(Psi)); x1m = nan(ny-1, nx, class(Psi)); x2p = nan(ny, nx-1, class(Psi)); x2m = nan(ny, nx-1, class(Psi)); %% % Loop over the blocks blknum = 0; for i=1:length(iy) iy0 = iy{i}; iy1 = iy0(1:end-1); iy2 = iy0(1:end); for j=1:length(ix) ix0 = ix{j}; ix1 = ix0(1:end); ix2 = ix0(1:end-1); blknum = blknum + 1; options.weight = weight(iy0,ix0); options.blknum = blknum; % Costantini's minimum network flow resolution for one block [x1p(iy1,ix1) x1m(iy1,ix1) x2p(iy2,ix2) x2m(iy2,ix2)] = ... cunwrap_blk(Psi(iy0,ix0), ... x1p(iy1,ix1), x1m(iy1,ix1),... x2p(iy2,ix2), x2m(iy2,ix2),... options); end end %% % Compute partial derivative Psi1, eqt (1,3) i = 1:(ny-1); j = 1:nx; [ROW_I ROW_J] = ndgrid(i,j); I_J = sub2ind(size(Psi),ROW_I,ROW_J); IP1_J = sub2ind(size(Psi),ROW_I+1,ROW_J); Psi1 = Psi(IP1_J) - Psi(I_J); % A priori knowledge that Psi1 is in [-pi,pi) Psi1 = mod(Psi1+pi,2*pi)-pi; % Compute partial derivative Psi2, eqt (2,4) i = 1:ny; j = 1:(nx-1); [ROW_I ROW_J] = ndgrid(i,j); I_J = sub2ind(size(Psi),ROW_I,ROW_J); I_JP1 = sub2ind(size(Psi),ROW_I,ROW_J+1); Psi2 = Psi(I_JP1) - Psi(I_J); % A priori knowledge that Psi1 is in [-pi,pi) Psi2 = mod(Psi2+pi,2*pi)-pi; % Compute the derivative jumps, eqt (20,21) k1 = x1p-x1m; k2 = x2p-x2m; % Round to integer solution (?) if roundK k1 = round(k1); k2 = round(k2); end % Sum the jumps with the wrapped partial derivatives, eqt (10,11) k1 = reshape(k1,[ny-1 nx]); k2 = reshape(k2,[ny nx-1]); k1 = k1+Psi1/(2*pi); k2 = k2+Psi2/(2*pi); %% % Integrate the partial derivatives, eqt (6) % Not sure why integrate this way is better than otherway around % Integration order, not documented intorder = getoption(options, 'IntOrder', 1); if intorder==1 K = cumsum([0 k2(1,:)]); K = [K; k1]; K = cumsum(K,1); else % Integration is this order does not work well (still mysterious for BL) K = cumsum([0; k1(:,1)]); K = [K k2]; K = cumsum(K,2); end PhiUnwrap = (2*pi)*K; end % cunwrap %% function [x1p x1m x2p x2m] = cunwrap_blk(Psi, ... X1p, X1m, X2p, X2m, options) % function [x1p x1m x2p x2m] = cunwrap_blk(Psi, ... % X1p, X1m, X2p, X2m, options) % Costantini's minimum network flow resolution for one block %% % if getoption(options, 'blknum', NaN) == 8 % save('debug.mat', 'Psi', 'X1p', 'X1m', 'X2p', 'X2m', 'options'); % end %% [ny nx] = size(Psi); verbose = getoption(options, 'verbose', true); % the width (in pixel) of the Gaussian kernel to limit effect of % patch that does not satisfy rotational relation CutSize = getoption(options, 'cutsize', 4); % Default weight w1 = ones(ny,1); w1([1 end])=0.5; w2 = ones(1,nx); w2([1 end])=0.5; weight = w1*w2; % tensorial product weight = getoption(options, 'weight', weight); % Compute partial derivative Psi1, eqt (1,3) i = 1:(ny-1); j = 1:nx; [ROW_I ROW_J] = ndgrid(i,j); I_J = sub2ind(size(Psi),ROW_I,ROW_J); IP1_J = sub2ind(size(Psi),ROW_I+1,ROW_J); Psi1 = Psi(IP1_J) - Psi(I_J); % A priori knowledge that Psi1 is in [-pi,pi) Psi1 = mod(Psi1+pi,2*pi)-pi; % Compute partial derivative Psi2, eqt (2,4) i = 1:ny; j = 1:(nx-1); [ROW_I ROW_J] = ndgrid(i,j); I_J = sub2ind(size(Psi),ROW_I,ROW_J); I_JP1 = sub2ind(size(Psi),ROW_I,ROW_J+1); Psi2 = Psi(I_JP1) - Psi(I_J); % A priori knowledge that Psi1 is in [-pi,pi) Psi2 = mod(Psi2+pi,2*pi)-pi; %% % The RHS is column-reshaping of a 2D array [ny-1] x [nx-1] % Build the equality constraint RHS (eqt 17) beq = 0; % Compute beq i = 1:(ny-1); j = 1:(nx-1); [ROW_I ROW_J] = ndgrid(i,j); I_J = sub2ind(size(Psi1),ROW_I,ROW_J); I_JP1 = sub2ind(size(Psi1),ROW_I,ROW_J+1); beq = beq + (Psi1(I_JP1)-Psi1(I_J)); I_J = sub2ind(size(Psi2),ROW_I,ROW_J); IP1_J = sub2ind(size(Psi2),ROW_I+1,ROW_J); beq = beq - (Psi2(IP1_J)-Psi2(I_J)); beq = -1/(2*pi)*beq; beq = round(beq); beq = beq(:); %% % The vector of LP is arranged as following: % x := (x1p, x1m, x2p, x2m).' % x1p, x1m: reshaping of [ny-1] x [nx] % x2p, x2m: reshaping of [ny] x [nx-1] % % Row index, used by all foure blocks in Aeq, beq i = 1:(ny-1); j = 1:(nx-1); [ROW_I ROW_J] = ndgrid(i,j); ROW_I_J = sub2ind([length(i) length(j)],ROW_I,ROW_J); nS0 = (nx-1)*(ny-1); % Use by S1p, S1m [COL_I COL_J] = ndgrid(i,j); COL_IJ_1 = sub2ind([length(i) length(j)+1],COL_I,COL_J); [COL_I COL_JP1] = ndgrid(i,j+1); COL_I_JP1 = sub2ind([length(i) length(j)+1],COL_I,COL_JP1); nS1 = (nx)*(ny-1); % Use by S2p, S2m [COL_I COL_J] = ndgrid(i,j); COL_IJ_2 = sub2ind([length(i)+1 length(j)],COL_I,COL_J); [COL_IP1 COL_J] = ndgrid(i+1,j); COL_IP1_J = sub2ind([length(i)+1 length(j)],COL_IP1,COL_J); nS2 = (nx-1)*(ny); % Build four indexes arrays that will be used to split x in four parts % 29/08/09 bug corrected offset1p = 0; idx1p = offset1p+(1:nS1); offset1m = idx1p(end); idx1m = offset1m+(1:nS1); offset2p = idx1m(end); idx2p = offset2p+(1:nS2); offset2m = idx2p(end); idx2m = offset2m+(1:nS2); % Equality constraint matrix (Aeq) S1p = + sparse(ROW_I_J, COL_I_JP1,1,nS0,nS1) ... - sparse(ROW_I_J, COL_IJ_1,1,nS0,nS1); S1m = -S1p; S2p = - sparse(ROW_I_J, COL_IP1_J,1,nS0,nS2) ... + sparse(ROW_I_J, COL_IJ_2,1,nS0,nS2); S2m = -S2p; % Matrix of the LHS of eqt (17) Aeq = [S1p S1m S2p S2m]; nvars = size(Aeq,2); % Clean up clear S1p S1m S2p S2m %% % force to be even CutSize = ceil(CutSize/2)*2; % Modify weight to limit the effect of points that violate % the rorational condition. The weight is graduataly increase % around the points. if CutSize>0 % mydisplay(verbose, '\tAdjust weight (CutSize = %d pixels)\n', CutSize); % Truncated Gaussian Kernel v = 1*linspace(-1,1,CutSize); [x y] = meshgrid(v,v); kernel = 1.1*exp(-(x.^2+y.^2)); rotdegradation = double(reshape(beq~=0, [ny nx]-1)); % 0 or 1 %mydisplay(verbose, '\tInconsistency = %d/%d\n', ... % sum(rotdegradation(:)), numel(beq)); rotdegradation = conv2(rotdegradation, kernel, 'full'); rotdegradation = rotdegradation(CutSize/2 + (0:ny-1),... CutSize/2 + (0:nx-1)); % mininum weight threshold wmin = 1e-2; % weight never goes under this value, small positive value rotdegradation = min(rotdegradation,1-wmin); weight = weight .* (1-rotdegradation); end c1 = 0.5*(weight(1:ny-1,:)+weight(1:ny-1,:)); c2 = 0.5*(weight(:,1:nx-1)+weight(:,1:nx-1)); % Cost vector, eqt (16) cost = zeros(nvars,1); cost(idx1p) = c1(:); cost(idx1m) = c1(:); cost(idx2p) = c2(:); cost(idx2m) = c2(:); %% % Lower and upper bound, eqt (18,19) L = zeros(nvars,1); U = Inf(size(L)); % No upper bound, U=[]; %% % Lock the x values to prior computed value (from calculation on other % blocks) i1 = find(~isnan(X1p)); i2 = find(~isnan(X2p)); % Lock method, not documented lockadd = 1; lockremove = 2; %#ok lockmethod = getoption(options, 'lockmethod', lockadd); if lockmethod==lockadd % Lock matrix and values, eqt (26, 27), larger system L1p = sparse(1:length(i1), idx1p(i1), 1, length(i1), size(Aeq,2)); L1m = sparse(1:length(i1), idx1m(i1), 1, length(i1), size(Aeq,2)); L2p = sparse(1:length(i2), idx2p(i2), 1, length(i2), size(Aeq,2)); L2m = sparse(1:length(i2), idx2m(i2), 1, length(i2), size(Aeq,2)); AL = [L1p; L1m; L2p; L2m]; bL = [X1p(i1); X1m(i1); X2p(i2); X2m(i2)]; clear L1p L1m L2p L2m % clean up % Find the rows in Aeq with all variables locked ColPatch = [offset1p+COL_IJ_1(:) offset1p+COL_I_JP1(:) ... offset2p+COL_IJ_2(:) offset2p+COL_IP1_J(:)]; [trash ColDone] = find(AL); %#ok remove = all(ismember(ColPatch, ColDone),2); Aeq = [Aeq(~remove,:); AL]; beq = [beq(~remove,:); bL]; % No need to bother with what already computed cost(idx1p(i1)) = 0; cost(idx1m(i1)) = 0; cost(idx2p(i2)) = 0; cost(idx2m(i2)) = 0; L(idx1p(i1)) = -Inf; L(idx1m(i1)) = -Inf; L(idx2p(i2)) = -Inf; L(idx2m(i2)) = -Inf; clear AL bL trash ColPatch ColDone remove i1 i2 % clean up else % Lock by remove the overlapped variables, smaller system % But *seems* more affected by error propagation % BL think both method should be strictly equivalent (!) % remove the equality contribution from the RHS lock = zeros(nvars,1,class(Aeq)); lock(idx1p(i1)) = X1p(i1); lock(idx1m(i1)) = X1m(i1); lock(idx2p(i2)) = X2p(i2); lock(idx2m(i2)) = X2m(i2); beq = beq - Aeq*lock; % Remove the variables vremove = [idx1p(i1) idx1m(i1) idx2p(i2) idx2m(i2)]; % keep is use later to dispatch partial derivative keep = true(nvars,1); keep(vremove) = false; Aeq(:,vremove) = []; L(vremove) = []; U(vremove) = []; cost(vremove) = []; % Find the rows in Aeq with all variables locked ColPatch = [offset1p+COL_IJ_1(:) offset1p+COL_I_JP1(:) ... offset2p+COL_IJ_2(:) offset2p+COL_IP1_J(:)]; % Remove the equations eremove = all(ismember(ColPatch, vremove),2); Aeq(eremove,:) = []; beq(eremove,:) = []; clear vremove eremove ColPatch lock % clean up end %% % To do: implement Bertsekas/Tseng's relaxation method, ref. [20] % Call LP solver %mydisplay(verbose, '\tMinimum network flow resolution\n'); %mydisplay(verbose, '\t\tmatrix size = (%d,%d)\n', size(Aeq,1),size(Aeq,2)); if ~isempty(which('linprog')) % Call Matlab Linprog % Adjust optional LP options at your preference, see % http://www.mathworks.com/access/helpdesk/help/toolbox/optim/ug/linprog.html % http://www.mathworks.com/access/helpdesk/help/toolbox/optim/ug/optimset.html %mydisplay(verbose, '\tLINPROG...\n'); % BL has not checked because he does not have the right toolbox %LPoption = getoption(options, 'LPoption', {}); LPoptions = optimset('Display','none','Algorithm','interior-point'); % LPoption2 = getoption(options, 'Display', 'none'); if ~iscell(LPoptions) LPoptions = {LPoptions}; end % LPoption = {optimset(...)} sol = linprog(cost,[],[],Aeq,beq,L,U,[],LPoptions{:}); elseif ~isempty(which('BuildMPS')) % Here is BL Linprog, call Matlab linprog instead to get "SOL", % the solution of the above LP problem mpsfile='costantini.mps'; % mydisplay(verbose, '\tConversion to MPS file\n'); Contain = BuildMPS([], [], Aeq, beq, cost, L, U, 'costantini'); OK = SaveMPS(mpsfile,Contain); if ~OK error('CUNWRAP: Cannot write mps file'); end PCxpath=App_path('PCx'); [OK outfile]=invokePCx(mpsfile,PCxpath,verbose==0); if ~OK % mydisplay(verbose, 'PCx path=%s\n', PCxpath); %mydisplay(verbose, 'Cannot invoke LP solver, PCx not installed?\n'); error('CUNWRAP: Cannot invoke PCx'); end [OK sol]=readPCxoutput(outfile); if ~OK error('CUNWRAP: Cannot read PCx outfile, L1 fit might fails.'); end else error('CUNWRAP: cannot detect network flow (LP) engine'); end %% % Displatch the LP solution if lockmethod==lockadd x = sol; else x = zeros(size(keep),class(sol)); x(keep) = sol; end x1p = reshape(x(idx1p), [ny-1 nx]); x1m = reshape(x(idx1m), [ny-1 nx]); x2p = reshape(x(idx2p), [ny nx-1]); x2m = reshape(x(idx2m), [ny nx-1]); end %% Get defaut option function value = getoption(options, name, defaultvalue) % function value = getoption(options, name, defaultvalue) value = defaultvalue; fields = fieldnames(options); found = strcmpi(name,fields); if any(found) i = find(found,1,'first'); if ~isempty(options.(fields{i})) value = options.(fields{i}); end end end %% function [ilist blocksize] = splitidx(blocksize, n, p) % function ilist = splitidx(blocksize, n, p) % % return the cell array, each element is subindex of (1:n) % The union is (1:n) with overlapping fraction is p (0<p<1) if blocksize>=n ilist = {1:n}; blocksize = n; else q = 1-p; % Number of blocks k = (n/blocksize - p) / q; k = ceil(k); % Readjust the block size, float blocksize = n/(k*q + p); % first index firstidx = round(linspace(1,n-ceil(blocksize)+1, k)); lastidx = round(firstidx+blocksize-1); lastidx(end) = n; % Make sure they are overlapped lastidx(1:end-1) = max(lastidx(1:end-1),firstidx(2:end)); % Put the indexes of k blocks into cell array ilist = cell(1,length(firstidx)); for k=1:length(ilist) ilist{k} = firstidx(k):lastidx(k); end blocksize = round(blocksize); end end
github
EPFL-LCSB/matTFA-master
solveTFAmodelCplex.m
.m
matTFA-master/matTFA/solveTFAmodelCplex.m
5,589
utf_8
8ab7d957942db50f3dd288fbaa9e3c70
function sol = solveTFAmodelCplex(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay,CPXPARAMdisp) % Solve a model using specific solver settings. More details in % changeToCPLEX_WithOptions % % INPUTS % tModel: a TFA-ready model (has a .A matrix) % TimeInSec: timelimit for the solver. % manualScalingFactor: manual scaling factor for the solver % mipTolInt: Integer tolerance of the solver % emphPar: Solver emphasis (trade-offs between speed, feasibility, % optimality, and moving bounds in MIP - see https://www.ibm.com/support/knowledgecenter/en/SSSA5P_12.6.0/ilog.odms.cplex.help/CPLEX/Parameters/topics/MIPEmphasis.html) % feasTol: solver tolerance for feasibility (error on constraints) % mipDisplay: verbosity of the MIP info display % CPXPARAMdisp: Turn on/off the cplex problem setup display % %% Changelog % 2017/04/26 - Modified by Pierre on Georgios Fengos's base, to incorporate % Vikash's Gurobi hooks in a more global fashion, in a similar way COBRA % solvers are handled. % Calls the global parameter TFA_MILP_SOLVER, and check if it set to % something. If not, default to CPLEX using Fengos's code. % In the long run, we should rename thins function to remove CPLEX from its % name. % TODO : Add parameter setting in gurobi call % global TFA_MILP_SOLVER if ~exist('TFA_MILP_SOLVER','var') || isempty(TFA_MILP_SOLVER) TFA_MILP_SOLVER = 'cplex_direct'; end solver = TFA_MILP_SOLVER; % solver = 'gurobi_direct'; if ~exist('manualScalingFactor','var') || isempty(manualScalingFactor) manualScalingFactor = []; end if ~exist('mipTolInt','var') || isempty(mipTolInt) mipTolInt = []; end if ~exist('emphPar','var') || isempty(emphPar) emphPar = []; end if ~exist('feasTol','var') || isempty(feasTol) feasTol = []; end if ~exist('scalPar','var') || isempty(scalPar) scalPar = []; end if ~exist('TimeInSec','var') || isempty(TimeInSec) TimeInSec = []; end if ~exist('mipDisplay','var') || isempty(mipDisplay) mipDisplay = []; end if ~exist('CPXPARAMdisp','var') || isempty(CPXPARAMdisp) CPXPARAMdisp = []; end switch solver %% Case CPLEX case 'cplex_direct' if isempty(which('cplex.p')) error('You need to add CPLEX to the Matlab-path!!') end sol = x_solveCplex(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay,CPXPARAMdisp); %% Case GUROBI case 'gurobi_direct' if isempty(which('gurobi')) error('You need to add Gurobi to the Matlab-path!!') end sol = x_solveGurobi(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay); end end %% Private function for CPLEX solve function sol = x_solveCplex(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay,CPXPARAMdisp) % this function solves a TFBA problem using CPLEX % if cplex is installed, and in the path if isempty(which('cplex.m')) error('cplex is either not installed or not in the path') end % Convert problem to cplex cplex = changeToCPLEX_WithOptions(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay,CPXPARAMdisp); % Optimize the problem try CplexSol = cplex.solve(); if isfield(cplex.Solution,'x') x = cplex.Solution.x; if ~isempty(x) sol.x = cplex.Solution.x; sol.val = cplex.Solution.objval; sol.cplexSolStatus = cplex.Solution.status; else sol.x = []; sol.val = []; disp('Empty solution'); warning('Cplex returned an empty solution!') sol.cplexSolStatus = 'Empty solution'; end else sol.x = []; sol.val = []; disp('No field cplex.Solution.x'); warning('The solver does not return a solution!') sol.cplexSolStatus = 'No field cplex.Solution.x'; end catch sol.x = NaN; sol.val = NaN; sol.cplexSolStatus = 'Solver crashed'; end delete(cplex) end %% Private function for GUROBI solve function sol = x_solveGurobi(tModel,TimeInSec,manualScalingFactor,mipTolInt,emphPar,feasTol,scalPar,mipDisplay) num_constr = length(tModel.constraintType); num_vars = length(tModel.vartypes); contypes = ''; vtypes = ''; % convert contypes and vtypes into the right format for i=1:num_constr contypes = strcat(contypes,tModel.constraintType{i,1}); end for i=1:num_vars vtypes = strcat(vtypes,tModel.vartypes{i,1}); end % TODO: Add Solver settings gmodel.A=tModel.A; gmodel.obj=tModel.f; gmodel.lb=tModel.var_lb; gmodel.ub=tModel.var_ub; gmodel.rhs=tModel.rhs; gmodel.sense=contypes; gmodel.vtype=vtypes; gmodel.varnames=tModel.varNames; if tModel.objtype==-1 gmodel.modelsense='max' elseif tModel.objtype==1 gmodel.modelsense='min' else error(['No objective type specified ' ... '(model.objtype should be in {-1,1})']); end try result=gurobi(gmodel); if isfield(result,'x') x = result.x; x(find(abs(x) < 1E-9))=0; else warning('The solver does not return a solution!') result.x=[]; result.objval=[]; end catch result.status='0'; x=NaN; result.x=NaN; result.objval=NaN; end sol.x=result.x; sol.val=result.objval; sol.status=result.status; % TODO: Add exitflag translation end
github
EPFL-LCSB/matTFA-master
solveFBAmodelCplex.m
.m
matTFA-master/matTFA/solveFBAmodelCplex.m
30,450
utf_8
6e803c4720697333350bcd6e8563f5b5
function FBAsolution = solveFBAmodelCplex(model, scalPar, feasTol, emphPar, osenseStr) %optimizeCbModel Solve a flux balance analysis problem % % Georgios Fengos 24/05/2016 Created this version of optimizeCbModel % to be able to control externally the cplex parameters %% Process arguments and set up problem if ~exist('osenseStr','var') osenseStr = 'max'; end allowLoops = true; if ~exist('scalPar','var') || isempty(scalPar) scalPar = []; end if ~exist('feasTol','var') || isempty(feasTol) feasTol = []; end if ~exist('emphPar','var') || isempty(emphPar) emphPar = []; end [minNorm, printLevel, primalOnlyFlag, ~] = getCobraSolverParams('LP',{'minNorm','printLevel','primalOnly','saveInput'}); % Figure out objective sense if strcmpi(osenseStr,'max') LPproblem.osense = -1; else LPproblem.osense = +1; end [nMets,nRxns] = size(model.S); % add csense %Doing this makes csense a double array. Totally smart design move. %LPproblem.csense = []; if ~isfield(model,'csense') % If csense is not declared in the model, assume that all % constraints are equalities. LPproblem.csense(1:nMets,1) = 'E'; else % if csense is in the model, move it to the lp problem structure if length(model.csense)~=nMets, warning('Length of csense is invalid! Defaulting to equality constraints.') LPproblem.csense(1:nMets,1) = 'E'; else model.csense = columnVector(model.csense); LPproblem.csense = model.csense; end end % Fill in the RHS vector if not provided if (~isfield(model,'b')) LPproblem.b = zeros(size(model.S,1),1); else LPproblem.b = model.b; end % Rest of the LP problem LPproblem.A = model.S; LPproblem.c = model.c; LPproblem.lb = model.lb; LPproblem.ub = model.ub; %Double check that all inputs are valid: if ~(verifyCobraProblem(LPproblem, [], [], false) == 1) warning('invalid problem'); return; end %% t1 = clock; % Solve initial LP % if allowLoops solution = solveCobraLP_edited(LPproblem,scalPar,feasTol,emphPar); % else % MILPproblem = addLoopLawConstraints(LPproblem, model, 1:nRxns); % solution = solveCobraMILP(MILPproblem); % end if (solution.stat ~= 1) % check if initial solution was successful. if printLevel>0 warning('Optimal solution was not found'); end FBAsolution.f = 0; FBAsolution.x = []; FBAsolution.stat = solution.stat; FBAsolution.origStat = solution.origStat; FBAsolution.solver = solution.solver; FBAsolution.time = etime(clock, t1); return; end objective = solution.obj; % save for later use. % Store results if (solution.stat == 1) %solution found. FBAsolution.x = solution.full(1:nRxns); %this line IS necessary. FBAsolution.f = model.c'*solution.full(1:nRxns); %objective from original optimization problem. if abs(FBAsolution.f - objective) > .01 display('warning: objective appears to have changed while performing secondary optimization (minNorm)'); end if (~primalOnlyFlag && allowLoops && any(~minNorm)) % rcost/dual only correct if not doing minNorm FBAsolution.y = solution.dual; FBAsolution.w = solution.rcost; end else %some sort of error occured. if printLevel>0 warning('Optimal solution was not found'); end FBAsolution.f = 0; FBAsolution.x = []; end FBAsolution.stat = solution.stat; FBAsolution.origStat = solution.origStat; FBAsolution.solver = solution.solver; FBAsolution.time = etime(clock, t1); end function solution = solveCobraLP_edited(LPproblem,scalPar,feasTol,emphPar) % solveCobraLP Solve constraint-based LP problems % Georgios Fengos 24/05/2016 Created this version of solveCobraLP % to be able to control externally the cplex parameters global CBTLPSOLVER if (~isempty(CBTLPSOLVER)) solver = CBTLPSOLVER; else error('No solver found. call changeCobraSolver(solverName)'); end optParamNames = {'minNorm','printLevel','primalOnly','saveInput', ... 'feasTol','optTol','EleNames','EqtNames','VarNames','EleNameFun', ... 'EqtNameFun','VarNameFun','PbName','MPSfilename'}; parameters = ''; % if nargin ~=1 % if mod(length(varargin),2)==0 % for i=1:2:length(varargin)-1 % if ismember(varargin{i},optParamNames) % parameters.(varargin{i}) = varargin{i+1}; % else % error([varargin{i} ' is not a valid optional parameter']); % end % end % elseif strcmp(varargin{1},'default') % parameters = 'default'; % elseif isstruct(varargin{1}) % parameters = varargin{1}; % else % display('Warning: Invalid number of parameters/values') % solution=[]; % return; % end % end [minNorm, printLevel, ~, saveInput, ~, ~] = ... getCobraSolverParams('LP',optParamNames(1:6),parameters); %Save Input if selected if ~isempty(saveInput) fileName = parameters.saveInput; if ~find(regexp(fileName,'.mat')) fileName = [fileName '.mat']; end display(['Saving LPproblem in ' fileName]); save(fileName,'LPproblem') end % [A,b,c,lb,ub,csense,osense] = deal(LPproblem.A,LPproblem.b,LPproblem.c,LPproblem.lb,LPproblem.ub,LPproblem.csense,LPproblem.osense); % if any(any(~isfinite(A))) % error('Cannot perform LP on a stoichiometric matrix with NaN of Inf coefficents.') % end % Defaults in case the solver does not return anything f = []; x = []; y = []; w = []; origStat = -99; stat = -99; t_start = clock; switch solver case 'cplex_direct' %% Tomlab cplex.m direct %Used with the current script, only some of the control affoarded with %this interface is provided. Primarily, this is to change the print %level and whether to minimise the Euclidean Norm of the internal %fluxes or not. %See solveCobraLPCPLEX.m for more refined control of cplex %Ronan Fleming 11/12/2008 if isfield(LPproblem,'basis') && ~isempty(LPproblem.basis) LPproblem.LPBasis = LPproblem.basis; end [solution LPprob] = solveCobraLPCPLEX_edited(LPproblem,printLevel,1,[],[],minNorm,scalPar,feasTol,emphPar); solution.basis = LPprob.LPBasis; solution.solver = solver; case 'gurobi5' %% Gurobi direct % 2017/04/26 Added by Pierre % TODO : Get the LP basis ? if isfield(LPproblem,'basis') && ~isempty(LPproblem.basis) LPproblem.LPBasis = LPproblem.basis; end [solution LPprob] = solveCobraLPGurobi(LPproblem,printLevel,1,[],[],minNorm,scalPar,feasTol,emphPar); solution.basis = [];%LPprob.LPBasis; solution.solver = solver; otherwise error(['Unknown solver: ' solver]); end if ~strcmp(solver,'cplex_direct') && ~strcmp(solver,'mps') %% Assign solution t = etime(clock, t_start); if ~exist('basis','var'), basis=[]; end [solution.full,solution.obj,solution.rcost,solution.dual,solution.solver,solution.stat,solution.origStat,solution.time,solution.basis] = ... deal(x,f,w,y,solver,stat,origStat,t,basis); end end function [solution,LPproblem] = solveCobraLPCPLEX_edited(LPproblem,printLevel,basisReuse,conflictResolve,contFunctName,minNorm,scalPar,feasTol,emphPar) % [solution,LPproblem]=solveCobraLPCPLEX(LPproblem,printLevel,basisReuse,conflictResolve,contFunctName,minNorm) % Georgios Fengos 24/05/2016 Created this version of solveCobraLPCPLEX % to be able to control externally the cplex parameters if ~exist('printLevel','var') printLevel=2; end if ~exist('basisReuse','var') basisReuse=0; end if ~exist('conflictResolve','var') conflictResolve=0; end if ~exist('contFunctName','var') cpxControl=[]; else if isstruct(contFunctName) cpxControl=contFunctName; else if ~isempty(contFunctName) %calls a user specified function to create a CPLEX control structure %specific to the users problem. A TEMPLATE for one such function is %CPLEXParamSet cpxControl=eval(contFunctName); else cpxControl=[]; end end end if ~exist('minNorm','var') minNorm=0; end if basisReuse if isfield(LPproblem,'LPBasis') basis=LPproblem.LPBasis; %use advanced starting information when optimization is initiated. cpxControl.ADVIND=1; else basis=[]; end else basis=[]; %do not use advanced starting information when optimization is initiated. cpxControl.ADVIND=0; end if ~isfield(LPproblem,'A') if ~isfield(LPproblem,'S') error('Equality constraint matrix must either be a field denoted A or S.') end LPproblem.A=LPproblem.S; end if ~isfield(LPproblem,'csense') nMet=size(LPproblem.A); if printLevel>0 fprintf('%s\n','Assuming equality constraints, i.e. S*v=b'); end %assuming equality constraints LPproblem.csense(1:nMet,1)='E'; end if ~isfield(LPproblem,'osense') %assuming maximisation LPproblem.osense=-1; if printLevel>0 fprintf('%s\n','Assuming maximisation of objective'); end end %get data [c,x_L,x_U,b,csense,osense] = deal(LPproblem.c,LPproblem.lb,LPproblem.ub,LPproblem.b,LPproblem.csense,LPproblem.osense); %modify objective to correspond to osense c=full(c*osense); %cplex expects it dense b=full(b); %Conflict groups descriptor (cpxBuildConflict can be used to generate the input). Set this if %conflict refinement is desired in the case that infeasibility is detected %by CPLEX. if conflictResolve [m_lin,n]=size(LPproblem.A); m_quad=0; m_sos=0; m_log=0; %determines how elaborate the output is mode='full';%'minimal'; fprintf('%s\n%s\n','Building Structure for Conflict Resolution...','...this slows CPLEX down so should not be used for repeated LP'); confgrps = cpxBuildConflict(n,m_lin,m_quad,m_sos,m_log,mode); prefix=pwd; suffix='LP_CPLEX_conflict_file.txt'; conflictFile=[prefix '\' suffix]; else confgrps=[]; conflictFile=[]; end %Name of file to write the CPLEX log information to. If empty, no log is %written. logfile=[]; %Name of a file to save the CPLEX problem object (Used for submitting %possible bugs in CPLEX to ILOG) savefile=[]; savemode=[]; % savefile='C:\CPLEX_possible_bug.txt'; % vector defining which callbacks to use in CPLEX. If the ith entry of the logical vector % callback is set, the corresponding callback is defined. The callback calls the m-file specified % in Table 7 below. The user may edit this file, or make a new copy, which is put in a directory % that is searched before the cplex directory in the Matlab path. callback=[]; %I'm not really sure what this option means as yet %this is not a tomlab problem so this is not needed Prob=[]; % variables not used in LP problems IntVars=[]; PI=[]; SC=[]; SI=[]; sos1=[]; sos2=[]; %quadratic constraint matrix, size n x n if sum(minNorm)~=0 if length(minNorm)==1 % same weighting of min norm for all variables F=speye(length(c))*minNorm; else if length(minNorm)~=length(c) error('Either minNorm is a scalar, or is an n x 1 vector') else % individual weighting of min norm for all variables F=spdiags(minNorm,0,length(c),length(c)); end end else F=[]; end %Structure array defining quadratic constraints qc=[]; %Structure telling whether and how you want CPLEX to perform a sensitivity analysis (SA). %This may be useful in future but probably will have more meaning with an %additional term in the objective saRequest =[]; %Vector with MIP starting solution, if known xIP=[]; %Logical constraints, i.e. an additional set of single-sided linear constraints that are controlled %by a binary variable (switch) in the problem logcon=[]; %call cplex tic; %tic; %by default use the complex ILOG-CPLEX interface ILOGcomplex=1; tomlab_cplex=0; %by default DO NOT use the tomlab_cplex interface if ~isempty(which('cplexlp')) && tomlab_cplex==0 if ILOGcomplex %complex ibm ilog cplex interface if ~isempty(csense) %set up constant vectors for CPLEX b_L(csense == 'E',1) = b(csense == 'E'); b_U(csense == 'E',1) = b(csense == 'E'); b_L(csense == 'G',1) = b(csense == 'G'); b_U(csense == 'G',1) = Inf; b_L(csense == 'L',1) = -Inf; b_U(csense == 'L',1) = b(csense == 'L'); else b_L = b; b_U = b; end % Initialize the CPLEX object try ILOGcplex = Cplex('fba'); catch ME error('CPLEX not installed or licence server not up') end ILOGcplex.Model.sense = 'minimize'; % Now populate the problem with the data ILOGcplex.Model.obj = c; ILOGcplex.Model.lb = x_L; ILOGcplex.Model.ub = x_U; if isfield(ILOGcplex.Model,'S') ILOGcplex.Model.A = LPproblem.S; elseif isfield(ILOGcplex.Model,'A') ILOGcplex.Model.A = LPproblem.A; end ILOGcplex.Model.lhs = b_L; ILOGcplex.Model.rhs = b_U; if ~isempty(F) %quadratic constraint matrix, size n x n ILOGcplex.Model.Q=F; end if ~isempty(cpxControl) if isfield(cpxControl,'LPMETHOD') %set the solver ILOGcplex.Param.lpmethod.Cur=cpxControl.LPMETHOD; end end if printLevel==0 ILOGcplex.DisplayFunc=[]; else %print level ILOGcplex.Param.barrier.display.Cur = printLevel; ILOGcplex.Param.simplex.display.Cur = printLevel; ILOGcplex.Param.sifting.display.Cur = printLevel; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% EDITED BY GF >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % |---------------------------| % | SCALING (PRECONDITIONING) | % |---------------------------| % Sometimes it can happen that the solver finds a solution, but % because of bad scaling (preconditioning) it does not return the % actual solution to the user, but an empty solution instead. % |-------------------------------------------| % | Value : Meaning | % |-------------------------------------------| % | -1 : No scaling | % | 0 : Equilibration scaling | % | 1 : More aggressive scaling (default) | % |-------------------------------------------| % To avoid this, we change the default of these parameter to no % scaling: if ~exist('scalPar','var') || isempty(scalPar) % LCSB default scalPar = -1; else if ~ismember(scalPar,[-1 0 1]) error('Parameter value out of range!') end end ILOGcplex.Param.read.scale.Cur = scalPar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % |-----------------------| % | FEASIBILITY TOLERANCE | % |-----------------------| % Specifies the feasibility tolerance, that is, the degree to which % values of the basic variables calculated by the simplex method may % violate their bounds. CPLEX? does not use this tolerance to relax the % variable bounds nor to relax right hand side values. This parameter % specifies an allowable violation. Feasibility influences the selection % of an optimal basis and can be reset to a higher value when a problem is % having difficulty maintaining feasibility during optimization. You can % also lower this tolerance after finding an optimal solution if there is % any doubt that the solution is truly optimal. If the feasibility tolerance % is set too low, CPLEX may falsely conclude that a problem is infeasible. % If you encounter reports of infeasibility during Phase II of the % optimization, a small adjustment in the feasibility tolerance may % improve performance. % |-------------------------------------------| % | Values : | % |-------------------------------------------| % | Range : from 1e-9 to 1e-1 | % | Cplex-Default: 1e-06 | % |-------------------------------------------| if ~exist('feasTol','var') || isempty(feasTol) % LCSB default feasTol = 1e-9; else if feasTol < 1e-9 || feasTol > 1e-1 error('Parameter value out of range!') end end ILOGcplex.Param.simplex.tolerances.feasibility.Cur = feasTol; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % |-----------------------| % | EMPHASIS ON PRECISION | % |-----------------------| % Emphasizes precision in numerically unstable or difficult problems. % This parameter lets you specify to CPLEX that it should emphParasize % precision in numerically difficult or unstable problems, with % consequent performance trade-offs in time and memory. % |-----------------------------------------------------------| % | Values : Meaning | % |-----------------------------------------------------------| % | 0 : Do not emphasize numerical precision; cplex-default | % | 1 : Exercise extreme caution in computation | % |-----------------------------------------------------------| if ~exist('emphPar','var') || isempty(emphPar) % LCSB default emphPar = 1; else if ~ismember(emphPar,[0 1]) error('Parameter value out of range!') end end ILOGcplex.Param.emphasis.numerical.Cur = emphPar; %<<<<<<<<<<<<<< EDITED BY GF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Optimize the problem ILOGcplex.solve(); if isfield(ILOGcplex.Solution, 'objval') solution.obj = osense*ILOGcplex.Solution.objval; solution.full = ILOGcplex.Solution.x; solution.rcost = ILOGcplex.Solution.reducedcost; solution.dual = ILOGcplex.Solution.dual; solution.nInfeas = NaN; solution.sumInfeas = NaN; %solution.stat = ILOGcplex.Solution. solution.origStat = ILOGcplex.Solution.status; solution.solver = ILOGcplex.Solution.method; solution.time = ILOGcplex.Solution.time; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% EDITED BY GF >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % I got this from somebody elses code, and thought it is a good % idea to avoid crashing if it is infeasible solution.obj = []; solution.full = []; solution.rcost = []; solution.dual = []; solution.nInfeas = NaN; solution.sumInfeas = NaN; %solution.stat = ILOGcplex.Solution. solution.origStat = []; solution.solver = []; solution.time = []; end %<<<<<<<<<<<<<< EDITED BY GF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else try ILOGcplex = Cplex('fba'); catch ME error('CPLEX not installed or licence server not up') end %simple ibm ilog cplex interface options = cplexoptimset; switch printLevel case 0 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); end if ~isempty(csense) if sum(minNorm)~=0 Aineq = [LPproblem.A(csense == 'L',:); - LPproblem.A(csense == 'G',:)]; bineq = [b(csense == 'L',:); - b(csense == 'G',:)]; % min 0.5*x'*H*x+f*x or f*x % st. Aineq*x <= bineq % Aeq*x = beq % lb <= x <= ub [x,fval,exitflag,output,lambda] = cplexqp(F,c,Aineq,bineq,LPproblem.A(csense == 'E',:),b(csense == 'E',1),x_L,x_U,[],options); else Aineq = [LPproblem.A(csense == 'L',:); - LPproblem.A(csense == 'G',:)]; bineq = [b(csense == 'L',:); - b(csense == 'G',:)]; % min c*x % st. Aineq*x <= bineq % Aeq*x = beq % lb <= x <= ub [x,fval,exitflag,output,lambda] = cplexlp(c,Aineq,bineq,LPproblem.A(csense == 'E',:),b(csense == 'E',1),x_L,x_U,[],options); end %primal solution.obj=osense*fval; solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=lambda.eqlin; else Aineq=[]; bineq=[]; if sum(minNorm)~=0 [x,fval,exitflag,output,lambda] = cplexqp(F,c,Aineq,bineq,LPproblem.A,b,x_L,x_U,[],options); else [x,fval,exitflag,output,lambda] = cplexlp(c,Aineq,bineq,LPproblem.A,b,x_L,x_U,[],options); end solution.obj=osense*fval; solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=sparse(size(LPproblem.A,1),1); solution.dual(csense == 'E')=lambda.eqlin; %this is the dual to the inequality constraints but it's not the chemical potential solution.dual(csense == 'L')=lambda.ineqlin(1:nnz(csense == 'L'),1); solution.dual(csense == 'G')=lambda.ineqlin(nnz(csense == 'L')+1:end,1); end %this is the dual to the simple ineequality constraints : reduced costs solution.rcost=lambda.lower-lambda.upper; solution.nInfeas = []; solution.sumInfeas = []; solution.origStat = output.cplexstatus; end %1 = (Simplex or Barrier) Optimal solution is available. Inform = solution.origStat; else %tomlab cplex interface if ~isempty(csense) %set up constant vectors for CPLEX b_L(csense == 'E',1) = b(csense == 'E'); b_U(csense == 'E',1) = b(csense == 'E'); b_L(csense == 'G',1) = b(csense == 'G'); b_U(csense == 'G',1) = Inf; b_L(csense == 'L',1) = -Inf; b_U(csense == 'L',1) = b(csense == 'L'); else b_L = b; b_U = b; end %tomlab cplex interface % minimize 0.5 * x'*F*x + c'x subject to: % x x_L <= x <= x_U % b_L <= Ax <= b_U [x, slack, v, rc, f_k, ninf, sinf, Inform, basis] = cplex(c, LPproblem.A, x_L, x_U, b_L, b_U, ... cpxControl, callback, printLevel, Prob, IntVars, PI, SC, SI, ... sos1, sos2, F, logfile, savefile, savemode, qc, ... confgrps, conflictFile, saRequest, basis, xIP, logcon); solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=v; %this is the dual to the simple ineequality constraints : reduced costs solution.rcost=rc; if Inform~=1 solution.obj = NaN; else if minNorm==0 solution.obj=f_k*osense; else solution.obj=c'*x*osense; end % solution.obj % norm(x) end solution.nInfeas = ninf; solution.sumInfeas = sinf; solution.origStat = Inform; end %timeTaken=toc; timeTaken=NaN; if Inform~=1 && ~isempty(which('cplex')) if conflictResolve ==1 if isfield(LPproblem,'mets') && isfield(LPproblem,'rxns') %this code reads the conflict resolution file and replaces the %arbitrary names with the abbreviations of metabolites and reactions [nMet,nRxn]=size(LPproblem.A); totAbbr=nMet+nRxn; conStrFind=cell(nMet+nRxn,1); conStrReplace=cell(nMet+nRxn,1); %only equality constraint rows for m=1:nMet conStrFind{m,1}=['c' int2str(m) ':']; conStrReplace{m,1}=[LPproblem.mets{m} ': ']; end %reactions for n=1:nRxn conStrFind{nMet+n,1}=['x' int2str(n) ' ']; conStrReplace{nMet+n,1}=[LPproblem.rxns{n} ' ']; end fid1 = fopen(suffix); fid2 = fopen(['COBRA_' suffix], 'w'); while ~feof(fid1) tline{1}=fgetl(fid1); %replaces all occurrences of the string str2 within string str1 %with the string str3. %str= strrep(str1, str2, str3) for t=1:totAbbr tline= strrep(tline, conStrFind{t}, conStrReplace{t}); end fprintf(fid2,'%s\n', tline{1}); end fclose(fid1); fclose(fid2); %delete other file without replacements % delete(suffix) else warning('Need reaction and metabolite abbreviations in order to make a readable conflict resolution file'); end fprintf('%s\n',['Conflict resolution file written to: ' prefix '\COBRA_' suffix]); fprintf('%s\n%s\n','The Conflict resolution file gives an irreducible infeasible subset ','of constraints which are making this LP Problem infeasible'); else if printLevel>0 fprintf('%s\n','No conflict resolution file. Perhaps set conflictResolve = 1 next time.'); end end solution.solver = 'cplex_direct'; end % Try to give back COBRA Standardized solver status: % 1 Optimal solution % 2 Unbounded solution % 0 Infeasible % -1 No solution reported (timelimit, numerical problem etc) if Inform==1 solution.stat = 1; if printLevel>0 %use tomlab code to print out exit meassage % [ExitText,ExitFlag] = cplexStatus(Inform); % solution.ExitText=ExitText; % solution.ExitFlag=ExitFlag; % fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); end else if Inform==2 solution.stat = 2; %use tomlab code to print out exit meassage % [ExitText,ExitFlag] = cplexStatus(Inform); % solution.ExitText=ExitText; % solution.ExitFlag=ExitFlag; % fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); else if Inform==3 solution.stat = 0; else %this is a conservative view solution.stat = -1; %use tomlab code to print out exit meassage % [ExitText,ExitFlag] = cplexStatus(Inform); % solution.ExitText=ExitText; % solution.ExitFlag=ExitFlag; % fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); end end end solution.time = timeTaken; %return basis if basisReuse LPproblem.LPBasis=basis; end if sum(minNorm)~=0 fprintf('%s\n','This objective corresponds to a flux with minimum Euclidean norm.'); fprintf('%s%d%s\n','The weighting for minimising the norm was ',minNorm,'.'); fprintf('%s\n','Check that the objective is the same without minimising the norm.'); end end function [solution,LPproblem] = solveCobraLPGurobi(LPproblem,printLevel,basisReuse,conflictResolve,contFunctName,minNorm,scalPar,feasTol,emphPar) %% gurobi5 / gurobi_direct % 2017/04/26 Pierre: Adding this as part of an effort to ad dgurobi hooks % in our functions. Adapted code from cobra/OptimizeCbModel.m % TODO: Add the same level of control as with the CPLEX interface written % by Georgios Fengos % Free academic licenses for the Gurobi solver can be obtained from % http://www.gurobi.com/html/academic.html solution = struct('x',[],'objval',[],'pi',[]); LPproblem.A = deal(sparse(LPproblem.A)); clear params % Use the default parameter settings if printLevel == 0 params.OutputFlag = 0; params.DisplayInterval = 1; else params.OutputFlag = 1; params.DisplayInterval = 5; end if exist('feasTol','var') & ~isempty(feasTol) params.FeasibilityTol = feasTol; end % params.OptimalityTol = optTol; if (isempty(LPproblem.csense)) clear LPproblem.csense LPproblem.csense(1:length(b),1) = '='; else LPproblem.csense(LPproblem.csense == 'L') = '<'; LPproblem.csense(LPproblem.csense == 'G') = '>'; LPproblem.csense(LPproblem.csense == 'E') = '='; LPproblem.csense = LPproblem.csense(:); end if LPproblem.osense == -1 LPproblem.osense = 'max'; else LPproblem.osense = 'min'; end LPproblem.modelsense = LPproblem.osense; [LPproblem.rhs,LPproblem.obj,LPproblem.sense] = deal(LPproblem.b,double(LPproblem.c),LPproblem.csense); solution = gurobi(LPproblem,params); % if strcmp(solution.status,'OPTIMAL') % stat = 1; % Optimal solution found % [x,f,y] = deal(solution.x,solution.objval,solution.pi); % elseif strcmp(solution.status,'INFEASIBLE') % stat = 0; % Infeasible % elseif strcmp(solution.status,'UNBOUNDED') % stat = 2; % Unbounded % elseif strcmp(solution.status,'INF_OR_UNBD') % stat = 0; % Gurobi reports infeasible *or* unbounded % else % stat = -1; % Solution not optimal or solver problem % end end
github
EPFL-LCSB/matTFA-master
splitString.m
.m
matTFA-master/matTFA/utilities/splitString.m
1,729
utf_8
d9ebd7e1d412e1d0b9832c5f9c1f89f6
function fields = splitString(string,delimiter) %splitString Splits a string Perl style % % fields = splitString(string,delimiter) % % string Either a single string or a cell array of strings % delimiter Splitting delimiter % % fields Either a single cell array of fields or a cell array of cell % arrays of fields % % Default delimiter is '\s' (whitespace) % Delimiters are perl regular expression style, e.g. '|' has to be expressed % as '\|' % Results are returned in the cell array fields % % 07/14/04 Markus Herrgard if (nargin < 2) delimiter = '\s'; end % Check if this is a list of strings or just a single string if iscell(string) stringList = string; for i = 1:length(stringList) fields{i} = splitOneString(stringList{i},delimiter); end else fields = splitOneString(string,delimiter); end fields = columnVector(fields); %% function fields = splitOneString(string,delimiter) % Internal function that splits one string [startIndex,endIndex] = regexp(string,delimiter); if (~isempty(startIndex)) cnt = 0; for i = 1:length(startIndex)+1 if (i == 1) if (endIndex(i) > 1) cnt = cnt + 1; fields{cnt} = string(1:endIndex(i)-1); end elseif (i == length(startIndex)+1) if (startIndex(i-1) < length(string)) cnt = cnt + 1; fields{cnt} = string(startIndex(i-1)+1:end); end else cnt = cnt + 1; fields{cnt} = string(startIndex(i-1)+1:endIndex(i)-1); end end else fields{1} = string; end fieldsOut = {}; cnt = 0; for i = 1:length(fields) if (~isempty(fields{i})) cnt = cnt+1; fieldsOut{cnt} = fields{i}; end end fields = fieldsOut;
github
EPFL-LCSB/matTFA-master
strescape.m
.m
matTFA-master/matTFA/utilities/MatlabBuiltInFunctions/strescape.m
1,148
utf_8
e50bfb2ad948fb14d6732ec00fbd2b6a
function escapedStr = strescape(str) %STRESCAPE Escape control character sequences in a string. % STRESCAPE(STR) converts the escape sequences in a string to the values % they represent. % % Example: % % strescape('Hello World\n') % % See also SPRINTF. % Copyright 2012 The MathWorks, Inc. escapeFcn = @escapeChar; %#ok<NASGU> escapedStr = regexprep(str, '\\(.|$)', '${escapeFcn($1)}'); end %-------------------------------------------------------------------------- function c = escapeChar(c) switch c case '0' % Null. c = char(0); case 'a' % Alarm. c = char(7); case 'b' % Backspace. c = char(8); case 'f' % Form feed. c = char(12); case 'n' % New line. c = char(10); case 'r' % Carriage return. c = char(13); case 't' % Horizontal tab. c = char(9); case 'v' % Vertical tab. c = char(11); case '\' % Backslash. case '' % Unescaped trailing backslash. c = '\'; otherwise warning(message('MATLAB:strescape:InvalidEscapeSequence', c, c)); end end
github
EPFL-LCSB/matTFA-master
strsplit.m
.m
matTFA-master/matTFA/utilities/MatlabBuiltInFunctions/strsplit.m
4,356
utf_8
27145ac2a6cf2a3d7f3e9c0f300d34e3
function [c, matches] = strsplit(str, aDelim, varargin) %STRSPLIT Split string at delimiter % C = STRSPLIT(S) splits the string S at whitespace into the cell array % of strings C. % % C = STRSPLIT(S, DELIMITER) splits S at DELIMITER into C. DELIMITER can % be a string or a cell array of strings. If DELIMITER is a cell array of % strings, STRSPLIT splits S along the elements in DELIMITER, in the % order in which they appear in the cell array. % % C = STRSPLIT(S, DELIMITER, PARAM1, VALUE1, ... PARAMN, VALUEN) modifies % the way in which S is split at DELIMITER. % Valid parameters are: % 'CollapseDelimiters' - If true (default), consecutive delimiters in S % are treated as one. If false, consecutive delimiters are treated as % separate delimiters, resulting in empty string '' elements between % matched delimiters. % 'DelimiterType' - DelimiterType can have the following values: % 'Simple' (default) - Except for escape sequences, STRSPLIT treats % DELIMITER as a literal string. % 'RegularExpression' - STRSPLIT treats DELIMITER as a regular % expression. % In both cases, DELIMITER can include the following escape % sequences: % \\ Backslash % \0 Null % \a Alarm % \b Backspace % \f Form feed % \n New line % \r Carriage return % \t Horizontal tab % \v Vertical tab % % [C, MATCHES] = STRSPLIT(...) also returns the cell array of strings % MATCHES containing the DELIMITERs upon which S was split. Note that % MATCHES always contains one fewer element than C. % % Examples: % % str = 'The rain in Spain stays mainly in the plain.'; % % % Split on all whitespace. % strsplit(str) % % {'The', 'rain', 'in', 'Spain', 'stays', % % 'mainly', 'in', 'the', 'plain.'} % % % Split on 'ain'. % strsplit(str, 'ain') % % {'The r', ' in Sp', ' stays m', 'ly in the pl', '.'} % % % Split on ' ' and on 'ain' (treating multiple delimiters as one). % strsplit(str, {' ', 'ain'}) % % ('The', 'r', 'in', 'Sp', 'stays', % % 'm', 'ly', 'in', 'the', 'pl', '.'} % % % Split on all whitespace and on 'ain', and treat multiple % % delimiters separately. % strsplit(str, {'\s', 'ain'}, 'CollapseDelimiters', false, ... % 'DelimiterType', 'RegularExpression') % % {'The', 'r', '', 'in', 'Sp', '', 'stays', % % 'm', 'ly', 'in', 'the', 'pl', '.'} % % See also REGEXP, STRFIND, STRJOIN. % Copyright 2012-2014 The MathWorks, Inc. narginchk(1, Inf); % Initialize default values. collapseDelimiters = true; delimiterType = 'Simple'; % Check input arguments. if ~ischar(str) error(message('MATLAB:strsplit:InvalidStringType')); end if nargin < 2 delimiterType = 'RegularExpression'; aDelim = {'\s'}; elseif ischar(aDelim) aDelim = {aDelim}; elseif ~iscellstr(aDelim) error(message('MATLAB:strsplit:InvalidDelimiterType')); end if nargin > 2 funcName = mfilename; p = inputParser; p.FunctionName = funcName; p.addParameter('CollapseDelimiters', collapseDelimiters); p.addParameter('DelimiterType', delimiterType); p.parse(varargin{:}); collapseDelimiters = verifyScalarLogical(p.Results.CollapseDelimiters, ... funcName, 'CollapseDelimiters'); delimiterType = validatestring(p.Results.DelimiterType, ... {'RegularExpression', 'Simple'}, funcName, 'DelimiterType'); end % Handle DelimiterType. if strcmp(delimiterType, 'Simple') % Handle escape sequences and translate. aDelim = strescape(aDelim); aDelim = regexptranslate('escape', aDelim); else % Check delimiter for regexp warnings. regexp('', aDelim, 'warnings'); end % Handle multiple delimiters. aDelim = strjoinTGL(aDelim, '|'); % Handle CollapseDelimiters. if collapseDelimiters aDelim = ['(?:', aDelim, ')+']; end % Split. [c, matches] = regexp(str, aDelim, 'split', 'match'); end %-------------------------------------------------------------------------- function tf = verifyScalarLogical(tf, funcName, parameterName) if isscalar(tf) && isnumeric(tf) && any(tf == [0, 1]) tf = logical(tf); else validateattributes(tf, {'logical'}, {'scalar'}, funcName, parameterName); end end
github
EPFL-LCSB/matTFA-master
generateDoc.m
.m
matTFA-master/ext/Cobra205_vDec2014/generateDoc.m
3,858
utf_8
fdb222d907785762dddb4a82c06b02f7
function generateDoc(pathname, graph) %generateDoc uses m2html to create a set of html docs %in the cba toolbox and place them in a directory called 'docs'. % % generateDoc(pathname, graph) % %OPTIONAL INPUTS % pathname Path to folder to generate documents for % graph Generate function dependcy graph (Default = off) Set to 'on' % %If the directory 'docs' exists, the user will be prompted %for notice that the contents of the directory will be %replaced with a new set of generated docs. % %This routine will exit if the user does not agree with this. %If the directory 'docs' does not exist, then it will be created. % %generateDoc uses m2html, therefore m2html must be in the path. %m2html will be located in the cba toolbox and added to the path %if not found on the path. % % Wing Choi 1/17/08 % Richard Que (8/06/2010) saveDir = pwd; %BUGFIX: Updated to work on Unix systems in addition to MS Windows %Do not remove this unless you've validated that your changes function %on Mac OS X and GNU/Linux if filesep == '/' cbaDir = filesep; else cbaDir = ''; end dN = ''; %locate the cbaToolbox from where matlab finds generateDoc mFilePath = mfilename('fullpath'); cbaDir = mFilePath(1:end-length(mfilename)-1); cd(cbaDir); %if pathname was not an input argument currentDir = pwd; if(nargin<1)||isempty(pathname) % parse out the current dir name, not the entire path display (' '); display(strcat('Creating html docs for --> ' , ' ' , currentDir)); reply = input('is this ok? y/n [n]: ', 's'); if ((isempty(reply)) || (reply ~= 'y')) cd(saveDir); return; end else cbaDir = pathname; end %Get Directory Name remain = currentDir; while true [str, remain] = strtok(remain,filesep); if isempty(str), break; end dirName = str; end if (exist('m2html','file') ~= 2) disp('m2html not found, adding it to path'); addpath(strcat(cbaDir,filesep,'external',filesep,'m2html')); %changed to reflect new folder structure end if (isdir('docs')) display ('The docs directory already exists') display ('I will remove the existing docs directory') display ('and replace its entire contents with newly') display ('generated html docs.') display (' '); reply = input('Do you want to replace the contents of the directory? y/n [n]: ', 's'); if ((isempty(reply)) || (reply ~= 'y')) cd(saveDir); return; end end preDirName = cbaDir(1:end-length(dirName)); if(nargin<2)||~strcmp(graph, 'on') dirNames = getDir(cbaDir,{'.svn','obsolete','docs','private','@template','toolboxes','internal','testing'}); for i=1:length(dirNames), dirNames{i} = strrep(dirNames{i},preDirName,''); end cd ..; m2html('mfiles',dirNames,'htmldir',strcat(dirName,filesep,'docs'),'recursive','off', 'global','on','template','frame', 'index','menu', 'globalHypertextLinks', 'on'); else dirNames = getDir(cbaDir,{'.svn','obsolete','docs','private','@template','internal','toolboxes','testing'}); for i=1:length(dirNames), dirNames{i} = strrep(dirNames{i},preDirName,''); end % go up one dir cd ..; % call m2html m2html('mfiles', dirNames, 'htmldir',strcat(dirName,filesep,'docs'),'recursive','off', 'global','on','template','frame', 'index','menu', 'globalHypertextLinks', 'on', 'graph', 'on'); end % cd back to saveDir again cd(saveDir); function directories = getDir(directory,ignore) %Get list of directories beneath the specified directory directories = {directory}; currDir = dir([directory,filesep,'*']); currDir = {currDir([currDir.isdir]).name}; currDir = currDir(~ismember(currDir,{'.','..',ignore{:}})); %Loop through the directory list and recursively call this function for i = 1:length(currDir) tmp = getDir([directory,filesep,currDir{i}],ignore); tmp = columnVector(tmp); directories = [directories; tmp(:)]; end
github
EPFL-LCSB/matTFA-master
solveFBAmodelCplex.m
.m
matTFA-master/ext/Cobra205_vDec2014/solveFBAmodelCplex.m
28,006
utf_8
6478764de59239a1782fac0520b6dc20
function FBAsolution = solveFBAmodelCplex(model, scalPar, feasTol, emphPar, osenseStr) %optimizeCbModel Solve a flux balance analysis problem % % Georgios Fengos 24/05/2016 Created this version of optimizeCbModel % to be able to control externally the cplex parameters %% Process arguments and set up problem if ~exist('osenseStr','var') osenseStr = 'max'; end allowLoops = true; if ~exist('scalPar','var') || isempty(scalPar) scalPar = []; end if ~exist('feasTol','var') || isempty(feasTol) feasTol = []; end if ~exist('emphPar','var') || isempty(emphPar) emphPar = []; end [minNorm, printLevel, primalOnlyFlag, ~] = getCobraSolverParams('LP',{'minNorm','printLevel','primalOnly','saveInput'}); % Figure out objective sense if strcmpi(osenseStr,'max') LPproblem.osense = -1; else LPproblem.osense = +1; end [nMets,nRxns] = size(model.S); % add csense %Doing this makes csense a double array. Totally smart design move. %LPproblem.csense = []; if ~isfield(model,'csense') % If csense is not declared in the model, assume that all % constraints are equalities. LPproblem.csense(1:nMets,1) = 'E'; else % if csense is in the model, move it to the lp problem structure if length(model.csense)~=nMets, warning('Length of csense is invalid! Defaulting to equality constraints.') LPproblem.csense(1:nMets,1) = 'E'; else model.csense = columnVector(model.csense); LPproblem.csense = model.csense; end end % Fill in the RHS vector if not provided if (~isfield(model,'b')) LPproblem.b = zeros(size(model.S,1),1); else LPproblem.b = model.b; end % Rest of the LP problem LPproblem.A = model.S; LPproblem.c = model.c; LPproblem.lb = model.lb; LPproblem.ub = model.ub; %Double check that all inputs are valid: if ~(verifyCobraProblem(LPproblem, [], [], false) == 1) warning('invalid problem'); return; end %% t1 = clock; % Solve initial LP % if allowLoops solution = solveCobraLP_edited(LPproblem,scalPar,feasTol,emphPar); % else % MILPproblem = addLoopLawConstraints(LPproblem, model, 1:nRxns); % solution = solveCobraMILP(MILPproblem); % end if (solution.stat ~= 1) % check if initial solution was successful. if printLevel>0 warning('Optimal solution was not found'); end FBAsolution.f = 0; FBAsolution.x = []; FBAsolution.stat = solution.stat; FBAsolution.origStat = solution.origStat; FBAsolution.solver = solution.solver; FBAsolution.time = etime(clock, t1); return; end objective = solution.obj; % save for later use. % Store results if (solution.stat == 1) %solution found. FBAsolution.x = solution.full(1:nRxns); %this line IS necessary. FBAsolution.f = model.c'*solution.full(1:nRxns); %objective from original optimization problem. if abs(FBAsolution.f - objective) > .01 display('warning: objective appears to have changed while performing secondary optimization (minNorm)'); end if (~primalOnlyFlag && allowLoops && any(~minNorm)) % rcost/dual only correct if not doing minNorm FBAsolution.y = solution.dual; FBAsolution.w = solution.rcost; end else %some sort of error occured. if printLevel>0 warning('Optimal solution was not found'); end FBAsolution.f = 0; FBAsolution.x = []; end FBAsolution.stat = solution.stat; FBAsolution.origStat = solution.origStat; FBAsolution.solver = solution.solver; FBAsolution.time = etime(clock, t1); end function solution = solveCobraLP_edited(LPproblem,scalPar,feasTol,emphPar) % solveCobraLP Solve constraint-based LP problems % Georgios Fengos 24/05/2016 Created this version of solveCobraLP % to be able to control externally the cplex parameters global CBTLPSOLVER if (~isempty(CBTLPSOLVER)) solver = CBTLPSOLVER; else error('No solver found. call changeCobraSolver(solverName)'); end optParamNames = {'minNorm','printLevel','primalOnly','saveInput', ... 'feasTol','optTol','EleNames','EqtNames','VarNames','EleNameFun', ... 'EqtNameFun','VarNameFun','PbName','MPSfilename'}; parameters = ''; % if nargin ~=1 % if mod(length(varargin),2)==0 % for i=1:2:length(varargin)-1 % if ismember(varargin{i},optParamNames) % parameters.(varargin{i}) = varargin{i+1}; % else % error([varargin{i} ' is not a valid optional parameter']); % end % end % elseif strcmp(varargin{1},'default') % parameters = 'default'; % elseif isstruct(varargin{1}) % parameters = varargin{1}; % else % display('Warning: Invalid number of parameters/values') % solution=[]; % return; % end % end [minNorm, printLevel, ~, saveInput, ~, ~] = ... getCobraSolverParams('LP',optParamNames(1:6),parameters); %Save Input if selected if ~isempty(saveInput) fileName = parameters.saveInput; if ~find(regexp(fileName,'.mat')) fileName = [fileName '.mat']; end display(['Saving LPproblem in ' fileName]); save(fileName,'LPproblem') end % [A,b,c,lb,ub,csense,osense] = deal(LPproblem.A,LPproblem.b,LPproblem.c,LPproblem.lb,LPproblem.ub,LPproblem.csense,LPproblem.osense); % if any(any(~isfinite(A))) % error('Cannot perform LP on a stoichiometric matrix with NaN of Inf coefficents.') % end % Defaults in case the solver does not return anything f = []; x = []; y = []; w = []; origStat = -99; stat = -99; t_start = clock; switch solver case 'cplex_direct' %% Tomlab cplex.m direct %Used with the current script, only some of the control affoarded with %this interface is provided. Primarily, this is to change the print %level and whether to minimise the Euclidean Norm of the internal %fluxes or not. %See solveCobraLPCPLEX.m for more refined control of cplex %Ronan Fleming 11/12/2008 if isfield(LPproblem,'basis') && ~isempty(LPproblem.basis) LPproblem.LPBasis = LPproblem.basis; end [solution LPprob] = solveCobraLPCPLEX_edited(LPproblem,printLevel,1,[],[],minNorm,scalPar,feasTol,emphPar); solution.basis = LPprob.LPBasis; solution.solver = solver; otherwise error(['Unknown solver: ' solver]); end if ~strcmp(solver,'cplex_direct') && ~strcmp(solver,'mps') %% Assign solution t = etime(clock, t_start); if ~exist('basis','var'), basis=[]; end [solution.full,solution.obj,solution.rcost,solution.dual,solution.solver,solution.stat,solution.origStat,solution.time,solution.basis] = ... deal(x,f,w,y,solver,stat,origStat,t,basis); end end function [solution,LPProblem] = solveCobraLPCPLEX_edited(LPProblem,printLevel,basisReuse,conflictResolve,contFunctName,minNorm,scalPar,feasTol,emphPar) % [solution,LPProblem]=solveCobraLPCPLEX(LPProblem,printLevel,basisReuse,conflictResolve,contFunctName,minNorm) % Georgios Fengos 24/05/2016 Created this version of solveCobraLPCPLEX % to be able to control externally the cplex parameters if ~exist('printLevel','var') printLevel=2; end if ~exist('basisReuse','var') basisReuse=0; end if ~exist('conflictResolve','var') conflictResolve=0; end if ~exist('contFunctName','var') cpxControl=[]; else if isstruct(contFunctName) cpxControl=contFunctName; else if ~isempty(contFunctName) %calls a user specified function to create a CPLEX control structure %specific to the users problem. A TEMPLATE for one such function is %CPLEXParamSet cpxControl=eval(contFunctName); else cpxControl=[]; end end end if ~exist('minNorm','var') minNorm=0; end if basisReuse if isfield(LPProblem,'LPBasis') basis=LPProblem.LPBasis; %use advanced starting information when optimization is initiated. cpxControl.ADVIND=1; else basis=[]; end else basis=[]; %do not use advanced starting information when optimization is initiated. cpxControl.ADVIND=0; end if ~isfield(LPProblem,'A') if ~isfield(LPProblem,'S') error('Equality constraint matrix must either be a field denoted A or S.') end LPProblem.A=LPProblem.S; end if ~isfield(LPProblem,'csense') nMet=size(LPProblem.A); if printLevel>0 fprintf('%s\n','Assuming equality constraints, i.e. S*v=b'); end %assuming equality constraints LPProblem.csense(1:nMet,1)='E'; end if ~isfield(LPProblem,'osense') %assuming maximisation LPProblem.osense=-1; if printLevel>0 fprintf('%s\n','Assuming maximisation of objective'); end end %get data [c,x_L,x_U,b,csense,osense] = deal(LPProblem.c,LPProblem.lb,LPProblem.ub,LPProblem.b,LPProblem.csense,LPProblem.osense); %modify objective to correspond to osense c=full(c*osense); %cplex expects it dense b=full(b); %Conflict groups descriptor (cpxBuildConflict can be used to generate the input). Set this if %conflict refinement is desired in the case that infeasibility is detected %by CPLEX. if conflictResolve [m_lin,n]=size(LPProblem.A); m_quad=0; m_sos=0; m_log=0; %determines how elaborate the output is mode='full';%'minimal'; fprintf('%s\n%s\n','Building Structure for Conflict Resolution...','...this slows CPLEX down so should not be used for repeated LP'); confgrps = cpxBuildConflict(n,m_lin,m_quad,m_sos,m_log,mode); prefix=pwd; suffix='LP_CPLEX_conflict_file.txt'; conflictFile=[prefix '\' suffix]; else confgrps=[]; conflictFile=[]; end %Name of file to write the CPLEX log information to. If empty, no log is %written. logfile=[]; %Name of a file to save the CPLEX problem object (Used for submitting %possible bugs in CPLEX to ILOG) savefile=[]; savemode=[]; % savefile='C:\CPLEX_possible_bug.txt'; % vector defining which callbacks to use in CPLEX. If the ith entry of the logical vector % callback is set, the corresponding callback is defined. The callback calls the m-file specified % in Table 7 below. The user may edit this file, or make a new copy, which is put in a directory % that is searched before the cplex directory in the Matlab path. callback=[]; %I'm not really sure what this option means as yet %this is not a tomlab problem so this is not needed Prob=[]; % variables not used in LP problems IntVars=[]; PI=[]; SC=[]; SI=[]; sos1=[]; sos2=[]; %quadratic constraint matrix, size n x n if sum(minNorm)~=0 if length(minNorm)==1 % same weighting of min norm for all variables F=speye(length(c))*minNorm; else if length(minNorm)~=length(c) error('Either minNorm is a scalar, or is an n x 1 vector') else % individual weighting of min norm for all variables F=spdiags(minNorm,0,length(c),length(c)); end end else F=[]; end %Structure array defining quadratic constraints qc=[]; %Structure telling whether and how you want CPLEX to perform a sensitivity analysis (SA). %This may be useful in future but probably will have more meaning with an %additional term in the objective saRequest =[]; %Vector with MIP starting solution, if known xIP=[]; %Logical constraints, i.e. an additional set of single-sided linear constraints that are controlled %by a binary variable (switch) in the problem logcon=[]; %call cplex tic; %tic; %by default use the complex ILOG-CPLEX interface ILOGcomplex=1; tomlab_cplex=0; %by default DO NOT use the tomlab_cplex interface if ~isempty(which('cplexlp')) && tomlab_cplex==0 if ILOGcomplex %complex ibm ilog cplex interface if ~isempty(csense) %set up constant vectors for CPLEX b_L(csense == 'E',1) = b(csense == 'E'); b_U(csense == 'E',1) = b(csense == 'E'); b_L(csense == 'G',1) = b(csense == 'G'); b_U(csense == 'G',1) = Inf; b_L(csense == 'L',1) = -Inf; b_U(csense == 'L',1) = b(csense == 'L'); else b_L = b; b_U = b; end % Initialize the CPLEX object try ILOGcplex = Cplex('fba'); catch ME error('CPLEX not installed or licence server not up') end ILOGcplex.Model.sense = 'minimize'; % Now populate the problem with the data ILOGcplex.Model.obj = c; ILOGcplex.Model.lb = x_L; ILOGcplex.Model.ub = x_U; if isfield(ILOGcplex.Model,'S') ILOGcplex.Model.A = LPProblem.S; elseif isfield(ILOGcplex.Model,'A') ILOGcplex.Model.A = LPProblem.A; end ILOGcplex.Model.lhs = b_L; ILOGcplex.Model.rhs = b_U; if ~isempty(F) %quadratic constraint matrix, size n x n ILOGcplex.Model.Q=F; end if ~isempty(cpxControl) if isfield(cpxControl,'LPMETHOD') %set the solver ILOGcplex.Param.lpmethod.Cur=cpxControl.LPMETHOD; end end if printLevel==0 ILOGcplex.DisplayFunc=[]; else %print level ILOGcplex.Param.barrier.display.Cur = printLevel; ILOGcplex.Param.simplex.display.Cur = printLevel; ILOGcplex.Param.sifting.display.Cur = printLevel; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% EDITED BY GF >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % |---------------------------| % | SCALING (PRECONDITIONING) | % |---------------------------| % Sometimes it can happen that the solver finds a solution, but % because of bad scaling (preconditioning) it does not return the % actual solution to the user, but an empty solution instead. % |-------------------------------------------| % | Value : Meaning | % |-------------------------------------------| % | -1 : No scaling | % | 0 : Equilibration scaling | % | 1 : More aggressive scaling (default) | % |-------------------------------------------| % To avoid this, we change the default of these parameter to no % scaling: if ~exist('scalPar','var') || isempty(scalPar) % LCSB default scalPar = -1; else if ~ismember(scalPar,[-1 0 1]) error('Parameter value out of range!') end end ILOGcplex.Param.read.scale.Cur = scalPar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % |-----------------------| % | FEASIBILITY TOLERANCE | % |-----------------------| % Specifies the feasibility tolerance, that is, the degree to which % values of the basic variables calculated by the simplex method may % violate their bounds. CPLEX? does not use this tolerance to relax the % variable bounds nor to relax right hand side values. This parameter % specifies an allowable violation. Feasibility influences the selection % of an optimal basis and can be reset to a higher value when a problem is % having difficulty maintaining feasibility during optimization. You can % also lower this tolerance after finding an optimal solution if there is % any doubt that the solution is truly optimal. If the feasibility tolerance % is set too low, CPLEX may falsely conclude that a problem is infeasible. % If you encounter reports of infeasibility during Phase II of the % optimization, a small adjustment in the feasibility tolerance may % improve performance. % |-------------------------------------------| % | Values : | % |-------------------------------------------| % | Range : from 1e-9 to 1e-1 | % | Cplex-Default: 1e-06 | % |-------------------------------------------| if ~exist('feasTol','var') || isempty(feasTol) % LCSB default feasTol = 1e-9; else if feasTol < 1e-9 || feasTol > 1e-1 error('Parameter value out of range!') end end ILOGcplex.Param.simplex.tolerances.feasibility.Cur = feasTol; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % |-----------------------| % | EMPHASIS ON PRECISION | % |-----------------------| % Emphasizes precision in numerically unstable or difficult problems. % This parameter lets you specify to CPLEX that it should emphParasize % precision in numerically difficult or unstable problems, with % consequent performance trade-offs in time and memory. % |-----------------------------------------------------------| % | Values : Meaning | % |-----------------------------------------------------------| % | 0 : Do not emphasize numerical precision; cplex-default | % | 1 : Exercise extreme caution in computation | % |-----------------------------------------------------------| if ~exist('emphPar','var') || isempty(emphPar) % LCSB default emphPar = 1; else if ~ismember(emphPar,[0 1]) error('Parameter value out of range!') end end ILOGcplex.Param.emphasis.numerical.Cur = emphPar; %<<<<<<<<<<<<<< EDITED BY GF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Optimize the problem ILOGcplex.solve(); if isfield(ILOGcplex.Solution, 'objval') solution.obj = osense*ILOGcplex.Solution.objval; solution.full = ILOGcplex.Solution.x; solution.rcost = ILOGcplex.Solution.reducedcost; solution.dual = ILOGcplex.Solution.dual; solution.nInfeas = NaN; solution.sumInfeas = NaN; %solution.stat = ILOGcplex.Solution. solution.origStat = ILOGcplex.Solution.status; solution.solver = ILOGcplex.Solution.method; solution.time = ILOGcplex.Solution.time; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% EDITED BY GF >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % I got this from somebody elses code, and thought it is a good % idea to avoid crashing if it is infeasible solution.obj = []; solution.full = []; solution.rcost = []; solution.dual = []; solution.nInfeas = NaN; solution.sumInfeas = NaN; %solution.stat = ILOGcplex.Solution. solution.origStat = []; solution.solver = []; solution.time = []; end %<<<<<<<<<<<<<< EDITED BY GF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else try ILOGcplex = Cplex('fba'); catch ME error('CPLEX not installed or licence server not up') end %simple ibm ilog cplex interface options = cplexoptimset; switch printLevel case 0 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); case 1 options = cplexoptimset(options,'Display','off'); end if ~isempty(csense) if sum(minNorm)~=0 Aineq = [LPProblem.A(csense == 'L',:); - LPProblem.A(csense == 'G',:)]; bineq = [b(csense == 'L',:); - b(csense == 'G',:)]; % min 0.5*x'*H*x+f*x or f*x % st. Aineq*x <= bineq % Aeq*x = beq % lb <= x <= ub [x,fval,exitflag,output,lambda] = cplexqp(F,c,Aineq,bineq,LPProblem.A(csense == 'E',:),b(csense == 'E',1),x_L,x_U,[],options); else Aineq = [LPProblem.A(csense == 'L',:); - LPProblem.A(csense == 'G',:)]; bineq = [b(csense == 'L',:); - b(csense == 'G',:)]; % min c*x % st. Aineq*x <= bineq % Aeq*x = beq % lb <= x <= ub [x,fval,exitflag,output,lambda] = cplexlp(c,Aineq,bineq,LPProblem.A(csense == 'E',:),b(csense == 'E',1),x_L,x_U,[],options); end %primal solution.obj=osense*fval; solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=lambda.eqlin; else Aineq=[]; bineq=[]; if sum(minNorm)~=0 [x,fval,exitflag,output,lambda] = cplexqp(F,c,Aineq,bineq,LPProblem.A,b,x_L,x_U,[],options); else [x,fval,exitflag,output,lambda] = cplexlp(c,Aineq,bineq,LPProblem.A,b,x_L,x_U,[],options); end solution.obj=osense*fval; solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=sparse(size(LPProblem.A,1),1); solution.dual(csense == 'E')=lambda.eqlin; %this is the dual to the inequality constraints but it's not the chemical potential solution.dual(csense == 'L')=lambda.ineqlin(1:nnz(csense == 'L'),1); solution.dual(csense == 'G')=lambda.ineqlin(nnz(csense == 'L')+1:end,1); end %this is the dual to the simple ineequality constraints : reduced costs solution.rcost=lambda.lower-lambda.upper; solution.nInfeas = []; solution.sumInfeas = []; solution.origStat = output.cplexstatus; end %1 = (Simplex or Barrier) Optimal solution is available. Inform = solution.origStat; else %tomlab cplex interface if ~isempty(csense) %set up constant vectors for CPLEX b_L(csense == 'E',1) = b(csense == 'E'); b_U(csense == 'E',1) = b(csense == 'E'); b_L(csense == 'G',1) = b(csense == 'G'); b_U(csense == 'G',1) = Inf; b_L(csense == 'L',1) = -Inf; b_U(csense == 'L',1) = b(csense == 'L'); else b_L = b; b_U = b; end %tomlab cplex interface % minimize 0.5 * x'*F*x + c'x subject to: % x x_L <= x <= x_U % b_L <= Ax <= b_U [x, slack, v, rc, f_k, ninf, sinf, Inform, basis] = cplex(c, LPProblem.A, x_L, x_U, b_L, b_U, ... cpxControl, callback, printLevel, Prob, IntVars, PI, SC, SI, ... sos1, sos2, F, logfile, savefile, savemode, qc, ... confgrps, conflictFile, saRequest, basis, xIP, logcon); solution.full=x; %this is the dual to the equality constraints but it's not the chemical potential solution.dual=v; %this is the dual to the simple ineequality constraints : reduced costs solution.rcost=rc; if Inform~=1 solution.obj = NaN; else if minNorm==0 solution.obj=f_k*osense; else solution.obj=c'*x*osense; end % solution.obj % norm(x) end solution.nInfeas = ninf; solution.sumInfeas = sinf; solution.origStat = Inform; end %timeTaken=toc; timeTaken=NaN; if Inform~=1 && ~isempty(which('cplex')) if conflictResolve ==1 if isfield(LPProblem,'mets') && isfield(LPProblem,'rxns') %this code reads the conflict resolution file and replaces the %arbitrary names with the abbreviations of metabolites and reactions [nMet,nRxn]=size(LPProblem.A); totAbbr=nMet+nRxn; conStrFind=cell(nMet+nRxn,1); conStrReplace=cell(nMet+nRxn,1); %only equality constraint rows for m=1:nMet conStrFind{m,1}=['c' int2str(m) ':']; conStrReplace{m,1}=[LPProblem.mets{m} ': ']; end %reactions for n=1:nRxn conStrFind{nMet+n,1}=['x' int2str(n) ' ']; conStrReplace{nMet+n,1}=[LPProblem.rxns{n} ' ']; end fid1 = fopen(suffix); fid2 = fopen(['COBRA_' suffix], 'w'); while ~feof(fid1) tline{1}=fgetl(fid1); %replaces all occurrences of the string str2 within string str1 %with the string str3. %str= strrep(str1, str2, str3) for t=1:totAbbr tline= strrep(tline, conStrFind{t}, conStrReplace{t}); end fprintf(fid2,'%s\n', tline{1}); end fclose(fid1); fclose(fid2); %delete other file without replacements % delete(suffix) else warning('Need reaction and metabolite abbreviations in order to make a readable conflict resolution file'); end fprintf('%s\n',['Conflict resolution file written to: ' prefix '\COBRA_' suffix]); fprintf('%s\n%s\n','The Conflict resolution file gives an irreducible infeasible subset ','of constraints which are making this LP Problem infeasible'); else if printLevel>0 fprintf('%s\n','No conflict resolution file. Perhaps set conflictResolve = 1 next time.'); end end solution.solver = 'cplex_direct'; end % Try to give back COBRA Standardized solver status: % 1 Optimal solution % 2 Unbounded solution % 0 Infeasible % -1 No solution reported (timelimit, numerical problem etc) if Inform==1 solution.stat = 1; if printLevel>0 %use tomlab code to print out exit meassage [ExitText,ExitFlag] = cplexStatus(Inform); solution.ExitText=ExitText; solution.ExitFlag=ExitFlag; fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); end else if Inform==2 solution.stat = 2; %use tomlab code to print out exit meassage [ExitText,ExitFlag] = cplexStatus(Inform); solution.ExitText=ExitText; solution.ExitFlag=ExitFlag; fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); else if Inform==3 solution.stat = 0; else %this is a conservative view solution.stat = -1; %use tomlab code to print out exit meassage [ExitText,ExitFlag] = cplexStatus(Inform); solution.ExitText=ExitText; solution.ExitFlag=ExitFlag; fprintf('\n%s%g\n',[ExitText ', Objective '], c'*solution.full*osense); end end end solution.time = timeTaken; %return basis if basisReuse LPProblem.LPBasis=basis; end if sum(minNorm)~=0 fprintf('%s\n','This objective corresponds to a flux with minimum Euclidean norm.'); fprintf('%s%d%s\n','The weighting for minimising the norm was ',minNorm,'.'); fprintf('%s\n','Check that the objective is the same without minimising the norm.'); end end
github
EPFL-LCSB/matTFA-master
geometricFBA.m
.m
matTFA-master/ext/Cobra205_vDec2014/geometricFBA.m
6,629
utf_8
511013ff705cedf3231d79af4e99e023
function flux = geometricFBA(model,varargin) %geometricFBA finds a unique optimal FBA solution that is (in some sense) %central to the range of possible fluxes; as described in % K Smallbone, E Simeonidis (2009). Flux balance analysis: % A geometric perspective. J Theor Biol 258: 311-315 % http://dx.doi.org/10.1016/j.jtbi.2009.01.027 % % flux = geometricFBA(model) % %INPUT % model COBRA model structure % %OPTIONAL INPUTS % Optional parameters can be entered as parameter name followed by % parameter value: i.e. ...,'epsilon',1e-9) % printLevel [default: 1] printing level % = 0 silent % = 1 show algorithm progress and times % epsilon [default: 1e-6] convergence tolerance of algorithm, % defined in more detail in paper above % flexRel [default: 0] flexibility to flux bounds % try e.g. 1e-3 if the algorithm has convergence problems % %OUTPUT % flux unique centered flux % %kieran smallbone, 5 May 2010 % % This script is made available under the Creative Commons % Attribution-Share Alike 3.0 Unported Licence (see % www.creativecommons.org). param = struct('epsilon',1e-6,'flexRel',0,'printLevel',1); field = fieldnames(param); if mod(nargin,2) ~= 1 % require odd number of inputs error('incorrect number of input parameters') else for k = 1:2:(nargin-1) param.(field{strcmp(varargin{k},field)}) = varargin{k+1}; end end param.flexTol = param.flexRel * param.epsilon; % absolute flexibility % determine optimum FBAsolution = optimizeCbModel(model); ind = find(model.c); if length(ind) == 1 model.lb(ind) = FBAsolution.f; end A = model.S; b = model.b; L = model.lb; U = model.ub; % ensure column vectors b = b(:); L = L(:); U = U(:); % Remove negligible elements J = any(A,2); A = A(J,:); b = b(J); % presolve v = nan(size(L)); J = (U-L < param.epsilon); v(J) = (L(J)+U(J))/2; J = find(isnan(v)); if param.printLevel fprintf('%s\t%g\n\n%s\t@%s\n','# reactions:',length(v),'iteration #0',datestr(now,16)); end L0 = L; U0 = U; for k = J(:)' f = zeros(length(v),1); f(k) = -1; [dummy,opt,conv] = easyLP(f,A,b,L0,U0); if conv vL = max(-opt,L(k)); else vL = L(k); end [dummy,opt,conv] = easyLP(-f,A,b,L0,U0); if conv vU = min(opt,U(k)); else vU = U(k); end if abs(vL) < param.epsilon vL = 0; end if abs(vU) < param.epsilon vU = 0; end vM = (vL + vU)/2; if abs(vM) < param.epsilon vM = 0; end if abs(vU - vL) < param.epsilon vL = (1-sign(vM)* param.flexTol)*vM; vU = (1+sign(vM)* param.flexTol)*vM; end L(k) = vL; U(k) = vU; end v = nan(size(L)); J = (U-L < param.epsilon); v(J) = (L(J)+U(J))/2; v = v.*(abs(v) > param.epsilon); if param.printLevel fprintf('%s\t\t%g\n%s\t\t%g\n\n','fixed:',sum(J),'@ zero:',sum(v==0)); end % iterate J = find(U-L >= param.epsilon); n = 1; mu = []; Z = []; while ~isempty(J) if param.printLevel fprintf('%s #%g\t@%s\n','iteration',n,datestr(now,16)); end if n == 1 M = zeros(size(L)); else M = (L+U)/2; end mu(:,n) = M; %#ok<AGROW> allL = L; allU = U; allA = A; allB = b; [a1,a2] = size(A); % build new matrices for k = 1:(n-1) [b1,b2] = size(allA); f = sparse(b2+2*a2,1); f((b2+1):end) = -1; opt = -Z(k); allA = [allA,sparse(b1,2*a2); speye(a2,a2),sparse(a2,b2-a2),-speye(a2),speye(a2); f(:)']; %#ok<AGROW> allB = [allB;mu(:,k);opt]; %#ok<AGROW> allL = [allL;zeros(2*a2,1)]; %#ok<AGROW> allU = [allU;inf*ones(2*a2,1)]; %#ok<AGROW> end [b1,b2] = size(allA); f = zeros(b2+2*a2,1); f((b2+1):end) = -1; allA = [allA,sparse(b1,2*a2); speye(a2,a2),sparse(a2,b2-a2),-speye(a2),speye(a2)]; %#ok<AGROW> allB = [allB;M]; %#ok<AGROW> allL = [allL;zeros(2*a2,1)]; %#ok<AGROW> allU = [allU;inf*ones(2*a2,1)]; %#ok<AGROW> [v,opt,conv] = easyLP(f,allA,allB,allL,allU); if ~conv, disp('error: no convergence'); flux = (L+U)/2; return; end opt = ceil(-opt/eps)*eps; Z(n) = opt; %#ok<AGROW> allA = [allA; sparse(f(:)')]; %#ok<AGROW> allB = [allB; -opt]; %#ok<AGROW> for k = J(:)' f = zeros(length(allL),1); f(k) = -1; [dummy,opt,conv] = easyLP(f,allA,allB,allL,allU); if conv vL = max(-opt,L(k)); else vL = L(k); end [dummy,opt,conv] = easyLP(-f,allA,allB,allL,allU); if conv vU = min(opt,U(k)); else vU = U(k); end if abs(vL) < param.epsilon vL = 0; end if abs(vU) < param.epsilon vU = 0; end vM = (vL + vU)/2; if abs(vM) < param.epsilon vM = 0; end if abs(vU - vL) < param.epsilon vL = (1-sign(vM)* param.flexTol)*vM; vU = (1+sign(vM)* param.flexTol)*vM; end L(k) = vL; U(k) = vU; end v = nan(size(L)); J = (U-L < param.epsilon); v(J) = (L(J)+U(J))/2; v = v.*(abs(v) > param.epsilon); if param.printLevel fprintf('%s\t\t%g\n%s\t\t%g\n\n','fixed:',sum(J),'@ zero:',sum(v==0)); end n = n+1; J = find(U-L >= param.epsilon); flux = v; end function [v,fOpt,conv] = easyLP(c,A,b,lb,ub) %easyLP % % solves the linear programming problem: % max c'x subject to % A x = b % lb <= x <= ub. % % Usage: [v,fOpt,conv] = easyLP(c,A,b,lb,ub) % % c objective coefficient vector % A LHS matrix % b RHS vector % lb lower bound % ub upper bound % % v solution vector % fOpt objective value % conv convergence of algorithm [0/1] % % the function is a wrapper for the "solveCobraLP" script. % %kieran smallbone, 5 may 2010 csense(1:length(b)) = 'E'; model = struct('A',A,'b',b,'c',full(c),'lb',lb,'ub',ub,'osense',-1,'csense',csense); solution = solveCobraLP(model); v = solution.full; fOpt = solution.obj; conv = solution.stat == 1;
github
EPFL-LCSB/matTFA-master
changeRxnMets.m
.m
matTFA-master/ext/Cobra205_vDec2014/changeRxnMets.m
3,484
utf_8
a54ed5421c1d7e06d54c21d49c1dd01a
function [model ModifiedRxns] = changeRxnMets(model,Mets2change,NewMets,Rxn,NewStoich) %changeRxnMets Change metabolites in a specified reaction, or % randomly chosen reactions. % % [model ModifiedRxns] = changeRxnMets(model,Mets2change,NewMets,Rxn,NewStoich) % %INPUTS % model COBRA model structure % Mets2change Cell array of metabolites to change % NewMets Cell array of replacement metabolites (must be in % order of those that will be replaced % Rxn reaction to change (string) or cell array, or if a number is put % here, that number of reactions (with Mets2change) will % be randomly chosen and the metabolites will be swapped % %OPTIONAL INPUT % NewStoich Stoichiometry of new metabs (conserved from old mets by default). % If multiple reactions are being changed, this must be % a mets x rxns matrix, % e.g. for 2 new reactions: Rxn = {'r1','r2'} % r1: 2 A + 3 B -> 1 C % r2: 4 A + 3 B -> 3 C % where A and C are the new metabolites, % NewMets = {'A', 'C'} % NewStoich = [ 2 4; 1 3] % %OUTPUTS % model COBRA model structure with changed reaction % ModifiedRxns Rxns which were modified % % Nathan Lewis (Apr 24, 2009) if nargin ==4 NewStoich = []; end %%% make sure metabolites are in the model OldMetInd = findMetIDs(model,Mets2change); NewMetInd = findMetIDs(model,NewMets); if min(OldMetInd) == 0 || min(NewMetInd) == 0 error('A metabolite wasn''t found in your model!') end if ~all(isnumeric(Rxn)) %%% make sure rxns are in the model RxnsInd = findRxnIDs(model,Rxn); if min(RxnsInd == 0) error('A reaction wasn''t found in your model!') end model = changeMets(model,OldMetInd,NewMetInd,RxnsInd,NewStoich); ModifiedRxns = model.rxns(RxnsInd); else %%% find all reactions with the old mets, and choose the specified number of rxns RxnsInd = 1:length(model.rxns); tempS = full(model.S); for i = 1:length(OldMetInd) RxnsInd = intersect(find(tempS(OldMetInd(i),:)),RxnsInd); end if length(RxnsInd)<Rxn warning('Fewer reactions have your metabolites than the number you wanted to randomly choose!') RxnsToSwitch = RxnsInd(ceil(rand(length(RxnsInd),1))); Rxn = length(RxnsToSwitch); else %%% chose the reactions to randomize RxnsToSwitch = []; Rxns2Exclude = findRxnIDs(model,{'DM_SC_PRECUSOR'}); for r=1:length(Rxns2Exclude) tmp = find(RxnsInd==Rxns2Exclude(r)); if ~isempty(tmp) RxnsInd(tmp) = []; end end while length(unique(RxnsToSwitch))<Rxn RxnsToSwitch = RxnsInd(ceil(rand(length(RxnsInd),1)*length(RxnsInd))); RxnsToSwitch = RxnsToSwitch(1:Rxn); end end model = changeMets(model,OldMetInd,NewMetInd,RxnsToSwitch,NewStoich); ModifiedRxns = model.rxns(RxnsToSwitch); end end function model = changeMets(model,OldMetInd,NewMetInd,RxnsInd,NewStoich) if isempty(NewStoich) NewStoich = model.S(OldMetInd,RxnsInd); end for i = 1:length(RxnsInd) model.S(OldMetInd,RxnsInd(i))=0; model.S(NewMetInd,RxnsInd(i))=NewStoich(:,i); end end
github
EPFL-LCSB/matTFA-master
convertModelToEX.m
.m
matTFA-master/ext/Cobra205_vDec2014/convertModelToEX.m
2,482
utf_8
262c28a115d8194846f4c7562681fe0e
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert Matlab Model to XPA format % Inputs: % model Model Structure % filename Filename of Output File (make sure to include '.txt' or % '.xpa') % rxnzero Matrix containing all no flux var rxns (to skip, set=0) % % Limitations: % -Works properly with only integer value reaction coeff. (except for .5 % or -.5) % Other non-integer value coeff. have to be edited manually % -Exchange reactions have to be clumped together in model % -If using rxnzero, make sure that EX reactions contain no compounds % that are not used in the uncommented reactions % % Aarash Bordbar, 07/06/07 % Updated Aarash Bordbar 02/22/10 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function convertModelToEX(model,filename,rxnzero) fid = fopen(filename,'w'); fprintf(fid,'(Internal Fluxes)\n'); EXrxns = [strmatch('EX_',model.rxns);strmatch('DM_',model.rxns)]; EXrxns = model.rxns(EXrxns); checkEX = ismember(model.rxns,EXrxns); % Reactions prior to exchange reactions for i = 1:length(model.rxns) if checkEX(i) == 0 for t = 1:size(rxnzero,1) if i == rxnzero(t) fprintf(fid,'// '); end end fprintf(fid,'%s\t',model.rxns{i}); if model.rev(i) == 0 fprintf(fid,'I\t'); else fprintf(fid,'R\t'); end reactionPlace = find(model.S(:,i)); if abs(model.S(reactionPlace,i)) > 1 - 1e-2 for j = 1:size(reactionPlace,1) fprintf(fid,'%i\t%s\t',model.S(reactionPlace(j),i),model.mets{reactionPlace(j)}); end else for j = 1:size(reactionPlace,1) newS(j,i) = 2*model.S(reactionPlace(j),i); fprintf(fid,'%i\t%s\t',newS(j,i),model.mets{reactionPlace(j)}); end end fprintf(fid,'\n'); end end % Exchange Reactions fprintf(fid,'(Exchange Fluxes)\n'); for i = 1:length(model.rxns) if checkEX(i) == 1 metabolitePlace = find(model.S(:,i)); fprintf(fid,'%s\t',model.mets{metabolitePlace}); if model.lb(i) >= 0 && model.ub(i) >= 0 fprintf(fid,'Output\n'); else if model.lb(i) <= 0 && model.ub(i) <= 0 fprintf(fid,'Input\n'); else fprintf(fid,'Free\n'); end end end end fclose(fid);
github
EPFL-LCSB/matTFA-master
pFBA.m
.m
matTFA-master/ext/Cobra205_vDec2014/pFBA.m
9,274
utf_8
ec4edfb9cb08758b017493c5cb612fcd
function [GeneClasses RxnClasses modelIrrevFM] = pFBA(model, varargin) % Parsimoneous enzyme usage Flux Balance Analysis - method that optimizes % the user's objective function and then minimizes the flux through the % model and subsequently classifies each gene by how it contributes to the % optimal solution. See Lewis, et al. Mol Syst Bio doi:10.1038/msb.2010.47 % % Inputs: % model COBRA model % % varargin: % 'geneoption' 1 = only minimize the sum of the flux through % gene-associated fluxes (default), 0 = minimize the % sum of all fluxes in the network % 'tol' tolerance (default = 1e-6) % 'map' map structure from readCbMap.m (no map written if empty % 'mapoutname' File Name for map % 'skipclass' 1 = Don't classify genes and reactions. Only return % model with the minimium flux set as upper bound. % 0 = classify genes and reactions (default). % % Output: % GeneClasses Structure with fields for each gene class % RxnsClasses Structure with fields for each reaction class % modelIrrevFM Irreversible model used for minimizing flux with % the minimum flux set as a flux upper bound % % % % ** note on maps: Red (6) = Essential reactions, Orange (5) = pFBA optima % reaction, Yellow (4) = ELE reactions, Green (3) = MLE reactions, % blue (2) = zero flux reactions, purple (1) = blocked reactions, % black (0) = not classified % % Example: % [GeneClasses RxnClasses modelIrrevFM] = pFBA(model, 'geneoption',0, 'tol',1e-7) % % by Nathan Lewis Aug 25, 2010 % if nargin < 2 tol = 1e-6; GeneOption = 1; map = []; % no map mapOutName = 'pFBA_map.svg'; skipclass = 0; end if mod(length(varargin),2)==0 for i=1:2:length(varargin)-1 switch lower(varargin{i}) case 'geneoption', GeneOption = varargin{i+1}; case 'tol', tol = varargin{i+1}; case 'map', map = varargin{i+1}; case 'mapoutname', mapOutName = varargin{i+1}; case 'skipclass', skipclass = varargin{i+1}; otherwise, options.(varargin{i}) = varargin{i+1}; end end else error('Invalid number of parameters/values'); end if ~exist('GeneOption','var'), GeneOption = 1; end if ~exist('tol','var'), tol = 1e-6; end if ~exist('map','var'), map = []; end if ~exist('mapOutName','var'), mapOutName = 'pFBA_map.svg'; end if ~exist('skipclass','var'), skipclass = 0; end if skipclass % skip the model reduction and gene/rxn classification % minimize the network flux FBAsoln = optimizeCbModel(model); model.lb(model.c==1) = FBAsoln.f; [ MinimizedFlux modelIrrevFM]= minimizeModelFlux_local(model,GeneOption); modelIrrevFM = changeRxnBounds(modelIrrevFM,'netFlux',MinimizedFlux.f,'b'); GeneClasses = []; RxnClasses = []; else % save a copy of the inputted model model_sav = model; % Remove all blocked reactions [selExc,selUpt] = findExcRxns(model,0,0); % find and open up all exchanges tempmodel = changeRxnBounds(model,model.rxns(selExc),-1000,'l'); tempmodel = changeRxnBounds(tempmodel,model.rxns(selExc),1000,'u'); tempmodel = reduceModel(tempmodel,tol); % reduce the model to find blocked reactions Blocked_Rxns = setdiff(model.rxns,regexprep(tempmodel.rxns,'_r$','')); model = removeRxns(model,setdiff(model.rxns,regexprep(tempmodel.rxns,'_r$',''))); % remove blocked reactions Ind2Remove = find(~and(sum(full(model.rxnGeneMat),1),1)); Blocked_genes = model.genes(Ind2Remove); model.genes(Ind2Remove)={'dead_end'}; % make sure genes that are unique to blocked reactions are tagged for removal % find essential genes grRatio = singleGeneDeletion(model); grRatio(isnan(grRatio))=0; pFBAEssential = model.genes(grRatio<tol); if nargout > 1 % find essential reactions RxnRatio = singleRxnDeletion(model); RxnRatio(isnan(RxnRatio))=0; pFBAEssentialRxns = model.rxns(RxnRatio<tol); end % remove zero flux rxns tempmodel = reduceModel(model,tol); ZeroFluxRxns = setdiff(model.rxns,regexprep(tempmodel.rxns,'_r$','')); model = removeRxns(model,ZeroFluxRxns); % find MLE reactions FBAsoln = optimizeCbModel(model); model.lb(model.c==1) = FBAsoln.f; [minFlux,maxFlux] = fluxVariability(model,100); for i = 1:length(minFlux) tmp(i,1) = max([abs(minFlux(i)) abs(maxFlux(i))])<tol; end MLE_Rxns = setdiff(model.rxns(tmp),ZeroFluxRxns); % minimize the network flux [ MinimizedFlux modelIrrevFM]= minimizeModelFlux_local(model,GeneOption); % separate pFBA optima rxns from ELE rxns modelIrrevFM = changeRxnBounds(modelIrrevFM,'netFlux',MinimizedFlux.f,'b'); [minFlux,maxFlux] = fluxVariability(modelIrrevFM,100); pFBAopt_Rxns = modelIrrevFM.rxns((abs(minFlux)+abs(maxFlux))>=tol); ELE_Rxns = modelIrrevFM.rxns((abs(minFlux)+abs(maxFlux))<=tol); pFBAopt_Rxns = unique(regexprep(pFBAopt_Rxns,'_[f|b]$','')); ELE_Rxns = unique(regexprep(ELE_Rxns,'_[f|b]$','')); ELE_Rxns = ELE_Rxns(~ismember(ELE_Rxns,pFBAopt_Rxns)); ELE_Rxns = ELE_Rxns(~ismember(ELE_Rxns,MLE_Rxns)); % determine pFBA optima genes pFBAopt_Rxns(ismember(pFBAopt_Rxns,'netFlux'))=[]; [geneList]=findGenesFromRxns(model,pFBAopt_Rxns); geneList2 = {}; for i = 1:length(geneList), geneList2(end+1:end+length(geneList{i}),1) = columnVector( geneList{i}); end pFBAOptima = unique(geneList2); % determine Zero Flux genes Ind2Remove = find(~and(sum(full(model.rxnGeneMat),1),1)); ZeroFluxGenes = unique(model.genes(Ind2Remove)); % determine ELE genes [geneList]=findGenesFromRxns(model,ELE_Rxns); geneList2 = {}; for i = 1:length(geneList) geneList2(end+1:end+length(geneList{i}),1) = columnVector( geneList{i}); end ELEGenes = unique(geneList2); ELEGenes = setdiff(ELEGenes,[pFBAOptima;ZeroFluxGenes]); % determine Met ineff genes MLEGenes = setdiff(model.genes, [pFBAOptima;ZeroFluxGenes;ELEGenes]); % clean up lists by removing non-genes pFBAOptima(~cellfun('isempty',regexp(pFBAOptima,'dead_end')))=[]; ELEGenes(~cellfun('isempty',regexp(ELEGenes ,'dead_end')))=[]; MLEGenes(~cellfun('isempty',regexp(MLEGenes,'dead_end')))=[]; ZeroFluxGenes(~cellfun('isempty',regexp(ZeroFluxGenes,'dead_end')))=[]; pFBAOptima(cellfun('isempty',pFBAOptima))=[]; ELEGenes(cellfun('isempty',ELEGenes ))=[]; MLEGenes(cellfun('isempty',MLEGenes))=[]; ZeroFluxGenes(cellfun('isempty',ZeroFluxGenes))=[]; % filter out essential genes from pFBA optima pFBAOptima(ismember(pFBAOptima,pFBAEssential))=[]; if nargout > 1 % filter out essential Rxns from pFBA optima pFBAopt_Rxns(ismember(pFBAopt_Rxns,pFBAEssentialRxns))=[]; end % prepare output variables GeneClasses.pFBAEssential =pFBAEssential; GeneClasses.pFBAoptima = pFBAOptima; GeneClasses.ELEGenes = ELEGenes; GeneClasses.MLEGenes = MLEGenes; GeneClasses.ZeroFluxGenes = ZeroFluxGenes; GeneClasses.Blockedgenes = Blocked_genes; RxnClasses.Essential_Rxns = pFBAEssentialRxns; RxnClasses.pFBAOpt_Rxns = pFBAopt_Rxns; RxnClasses.ELE_Rxns = ELE_Rxns; RxnClasses.MLE_Rxns = MLE_Rxns; RxnClasses.ZeroFlux_Rxns = ZeroFluxRxns; RxnClasses.Blocked_Rxns = Blocked_Rxns; if ~isempty(map) MapVector = zeros(length(model_sav.rxns),1); MapVector(ismember(model_sav.rxns,Blocked_Rxns))= 1; MapVector(ismember(model_sav.rxns,ZeroFluxRxns))= 2; MapVector(ismember(model_sav.rxns,MLE_Rxns))= 3; MapVector(ismember(model_sav.rxns,ELE_Rxns))= 4; MapVector(ismember(model_sav.rxns,pFBAopt_Rxns))= 5; MapVector(ismember(model_sav.rxns,pFBAEssentialRxns))= 6; options.lb = 0; options.ub = 6; tmpCmap = hsv(18); tmpCmap = [tmpCmap([1,3,4,6,11,14],:); 0 0 0;]; options.fileName = mapOutName; options.colorScale = flipud(round(tmpCmap*255)); global CB_MAP_OUTPUT if ~exist('CB_MAP_OUTPUT', 'var') || isempty(CB_MAP_OUTPUT) changeCbMapOutput('svg'); end drawFlux(map, model_sav, MapVector, options); end end end function [ MinimizedFlux modelIrrev]= minimizeModelFlux_local(model,GeneOption) % This function finds the minimum flux through the network and returns the % minimized flux and an irreversible model % convert model to irrev modelIrrev = convertToIrreversible(model); % add pseudo-metabolite to measure flux through network if nargin==1,GeneOption=0; end if GeneOption==0, % signal that you want to minimize the sum of all gene and non-gene associated fluxes modelIrrev.S(end+1,:) = ones(size(modelIrrev.S(1,:))); elseif GeneOption==1, % signal that you want to minimize the sum of only gene-associated fluxes %find all reactions which are gene associated Ind=find(sum(modelIrrev.rxnGeneMat,2)>0); modelIrrev.S(end+1,:) = zeros(size(modelIrrev.S(1,:))); modelIrrev.S(end,Ind) = 1; end modelIrrev.b(end+1) = 0; modelIrrev.mets{end+1} = 'fluxMeasure'; % add a pseudo reaction that measures the flux through the network modelIrrev = addReaction(modelIrrev,'netFlux',{'fluxMeasure'},[-1],false,0,inf,0,'',''); % set the flux measuring demand as the objective modelIrrev.c = zeros(length(modelIrrev.rxns),1); modelIrrev = changeObjective(modelIrrev, 'netFlux'); % minimize the flux measuring demand (netFlux) MinimizedFlux = optimizeCbModel(modelIrrev,'min'); end
github
EPFL-LCSB/matTFA-master
reduceModel.m
.m
matTFA-master/ext/Cobra205_vDec2014/reduceModel.m
8,348
utf_8
1d56cf233017a4d6aa106e6c8714ab94
function [modelRed,hasFlux,maxes,mins] = reduceModel(model,tol,irrevFlag,verbFlag,negFluxAllowedFlag,checkConsistencyFlag,changeBoundsFlag) %reduceModel Removes from the model all of the reactions that are never used (max and % min are < tol). Finds the minimal bounds for the flux through each reaction. % Also returns the results for flux variability analysis (maxes, mins). % % [modelRed,hasFlux,maxes,mins] = reduceModel(model,tol,irrevFlag,verbFlag,negFluxAllowedFlag,checkConsistencyFlag,changeBoundsFlag) % %INPUT % model COBRA model structure % %OPTIONAL INPUTS % tol Tolerance for non-zero bounds - bounds smaller in absolute % value than this value will be set to zero (Default = 1e-6) % irrevFlag Determines if the models should be treated using % the irreversible form. (Default = false) % verbFlag Verbose output (Default = false) % negFluxAllowedFlag Allow negative fluxes through irrev reactions % (Default = false) % checkConsistencyFlag Do a consistency check of the optimal solution % (Default = true) % changeBoundsFlag Change upper/lower bounds to the minimal bounds % (Default = true) % %OUTPUTS % modelRed Reduced model % hasFlux The indexes of the reactions that are not blocked % in the model % maxes Maximum fluxes % mins Minimum fluxes % % Gregory Hannum and Markus Herrgard 7/20/05 % Sets the tolerance for zero flux determination if nargin < 2 global CBT_LP_PARAMS if (exist('CBT_LP_PARAMS', 'var')) if isfield(CBT_LP_PARAMS, 'objTol') tol = CBT_LP_PARAMS.objTol; else tol = 1e-6 end else tol = 1e-6; end end % Sets the irrevFlag to default if nargin < 3 irrevFlag = false; end % Print out more stuff if nargin < 4 verbFlag = false; end % Allow negative irreversible fluxes (default: reverse the reaction % direction) if (nargin < 5) negFluxAllowedFlag = false; end % Check if the reduced model produces consistent results if (nargin < 6) checkConsistencyFlag = true; end % Change to minimal bounds if (nargin < 7) changeBoundsFlag = true; end %declare some variables maxes = []; mins = []; %modelRed = model; [nMets,nRxns]= size(model.S); %obtain maxes and mins for the fluxes rxnID = 1; h = waitbar(0,'Model reduction in progress ...'); while rxnID <= nRxns if mod(rxnID,10) == 0 waitbar(rxnID/nRxns,h); end rxnName = model.rxns{rxnID}; if (verbFlag) fprintf('%s\t',rxnName); end % Set the objective function to the current reactiom tempModel = changeObjective(model,rxnName); if (irrevFlag && model.rev(rxnID)) % Make the forward reaction reversible temporarily tempModel.lb(rxnID) = -tempModel.ub(rxnID+1); % Disable the reverse reaction tempModel.ub(rxnID+1) = 0; end %solve for the minimum and maximum for the current reaction sol = optimizeCbModel(tempModel,'max',[]); if (sol.stat > 0) maxBound = sol.f; else maxBound = model.ub(rxnID); end sol = optimizeCbModel(tempModel,'min',[]); if (sol.stat > 0) minBound = sol.f; else minBound = model.lb(rxnID); end %eliminate very small boundaries and set predetermined reversible boundaries if abs(maxBound) < tol maxBound = 0; end % Ignore negative lower bounds for irrev reactions if abs(minBound) < tol || (minBound < 0 && ~model.rev(rxnID)) minBound = 0; end %set the new appropriate bounds if (irrevFlag && model.rev(rxnID)) if minBound < 0 && maxBound < 0 % Negative flux mins(rxnID) = 0; mins(rxnID+1) = -maxBound; maxes(rxnID) = 0; maxes(rxnID+1) = -minBound; elseif minBound < 0 && maxBound >= 0 % Reversible flux mins(rxnID:rxnID+1) = 0; maxes(rxnID) = maxBound; maxes(rxnID+1) = -minBound; elseif minBound >= 0 && maxBound >= 0 % Positive flux mins(rxnID) = minBound; mins(rxnID+1) = 0; maxes(rxnID) = maxBound; maxes(rxnID+1) = 0; end if (verbFlag) fprintf('%g\t%g\n',mins(rxnID),maxes(rxnID)); fprintf('%s\t',model.rxns{rxnID+1}); fprintf('%g\t%g\n',mins(rxnID+1),maxes(rxnID+1)); end % Jump over the reverse direction rxnID = rxnID + 1; else maxes(rxnID)=maxBound; mins(rxnID)=minBound; if (verbFlag) fprintf('%g\t%g\n',minBound,maxBound); end end rxnID = rxnID + 1; end if ( regexp( version, 'R20') ) close(h); end if (verbFlag) fprintf('\n'); end % Create a list of flux indexes that have non-zero flux (hasFlux) hasFluxSel = (abs(maxes) > tol | abs(mins) > tol); hasFlux = find(hasFluxSel); hasFlux = columnVector(hasFlux); % Remove reactions that are blocked modelRed = removeRxns(model,model.rxns(~hasFluxSel),irrevFlag,true); % Update bounds if (changeBoundsFlag) modelRed.lb = columnVector(mins(hasFlux)); modelRed.ub = columnVector(maxes(hasFlux)); selInconsistentBounds = (modelRed.ub < modelRed.lb); modelRed.ub(selInconsistentBounds) = modelRed.lb(selInconsistentBounds); %update the reversible list with new bounds nRxnsNew = size(modelRed.S,2); for rxnID = 1:nRxnsNew if (~irrevFlag) if (modelRed.lb(rxnID) >= 0) % Only runs in positive direction modelRed.rev(rxnID) = false; end if (modelRed.ub(rxnID) <= 0) % Only runs in negative direction -> reverse the reaction modelRed.rev(rxnID) = false; if (~negFluxAllowedFlag) ubTmp = modelRed.ub(rxnID); lbTmp = modelRed.lb(rxnID); modelRed.S(:,rxnID) = -modelRed.S(:,rxnID); modelRed.ub(rxnID) = -lbTmp; modelRed.lb(rxnID) = -ubTmp; modelRed.c(rxnID) = -modelRed.c(rxnID); modelRed.rxns{rxnID} = [modelRed.rxns{rxnID} '_r']; end end end end if (checkConsistencyFlag) fprintf('Perform model consistency check\n'); modelOK = checkConsistency(model,modelRed,tol); if (~modelOK) modelRed = expandBounds(model,modelRed,tol); end end else if (checkConsistencyFlag) fprintf('Perform model consistency check\n'); modelOK = checkConsistency(model,modelRed,tol); end end %% function modelRed = expandBounds(model,modelRed,tol) % Expand bounds to achieve the desired objective value % % modelRed = expandBounds(model,modelRed,tol) % modelOK = false; cushion = tol; tempModel = modelRed; while (~modelOK) narrowInd = find(modelRed.ub-modelRed.lb < cushion & modelRed.ub ~= modelRed.lb); tempModel.lb(narrowInd) = tempModel.lb(narrowInd) - cushion; narrowIrrevInd =intersect(narrowInd,find(~tempModel.rev)); tempModel.lb(narrowIrrevInd) = max(tempModel.lb(narrowIrrevInd),0); tempModel.ub(narrowInd) = tempModel.ub(narrowInd) + cushion; modelRed.lb(narrowInd) = tempModel.lb(narrowInd); modelRed.ub(narrowInd) = tempModel.ub(narrowInd); cushion = cushion*2; modelOK = checkConsistency(model,tempModel,tol); end %% function modelOK = checkConsistency(model,modelRed,tol) % % modelOK = checkConsistency(model,modelRed,tol) % if (sum(model.c ~= 0) > 0) % Original model solOrigMax = optimizeCbModel(model,'max',[]); solOrigMin = optimizeCbModel(model,'min',[]); % Reduced model solRedMax = optimizeCbModel(modelRed,'max',[]); solRedMin = optimizeCbModel(modelRed,'min',[]); diffMax = abs(solRedMax.f - solOrigMax.f); diffMin = abs(solRedMin.f - solOrigMin.f); if (diffMax > tol || diffMin > tol) fprintf('Inconsistent objective values %g %g %g %g\n',solOrigMax.f,solRedMax.f,solOrigMin.f,solRedMin.f); modelOK = false; else fprintf('Model is consistent\n'); modelOK = true; end else modelOK = true; end
github
EPFL-LCSB/matTFA-master
drawLine.m
.m
matTFA-master/ext/Cobra205_vDec2014/maps/tools/drawLine.m
6,310
utf_8
4e8f08121c24f5717852ff9ffa6451d7
function drawLine(node1,node2,map,edgeColor,edgeArrowColor,edgeWeight,nodeWeight,rxnDir,rxnDirMultiplier) %drawLine % % drawLine(node1,node2,map,edgeColor,edgeArrowColor,edgeWeight,nodeWeight) % %INPUTS % node1 start node % node2 end node % map COBRA map structure % edgeColor Line color % edgeArrowColor Arrowhead color % edgeWeight Line width % %OPTIONAL INPUT % nodeWeight Node size % % if nargin < 9 rxnDirMultipler = 2; end if nargin < 8 rxnDir = 0; end if (nargin < 7) rad = 20; else index1 = find(map.molIndex(:) == node1); index2 = find(map.molIndex(:) == node2); if length(index1) == 1 rad = nodeWeight(index1); elseif length(index2) == 1 rad = nodeWeight(index2); else rad = 20; end end if isnan(node1) || isnan(node2) return; end [type1, nodePos(:,1)] = getType(node1, map); [type2, nodePos(:,2)] = getType(node2, map); p1 = nodePos(:,1); p2 = nodePos(:,2); if type1 == 1 && type2 == 1 drawVector(nodePos(:,1),nodePos(:,2),edgeColor,edgeWeight); elseif type1 == 1 && type2 == 2 %drawCircle(p2, 3, 'r'); index1 = find(map.connection(:,1) == node2); index2 = find(map.connection(:,2) == node2); isend = 0; if map.connectionReversible(index1) == 1 isend = 1; end if length(index1) == 1 && length(index2) == 1 % case metabolite to center reaction. [point1,dir] = c2p(nodePos(:,1),nodePos(:,2),rad); drawVector(point1, nodePos(:,2),edgeColor,edgeWeight); if isend if rxnDir < 0, rad = rad*rxnDirMultiplier; end drawArrowhead(point1,dir,rad,edgeArrowColor); end elseif length(index1) > 1 && length(index2) == 1 display('blah'); % for some reason this doesn't happen. (metabolite node cannot have more than one point) elseif length(index1) == 1 && length(index2) > 1 othernode = map.connection(index1,2); [t3,p3] = getType(othernode, map); %%%p3 = p3'; direction = p2-p3; %direction = p3-p2; if any(direction~=0) dirnorm = direction/(norm(direction)); else dirnorm = zeros(size(direction)); end multiplier = dirnorm' * (p1-p2); multiplier = max([.3*norm(p2-p1), multiplier]); ptemp = p2 + multiplier*dirnorm; distance = norm(ptemp-p1); if distance < multiplier multiplier = mean([multiplier, distance]); end ptemp = p2 + multiplier*dirnorm; %drawCircle(ptemp,5,'m'); %drawCircle(p3,5,'g'); [p1,dir] = c2p(p1,ptemp,rad); drawBezier([p2,ptemp,p1],edgeColor,edgeWeight); if isend if rxnDir < 0, rad = rad*rxnDirMultiplier; end drawArrowhead(p1,dir,rad,edgeArrowColor) end else display('oops'); end elseif type1 == 2 && type2 == 1 %drawCircle(p1, 3, 'y'); index1 = find(map.connection(:,1) == node1); index2 = find(map.connection(:,2) == node1); % if length(index1) == 1 && length(index2) == 1 % case metabolite to center reaction. % [point2,dir] = c2p(nodePos(:,2),nodePos(:,1),rad); % drawVector(nodePos(:,1), point2,edgeColor,edgeWeight); % drawArrowhead(point2,dir,rad,edgeArrowColor); % elseif length(index1) > 1 && length(index2) == 1 othernode = map.connection(index2,1); [t3,p3] = getType(othernode, map); %%%p3 = p3'; direction = p1-p3; if any(direction~=0) dirnorm = direction/(norm(direction)); else dirnorm = zeros(size(direction)); end multiplier = dirnorm' * (p2-p1); multiplier = max([ .3*norm(p2-p1), multiplier]); ptemp = p1 + multiplier*dirnorm; distance = norm(ptemp-p2); if distance < multiplier multiplier = mean([multiplier, distance]); end ptemp = p1 + multiplier*dirnorm; %drawCircle(ptemp,5,'m'); %drawCircle(p3,5,'g'); [p2,dir] = c2p(p2,ptemp,rad); drawBezier([p1,ptemp,p2],edgeColor,edgeWeight); if rxnDir > 0, rad = rad*rxnDirMultiplier; end drawArrowhead(p2,dir,rad,edgeArrowColor); % elseif length(index1) == 1 && length(index2) > 1 % display('blah2');% for some reason this doesn't happen. % else % display('oops'); % end elseif type1 ==2 && type2 == 2 drawVector(nodePos(:,1),nodePos(:,2),edgeColor,edgeWeight); else display('oops'); pause; end % % display the reaction label in case of a midpoint % if rxnTextWeight ~= 0 % if type1 == 2 % index1 = find(map.rxnIndex == node1); % if map.rxnLabelPosition(1,index1)~= 0 % index2 = find(map.connection(:,1) == node1); % drawText(map.rxnLabelPosition(1,index1),map.rxnLabelPosition(2,index1),map.connectionAbb(index2),rxnTextWeight,'italic;'); % end % end % if type2 == 2 % index1 = find(map.rxnIndex == node1); % if map.rxnLabelPosition(1,index1)~= 0 % index2 = find(map.connection(:,2) == node2); % drawText(map.rxnLabelPosition(1,index1),map.rxnLabelPosition(2,index1),map.connectionAbb(index2),rxnTextWeight,'italic'); % end % end % end end function [type, position] = getType(node, map) % you could also have it output a third value which could be the index of the preceding node. molIndex = find(map.molIndex == node); rxnIndex = find(map.rxnIndex == node); if ~isempty(molIndex) type = 1; %molecule position = map.molPosition(:,molIndex); elseif ~isempty(rxnIndex) type = 2; % reaction. position = map.rxnPosition(:,rxnIndex); %Add more code here to figure out subtype of reaction node. else % should never get here, but go ahead and scan for errors. display('errorXYZ in drawLine.m'); % pause; end if numel(molIndex) > 1 || numel(rxnIndex) > 1 % this means that it is not unique. display('error2'); % pause; end end % move p1 from the center of the circle to the pyrimid of the circle in the % direction of p2 function [point,dir] = c2p(p1,p2,rad) dir = p2-p1; point = p1+rad*(dir/sqrt(dir(1)^2+dir(2)^2)); end
github
EPFL-LCSB/matTFA-master
calcGroupStats.m
.m
matTFA-master/ext/Cobra205_vDec2014/tools/calcGroupStats.m
3,452
utf_8
06bebf75a99b8cf627b1054f5738961f
function [groupStat,groupList,groupCnt,zScore] = calcGroupStats(data,groups,statName,groupList,randStat,nRand) %calcGroupStats Calculate statistics such as mean or standard deviation for %subgroups of a population % % [groupStat,groupList,groupCnt,zScore] = % calcGroupStats(data,groups,statName,groupList,randStat,nRand) % % data Matrix of data (individuals x variables) % groups Group identifier for each individual % statName Name of the statistic to be computed for each group: % 'mean': mean value for group (default) % 'std': standard deviation for group % 'median': median for group % 'count': sum total of variable values for group % groupList List of group identifiers to be considered (optional, default % all values occurring in groups) % randStat Perform randomization analysis % nRand # of randomizations % % Group identifier can be either strings or numerical values % % groupStat Matrix of group statistic values for each group and variable % groupList List of group identifiers considered % groupCount Number of individuals in a group % % Markus Herrgard 2006 [nItems,nSets] = size(data); if (nargin < 3) statName = 'mean'; end if (nargin < 4) groupList = unique(groups); end if (isempty(groupList)) groupList = unique(groups); end if (nargin < 5) randStat = false; end if (nargin < 6) nRand = 1000; end if iscell(groups) cellFlag = true; else cellFlag = false; end for i = 1:length(groupList) if (cellFlag) selGroup = strcmp(groups,groupList{i}); else selGroup = (groups == groupList(i)); end selData = data(selGroup,:); groupCnt(i) = sum(selGroup); groupStat(i,:) = calcStatInternal(groupCnt(i),selData,statName,nSets); end groupCnt = groupCnt'; if (randStat) groupCntList = unique(groupCnt); zScore = zeros(length(groupList),nSets); for i = 1:length(groupCntList) thisGroupCnt = groupCntList(i); selGroups = find(groupCnt == thisGroupCnt); if (thisGroupCnt > 0) for j = 1:nRand randInd = randperm(nItems); randData = data(randInd(1:thisGroupCnt),:); groupStatRand(j,:) = calcStatInternal(thisGroupCnt,randData,statName,nSets); end groupStatRandMean = nanmean(groupStatRand); groupStatRandStd = nanstd(groupStatRand); nGroups = length(selGroups); zScore(selGroups,:) = (groupStat(selGroups,:)-repmat(groupStatRandMean,nGroups,1))./repmat(groupStatRandStd,nGroups,1); end end end function groupStat = calcStatInternal(groupCnt,data,statName,nSets) if (groupCnt > 0) switch lower(statName) case 'mean' if (groupCnt > 1) groupStat = nanmean(data); else groupStat = data; end case 'std' if (groupCnt > 1) groupStat = nanstd(data); else groupStat = zeros(1,nSets); end case 'median' if (groupCnt > 1) groupStat = nanmedian(data); else groupStat = data; end case 'count' if (groupCnt > 1) groupStat = nansum(data); else groupStat = data; end end else groupStat = ones(1,nSets)*NaN; end
github
EPFL-LCSB/matTFA-master
solveBooleanRegModel.m
.m
matTFA-master/ext/Cobra205_vDec2014/rFBA/solveBooleanRegModel.m
3,855
utf_8
c3c1af861606efb5eb37d3e177c748a7
function [finalState,finalInputs1States,finalInputs2States] = solveBooleanRegModel(model,initialState,inputs1States,inputs2States) % solveBooleanRegModel - determines the next state of the regulatory % network based on the current state. Called by optimizeRegModel and % dynamicRFBA % % [finalState,finalInputs1States,finalInputs2States] = % solveBooleanRegModel(model,initialState,inputs1States,inputs2States) % % model a regulatory COBRA model % initialState initial state of regulatory network % inputs1States initial state of type 1 inputs (metabolites) % inputs2States initial state of type 2 inputs (reactions) % % finalState final state of regulatory network % finalInputs1States final state of type 1 inputs % finalInputs2States final state of type 2 inputs % % Jeff Orth 7/24/08 % determine state of inputs % determine external metabolite levels from exchange rxn bounds (maybe change this later) finalInputs1States = []; [selExc,selUpt] = findExcRxns(model); %get all exchange rxns for i = 1:length(model.regulatoryInputs1) met = model.regulatoryInputs1{i}; fullS = full(model.S); rxnID = intersect(find(fullS(findMetIDs(model,met),:)),find(selExc)); if model.lb(rxnID) < 0 finalInputs1States(i,1) = true; else finalInputs1States(i,1) = false; end end % apply initialState to model, get rxn fluxes drGenes = {}; for i = 1:length(model.regulatoryGenes) if initialState(i) == false drGenes{length(drGenes)+1} = model.regulatoryGenes{i}; end end drGenes = intersect(model.genes,drGenes); % remove genes not associated with rxns modelDR = deleteModelGenes(model,drGenes); % set rxns to 0 fbasolDR = optimizeCbModel(modelDR,'max',true); % if rxn flux = 0, set state to false finalInputs2States = []; if ~any(fbasolDR.x) finalInputs2States = false.*ones(length(model.regulatoryInputs2),1); else for i = 1:length(model.regulatoryInputs2) rxnFlux = fbasolDR.x(findRxnIDs(model,model.regulatoryInputs2{i})); if rxnFlux == 0 finalInputs2States(i,1) = false; else finalInputs2States(i,1) = true; end end end % determine state of genes ruleList = parseRegulatoryRules(model); %get the set of rules in a form that can be evaluated geneStates = []; for i = 1:length(model.regulatoryRules) geneStates(i,1) = eval(ruleList{i}); end finalState = geneStates; %% parseRegulatoryRules function ruleList = parseRegulatoryRules(model) ruleList = cell(length(model.regulatoryRules),1); %preallocate array for i = 1:length(model.regulatoryRules) fields = splitString(model.regulatoryRules{i},'[\s~|&()]'); newFields = fields; for j = 1:length(fields) %iterate through words and replace word = fields{j}; if strcmp(word,'true') newFields{j} = 'true'; elseif strcmp(word,'false') newFields{j} = 'false'; else if any(strcmp(word,model.regulatoryGenes)) index = find(strcmp(word,model.regulatoryGenes)); newFields{j} = ['initialState(',num2str(index),')']; elseif any(strcmp(word,model.regulatoryInputs1)) index = find(strcmp(word,model.regulatoryInputs1)); newFields{j} = ['inputs1States(',num2str(index),')']; elseif any(strcmp(word,model.regulatoryInputs2)) index = find(strcmp(word,model.regulatoryInputs2)); newFields{j} = ['inputs2States(',num2str(index),')']; else newFields{j} = ''; %no match, delete the invalid word end end end newRule = model.regulatoryRules{i}; for j = 1:length(fields) newRule = strrep(newRule,fields{j},newFields{j}); end ruleList{i} = newRule; end
github
EPFL-LCSB/matTFA-master
readCbModel.m
.m
matTFA-master/ext/Cobra205_vDec2014/io/readCbModel.m
12,794
utf_8
96786224cfdf9e5aa3330142d7524196
function model = readCbModel(fileName,defaultBound,fileType,modelDescription,compSymbolList,compNameList) %readCbModel Read in a constraint-based model % % model = readCbModel(fileName,defaultBound,fileType,modelDescription) % % If no arguments are passed to the function, the user will be prompted for % a file name. % %OPTIONAL INPUTS % fileName File name for file to read in (optional) % defaultBound Default value for maximum flux through a reaction if % not given in the SBML file (Default = 1000) % fileType File type for input files: 'SBML', 'SimPheny', or % 'SimPhenyPlus', 'SimPhenyText' (Default = 'SBML') % * SBML indicates a file in SBML format % * SimPheny is a set of three files in SimPheny % simulation output format % * SimPhenyPlus is the same as SimPheny except with % additionalfiles containing gene-protein-reaction % associations andcompound information % * SimPhenyText is the same as SimPheny except with % additionaltext file containing gene-protein-reaction % associations % modelDescription Description of model contents % compSymbolList Compartment Symbol List % compNameList Name of compartments corresponding to compartment % symbol list % %OUTPUT % Returns a model in the COBRA format: % % model % description Description of model contents % rxns Reaction names % mets Metabolite names % S Stoichiometric matrix % lb Lower bounds % ub Upper bounds % rev Reversibility vector % c Objective coefficients % subSystems Subsystem name for each reaction (opt) % grRules Gene-reaction association rule for each reaction (opt) % rules Gene-reaction association rule in computable form (opt) % rxnGeneMat Reaction-to-gene mapping in sparse matrix form (opt) % genes List of all genes (opt) % rxnNames Reaction description (opt) % metNames Metabolite description (opt) % metFormulas Metabolite chemical formula (opt) % %EXAMPLES OF USE: % % 1) Load a file to be specified in a dialog box: % % model = readCbModel; % % 2) Load model named 'iJR904' in SBML format with maximum flux set % at 1000 (requires file named 'iJR904.xml' to exist) % % model = readCbModel('iJR904',1000,'SBML'); % % 3) Load model named 'iJR904' in SimPheny format with maximum flux set % at 500 (requires files named 'iJR904.rxn', 'iJR904.met', and 'iJR904.sto' to exist) % % model = readCbModel('iJR904',500,'SimPheny'); % % 4) Load model named 'iJR904' in SimPheny format with gpr and compound information % (requires files named 'iJR904.rxn', 'iJR904.met','iJR904.sto', % 'iJR904_gpr.txt', and 'iJR904_cmpd.txt' to exist) %, % model = readCbModel('iJR904',500,'SimPhenyPlus'); % % Markus Herrgard 7/11/06 % % Richard Que 02/08/10 - Added inptus for compartment names and symbols %% Process arguments if (nargin < 2) defaultBound = 1000; else if (isempty(defaultBound)) defaultBound = 1000; end end if (nargin < 3) fileType = 'SBML'; if (isempty(fileType)) fileType = 'SBML'; end end % Open a dialog to select file if (nargin < 1) [fileNameFull,filePath] = uigetfile({'*.xml';'*.sto'}); if (fileNameFull) [t1,t2,t3,t4,tokens] = regexp(fileNameFull,'(.*)\.(\w*)'); noPathName = tokens{1}{1}; fileTypeTmp = tokens{1}{2}; fileName = [filePath noPathName]; else model = 0; return; end switch fileTypeTmp case 'xml' fileType = 'SBML'; case 'sto' fileType = 'SimPheny'; otherwise error('Cannot process this file type'); end end if (nargin < 4) if (exist('filePath')) modelDescription = noPathName; else modelDescription = fileName; end end if (nargin < 5) compSymbolList = {}; compNameList = {}; end switch fileType case 'SBML', if isempty(regexp(fileName,'\.xml$', 'once')) model = readSBMLCbModel([fileName '.xml'],defaultBound,compSymbolList,compNameList); else model = readSBMLCbModel(fileName,defaultBound,compSymbolList,compNameList); end case 'SimPheny', model = readSimPhenyCbModel(fileName,defaultBound,compSymbolList,compNameList); case 'SimPhenyPlus', model = readSimPhenyCbModel(fileName,defaultBound,compSymbolList,compNameList); model = readSimPhenyGprCmpd(fileName,model); case 'SimPhenyText', model = readSimPhenyCbModel(fileName,defaultBound,compSymbolList,compNameList); model = readSimPhenyGprText([fileName '_gpra.txt'],model); otherwise, error('Unknown file type'); end % Check reversibility model = checkReversibility(model); % Check uniqueness of metabolite and reaction names checkCobraModelUnique(model); model.b = zeros(length(model.mets),1); model.description = modelDescription; % End main function %% Make sure reversibilities are correctly indicated in the model function model = checkReversibility(model) selRev = (model.lb < 0 & model.ub > 0); model.rev(selRev) = 1; %% readSBMLCbModel Read SBML format constraint-based model function model = readSBMLCbModel(fileName,defaultBound,compSymbolList,compNameList) if ~(exist(fileName,'file')) error(['Input file ' fileName ' not found']); end if isempty(compSymbolList) compSymbolList = {'c','m','v','x','e','t','g','r','n','p'}; compNameList = {'Cytosol','Mitochondria','Vacuole','Peroxisome','Extra-organism','Pool','Golgi Apparatus','Endoplasmic Reticulum','Nucleus','Periplasm'}; end % Read SBML modelSBML = TranslateSBML(fileName); % Convert model = convertSBMLToCobra(modelSBML,defaultBound,compSymbolList,compNameList); %% function model = readSimPhenyCbModel(baseName,defaultBound,compSymbolList,compNameList) %readSimPhenyCbModel Read a SimPheny metabolic model % % model = readSimPhenyCbModel(baseName,defaultBound) % % baseName Base filename for models % vMax Maximum flux through a reaction % % model.mets Metabolite names % model.rxns Reaction names % model.rev Reversible (1)/Irreversible (0) % model.lb Lower bound % model.ub Upper bound % model.c Objective coefficients % model.S Stoichiometric matrix % % Markus Herrgard 8/3/04 if (nargin < 2) defaultBound = 1000; end if ~(exist([baseName '.met'],'file') & exist([baseName '.rxn'],'file') & exist([baseName '.sto'],'file')) error('One or more input files not found'); end if isempty(compSymbolList) compSymbolList = {'c','m','v','x','e','t','g','r','n','p'}; compNameList = {'Cytosol','Mitochondria','Vacuole','Peroxisome','Extra-organism','Pool','Golgi Apparatus','Endoplasmic Reticulum','Nucleus','Periplasm'}; end % Get the metabolite names fid = fopen([baseName '.met']); cnt = 0; while 1 tline = fgetl(fid); if ~ischar(tline), break, end if (~isempty(regexp(tline,'^\d', 'once'))) cnt = cnt + 1; fields = splitString(tline,'\t'); mets{cnt} = fields{2}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % mets{cnt} = strrep(mets{cnt}, '(', '['); % mets{cnt} = strrep(mets{cnt}, ')', ']'); comp{cnt,1} = fields{4}; % compSymb = compSymbolList{strcmp(compNameList,comp{cnt})}; compSymb = 0; TF = strcmp('comp{cnt}', compNameList); for n = 1:length(compNameList) if TF(n) compSymb = compSymbolList{n}; end end if (isempty(compSymb)) compSymb = comp{cnt}; end if (~isempty(regexp(mets{cnt},'\(', 'once'))) mets{cnt} = strrep(mets{cnt},'(','['); mets{cnt} = strrep(mets{cnt},')',']'); else mets{cnt} = [mets{cnt} '[' compSymb ']']; end metNames{cnt} = fields{3}; end end fclose(fid); mets = columnVector(mets); metNames = columnVector(metNames); % Get the reaction names, lower/upper bounds, and reversibility fid = fopen([baseName '.rxn']); cnt = 0; startRxns = false; while 1 tline = fgetl(fid); if ~ischar(tline), break, end if (regexp(tline,'^REACTION')) startRxns = true; end if (startRxns & ~isempty(regexp(tline,'^\d', 'once'))) cnt = cnt + 1; fields = splitString(tline,'\t'); rxns{cnt} = fields{2}; rxnNames{cnt} = fields{3}; revStr{cnt} = fields{4}; lb(cnt) = str2num(fields{5}); ub(cnt) = str2num(fields{6}); c(cnt) = str2num(fields{7}); end end fclose(fid); revStr = columnVector(revStr); rev = strcmp(revStr,'Reversible'); rxns = columnVector(rxns); rxnNames = columnVector(rxnNames); lb = columnVector(lb); ub = columnVector(ub); c = columnVector(c); lb(lb < -defaultBound) = -defaultBound; ub(ub > defaultBound) = defaultBound; % Get the stoichiometric matrix fid = fopen([baseName '.sto']); fid2 = fopen('load_simpheny.tmp','w'); while 1 tline = fgetl(fid); if ~ischar(tline), break, end % This here might give some problems, but it worked for the iJR904 % model if (~isempty(regexp(tline,'^[-0123456789.]', 'once'))) fprintf(fid2,[tline '\n']); else % For debugging %tline end end fclose(fid); fclose(fid2); S = load('load_simpheny.tmp'); % tmp = regexp(rxns,'deleted'); % sel_rxn = ones(length(rxns),1); % for i = 1:length(tmp) % if (~isempty(tmp{i})) % sel_rxn(i) = 0; % end % end % % tmp = regexp(mets,'deleted'); % sel_met = ones(length(mets),1); % for i = 1:length(tmp) % if (~isempty(tmp{i})) % sel_met(i) = 0; % end % end % Store the variables in a structure model.mets = mets; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% model.metComps = comp; model.metNames = metNames; model.rxns = removeDeletedTags(rxns); model.rxnNames = rxnNames; model.rev = rev; model.lb = lb; model.ub = ub; model.c = c; model.S = sparse(S); % Delete the temporary file delete('load_simpheny.tmp'); %% function list = removeDeletedTags(list) %removeDeletedTags Get rid of the [deleted tags in the SimPheny files % % list = removeDeletedTags(list) % % 5/19/05 Markus Herrgard for i = 1:length(list) item = list{i}; ind = strfind(item,' [deleted'); if (~isempty(ind)) list{i} = item(1:(ind-1)); end end %% readSimPhenyGprCmpd Read SimPheny GPRA and compound data and integrate it % with the model function model = readSimPhenyGprCmpd(baseName,model) [rxnInfo,rxns,allGenes] = readSimPhenyGPR([baseName '_gpr.txt']); nRxns = length(model.rxns); % Construct gene to rxn mapping rxnGeneMat = sparse(nRxns,length(allGenes)); h = waitbar(0,'Constructing GPR mapping ...'); for i = 1:nRxns rxnID = find(ismember(rxns,model.rxns{i})); if (~isempty(rxnID)) if mod(i,10) == 0 waitbar(i/nRxns,h); end [tmp,geneInd] = ismember(rxnInfo(rxnID).genes,allGenes); rxnGeneMat(i,geneInd) = 1; rules{i} = rxnInfo(rxnID).rule; grRules{i} = rxnInfo(rxnID).gra; grRules{i} = regexprep(grRules{i},'\s{2,}',' '); grRules{i} = regexprep(grRules{i},'( ','('); grRules{i} = regexprep(grRules{i},' )',')'); subSystems{i} = rxnInfo(rxnID).subSystem; for j = 1:length(geneInd) %rules{i} = strrep(rules{i},['x(' num2str(j) ')'],['x(' num2str(geneInd(j)) ')']); rules{i} = strrep(rules{i},['x(' num2str(j) ')'],['x(' num2str(geneInd(j)) '_TMP_)']); end rules{i} = strrep(rules{i},'_TMP_',''); else rules{i} = ''; grRules{i} = ''; subSystems{i} = ''; end end if ( regexp( version, 'R20') ) close(h); end %% Read SimPheny cmpd output file [metInfo,mets] = readSimPhenyCMPD([baseName '_cmpd.txt']); baseMets = parseMetNames(model.mets); nMets = length(model.mets); h = waitbar(0,'Constructing metabolite lists ...'); for i = 1:nMets if mod(i,10) == 0 waitbar(i/nMets,h); end metID = find(ismember(mets,baseMets{i})); if (~isempty(metID)) metFormulas{i} = metInfo(metID).formula; else metFormulas{i} = ''; end end if ( regexp( version, 'R20') ) close(h); end model.rxnGeneMat = rxnGeneMat; model.rules = columnVector(rules); model.grRules = columnVector(grRules); model.genes = columnVector(allGenes); model.metFormulas = columnVector(metFormulas); model.subSystems = columnVector(subSystems);
github
EPFL-LCSB/matTFA-master
convertCobraToSBML.m
.m
matTFA-master/ext/Cobra205_vDec2014/io/convertCobraToSBML.m
10,266
utf_8
ff076a85c6b0755e496ccb290d0442e2
function sbmlModel = convertCobraToSBML(model,sbmlLevel,sbmlVersion,compSymbolList,compNameList,debug_function) %convertCobraToSBML converts a cobra structure to an sbml %structure using the structures provided in the SBML toolbox 3.1.0 % % sbmlModel = convertCobraToSBML(model,sbmlLevel,sbmlVersion,compSymbolList,compNameList) % %INPUTS % model COBRA model structure % %OPTIONAL INPUTS % sbmlLevel SBML Level (default = 2) % sbmlVersion SBML Version (default = 1) % compSymbolList List of compartment symbols % compNameList List of copmartment names correspoding to compSymbolList % %OUTPUT % sbmlModel SBML MATLAB structure % % %NOTE: The name mangling of reaction and metabolite ids is necessary %for compliance with the SBML sID standard. % %NOTE: Sometimes the Model_create function doesn't listen to the %sbmlVersion parameter, so it is essential that the items that %are added to the sbmlModel are defined with the sbmlModel's level %and version: sbmlModel.SBML_level,sbmlModel.SBML_version % %NOTE: Some of the structures are recycled to reduce to overhead for %their creation. There's a chance this can cause bugs in the future. % %NOTE: Currently, I don't add in the boundary metabolites. % %NOTE: Speed could probably be improved by directly adding structures to %lists in a struct instead of using the SBML _addItem function, but this %could break in future versions of the SBML toolbox. % %POTENTIAL FUTURE BUG: To speed things up, sbml structs have been %recycled and are directly appended into lists instead of using _addItem if (~exist('sbmlLevel','var') || isempty(sbmlLevel)) sbmlLevel = 2; end if (~exist('sbmlVersion','var') || isempty(sbmlVersion)) sbmlVersion = 1; end if (~exist('debug_function','var') || isempty(debug_function)) debug_function = 0; end reaction_units = 'mmol_per_gDW_per_hr'; sbmlModel = Model_create(sbmlLevel, sbmlVersion); sbmlModel.namespaces = struct(); sbmlModel.namespaces.prefix = ''; sbmlModel.namespaces.uri = 'http://www.sbml.org/sbml/level2'; if isfield(model,'description') sbmlModel.id = strrep(strrep(strrep(model.description,'.','_'), filesep, '_'), ':','_'); else sbmlModel.id = ''; end %POTENTIAL FUTURE BUG: Create temporary structs to speed things up. tmp_unit = Unit_create(sbmlModel.SBML_level, sbmlModel.SBML_version); tmp_species = Species_create(sbmlModel.SBML_level, sbmlModel.SBML_version); sbml_tmp_compartment = Compartment_create(sbmlModel.SBML_level, sbmlModel.SBML_version); sbml_tmp_parameter = Parameter_create(sbmlModel.SBML_level, sbmlModel.SBML_version); sbml_tmp_species_ref = SpeciesReference_create(sbmlModel.SBML_level, sbmlModel.SBML_version); sbml_tmp_reaction = Reaction_create(sbmlModel.SBML_level, sbmlModel.SBML_version); sbml_tmp_law = KineticLaw_create(sbmlModel.SBML_level, sbmlModel.SBML_version); tmp_unit_definition = UnitDefinition_create(sbmlModel.SBML_level, sbmlModel.SBML_version); %% Compartments if ~exist('compSymbolList','var') || isempty(compSymbolList) compSymbolList = {'c','m','v','x','e','t','g','r','n','p','l'}; compNameList = {'Cytoplasm','Mitochondrion','Vacuole','Peroxisome','Extracellular','Pool','Golgi','Endoplasmic_reticulum','Nucleus','Periplasm','Lysosome'}; end %Create and add the unit definition to the sbml model struct. tmp_unit_definition.id = reaction_units; %The 4 following lists are in matched order for each unit. unit_kinds = {'mole','gram','second'}; unit_exponents = [1 -1 -1]; unit_scales = [-3 0 0]; unit_multipliers = [1 1 1.0/60/60]; %Add the units to the unit definition for i = 1:size(unit_kinds, 2) tmp_unit.kind = unit_kinds{ i }; tmp_unit.exponent = unit_exponents(i); tmp_unit.scale = unit_scales(i); tmp_unit.multiplier = unit_multipliers(i); tmp_unit_definition = UnitDefinition_addUnit(tmp_unit_definition, tmp_unit); end if debug_function if ~isSBML_Unit(tmp_unit_definition) error('unit definition failed') end end sbmlModel = Model_addUnitDefinition(sbmlModel, tmp_unit_definition); %List to hold the compartment ids. the_compartments = {}; %separate metabolite and compartment [tokens tmp_met_struct] = regexp(model.mets,'(?<met>.+)\[(?<comp>.+)\]|(?<met>.+)\((?<comp>.+)\)','tokens','names'); for (i=1:size(model.mets, 1)) tmp_notes=''; tmp_met = tmp_met_struct{i}.met; %Change id to correspond to SBML id specifications tmp_met = strcat('M_', (tmp_met), '_', tmp_met_struct{i}.comp); model.mets{ i } = formatForSBMLID(tmp_met); tmp_species.id = formatForSBMLID(tmp_met); tmp_species.compartment = formatForSBMLID(tmp_met_struct{i}.comp); if isfield(model, 'metNames') tmp_species.name = (model.metNames{i}); end if isfield(model, 'metFormulas') tmp_notes = [tmp_notes '<p>FORMULA: ' model.metFormulas{i} '</p>']; end if isfield(model, 'metCharge') %NOTE: charge is being removed in SBML level 3 % tmp_species.charge = model.metCharge(i); % tmp_species.isSetCharge = 1; tmp_notes = [tmp_notes '<p>CHARGE: ' num2str(model.metCharge(i)) '</p>']; end if ~isempty(tmp_notes) tmp_species.notes = ['<body xmlns="http://www.w3.org/1999/xhtml">' tmp_notes '</body>']; end sbmlModel.species = [ sbmlModel.species tmp_species ]; %This is where the compartment symbols are aggregated. the_compartments{ i } = tmp_species.compartment ; end if debug_function for (i = 1:size(sbmlModel.species, 2)) if ~isSBML_Species(sbmlModel.species(i), sbmlLevel, sbmlVersion) error('SBML species failed to pass test') end end end %Add the unique compartments to the model struct. the_compartments = unique(the_compartments); for (i=1:size(the_compartments,2)) tmp_id = the_compartments{1,i}; tmp_symbol_index = find(strcmp(formatForSBMLID(compSymbolList),tmp_id)); %Check that symbol is in compSymbolList if ~isempty(tmp_symbol_index) tmp_name = compNameList{tmp_symbol_index}; else error(['Unknown compartment: ' tmp_id '. Be sure that ' tmp_id ' is specified in compSymbolList and compNameList.']) end tmp_id = formatForSBMLID(tmp_id); sbml_tmp_compartment.id = tmp_id; sbml_tmp_compartment.name = tmp_name; sbmlModel = Model_addCompartment(sbmlModel, sbml_tmp_compartment); end if debug_function for (i = 1:size(sbmlModel.compartment, 2)) if ~isSBML_Compartment(sbmlModel.compartment(i), sbmlLevel, sbmlVersion) error('SBML compartment failed to pass test') end end end %Add the reactions to the model struct. Use the species references. sbml_tmp_parameter.units = reaction_units; sbml_tmp_parameter.isSetValue = 1; for (i=1:size(model.rxns, 1)) tmp_id = strcat('R_', formatForSBMLID(model.rxns{i})); model.rxns{i} = tmp_id; met_idx = find(model.S(:, i)); sbml_tmp_reaction.notes = ''; %Reset the fields that have been filled. sbml_tmp_reaction.reactant = []; sbml_tmp_reaction.product = []; sbml_tmp_reaction.kineticLaw = []; sbml_tmp_reaction.id = tmp_id; if isfield(model, 'rxnNames') sbml_tmp_reaction.name = model.rxnNames{i}; end if isfield(model, 'rev') sbml_tmp_reaction.reversible = model.rev(i); end sbml_tmp_law.parameter = []; sbml_tmp_law.formula = 'FLUX_VALUE'; sbml_tmp_parameter.id = 'LOWER_BOUND'; sbml_tmp_parameter.value = model.lb(i); sbml_tmp_law.parameter = [ sbml_tmp_law.parameter sbml_tmp_parameter ]; sbml_tmp_parameter.id = 'UPPER_BOUND'; sbml_tmp_parameter.value = model.ub(i); sbml_tmp_law.parameter = [ sbml_tmp_law.parameter sbml_tmp_parameter ]; sbml_tmp_parameter.id = 'FLUX_VALUE'; sbml_tmp_parameter.value = 0; sbml_tmp_law.parameter = [ sbml_tmp_law.parameter sbml_tmp_parameter ]; sbml_tmp_parameter.id = 'OBJECTIVE_COEFFICIENT'; sbml_tmp_parameter.value = model.c(i); sbml_tmp_law.parameter = [ sbml_tmp_law.parameter sbml_tmp_parameter ]; sbml_tmp_reaction.kineticLaw = sbml_tmp_law; %Add in other notes tmp_note = ''; if isfield(model, 'grRules') tmp_note = [tmp_note '<p>GENE_ASSOCIATION: ' model.grRules{i} '</p>' ]; end if isfield(model, 'subSystems') tmp_note = [ tmp_note ' <p>SUBSYSTEM: ' model.subSystems{i} '</p>']; end if isfield(model, 'rxnECNumbers') tmp_note = [ tmp_note ' <p>EC Number: ' model.rxnECNumbers{i} '</p>']; end if isfield(model, 'confidenceScores') tmp_note = [ tmp_note ' <p>Confidence Level: ' model.confidenceScores{i} '</p>']; end if isfield(model, 'rxnReferences') tmp_note = [ tmp_note ' <p>AUTHORS: ' model.rxnReferences{i} '</p>']; end if isfield(model, 'rxnNotes') tmp_note = [ tmp_note ' <p>' model.rxnNotes{i} '</p>']; end if ~isempty(tmp_note) sbml_tmp_reaction.notes = ['<body xmlns="http://www.w3.org/1999/xhtml">' tmp_note '</body>']; end %Add in the reactants and products for (j_met=1:size(met_idx,1)) tmp_idx = met_idx(j_met,1); sbml_tmp_species_ref.species = model.mets{tmp_idx}; met_stoich = model.S(tmp_idx, i); sbml_tmp_species_ref.stoichiometry = abs(met_stoich); if (met_stoich > 0) sbml_tmp_reaction.product = [ sbml_tmp_reaction.product sbml_tmp_species_ref ]; else sbml_tmp_reaction.reactant = [ sbml_tmp_reaction.reactant sbml_tmp_species_ref]; end end sbmlModel.reaction = [ sbmlModel.reaction sbml_tmp_reaction ]; end if debug_function for (i = 1:size(sbmlModel.reaction, 2)) if ~isSBML_Reaction(sbmlModel.reaction(i), sbmlLevel, sbmlVersion) error('SBML reaction failed to pass test') end end end %% Format For SBML function str = formatForSBMLID(str) str = strrep(str,'-','_DASH_'); str = strrep(str,'/','_FSLASH_'); str = strrep(str,'\','_BSLASH_'); str = strrep(str,'(','_LPAREN_'); str = strrep(str,')','_RPAREN_'); str = strrep(str,'[','_LSQBKT_'); str = strrep(str,']','_RSQBKT_'); str = strrep(str,',','_COMMA_'); str = strrep(str,'.','_PERIOD_'); str = strrep(str,'''','_APOS_'); str = regexprep(str,'\(e\)$','_e'); str = strrep(str,'&','&amp;'); str = strrep(str,'<','&lt;'); str = strrep(str,'>','&gt;'); str = strrep(str,'"','&quot;');
github
EPFL-LCSB/matTFA-master
writeCbModel.m
.m
matTFA-master/ext/Cobra205_vDec2014/io/writeCbModel.m
10,729
utf_8
0a6994071e50ffd3dc681e8043552a69
function writeCbModel(model,format,fileName,compSymbolList,compNameList,sbmlLevel,sbmlVersion) %writeCbModel Write out COBRA models in various formats % % writeCbModel(model,format,fileName,compSymbolList,compNameList,sbmlLevel,sbmlVersion) % %INPUTS % model Standard COBRA model structure % format File format to be used ('text','xls' or 'sbml') % %OPTIONAL INPUTS % fileName File name for output file (optional, default opens % dialog box) % compSymbolList List of compartment symbols % compNameList List of compartment names corresponding to compSymbolList % sbmlLevel SBML Level (default = 2) % sbmlVersion SBML Version (default = 1) % % Markus Herrgard 2/5/07 % Ines Thiele 01/10 - Added more options for field to write in xls format % Richard Que (3/17/10) Added ability to specify compartment names and % symbols if nargin < 4 compSymbolList = {}; compNameList = {}; end if nargin < 6 sbmlLevel = 2; sbmlVersion = 1; end [nMets,nRxns] = size(model.S); formulas = printRxnFormula(model,model.rxns,false,false,false,1,false); %% Open a dialog to select file name if (nargin < 3 & ~strcmp(format,'sbml')) switch format case 'xls' [fileNameFull,filePath] = uiputfile({'*.xls'}); case {'text','txt'} [fileNameFull,filePath] = uiputfile({'*.txt'}); case 'xml' [fileNameFull,filePath] = uiputfile({'*.xml'}); otherwise [fileNameFull,filePath] = uiputfile({'*'}); end if (fileNameFull) [t1,t2,t3,t4,tokens] = regexp(fileNameFull,'(\w*)\.(\w*)'); fileName = [filePath tokens{1}{1}]; switch tokens{1}{2} case 'xls' format = 'xls'; case 'txt' format = 'text'; fileName = [fileName '.txt']; case 'xml' format = 'sbml'; % fprintf('Note that you will be asked to supply the file name again (this is a feature, not a bug)'); otherwise format = 'unknown'; end else return; end end switch format %% Text file case {'text','txt'} fid = fopen(fileName,'w'); fprintf(fid,'Rxn name\t'); if (isfield(model,'rxnNames')) fprintf(fid,'Rxn description\t'); end fprintf(fid,'Formula\t'); if (isfield(model,'grRules')) fprintf(fid,'Gene-reaction association\t'); end fprintf(fid,'Reversible\tLB\tUB\tObjective\n'); for i = 1:nRxns fprintf(fid,'%s\t',model.rxns{i}); if (isfield(model,'rxnNames')) fprintf(fid,'%s\t',model.rxnNames{i}); end fprintf(fid,'%s\t',formulas{i}); if (isfield(model,'grRules')) fprintf(fid,'%s\t',model.grRules{i}); end fprintf(fid,'%d\t%6.2f\t%6.2f\t%6.2f\n',model.rev(i),model.lb(i),model.ub(i),model.c(i)); end fprintf(fid,'Metabolite name\tMetabolite description\tMetabolite formula\n'); for i = 1:nMets fprintf(fid,'%s',model.mets{i}); if isfield(model,'metNames') fprintf(fid,'\t%s',model.metNames{i}); end if isfield(model,'metFormulas') fprintf(fid,'\t%s',model.metFormulas{i}); end fprintf(fid,'\n'); end fclose(fid); %% Excel file case 'xls' tmpData{1,1} = 'Rxn name'; tmpData{1,2} = 'Rxn description'; baseInd = 3; tmpData{1,baseInd} = 'Formula'; tmpData{1,baseInd+1} = 'Gene-reaction association'; tmpData{1,baseInd+2} = 'Genes'; tmpData{1,baseInd+3} = 'Proteins'; tmpData{1,baseInd+4} = 'Subsystem'; tmpData{1,baseInd+5} = 'Reversible'; tmpData{1,baseInd+6} = 'LB'; tmpData{1,baseInd+7} = 'UB'; tmpData{1,baseInd+8} = 'Objective'; tmpData{1,baseInd+9} = 'Confidence Score'; tmpData{1,baseInd+10} = 'EC Number'; tmpData{1,baseInd+11} = 'Notes'; tmpData{1,baseInd+12} = 'References'; for i = 1:nRxns tmpData{i+1,1} = chopForExcel(model.rxns{i}); if (isfield(model,'rxnNames')) tmpData{i+1,2} = chopForExcel(model.rxnNames{i}); else tmpData{i+1,2} = ''; end tmpData{i+1,baseInd} = chopForExcel(formulas{i}); if (isfield(model,'geneNameRules')) tmpData{i+1,baseInd+1} = chopForExcel(model.geneNameRules{i}); elseif (isfield(model,'grRules')) tmpData{i+1,baseInd+1} = chopForExcel(model.grRules{i}); else tmpData{i+1,baseInd+1} = ''; end if (isfield(model,'geneNames')) geneNames = model.geneNames(model.rxnGeneMat(i,:) == 1); tmpData{i+1,baseInd+2} = constructGeneStr(geneNames); elseif (isfield(model,'genes')) geneNames = model.genes(model.rxnGeneMat(i,:) == 1); tmpData{i+1,baseInd+2} = constructGeneStr(geneNames); else tmpData{i+1,baseInd+2} = ''; end if (isfield(model,'proteins')) tmpData{i+1,baseInd+3} = chopForExcel(model.proteins{i}); else tmpData{i+1,baseInd+3} = ''; end if (isfield(model,'subSystems')) tmpData{i+1,baseInd+4} = chopForExcel(char(model.subSystems{i})); else tmpData{i+1,baseInd+4} = ''; end tmpData{i+1,baseInd+5} = model.rev(i)*1.0; tmpData{i+1,baseInd+6} = model.lb(i); tmpData{i+1,baseInd+7} = model.ub(i); tmpData{i+1,baseInd+8} = model.c(i); if (isfield(model,'confidenceScores')) tmpData{i+1,baseInd+9} = chopForExcel(num2str(model.confidenceScores{i})); else tmpData{i+1,baseInd+9} = ''; end if (isfield(model,'rxnECNumbers')) tmpData{i+1,baseInd+10} = chopForExcel(model.rxnECNumbers{i}); else tmpData{i+1,baseInd+10} = ''; end if (isfield(model,'rxnNotes')) tmpData{i+1,baseInd+11} = chopForExcel(char(model.rxnNotes{i})); else tmpData{i+1,baseInd+11} = ''; end if (isfield(model,'rxnReferences')) tmpData{i+1,baseInd+12} = chopForExcel(char(model.rxnReferences{i})); else tmpData{i+1,baseInd+12} = ''; end end %keyboard xlswrite(fileName,tmpData,'reactions'); if isfield(model,'metNames') tmpMetData{1,1} = 'Metabolite name'; tmpMetData{1,2} = 'Metabolite description'; tmpMetData{1,3} = 'Metabolite neutral formula'; tmpMetData{1,4} = 'Metabolite charged formula'; tmpMetData{1,5} = 'Metabolite charge'; tmpMetData{1,6} = 'Metabolite Compartment'; tmpMetData{1,7} = 'Metabolite KEGGID'; tmpMetData{1,8} = 'Metabolite PubChemID'; tmpMetData{1,9} = 'Metabolite CheBI ID'; tmpMetData{1,10} = 'Metabolite Inchi String'; tmpMetData{1,11} = 'Metabolite Smile'; for i = 1:nMets tmpMetData{i+1,1} = chopForExcel(model.mets{i}); tmpMetData{i+1,2} = chopForExcel(model.metNames{i}); if isfield(model,'metFormulasNeutral') tmpMetData{i+1,3} = chopForExcel(model.metFormulasNeutral{i}); else tmpMetData{i+1,3} = ''; end if isfield(model,'metFormulas') tmpMetData{i+1,4} = chopForExcel(model.metFormulas{i}); else tmpMetData{i+1,4} = ''; end if isfield(model,'metCharge') tmpMetData{i+1,5} = chopForExcel(model.metCharge(i)); else tmpMetData{i+1,5} = ''; end if isfield(model,'metCompartment') tmpMetData{i+1,6} = chopForExcel(model.metCompartment{i}); else tmpMetData{i+1,6} = ''; end if isfield(model,'metKEGGID') tmpMetData{i+1,7} = chopForExcel(model.metKEGGID{i}); else tmpMetData{i+1,7} = ''; end if isfield(model,'metPubChemID') if iscell(model.metPubChemID(i)) tmpMetData{i+1,8} = chopForExcel(model.metPubChemID{i}); else tmpMetData{i+1,8} = chopForExcel(model.metPubChemID(i)); end else tmpMetData{i+1,8} = ''; end if isfield(model,'metChEBIID') tmpMetData{i+1,9} = chopForExcel(model.metChEBIID(i)); else tmpMetData{i+1,9} = ''; end if isfield(model,'metInchiString') tmpMetData{i+1,10} = chopForExcel(model.metInchiString{i}); else tmpMetData{i+1,10} = ''; end if isfield(model,'metSmiles') tmpMetData{i+1,11} = chopForExcel(model.metSmiles{i}); else tmpMetData{i+1,11} = ''; end end xlswrite(fileName,tmpMetData,'metabolites'); else xlswrite(fileName,model.mets,'metabolites'); end %% SBML case 'sbml' sbmlModel = convertCobraToSBML(model,sbmlLevel,sbmlVersion,compSymbolList,compNameList); if exist('fileName','var')&&~isempty(fileName) OutputSBML(sbmlModel,fileName); else OutputSBML(sbmlModel); end %% Unknown otherwise error('Unknown file format'); end %% Chop strings for excel output function strOut = chopForExcel(str) if (length(str) > 5000) strOut = str(1:5000); fprintf('String longer than 5000 characters - truncated for Excel output\n%s\n',str); else strOut = str; end %% Construct gene name string function geneStr = constructGeneStr(geneNames) geneStr = ''; for i = 1:length(geneNames) geneStr = [geneStr ' ' geneNames{i}]; end geneStr = strtrim(geneStr);
github
EPFL-LCSB/matTFA-master
convertSBMLToCobra.m
.m
matTFA-master/ext/Cobra205_vDec2014/io/convertSBMLToCobra.m
14,410
utf_8
ca4c9588a99e906f4a3636188d2c0574
function model = convertSBMLToCobra(modelSBML,defaultBound,compSymbolList,compNameList) %convertSBMLToCobra Convert SBML format model (created using SBML Toolbox) %to Cobra format % % model = convertSBMLToCobra(modelSBML,defaultBound) % %INPUTS % modelSBML SBML model structure % %OPTIONAL INPUTS % defaultBound Maximum bound for model (Default = 1000) % compSymbolList List of compartment symbols % compNameList List of compartment names corresponding to compSymbolList % %OUTPUT % model COBRA model structure % Markus Herrgard 1/25/08 % % Ines Thiele 01/27/2010 - I added new field to be read-in from SBML file % if provided in file (e.g., references, comments, metabolite IDs, etc.) % % Richard Que 02/08/10 - Properly format reaction and metabolite fields % from SBML. % if (nargin < 2) defaultBound = 1000; end if nargin < 3 compSymbolList = {}; compNameList = {}; end nMetsTmp = length(modelSBML.species); nRxns = length(modelSBML.reaction); %% Construct initial metabolite list formulaCount = 0; speciesList = {}; chargeList = []; metFormulas = {}; haveFormulasFlag = false; tmpSpecies = []; for i = 1:nMetsTmp % Ignore boundary metabolites if (~modelSBML.species(i).boundaryCondition) %Check for the Palsson lab _b$ boundary condition indicator if (isempty(regexp(modelSBML.species(i).id,'_b$'))); tmpSpecies = [ tmpSpecies modelSBML.species(i)]; speciesList{end+1} = modelSBML.species(i).id; notesField = modelSBML.species(i).notes; % Get formula if in notes field if (~isempty(notesField)) [tmp,tmp,tmp,tmp,formula,tmp,tmp,tmp,tmp,charge] = parseSBMLNotesField(notesField); tmpCharge = charge; metFormulas {end+1} = formula; formulaCount = formulaCount + 1; haveFormulasFlag = true; end chargeList= [chargeList modelSBML.species(i).charge]; end end end nMets = length(speciesList); %% Construct stoichiometric matrix and reaction list S = sparse(nMets,nRxns); rev = zeros(nRxns,1); lb = zeros(nRxns,1); ub = zeros(nRxns,1); c = zeros(nRxns,1); rxns = cell(nRxns,1); rules = cell(nRxns,1); genes = cell(nRxns,1); allGenes = {}; h = waitbar(0,'Reading SBML file ...'); hasNotesField = false; for i = 1:nRxns if mod(i,10) == 0 waitbar(i/nRxns,h); end % Read the gpra from the notes field notesField = modelSBML.reaction(i).notes; if (~isempty(notesField)) [geneList,rule,subSystem,grRule,formula,confidenceScore, citation, comment, ecNumber] = parseSBMLNotesField(notesField); subSystems{i} = subSystem; genes{i} = geneList; allGenes = [allGenes geneList]; rules{i} = rule; grRules{i} = grRule; hasNotesField = true; confidenceScores{i}= confidenceScore; citations{i} = citation; comments{i} = comment; ecNumbers{i} = ecNumber; end rev(i) = modelSBML.reaction(i).reversible; rxnNameTmp = regexprep(modelSBML.reaction(i).name,'^R_',''); rxnNames{i} = regexprep(rxnNameTmp,'_+',' '); rxnsTmp = regexprep(modelSBML.reaction(i).id,'^R_',''); rxns{i} = cleanUpFormatting(rxnsTmp); % Construct S-matrix reactantStruct = modelSBML.reaction(i).reactant; for j = 1:length(reactantStruct) speciesID = find(strcmp(reactantStruct(j).species,speciesList)); if (~isempty(speciesID)) stoichCoeff = reactantStruct(j).stoichiometry; S(speciesID,i) = -stoichCoeff; end end productStruct = modelSBML.reaction(i).product; for j = 1:length(productStruct) speciesID = find(strcmp(productStruct(j).species,speciesList)); if (~isempty(speciesID)) stoichCoeff = productStruct(j).stoichiometry; S(speciesID,i) = stoichCoeff; end end if isfield(modelSBML.reaction(i).kineticLaw,'parameter') parameters = modelSBML.reaction(i).kineticLaw.parameter; else parameters =[]; end if (~isempty(parameters)) for j = 1:length(parameters) paramStruct = parameters(j); switch paramStruct.id case 'LOWER_BOUND' lb(i) = paramStruct.value; if (lb(i) < -defaultBound) lb(i) = -defaultBound; end case 'UPPER_BOUND' ub(i) = paramStruct.value; if (ub(i) > defaultBound) ub(i) = defaultBound; end case 'OBJECTIVE_COEFFICIENT' c(i) = paramStruct.value; end end else ub(i) = defaultBound; if (rev(i) == 1) lb(i) = -defaultBound; else lb(i) = 0; end end end %close the waitbar if this is matlab if (regexp(version, 'R20')) close(h); end allGenes = unique(allGenes); %% Construct gene to rxn mapping if (hasNotesField) rxnGeneMat = sparse(nRxns,length(allGenes)); h = waitbar(0,'Constructing GPR mapping ...'); for i = 1:nRxns if mod(i,10) == 0 waitbar(i/nRxns,h); end if iscell(genes{i}) [tmp,geneInd] = ismember(genes{i},allGenes); else [tmp,geneInd] = ismember(num2cell(genes{i}),allGenes); end rxnGeneMat(i,geneInd) = 1; for j = 1:length(geneInd) rules{i} = strrep(rules{i},['x(' num2str(j) ')'],['x(' num2str(geneInd(j)) '_TMP_)']); end rules{i} = strrep(rules{i},'_TMP_',''); end %close the waitbar if this is matlab if (regexp(version, 'R20')) close(h); end end %% Construct metabolite list mets = cell(nMets,1); compartmentList = cell(length(modelSBML.compartment),1); if isempty(compSymbolList), useCompList = true; else useCompList = false; end for i=1:length(modelSBML.compartment) compartmentList{i} = modelSBML.compartment(i).id; end h = waitbar(0,'Constructing metabolite lists ...'); hasAnnotationField = 0; for i = 1:nMets if mod(i,10) == 0 waitbar(i/nMets,h); end % Parse metabolite id's % Get rid of the M_ in the beginning of metabolite id's metID = regexprep(speciesList{i},'^M_',''); metID = regexprep(metID,'^_',''); % Find compartment id tmpCell = {}; if useCompList for j=1:length(compartmentList) tmpCell = regexp(metID,['_(' compartmentList{j} ')$'],'tokens'); if ~isempty(tmpCell), break; end end if isempty(tmpCell), useCompList = false; end elseif ~isempty(compSymbolList) for j = 1: length(compSymbolList) tmpCell = regexp(metID,['_(' compSymbolList{j} ')$'],'tokens'); if ~isempty(tmpCell), break; end end end if isempty(tmpCell), tmpCell = regexp(metID,'_(.)$','tokens'); end if ~isempty(tmpCell) compID = tmpCell{1}; metTmp = [regexprep(metID,['_' compID{1} '$'],'') '[' compID{1} ']']; else metTmp = metID; end %Clean up met ID mets{i} = cleanUpFormatting(metTmp); % Parse metabolite names % Clean up some of the weird stuff in the sbml files metNamesTmp = regexprep(tmpSpecies(i).name,'^M_',''); metNamesTmp = cleanUpFormatting(metNamesTmp); metNamesTmp = regexprep(metNamesTmp,'^_',''); % metNamesTmp = strrep(metNamesTmp,'_','-'); metNamesTmp = regexprep(metNamesTmp,'-+','-'); metNamesTmp = regexprep(metNamesTmp,'-$',''); metNamesAlt{i} = metNamesTmp; % Separate formulas from names %[tmp,tmp,tmp,tmp,tokens] = regexp(metNamesTmp,'(.*)-((([A(Ag)(As)C(Ca)(Cd)(Cl)(Co)(Cu)F(Fe)H(Hg)IKLM(Mg)(Mn)N(Na)(Ni)OPRS(Se)UWXY(Zn)]?)(\d*)))*$'); if (~haveFormulasFlag) [tmp,tmp,tmp,tmp,tokens] = regexp(metNamesTmp,'(.*)_((((A|Ag|As|C|Ca|Cd|Cl|Co|Cu|F|Fe|H|Hg|I|K|L|M|Mg|Mn|Mo|N|Na|Ni|O|P|R|S|Se|U|W|X|Y|Zn)?)(\d*)))*$'); if (isempty(tokens)) if length(metFormulas)<i||(metFormulas{i}=='') metFormulas{i} = ''; end metNames{i} = metNamesTmp; else formulaCount = formulaCount + 1; metFormulas{i} = tokens{1}{2}; metNames{i} = tokens{1}{1}; end else metNames{i} = metNamesTmp; end if isfield(modelSBML.species(i),'annotation') hasAnnotationField = 1; [metCHEBI,metKEGG,metPubChem,metInChI] = parseSBMLAnnotationField(modelSBML.species(i).annotation); metCHEBIID{i} = metCHEBI; metKEGGID{i} = metKEGG; metPubChemID{i} = metPubChem; metInChIString{i} = metInChI; end end if ( regexp( version, 'R20') ) close(h); end %% Collect everything into a structure model.rxns = rxns; model.mets = mets; model.S = S; model.rev = rev; model.lb = lb; model.ub = ub; model.c = c; model.metCharge = transpose(chargeList); if (hasNotesField) model.rules = rules; model.genes = columnVector(allGenes); model.rxnGeneMat = rxnGeneMat; model.grRules = columnVector(grRules); model.subSystems = columnVector(subSystems); model.confidenceScores = columnVector(confidenceScores); model.rxnReferences = columnVector(citations); model.rxnECNumbers = columnVector(ecNumbers); model.rxnNotes = columnVector(comments); end model.rxnNames = columnVector(rxnNames); % Only include formulas if at least 90% of metabolites have them (otherwise % the "formulas" are probably just parts of metabolite names) if (formulaCount < 0.9*nMets) model.metNames = columnVector(metNamesAlt); else model.metNames = columnVector(metNames); model.metFormulas = columnVector(metFormulas); end if (hasAnnotationField) model.metChEBIID = columnVector(metCHEBIID); model.metKEGGID = columnVector(metKEGGID); model.metPubChemID = columnVector(metPubChemID); model.metInChIString = columnVector(metInChIString); end %% function [genes,rule,subSystem,grRule,formula,confidenceScore,citation,comment,ecNumber,charge] = parseSBMLNotesField(notesField) %parseSBMLNotesField Parse the notes field of an SBML file to extract %gene-rxn associations % % [genes,rule] = parseSBMLNotesField(notesField) % % Markus Herrgard 8/7/06 % Ines Thiele 1/27/10 Added new fields % Handle different notes fields if isempty(regexp(notesField,'html:p', 'once')) tag = 'p'; else tag = 'html:p'; end subSystem = ''; grRule = ''; genes = {}; rule = ''; formula = ''; confidenceScore = ''; citation = ''; ecNumber = ''; comment = ''; charge = []; Comment = 0; [tmp,fieldList] = regexp(notesField,['<' tag '>.*?</' tag '>'],'tokens','match'); for i = 1:length(fieldList) fieldTmp = regexp(fieldList{i},['<' tag '>(.*)</' tag '>'],'tokens'); fieldStr = fieldTmp{1}{1}; if (regexp(fieldStr,'GENE_ASSOCIATION')) gprStr = regexprep(strrep(fieldStr,'GENE_ASSOCIATION:',''),'^(\s)+',''); grRule = gprStr; [genes,rule] = parseBoolean(gprStr); elseif (regexp(fieldStr,'GENE ASSOCIATION')) gprStr = regexprep(strrep(fieldStr,'GENE ASSOCIATION:',''),'^(\s)+',''); grRule = gprStr; [genes,rule] = parseBoolean(gprStr); elseif (regexp(fieldStr,'SUBSYSTEM')) subSystem = regexprep(strrep(fieldStr,'SUBSYSTEM:',''),'^(\s)+',''); subSystem = strrep(subSystem,'S_',''); subSystem = regexprep(subSystem,'_+',' '); if (isempty(subSystem)) subSystem = 'Exchange'; end elseif (regexp(fieldStr,'EC Number')) ecNumber = regexprep(strrep(fieldStr,'EC Number:',''),'^(\s)+',''); elseif (regexp(fieldStr,'FORMULA')) formula = regexprep(strrep(fieldStr,'FORMULA:',''),'^(\s)+',''); elseif (regexp(fieldStr,'CHARGE')) charge = str2num(regexprep(strrep(fieldStr,'CHARGE:',''),'^(\s)+','')); elseif (regexp(fieldStr,'AUTHORS')) if isempty(citation) citation = strcat(regexprep(strrep(fieldStr,'AUTHORS:',''),'^(\s)+','')); else citation = strcat(citation,';',regexprep(strrep(fieldStr,'AUTHORS:',''),'^(\s)+','')); end elseif Comment == 1 && isempty(regexp(fieldStr,'genes:', 'once')) Comment = 0; comment = fieldStr; elseif (regexp(fieldStr,'Confidence')) confidenceScore = regexprep(strrep(fieldStr,'Confidence Level:',''),'^(\s)+',''); Comment = 1; end end %% function [metCHEBI,metKEGG,metPubChem,metInChI] = parseSBMLAnnotationField(annotationField) %parseSBMLAnnotationField Parse the annotation field of an SBML file to extract %metabolite information associations % % [genes,rule] = parseSBMLAnnotationField(annotationField) % % Ines Thiele 1/27/10 Added new fields % Handle different notes fields metPubChem = ''; metCHEBI = ''; metKEGG = ''; metPubChem = ''; metInChI=''; [tmp,fieldList] = regexp(annotationField,'<rdf:li rdf:resource="urn:miriam:(\w+).*?"/>','tokens','match'); %fieldTmp = regexp(fieldList{i},['<' tag '>(.*)</' tag '>'],'tokens'); for i = 1:length(fieldList) fieldTmp = regexp(fieldList{i},['<rdf:li rdf:resource="urn:miriam:(.*)"/>'],'tokens'); fieldStr = fieldTmp{1}{1}; if (regexp(fieldStr,'obo.chebi')) metCHEBI = strrep(fieldStr,'obo.chebi:CHEBI%',''); elseif (regexp(fieldStr,'kegg.compound')) metKEGG = strrep(fieldStr,'kegg.compound:',''); elseif (regexp(fieldStr,'pubchem.substance')) metPubChem = strrep(fieldStr,'pubchem.substance:',''); end end % get InChI string fieldTmp = regexp(annotationField,'<in:inchi xmlns:in="http://biomodels.net/inchi" metaid="(.*?)">(.*?)</in:inchi>','tokens'); if ~isempty(fieldTmp) fieldStr = fieldTmp{1}{2}; if (regexp(fieldStr,'InChI')) metInChI = strrep(fieldStr,'InChI=',''); end end %% Cleanup Formatting function str = cleanUpFormatting(str) str = strrep(str,'-DASH-','-'); str = strrep(str,'_DASH_','-'); str = strrep(str,'_FSLASH_','/'); str = strrep(str,'_BSLASH_','\'); str = strrep(str,'_LPAREN_','('); str = strrep(str,'_LSQBKT_','['); str = strrep(str,'_RSQBKT_',']'); str = strrep(str,'_RPAREN_',')'); str = strrep(str,'_COMMA_',','); str = strrep(str,'_PERIOD_','.'); str = strrep(str,'_APOS_',''''); str = regexprep(str,'_e_$','(e)'); str = regexprep(str,'_e$','(e)'); str = strrep(str,'&amp;','&'); str = strrep(str,'&lt;','<'); str = strrep(str,'&gt;','>'); str = strrep(str,'&quot;','"');
github
EPFL-LCSB/matTFA-master
lp_solve.m
.m
matTFA-master/ext/Cobra205_vDec2014/solvers/lp_solve.m
2,708
utf_8
80baa061e65e08df66a4b417047cd713
%LP_SOLVE Solves mixed integer linear programming problems. % % SYNOPSIS: [obj,x,duals,stat] = lp_solve(f,a,b,e,vlb,vub,xint,scalemode,keep) % % solves the MILP problem % % max v = f'*x % a*x <> b % vlb <= x <= vub % x(int) are integer % % ARGUMENTS: The first four arguments are required: % % f: n vector of coefficients for a linear objective function. % a: m by n matrix representing linear constraints. % b: m vector of right sides for the inequality constraints. % e: m vector that determines the sense of the inequalities: % e(i) = -1 ==> Less Than % e(i) = 0 ==> Equals % e(i) = 1 ==> Greater Than % vlb: n vector of lower bounds. If empty or omitted, % then the lower bounds are set to zero. % vub: n vector of upper bounds. May be omitted or empty. % xint: vector of integer variables. May be omitted or empty. % scalemode: scale flag. Off when 0 or omitted. % keep: Flag for keeping the lp problem after it's been solved. % If omitted, the lp will be deleted when solved. % % OUTPUT: A nonempty output is returned if a solution is found: % % obj: Optimal value of the objective function. % x: Optimal value of the decision variables. % duals: solution of the dual problem. function [obj, x, duals, stat] = lp_solve(f, a, b, e, vlb, vub, xint, scalemode, keep) if nargin == 0 help lp_solve; return; end [m,n] = size(a); lp = mxlpsolve('make_lp', m, n); mxlpsolve('set_verbose', lp, 3); mxlpsolve('set_mat', lp, a); mxlpsolve('set_rh_vec', lp, b); mxlpsolve('set_obj_fn', lp, f); mxlpsolve('set_maxim', lp); % default is solving minimum lp. for i = 1:length(e) if e(i) < 0 con_type = 1; elseif e(i) == 0 con_type = 3; else con_type = 2; end mxlpsolve('set_constr_type', lp, i, con_type); end if nargin > 4 for i = 1:length(vlb) mxlpsolve('set_lowbo', lp, i, vlb(i)); end end if nargin > 5 for i = 1:length(vub) mxlpsolve('set_upbo', lp, i, vub(i)); end end if nargin > 6 for i = 1:length(xint) mxlpsolve('set_int', lp, xint(i), 1); end end if nargin > 7 if scalemode ~= 0 mxlpsolve('set_scaling', lp, scalemode); end end result=mxlpsolve('solve', lp); if result == 0 | result == 1 | result == 11 | result == 12 % [obj, x, duals, stat] = mxlpsolve('get_solution', lp), result; [obj, x, duals] = mxlpsolve('get_solution', lp); stat = result; else obj = []; x = []; duals = []; stat = result; end if nargin < 9 mxlpsolve('delete_lp', lp); end
github
EPFL-LCSB/matTFA-master
cpxcb_INCUMBENT.m
.m
matTFA-master/ext/Cobra205_vDec2014/solvers/cpxcb_INCUMBENT.m
3,387
utf_8
c53a9437062846671fbafd7691e91c80
% function ret = cpxcb_INCUMBENT(x,f,Prob,cbxCBInfo) % % CPLEX MIP Incumbent callback % % Called from TOMLAB /CPLEX during mixed integer optimization when a new integer % solution has been found but before this solution has replaced the current best known integer solution. % % This file can be used to perform any desired analysis of the new integer % solution and return a status flag to the solver deciding whether to stop % or continue the optimization, and also whether to accept or discard the newly % found solution. % % This callback is enabled by setting callback(14)=1 in the call to % cplex.m, or Prob.MIP.callback(14)=1 if using tomRun('cplex',...) % % cpxcb_INCUMBENT is called by the solver with three arguments: % % x - the new integer solution % f - the objective value at x % Prob - the Tomlab problem structure % % cpxcb_INCUMBENT should return one of the following scalar values: % % 0 Continue optimization and accept new integer solution % 1 Continue optimization but discard new integer solution % 2 Stop optimization and accept new integer solution % 3 Stop optimization adn discard new integer solution % % Any other return value will be interpreted as 0. % % If modifying this file, it is recommended to make a copy of it which % is placed before the original file in the MATLAB path. % % Anders Goran, Tomlab Optimization Inc., E-mail: [email protected] % Copyright (c) 2002-2007 by Tomlab Optimization Inc., $Release: 10.1.0$ % Written Jun 1, 2007. Last modified Jun 1, 2007. function ret = cpxcb_INCUMBENT(x,f,Prob) % ADD USER CODE HERE. % Accepted return values are: % % 0 Continue optimization and accept new integer solution % 1 Continue optimization but discard new integer solution % 2 Stop optimization and accept new integer solution % 3 Stop optimization adn discard new integer solution % % Any other return value will be interpreted as 0. global MILPproblemType; switch MILPproblemType case 'OptKnock' % Allow printing intermediate OptKnock solutions global cobraIntSolInd; global cobraContSolInd; global selectedRxnIndIrrev; global rxnList; global irrev2rev; global biomassRxnID; global solutionFileName; global OptKnockKOrxnList; global OptKnockObjective; global OptKnockGrowth; global solID; % Initialize if isempty(solID) solID = 0; OptKnockObjective = []; OptKnockGrowth = []; OptKnockKOrxnList = {}; end solID = solID + 1; % Get the reactions OptKnockObjective(solID) = -f; optKnockRxnInd = selectedRxnIndIrrev(x(cobraIntSolInd) < 1e-4); optKnockRxns = rxnList(unique(irrev2rev(optKnockRxnInd))); OptKnockKOrxnList{solID} = optKnockRxns; % Get the growth rate fluxes = x(cobraContSolInd); growth = fluxes(biomassRxnID); OptKnockGrowth(solID) = growth; fprintf('OptKnock\t%f\t%f\t',-f,growth); for i = 1:length(optKnockRxns) fprintf('%s ',optKnockRxns{i}); end fprintf('\n'); save(solutionFileName,'OptKnockKOrxnList','OptKnockObjective','OptKnockGrowth'); ret = 0; otherwise ret = 0; end
github
EPFL-LCSB/matTFA-master
solveCobraLP.m
.m
matTFA-master/ext/Cobra205_vDec2014/solvers/solveCobraLP.m
21,393
utf_8
015fc2b9bee21ee6eb4f30f6e94e39d8
function solution = solveCobraLP(LPproblem, varargin) %solveCobraLP Solve constraint-based LP problems % % solution = solveCobraLP(LPproblem, parameters) % %INPUT % LPproblem Structure containing the following fields describing the LP % problem to be solved % A LHS matrix % b RHS vector % c Objective coeff vector % lb Lower bound vector % ub Upper bound vector % osense Objective sense (-1 max, +1 min) % csense Constraint senses, a string containting the constraint sense for % each row in A ('E', equality, 'G' greater than, 'L' less than). % %OPTIONAL INPUTS % Optional parameters can be entered using parameters structure or as % parameter followed by parameter value: i.e. ,'printLevel',3) % % parameters Structure containing optional parameters as fields. % Setting parameters = 'default' uses default setting set in % getCobraSolverParameters. % printLevel Printing level % = 0 Silent (Default) % = 1 Warnings and Errors % = 2 Summary information % = 3 More detailed information % > 10 Pause statements, and maximal printing (debug mode) % saveInput Saves LPproblem to filename specified in field. % i.e. parameters.saveInput = 'LPproblem.mat'; % minNorm {(0), scalar , n x 1 vector}, where [m,n]=size(S); % If not zero then, minimise the Euclidean length % of the solution to the LP problem. minNorm ~1e-6 should be % high enough for regularisation yet maintain the same value for % the linear part of the objective. However, this should be % checked on a case by case basis, by optimization with and % without regularisation. % primalOnly {(0),1} 1=only return the primal vector (lindo solvers) % % optional parameters can also be set through the % solver can be set through changeCobraSolver('LP', value); % changeCobraSolverParames('LP', 'parameter', value) function. This % includes the minNorm and the printLevel flags % %OUTPUT % solution Structure containing the following fields describing a LP % solution % full Full LP solution vector % obj Objective value % rcost Reduced costs % dual Dual solution % solver Solver used to solve LP problem % % stat Solver status in standardized form % 1 Optimal solution % 2 Unbounded solution % 0 Infeasible % -1 No solution reported (timelimit, numerical problem etc) % % origStat Original status returned by the specific solver % time Solve time in seconds % % % Markus Herrgard 08/29/06 % Ronan Fleming 11/12/08 'cplex_direct' allows for more refined control % of cplex than tomlab tomrun % Ronan Fleming 04/25/09 Option to minimise the Euclidean Norm of internal % fluxes using either 'cplex_direct' solver or 'pdco' % Jan Schellenberger 09/28/09 Changed header to be much simpler. All parameters % now accessed through % changeCobraSolverParams(LP, parameter,value) % Richard Que 11/30/09 Changed handling of optional parameters to use % getCobraSolverParams(). % Ronan Fleming 12/07/09 Commenting of input/output % Ronan Fleming 21/01/10 Not having second input, means use the parameters as specified in the % global paramerer variable, rather than 'default' parameters % Steinn Gudmundsson 03/03/10 Added support for the Gurobi solver % Tim Harrington 05/18/12 Added support for the Gurobi 5.0 solver %% Process arguments etc global CBTLPSOLVER if (~isempty(CBTLPSOLVER)) solver = CBTLPSOLVER; else error('No solver found. call changeCobraSolver(solverName)'); end optParamNames = {'minNorm','printLevel','primalOnly','saveInput', ... 'feasTol','optTol','EleNames','EqtNames','VarNames','EleNameFun', ... 'EqtNameFun','VarNameFun','PbName','MPSfilename'}; parameters = ''; if nargin ~=1 if mod(length(varargin),2)==0 for i=1:2:length(varargin)-1 if ismember(varargin{i},optParamNames) parameters.(varargin{i}) = varargin{i+1}; else error([varargin{i} ' is not a valid optional parameter']); end end elseif strcmp(varargin{1},'default') parameters = 'default'; elseif isstruct(varargin{1}) parameters = varargin{1}; else display('Warning: Invalid number of parameters/values') solution=[]; return; end end [minNorm, printLevel, primalOnlyFlag, saveInput, feasTol, optTol] = ... getCobraSolverParams('LP',optParamNames(1:6),parameters); %Save Input if selected if ~isempty(saveInput) fileName = parameters.saveInput; if ~find(regexp(fileName,'.mat')) fileName = [fileName '.mat']; end display(['Saving LPproblem in ' fileName]); save(fileName,'LPproblem') end [A,b,c,lb,ub,csense,osense] = deal(LPproblem.A,LPproblem.b,LPproblem.c,LPproblem.lb,LPproblem.ub,LPproblem.csense,LPproblem.osense); % if any(any(~isfinite(A))) % error('Cannot perform LP on a stoichiometric matrix with NaN of Inf coefficents.') % end % Defaults in case the solver does not return anything f = []; x = []; y = []; w = []; origStat = -99; stat = -99; t_start = clock; switch solver %% GLPK case 'glpk' params.msglev = printLevel; % level of verbosity params.tolbnd = feasTol; %tolerance params.toldj = optTol; %tolerance if (isempty(csense)) clear csense csense(1:length(b),1) = 'S'; else csense(csense == 'L') = 'U'; csense(csense == 'G') = 'L'; csense(csense == 'E') = 'S'; csense = columnVector(csense); end %glpk needs b to be full, not sparse -Ronan b=full(b); [x,f,y,w,stat,origStat] = solveGlpk(c,A,b,lb,ub,csense,osense,params); case {'lindo_new','lindo_old'} %% LINDO if (strcmp(solver,'lindo_new')) % Use new API (>= 2.0) [f,x,y,w,s,origStat] = solveCobraLPLindo(A,b,c,csense,lb,ub,osense,primalOnlyFlag,false); % Note that status handling may change (see Lindo.h) if (origStat == 1 || origStat == 2) stat = 1; % Optimal solution found elseif (origStat == 4) stat = 2; % Unbounded elseif (origStat == 3 || origStat == 6) stat = 0; % Infeasible else stat = -1; % Solution not optimal or solver problem end else % Use old API [f,x,y,w,s,origStat] = solveCobraLPLindo(A,b,c,csense,lb,ub,osense,primalOnlyFlag,true); % Note that status handling may change (see Lindo.h) if (origStat == 2 || origStat == 3) stat = 1; % Optimal solution found elseif (origStat == 5) stat = 2; % Unbounded elseif (origStat == 4 || origStat == 6) stat = 0; % Infeasible else stat = -1; % Solution not optimal or solver problem end end %[f,x,y,s,w,stat] = LMSolveLPNew(A,b,c,csense,lb,ub,osense,0); case 'lp_solve' %% lp_solve if (isempty(csense)) [f,x,y,origStat] = lp_solve(c*(-osense),A,b,zeros(size(A,1),1),lb,ub); f = f*(-osense); else e(csense == 'E') = 0; e(csense == 'G') = 1; e(csense == 'L') = -1; [f,x,y,origStat] = lp_solve(c*(-osense),A,b,e,lb,ub); f = f*(-osense); end % Note that status handling may change (see lp_lib.h) if (origStat == 0) stat = 1; % Optimal solution found elseif (origStat == 3) stat = 2; % Unbounded elseif (origStat == 2) stat = 0; % Infeasible else stat = -1; % Solution not optimal or solver problem end s = []; w = []; case 'mosek' %% mosek %if mosek is installed, and the paths are added ahead of matlab's %built in paths, then mosek linprog shaddows matlab linprog and %is used preferentially switch printLevel case 0 options.Display='off'; case 1 options.Display='final'; case 2 options.Display='iter'; otherwise % Ask for default options for a function. options = optimset; end if (isempty(csense)) [x,f,origStat,output,lambda] = linprog(c*osense,[],[],A,b,lb,ub,[],options); else Aeq = A(csense == 'E',:); beq = b(csense == 'E'); Ag = A(csense == 'G',:); bg = b(csense == 'G'); Al = A(csense == 'L',:); bl = b(csense == 'L'); clear A; A = [Al;-Ag]; clear b; b = [bl;-bg]; [x,f,origStat,output,lambda] = linprog(c*osense,A,b,Aeq,beq,lb,ub,[],options); end y = []; if (origStat > 0) stat = 1; % Optimal solution found f = f*osense; y = lambda.eqlin; elseif (origStat < 0) stat = 0; % Infeasible else stat = -1; % Solution did not converge end case 'gurobi' %% gurobi % Free academic licenses for the Gurobi solver can be obtained from % http://www.gurobi.com/html/academic.html % % The code below uses Gurobi Mex to interface with Gurobi. It can be downloaded from % http://www.convexoptimization.com/wikimization/index.php/Gurobi_Mex:_A_MATLAB_interface_for_Gurobi clear opts % Use the default parameter settings if printLevel == 0 % Version v1.10 of Gurobi Mex has a minor bug. For complete silence % Remove Line 736 of gurobi_mex.c: mexPrintf("\n"); opts.Display = 0; opts.DisplayInterval = 0; else opts.Display = 1; end opts.FeasibilityTol = feasTol; opts.OptimalityTol = optTol; if (isempty(csense)) clear csense csense(1:length(b),1) = '='; else csense(csense == 'L') = '<'; csense(csense == 'G') = '>'; csense(csense == 'E') = '='; csense = csense(:); end %gurobi_mex doesn't cast logicals to doubles automatically c = double(c); [x,f,origStat,output,y] = gurobi_mex(c,osense,sparse(A),b, ... csense,lb,ub,[],opts); if origStat==2 stat = 1; % Optimal solutuion found elseif origStat==3 stat = 0; % Infeasible elseif origStat==5 stat = 2; % Unbounded elseif origStat==4 stat = 0; % Gurobi reports infeasible *or* unbounded else stat = -1; % Solution not optimal or solver problem end case 'gurobi5' %% gurobi 5 % Free academic licenses for the Gurobi solver can be obtained from % http://www.gurobi.com/html/academic.html resultgurobi = struct('x',[],'objval',[],'pi',[]); LPproblem.A = deal(sparse(LPproblem.A)); clear params % Use the default parameter settings if printLevel == 0 params.OutputFlag = 0; params.DisplayInterval = 1; else params.OutputFlag = 1; params.DisplayInterval = 5; end params.FeasibilityTol = feasTol; params.OptimalityTol = optTol; if (isempty(LPproblem.csense)) clear LPproblem.csense LPproblem.csense(1:length(b),1) = '='; else LPproblem.csense(LPproblem.csense == 'L') = '<'; LPproblem.csense(LPproblem.csense == 'G') = '>'; LPproblem.csense(LPproblem.csense == 'E') = '='; LPproblem.csense = LPproblem.csense(:); end if LPproblem.osense == -1 LPproblem.osense = 'max'; else LPproblem.osense = 'min'; end LPproblem.modelsense = LPproblem.osense; [LPproblem.rhs,LPproblem.obj,LPproblem.sense] = deal(LPproblem.b,double(LPproblem.c),LPproblem.csense); resultgurobi = gurobi(LPproblem,params); if strcmp(resultgurobi.status,'OPTIMAL') stat = 1; % Optimal solution found [x,f,y] = deal(resultgurobi.x,resultgurobi.objval,resultgurobi.pi); elseif strcmp(resultgurobi.status,'INFEASIBLE') stat = 0; % Infeasible elseif strcmp(resultgurobi.status,'UNBOUNDED') stat = 2; % Unbounded elseif strcmp(resultgurobi.status,'INF_OR_UNBD') stat = 0; % Gurobi reports infeasible *or* unbounded else stat = -1; % Solution not optimal or solver problem end case 'matlab' %matlab is not a reliable LP solver if (isempty(csense)) [x,f,origStat,output,lambda] = linprog(c*osense,[],[],A,b,lb,ub); else Aeq = A(csense == 'E',:); beq = b(csense == 'E'); Ag = A(csense == 'G',:); bg = b(csense == 'G'); Al = A(csense == 'L',:); bl = b(csense == 'L'); clear A; A = [Al;-Ag]; clear b; b = [bl;-bg]; [x,f,origStat,output,lambda] = linprog(c*osense,A,b,Aeq,beq,lb,ub); end y = []; if (origStat > 0) stat = 1; % Optimal solution found f = f*osense; y = lambda.eqlin; elseif (origStat < 0) stat = 0; % Infeasible else stat = -1; % Solution did not converge end case 'tomlab_cplex' %% Tomlab if (~isempty(csense)) b_L(csense == 'E') = b(csense == 'E'); b_U(csense == 'E') = b(csense == 'E'); b_L(csense == 'G') = b(csense == 'G'); b_U(csense == 'G') = 1e6; b_L(csense == 'L') = -1e6; b_U(csense == 'L') = b(csense == 'L'); else b_L = b; b_U = b; end tomlabProblem = lpAssign(osense*c,A,b_L,b_U,lb,ub); %Result = tomRun('cplex', tomlabProblem, 0); % This is faster than using tomRun %set parameters tomlabProblem.optParam = optParamDef('cplex',tomlabProblem.probType); tomlabProblem.QP.F = []; tomlabProblem.PriLevOpt = printLevel; %if basis is availible use it if isfield(LPproblem,'basis') && ~isempty(LPproblem.basis) tomlabProblem.MIP.basis = LPproblem.basis; end %set tolerance tomlabProblem.MIP.cpxControl.EPRHS = feasTol; tomlabProblem.MIP.cpxControl.EPOPT = optTol; %solve Result = cplexTL(tomlabProblem); % Assign results x = Result.x_k; f = osense*sum(tomlabProblem.QP.c.*Result.x_k); % [Result.f_k f] origStat = Result.Inform; w = Result.v_k(1:length(lb)); y = Result.v_k((length(lb)+1):end); basis = Result.MIP.basis; if (origStat == 1) stat = 1; elseif (origStat == 3) stat = 0; elseif (origStat == 2 || origStat == 4) stat = 2; else stat = -1; end case 'cplex_direct' %% Tomlab cplex.m direct %Used with the current script, only some of the control affoarded with %this interface is provided. Primarily, this is to change the print %level and whether to minimise the Euclidean Norm of the internal %fluxes or not. %See solveCobraLPCPLEX.m for more refined control of cplex %Ronan Fleming 11/12/2008 if isfield(LPproblem,'basis') && ~isempty(LPproblem.basis) LPproblem.LPBasis = LPproblem.basis; end [solution LPprob] = solveCobraLPCPLEX(LPproblem,printLevel,1,[],[],minNorm); solution.basis = LPprob.LPBasis; solution.solver = solver; case 'lindo' error('Solver type lindo is obsolete - use lindo_new or lindo_old instead'); case 'pdco' %----------------------------------------------------------------------- % pdco.m: Primal-Dual Barrier Method for Convex Objectives (16 Dec 2008) %----------------------------------------------------------------------- % AUTHOR: % Michael Saunders, Systems Optimization Laboratory (SOL), % Stanford University, Stanford, California, USA. %Interfaced with Cobra toolbox by Ronan Fleming, 27 June 2009 [nMet,nRxn]=size(LPproblem.A); x0 = ones(nRxn,1); y0 = ones(nMet,1); z0 = ones(nRxn,1); %setting d1 to zero is dangerous numerically, but is necessary to avoid %minimising the Euclidean norm of the optimal flux. A more %numerically stable way is to use pdco via solveCobraQP, which has %a more reasonable d1 and should be more numerically robust. -Ronan d1=0; d2=1e-6; options = pdcoSet; options.FeaTol = 1e-12; options.OptTol = 1e-12; %pdco is a general purpose convex optization solver, not only a %linear optimization solver. As such, much control over the optimal %solution and the method for solution is available. However, this %also means you may have to tune the various parameters here, %especially xsize and zsize (see pdco.m) to get the real optimal %objective value xsize = 1000; zsize = 10000; options.Method=2; %QR options.MaxIter=100; options.Print=printLevel; [x,y,w,inform,PDitns,CGitns,time] = ... pdco(osense*c*10000,A,b,lb,ub,d1,d2,options,x0,y0,z0,xsize,zsize); f= c'*x; % inform = 0 if a solution is found; % = 1 if too many iterations were required; % = 2 if the linesearch failed too often; % = 3 if the step lengths became too small; % = 4 if Cholesky said ADDA was not positive definite. if (inform == 0) stat = 1; elseif (inform == 1 || inform == 2 || inform == 3) stat = 0; else stat = -1; end origStat=inform; case 'mps' %% BuildMPS % This calls buildMPS and generates a MPS format description of the % problem as the result % Build MPS Author: Bruno Luong % Interfaced with CobraToolbox by Richard Que (12/18/09) display('Solver set to MPS. This function will output an MPS matrix string for the LP problem'); %Get optional parameters [EleNames,EqtNames,VarNames,EleNameFun,EqtNameFun,VarNameFun,PbName,MPSfilename] = ... getCobraSolverParams('LP',{'EleNames','EqtNames','VarNames','EleNameFun','EqtNameFun','VarNameFun','PbName','MPSfilename'},parameters); %split A matrix for L and E csense Ale = A(csense=='L',:); ble = b(csense=='L'); Aeq = A(csense=='E',:); beq = b(csense=='E'); %%%%Adapted from BuildMPS%%%%% [neq nvar]=size(Aeq); nle=size(Ale,1); if isempty(EleNames) EleNames=arrayfun(EleNameFun,(1:nle),'UniformOutput', false); end if isempty(EqtNames) EqtNames=arrayfun(EqtNameFun,(1:neq),'UniformOutput', false); end if isempty(VarNames) VarNames=arrayfun(VarNameFun,(1:nvar),'UniformOutput', false); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [solution] = BuildMPS(Ale, ble, Aeq, beq, c, lb, ub, PbName,'MPSfilename',MPSfilename,'EleNames',EleNames,'EqtNames',EqtNames,'VarNames',VarNames); otherwise error(['Unknown solver: ' solver]); end if ~strcmp(solver,'cplex_direct') && ~strcmp(solver,'mps') %% Assign solution t = etime(clock, t_start); if ~exist('basis','var'), basis=[]; end [solution.full,solution.obj,solution.rcost,solution.dual,solution.solver,solution.stat,solution.origStat,solution.time,solution.basis] = ... deal(x,f,w,y,solver,stat,origStat,t,basis); end %% solveGlpk Solve actual LP problem using glpk and return relevant results function [x,f,y,w,stat,origStat] = solveGlpk(c,A,b,lb,ub,csense,osense,params) % Old way of calling glpk %[x,f,stat,extra] = glpkmex(osense,c,A,b,csense,lb,ub,[],params); [x,f,origStat,extra] = glpk(c,A,b,lb,ub,csense,[],osense,params); y = extra.lambda; w = extra.redcosts; % Note that status handling may change (see glplpx.h) if (origStat == 180 || origStat == 5) stat = 1; % Optimal solution found elseif (origStat == 182 || origStat == 183 || origStat == 3 || origStat == 110) stat = 0; % Infeasible elseif (origStat == 184 || origStat == 6) stat = 2; % Unbounded else stat = -1; % Solution not optimal or solver problem end
github
EPFL-LCSB/matTFA-master
optGeneFitnessTilt.m
.m
matTFA-master/ext/Cobra205_vDec2014/design/optGeneFitnessTilt.m
4,526
utf_8
b9d818464262c0403801cde0424f0834
function [val] = optGeneFitnessTilt(rxn_vector_matrix, model, targetRxn, rxnListInput, isGeneList) %optGeneFitnessTilt GeneOptFitness the fitness function % % [val] = optGeneFitnessTilt(rxn_vector_matrix, model, targetRxn, rxnListInput, isGeneList) % %INPUTS % rxn_vector_matrix % model % targetRxn % rxnListInput % isGeneList % %OUTPUT % val fitness value % % global MaxKnockOuts %size(rxn_vector_matrix) popsize = size(rxn_vector_matrix,1); val = zeros(1,popsize); for i = 1:popsize rxn_vector = rxn_vector_matrix(i,:); rxnList = rxnListInput(logical(rxn_vector)); %see if we've done this before val_temp = memoize(rxn_vector); if ~ isempty(val_temp) val(i) = val_temp; continue; end % check to see if mutations is above the max number allowed nummutations = sum(rxn_vector); if nummutations > MaxKnockOuts continue; end % generate knockout. if isGeneList modelKO = deleteModelGenes(model, rxnList); else % is reaction list [isValidRxn,removeInd] = ismember(rxnList,model.rxns); removeInd = removeInd(isValidRxn); modelKO = model; modelKO.ub(removeInd) = 0; modelKO.lb(removeInd) = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % augment BOF (tilt) [modelKO] = augmentBOF(modelKO, targetRxn, .001); % find growthrate if exist('LPBasis', 'var') modelKO.LPBasis = LPBasis; end [slnKO, LPOUT] = solveCobraLPCPLEX(modelKO, 0,1); LPBasis = LPOUT.LPBasis; growthrate = slnKO.obj; [tmp,tar_loc] = ismember(targetRxn,modelKO.rxns); minProdAtSetGR = slnKO.full(tar_loc); % check to ensure that GR is above a certain value if growthrate < .10 continue; end % % display('second optimization'); % % find the lowesest possible production rate (a hopefully high number) % % at the max growth rate minus some set factor gamma (a growth rate slightly % % smaller than the max). A positive value will eliminate solutions where the % % production envelope has a vertical line at the max GR, a "non-unique" % % solution. Set value to zero if "non-unique" solutions are not an issue. % gamma = 0.01; % proportional to Grwoth Rate (hr-1), a value around 0.5 max. % % %find indicies of important vectors % indBOF = find(modelKO.c); % indTar = findRxnIDs(modelKO, targetRxn); % % generate a model with a fixed max KO growth rate % modelKOsetGR = modelKO; % modelKOsetGR.lb(indBOF) = growthrate - gamma; % this growth rate is required as lb. % modelKOsetGR.c = zeros(size(modelKO.c)); % modelKOsetGR.c(indTar) = -1; % minimize for this variable b/c we want to look at the very minimum production. % % % find the minimum production rate for the targeted reaction. % % % slnKOsetGR = optimizeCbModel(modelKOsetGR); % % minProdAtSetGR1 = -slnKOsetGR.f; % This should be a negative value b/c of the minimization setup, so -1 is necessary. % % if exist('LPBasis2', 'var') % modelKOsetGR.LPBasis = LPBasis2; % end % % [slnKOsetGR, LPOUT2] = solveCobraLPCPLEX(modelKOsetGR, 0,1); % LPBasis2 = LPOUT2.LPBasis; % minProdAtSetGR = -slnKOsetGR.obj; % objective function for optGene algorithm = val (needs to be a negative value, since it is % a minimization) val(i) = -minProdAtSetGR; % penalty for a greater number of mutations %val(i) = -minProdAtSetGR * (.98^nummutations); % select best substrate-specific productivity % val(i) = -minProdAtSetGR * (.98^nummutations) * growthrate; % check to prevent very small values from being considerered improvments if val(i) > -1e-3 val(i) = 0; end memoize(rxn_vector, val(i)); end return; %% Memoize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% MEMOIZE %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % internal function to speed things up. function [value] = memoize(gene_vector, value) global HTABLE hashkey = num2str(gene_vector); hashkey = strrep(hashkey,' ',''); % cut out white space from string (more space efficient). if nargin == 1 value = HTABLE.get(hashkey); return; else if HTABLE.size() > 50000 HTABLE = java.util.Hashtable; %reset the hashtable if more than 50,000 entries. end HTABLE.put(hashkey, value); value = []; return; end return
github
EPFL-LCSB/matTFA-master
GDLS.m
.m
matTFA-master/ext/Cobra205_vDec2014/design/GDLS.m
14,440
utf_8
217f0fb80c846b4d2bb8d8b633753282
function [gdlsSolution, bilevelMILPProblem, gdlsSolutionStructs] = GDLS(model, targetRxns, varargin) %GDLS (Genetic Design through Local Search) attempts to find genetic % designs with greater in silico production of desired metabolites. % % [gdlsSolution, bilevelMILPProblem, gdlsSolutionStructs] = GDLS(model, varargin) % %INPUTS % model Cobra model structure % targetRxn Reaction(s) to be maximized (Cell array of strings) % %OPTIONAL INPUTS % varargin parameters entered using either a structure or list of % parameter, parameter value % List of optional parameters % 'nbhdsz' Neighborhood size (default: 1) % 'M' Number of search paths (default: 1) % 'maxKO' Maximum number of knockouts (default: 50) % 'koCost' Cost for knocking out a reaction, gene set, or gene % A different cost can be set for each knockout. % (default: 1 for each knockout) % 'selectedRxns' List of reactions/geneSets that can be knocked out % 'koType' What to knockout: reactions, gene sets, or genes % {('rxns'), 'geneSets', 'genes'} % 'iterationLimit' Maximum number of iterations (default: 70) % 'timeLimit' Maximum run time in seconds (default: 252000) % 'minGrowth' Minimum growth rate % %OUTPUTS % gdlsSolution GDLS solution structure (similar to OptKnock sol struct) % bilevelMILPProblem Problem structure used in computation % % Adapted from Desmond S Lun's gdls scripts. % Richard Que (1/28/2010) MAXFLUX = 1000; MAXDUAL = 1000; EPS = 1e-4; gdlsSolutionStructs = []; if nargin < 2 error('Model and target reaction(s) must be specified') elseif mod((nargin-2),2)==0 %manual entry options.targetRxns = targetRxns; for i=1:2:(nargin-2) if ismember(varargin{i},{'nbhdsz','M','maxKO','selectedRxns','koType','koCost','minGrowth', ... 'timeLimit','iterationLimit'}) options.(varargin{i}) = varargin{i+1}; else display(['Unknown option ' varargin{i}]); end end elseif isstruct(targetRxns) %options structure options = varargin{1}; else error('Invalid number of entries') end %Default Values if ~isfield(options,'koType'), options.koType = 'rxns'; end if ~isfield(options,'nbhdsz'), options.nbhdsz=1; end if ~isfield(options,'M'), options.M=1; end if ~isfield(options,'maxKO'), options.maxKO=50; end if ~isfield(options,'iterationLimit'), options.iterationLimit=70; end if ~isfield(options,'timeLimit'), options.timeLimit=252000 ; end if isfield(options,'targetRxns') selTargetRxns = logical(ismember(model.rxns,options.targetRxns)); if ~any(selTargetRxns) error([options.targetRxns ' not found. Double check spelling.']); end else error('No target reaction specified') end if isfield(options,'selectedRxns') selSelectedRxns = logical(ismember(model.rxns,options.selectedRxns)); else selSelectedRxns = true(length(model.rxns),1); end switch lower(options.koType) case 'rxns' %% Generate selection reaction matrix model.selRxnMatrix = selMatrix(selSelectedRxns)'; possibleKOList = model.rxns(selSelectedRxns); case 'genesets' %% Generate reaction gene set mapping matrix %remove biomass reaction from grRules and generate unique gene set list possibleKOList = unique(model.grRules(selSelectedRxns)); if isempty(possibleKOList{1}), possibleKOList = possibleKOList(2:end); end for i = 1:length(possibleKOList) model.selRxnMatrix(:,i) = double(strcmp(possibleKOList{i},model.grRules)); end case 'genes' %% Use rxnGeneMat as selRxnMatrix model.selRxnMatrix = model.rxnGeneMat; possibleKOList = model.genes; otherwise error('Unrecognized KO type') end %% Generate koCost if not present if ~isfield(options,'koCost') if isfield(model,'koCost') if length(model.koCost) == 1 options.koCost = ones(length(possibleKOList,1)) * model.koCost; else options.koCost = model.koCost; end else options.koCost = ones(length(possibleKOList),1); end elseif length(model.koCost) == 1 options.koCost = ones(length(possibleKOList,1)) * model.koCost; else options.koCost = model.koCost; end %index exchange reactions [selExc] = findExcRxns(model,true,true); %% Setup model model.ub(isinf(model.ub)) = MAXFLUX; model.ub(model.ub>MAXFLUX) = MAXFLUX; model.lb(isinf(model.lb)) = -MAXFLUX; model.lb(model.lb<-MAXFLUX) = -MAXFLUX; model.rxnsPresent = ones(length(model.rxns),1); %% Create Baseline solution0 = fluxBalance(model,selTargetRxns); %% Create bi-level MILP problem [nMets nRxns] = size(model.S); nInt = size(model.selRxnMatrix,2); jMu = find(~isinf(model.lb)); nMu = length(jMu); jNu = find(~isinf(model.ub)); nNu = length(jNu); y0 = (model.selRxnMatrix' * ~model.rxnsPresent) ~= 0; y0 = repmat(y0,1,options.M); y0p = y0; iiter = 1; change = true; t1 = clock; while change change = false; y = false(nInt, 0); fmax = zeros(1, 0); for istart = 1:size(y0, 2) for irun = 1:options.M c = [selTargetRxns; zeros(nMets, 1); zeros(nMu, 1); zeros(nNu, 1); zeros(nRxns, 1); zeros(nInt, 1)]; %x= [ v lambda mu nu xi y ] A = [ model.S sparse(nMets, nMets) sparse(nMets, nMu) sparse(nMets, nNu) sparse(nMets, nRxns) sparse(nMets, nInt); sparse(nRxns, nRxns) model.S' -sparse(jMu, 1:nMu, ones(nMu, 1), nRxns, nMu) sparse(jNu, 1:nNu, ones(nNu, 1), nRxns, nNu) speye(nRxns) sparse(nRxns, nInt); speye(nRxns) sparse(nRxns, nMets) sparse(nRxns, nMu) sparse(nRxns, nNu) sparse(nRxns, nRxns) model.selRxnMatrix .* repmat(model.lb, 1, nInt); speye(nRxns) sparse(nRxns, nMets) sparse(nRxns, nMu) sparse(nRxns, nNu) sparse(nRxns, nRxns) model.selRxnMatrix .* repmat(model.ub, 1, nInt); sparse(nRxns, nRxns) sparse(nRxns, nMets) sparse(nRxns, nMu) sparse(nRxns, nNu) speye(nRxns) model.selRxnMatrix * MAXDUAL; sparse(nRxns, nRxns) sparse(nRxns, nMets) sparse(nRxns, nMu) sparse(nRxns, nNu) speye(nRxns) -model.selRxnMatrix * MAXDUAL; model.c' sparse(1, nMets) model.lb(jMu)' -model.ub(jNu)' sparse(1, nRxns) sparse(1, nInt); sparse(1, nRxns) sparse(1, nMets) sparse(1, nMu) sparse(1, nNu) sparse(1, nRxns) ((y0(:, istart) == 0) - (y0(:, istart) == 1))'; sparse(size(y, 2), nRxns) sparse(size(y, 2), nMets) sparse(size(y, 2), nMu) sparse(size(y, 2), nNu) sparse(size(y, 2), nRxns) ((y == 0) - (y == 1))'; sparse(1, nRxns) sparse(1, nMets) sparse(1, nMu) sparse(1, nNu) sparse(1, nRxns) options.koCost'; ]; b = [ zeros(nMets, 1); model.c; model.lb; model.ub; zeros(nRxns, 1); zeros(nRxns, 1); 0; options.nbhdsz - nnz(y0(:, istart)); ones(size(y, 2), 1) - sum((y ~= 0), 1)'; options.maxKO; ]; csense = char(['E' * ones(nMets, 1); 'E' * ones(nRxns, 1); 'G' * ones(nRxns, 1); 'L' * ones(nRxns, 1); 'G' * ones(nRxns, 1); 'L' * ones(nRxns, 1); 'E'; 'L'; 'G' * ones(size(y, 2), 1); 'L'; ]); lb = [ model.lb; -Inf * ones(nMets, 1); zeros(nMu, 1); zeros(nNu, 1); -Inf * ones(nRxns, 1); zeros(nInt, 1) ]; ub = [ model.ub; Inf * ones(nMets, 1); Inf * ones(nMu, 1); Inf * ones(nNu, 1); Inf * ones(nRxns, 1); ones(nInt, 1) ]; vartype = char(['C' * ones(nRxns, 1); 'C' * ones(nMets, 1); 'C' * ones(nMu, 1); 'C' * ones(nNu, 1); 'C' * ones(nRxns, 1); 'B' * ones(nInt, 1); ]); osense = -1; %maximize if isfield(options,'minGrowth') A = [A; model.c' sparse(1, nMets + nMu + nNu + nRxns + nInt)]; b = [b; options.minGrowth]; csense = [csense; 'G']; end [bilevelMILPProblem.c, bilevelMILPProblem.A,... bilevelMILPProblem.b, bilevelMILPProblem.lb,... bilevelMILPProblem.ub, bilevelMILPProblem.csense,... bilevelMILPProblem.vartype, bilevelMILPProblem.osense,... bilevelMILPProblem.x0] = ... deal(c, A, b, lb, ub, csense, vartype, osense, []); %solve solution1 = solveCobraMILP(bilevelMILPProblem); %check solver status if solution1.stat~=1 continue; %non optimal solution end yt = solution1.full((end - nInt + 1):end) > EPS; model.rxnsPresent = ~(model.selRxnMatrix * yt); solution2 = fluxBalance(model,selTargetRxns,false); if abs(solution2.obj - solution1.obj) > EPS continue; %inconsistent end fmax(:, end + 1) = solution1.obj; y(:, end + 1) = yt; end end if size(y, 2) == 0 continue; end [fmaxsort, ifmaxsort] = sort(fmax); y = y(:, ifmaxsort); y = y(:, max([1 size(y, 2) - options.M + 1]):end); y = shrinkKnockouts(y, model, selTargetRxns); if size(y, 2) ~= size(y0, 2) || any(any(y~=y0))&&any(any(y~=y0p)) y0p=y0; y0 = y; change = true; end fprintf('Iteration %d\n', iiter); fprintf('----------%s\n', char('-' * ones(1, floor(log10(iiter)) + 1))); for iend = 1:size(y0, 2) model.rxnsPresent = ~(model.selRxnMatrix * y0(:, iend)); [solSynMax solSynMin solBiomass] = fluxBalance(model,selTargetRxns); fprintf('Knockout cost: %d\n', options.koCost' * y0(:, iend)); if nnz(y0) > 0 fprintf('Knockouts:\n%s', sprintf('\t%s\n', possibleKOList{y0(:, iend)})); end printLabeledData(model.rxns(selExc),solSynMax.full(selExc),true); fprintf('\n'); %Save Solutions gdlsSolutionStructs.(sprintf('Iteration_%d',iiter)).(sprintf('solution_%2',i)).solBiomass = solBiomass; gdlsSolutionStructs.(sprintf('Iteration_%d',iiter)).(sprintf('solution_%2',i)).solSynMin = solSynMin; gdlsSolutionStructs.(sprintf('Iteration_%d',iiter)).(sprintf('solution_%2',i)).solSynMax = solSynMax; end elapsed_time = etime(clock,t1) iiter = iiter + 1; if (elapsed_time >= options.timeLimit) || (iiter >= options.iterationLimit) break; end end %Generate Solution Structure fprintf('\nGenerating Output\n'); gdlsSolution.int = y0; gdlsSolutions.KOs = cell(max(sum(y0,2)),size(y0,2)); for i = 1:size(y0,2) gdlsSolution.KOs(1:nnz(y0(:,i)),i) = possibleKOList(y0(:,i)); [solSynMax solSynMin solBiomass] = fluxBalance(model,selTargetRxns,false); gdlsSolution.biomass(1,i) = solBiomass.obj; gdlsSolution.minTargetProd(1,i) = solSynMin.obj; gdlsSolution.maxTargetProd(1,i) = solSynMax.obj; end end function y = shrinkKnockouts(y, model, selTargetRxns) for iycol = 1:size(y, 2) model.rxnsPresent = ~(model.selRxnMatrix * y(:, iycol)); solution1 = fluxBalance(model, selTargetRxns, false); for i = find(y(:, iycol))' yt = y(:, iycol); yt(i) = 0; model.rxnsPresent = ~(model.selRxnMatrix * yt); solution2 = fluxBalance(model, selTargetRxns, false); if solution2.obj >= solution1.obj y(:, iycol) = yt; y(:, iycol) = shrinkKnockouts(y(:, iycol), model, selTargetRxns); end end end y = unique(y', 'rows')'; end function [solSynMax solSynMin solBiomass] = fluxBalance(model,selTargetRxns,verbFlag) if nargin < 3 verbFlag = true; end model.x0 = []; modelb = model; model_syn = model; [nMets nRxns] = size(model.S); yt = model.rxnsPresent; modelb.A = [ model.S; sparse(1:nnz(~yt), find(~yt), ones(nnz(~yt), 1), nnz(~yt), nRxns) ]; modelb.b = [ zeros(nMets, 1); zeros(nnz(~yt), 1) ]; modelb.csense = char('E' * ones(1, nMets + nnz(~yt))); modelb.vartype = char('C' * ones(1, nRxns)); modelb.osense = -1; solBiomass = solveCobraMILP(modelb); model_syn.A = [ model.S; sparse(1:nnz(~yt), find(~yt), ones(nnz(~yt), 1), nnz(~yt), nRxns); model.c' ]; model_syn.b = [ zeros(nMets, 1); zeros(nnz(~yt), 1); solBiomass.obj ]; model_syn.c = selTargetRxns; model_syn.csense = char('E' * ones(1, nMets + nnz(~yt) + 1)); model_syn.vartype = char('C' * ones(1, nRxns)); model_syn.osense = -1; solSynMax = solveCobraMILP(model_syn); model_syn.osense = 1; solSynMin = solveCobraMILP(model_syn); if verbFlag fprintf('Biomass flux: %f\n', solBiomass.obj); fprintf('Synthetic flux: [%f, %f]\n', solSynMin.obj, solSynMax.obj); end end
github
EPFL-LCSB/matTFA-master
optGene.m
.m
matTFA-master/ext/Cobra205_vDec2014/design/optGene.m
10,378
utf_8
096047845ee9473fe011e1224eda05b7
function [x, population, scores, optGeneSol] = optGene(model, targetRxn, substrateRxn, generxnList, MaxKOs, population) %OPTGENE implements the optgene algorithm. % % [x, population, scores, optGeneSol] = optGene(model, targetRxn, substrateRxn, generxnList, MaxKOs, population) % %INPTUS % mode Model of reconstruction % targetRxn String name of reaction which is to be maximized. % generxnList List of genes or rxns which can be knocked out. The % program will guess which of the two it is, based on the % content in model. % %OPTIONAL INPUT % population population matrix (binary matrix). Use this % parameter to interrupt simulation and resume afterwards. % %OUTPUTS % x best optimized value found % population Population of individuals. Pass this back into optgene to % continue simulating where you left off. % scores An array of scores % optGeneSol optGene solution strcture % % Jan Schellenberger and Adam Feist 04/08/08 % hash table for hashing results... faster than not using it. global HTABLE HTABLE = java.util.Hashtable; global MaxKnockOuts ngenes = length(generxnList); % figure out if list is genes or reactions rxnok = 1; geneok = 1; for i = 1:length(generxnList) if(~ ismember(generxnList{i}, model.rxns)), rxnok = 0; end if(~ ismember(generxnList{i}, model.genes)),geneok = 0; end end if geneok display('assuming list is genes'); elseif rxnok display('assuming list is reactions'); else display('list appears to be neither genes nor reactions: aborting'); return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% PARAMETERS - set parameters here %%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 5 MaxKnockOuts = 10; else MaxKnockOuts = MaxKOs; end mutationRate = 1/ngenes; % paper: a mutation rate of 1/(genome size) was found to be optimal for both representations. crossovermutationRate = mutationRate*.2; % the rate of mutation after a crossover. This value should probably be fairly low. It is only there to ensure that not every member of the population ends up with the same genotype. CrossoverFraction = .80; % Percentage of offspring created by crossing over (as opposed to mutation). 0.7 - 0.8 were found to generate the highest mean, but this can be adjusted. PopulationSize = [125 125 125 125]; % paper: it was found that an increase beyond 125 individuals did not improve the results significantly. Generations = 10000; % paper: 5000. maximum number of generations to perform TimeLimit = 3600*24*2; % global time limit in seconds StallTimeLimit = 3600*24*1; % Stall time limit (terminate after this much time of not finding an improvement in fitness) StallGenLimit = 10000; % terminate after this many generations of not finding an improvement PlotFcns = {@gaplotscores, @gaplotbestf, @gaplotscorediversity, @gaplotstopping, @gaplotmutationdiversity}; % what to plot. crossfun = @(a,b,c,d,e,f) crossoverCustom(a,b,c,d,e,f,crossovermutationRate); MigrationFraction = .1; % how many individuals migrate (.1 * 125 ~ 12 individuals). MigrationInterval = 100; % how often individuals migrate from one population to another. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% END PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% InitialPopulation = []; if nargin > 5 InitialPopulation = double(population); end options = gaoptimset( ... 'PopulationType', 'bitstring', ... 'CreationFcn', @lowmutationcreation, ... 'MutationFcn', {@mutationUniformEqual, mutationRate}, ... 'PopulationSize', PopulationSize, ... 'StallTimeLimit', StallTimeLimit, ... 'TimeLimit', TimeLimit, ... 'PlotFcns', PlotFcns, ... 'InitialPopulation', InitialPopulation, ... 'CrossoverFraction', CrossoverFraction, ... 'CrossoverFcn', crossfun, ... 'StallGenLimit', StallGenLimit, ... 'Generations', Generations, ... 'TolFun', 1e-10, ... 'Vectorize', 'on', ... 'MigrationFraction', MigrationFraction, ... 'MigrationInterval', MigrationInterval ... ... % 'SelectionFcn', @selectionstochunif ... ); % options % pause; %finess function call %FitnessFunction = @(x) optGeneFitness(x,model,targetRxn, generxnList, geneok); FitnessFunction = @(x) optGeneFitnessTilt(x,model,targetRxn, generxnList, geneok); gap.fitnessfcn = FitnessFunction; gap.nvars = ngenes; gap.options = options; [x,FVAL,REASON,OUTPUT,population, scores] = ga(gap); % save the solution [optGeneSol] = GetOptGeneSol(model, targetRxn, substrateRxn, generxnList, population, x, scores, geneok); % in case of genes return; %% Creation Function % generates initial warmup with much lower number of mutations (on average % one mutation per function [Population] = lowmutationcreation(GenomeLength,FitnessFcn,options) totalPopulation = sum(options.PopulationSize); initPopProvided = size(options.InitialPopulation,1); individualsToCreate = totalPopulation - initPopProvided; % Initialize Population to be created Population = true(totalPopulation,GenomeLength); % Use initial population provided already if initPopProvided > 0 Population(1:initPopProvided,:) = options.InitialPopulation; end % Create remaining population Population(initPopProvided+1:end,:) = logical(1/GenomeLength > rand(individualsToCreate,GenomeLength)); return; %% Mutation Function %%%%%%%%%%%%%%%%%%%%%%%%%%% %%% mutation function %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%% function mutationChildren = mutationUniformEqual(parents,options,GenomeLength,FitnessFcn,state,thisScore,thisPopulation,mutationRate) global MaxKnockOuts if(nargin < 8) mutationRate = 0.01; % default mutation rate end mutationChildren = zeros(length(parents),GenomeLength); for i=1:length(parents) child = thisPopulation(parents(i),:); kos = sum(child); mutationPoints = find(rand(1,length(child)) < mutationRate); child(mutationPoints) = ~child(mutationPoints); if MaxKnockOuts > 0 while(sum(child(:))> MaxKnockOuts) ind2 = find(child); removeindex = ind2(randint(1,1,length(ind2))+1); child(removeindex) = 0; end end % with 50% chance, you will have fewer knockouts after mutation % than before. This is to stop aquiring so many mutations. if rand > .5 && kos > 1 while(sum(child(:))>= kos) ind2 = find(child); removeindex = ind2(randint(1,1,length(ind2))+1); child(removeindex) = 0; end end mutationChildren(i,:) = child; end return; %% Crossover Function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% crossover function %%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function xoverKids = crossoverCustom(parents,options,GenomeLength,FitnessFcn,unused,thisPopulation, mutationRate) nKids = length(parents)/2; % Extract information about linear constraints % Allocate space for the kids xoverKids = zeros(nKids,GenomeLength); global MaxKnockOuts; % To move through the parents twice as fast as thekids are % being produced, a separate index for the parents is needed index = 1; % for each kid... for i=1:nKids % get parents r1 = parents(index); index = index + 1; r2 = parents(index); index = index + 1; % Randomly select half of the genes from each parent % This loop may seem like brute force, but it is twice as fast as the % vectorized version, because it does no allocation. for j = 1:GenomeLength if(rand > 0.5) xoverKids(i,j) = thisPopulation(r1,j); else xoverKids(i,j) = thisPopulation(r2,j); end end if MaxKnockOuts>0 while(sum(xoverKids(i,:))> MaxKnockOuts) ind2 = find(xoverKids(i,:)); removeindex = ind2(randint(1,1,length(ind2))+1); xoverKids(i,removeindex) = 0; end end end % also apply mutations to crossover kids... xoverKids = mutationUniformEqual(1:size(xoverKids,1) ,[],GenomeLength,[],[],[],xoverKids,mutationRate); return; function state = gaplotmutationdiversity(options,state,flag,p1) %GAPLOTSCOREDIVERSITY Plots a histogram of this generation's scores. % STATE = GAPLOTSCOREDIVERSITY(OPTIONS,STATE,FLAG) plots a histogram of current % generation's scores. % % Example: % Create an options structure that uses GAPLOTSCOREDIVERSITY % as the plot function % options = gaoptimset('PlotFcns',@gaplotscorediversity); % Copyright 2003-2007 The MathWorks, Inc. % $Revision: 1.6.4.3 $ $Date: 2007/05/23 18:49:53 $ global MaxKnockOuts if nargin < 4 p1 = 10; end p1 = MaxKnockOuts+1; p1 = [0:(MaxKnockOuts)]; switch flag case 'init' title('Mutation Histogram','interp','none') xlabel('number of mutations'); ylabel('Number of individuals'); case 'iter' % Check if Rank is a field and there are more than one objectives, then plot for Rank == 1 if size(state.Score,2) > 1 && isfield(state,'Rank') index = (state.Rank == 1); % When there is one point hist will treat it like a vector % instead of matrix; we need to add one more duplicate row if nnz(index) > 1 set(gca,'ylimmode','auto'); hist(sum(state.Population(index,:)),p1); else set(gca,'ylim',[0 1]); hist([sum(state.Population(index,:)); sum(state.Population(index,:))],p1); end % Legend for each function <min max> values on the Pareto front nObj = size(state.Score,2); fminval = min(state.Score(index,:),[],1); fmaxval = max(state.Score(index,:),[],1); legendText = cell(1,nObj); for i = 1:nObj legendText{i} = ['fun',num2str(i),' [',sprintf('%g ',fminval(i)), ... sprintf('%g',fmaxval(i)),']']; end legend(legendText); else % else plot all score hist(sum(state.Population,2),p1); end end
github
EPFL-LCSB/matTFA-master
optGeneFitness.m
.m
matTFA-master/ext/Cobra205_vDec2014/design/optGeneFitness.m
4,201
utf_8
af651aa05b3544eb6d725b9ac5cfa801
function [val] = optGeneFitness(rxn_vector_matrix, model, targetRxn, rxnListInput, isGeneList) %optGeneFitness GeneOptFitness the fitness function % % [val] = optGeneFitness(rxn_vector_matrix, model, targetRxn, rxnListInput, isGeneList) % %INPUTS % rxn_vector_matrix % model % targetRxn % rxnListInput % isGeneList % %OUTPUT % val % % global MaxKnockOuts %size(rxn_vector_matrix) popsize = size(rxn_vector_matrix,1); val = zeros(1,popsize); for i = 1:popsize rxn_vector = rxn_vector_matrix(i,:); rxnList = rxnListInput(logical(rxn_vector)); %see if we've done this before val_temp = memoize(rxn_vector); if ~ isempty(val_temp) val(i) = val_temp; continue; end % check to see if mutations is above the max number allowed nummutations = sum(rxn_vector); if nummutations > MaxKnockOuts continue; end % generate knockout. if isGeneList modelKO = deleteModelGenes(model, rxnList); else % is reaction list [isValidRxn,removeInd] = ismember(rxnList,model.rxns); removeInd = removeInd(isValidRxn); modelKO = model; modelKO.ub(removeInd) = 0; modelKO.lb(removeInd) = 0; end % find growthrate; % slnKO = optimizeCbModel(modelKO); % growthrate1 = slnKO.f; %max growth rate. if exist('LPBasis', 'var') modelKO.LPBasis = LPBasis; end [slnKO, LPOUT] = solveCobraLPCPLEX(modelKO, 0,1); LPBasis = LPOUT.LPBasis; growthrate = slnKO.obj; % check to ensure that GR is above a certain value if growthrate < .10 continue; end % display('second optimization'); % find the lowesest possible production rate (a hopefully high number) % at the max growth rate minus some set factor gamma (a growth rate slightly % smaller than the max). A positive value will eliminate solutions where the % production envelope has a vertical line at the max GR, a "non-unique" % solution. Set value to zero if "non-unique" solutions are not an issue. gamma = 0.01; % proportional to Grwoth Rate (hr-1), a value around 0.5 max. %find indicies of important vectors indBOF = find(modelKO.c); indTar = findRxnIDs(modelKO, targetRxn); % generate a model with a fixed max KO growth rate modelKOsetGR = modelKO; modelKOsetGR.lb(indBOF) = growthrate - gamma; % this growth rate is required as lb. modelKOsetGR.c = zeros(size(modelKO.c)); modelKOsetGR.c(indTar) = -1; % minimize for this variable b/c we want to look at the very minimum production. % find the minimum production rate for the targeted reaction. % slnKOsetGR = optimizeCbModel(modelKOsetGR); % minProdAtSetGR1 = -slnKOsetGR.f; % This should be a negative value b/c of the minimization setup, so -1 is necessary. if exist('LPBasis2', 'var') modelKOsetGR.LPBasis = LPBasis2; end [slnKOsetGR, LPOUT2] = solveCobraLPCPLEX(modelKOsetGR, 0,1); LPBasis2 = LPOUT2.LPBasis; minProdAtSetGR = -slnKOsetGR.obj; % objective function for optGene algorithm = val (needs to be a negative value, since it is % a minimization) val(i) = -minProdAtSetGR; % penalty for a greater number of mutations % val(i) = -minProdAtSetGR * (.98^nummutations); % select best substrate-specific productivity % val(i) = -minProdAtSetGR * (.98^nummutations) * growthrate; % check to prevent very small values from being considerered improvments if val(i) > -1e-3 val(i) = 0; end memoize(rxn_vector, val(i)); end return; %% Memoize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% MEMOIZE %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % internal function to speed things up. function [value] = memoize(gene_vector, value) global HTABLE hashkey = num2str(gene_vector); hashkey = strrep(hashkey,' ',''); % cut out white space from string (more space efficient). if nargin == 1 value = HTABLE.get(hashkey); return; else if HTABLE.size() > 10000 HTABLE = java.util.Hashtable; %reset the hashtable if more than 10,000 entries. end HTABLE.put(hashkey, value); value = []; return; end return
github
EPFL-LCSB/matTFA-master
compareMultSamp.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/compareMultSamp.m
3,253
utf_8
2cdd10a7b9419f8d2af32bf86b455456
function [totalz,zscore,mdvs] = compareMultSamp(xglc,model,samps,measuredMetabolites) % Compare the multiple sets of samples % xglc is optional, a random sugar distribution is calculated if empty % expects samp1 and samp2 to have a field named points containing % an array of sampled points % expects model.rxns to contain a list of rxn names % measuredMetabolites is an optional parameter fed to calcMDVfromSamp.m % which only calculates the MDVs for the metabolites listed in this % array. e.g. % % totalz is the sum of all zscores % zscore is the calculated difference for each mdv element distributed % across all the points % mdv1,mdv2 each containing fields: % - mdv - the calculated mdv distribution converted from the idv % solved from each point contained in their respective samples sampX % - names - the names of the metabolites % - ave - the average of each mdv element across all of the points % - stdev - the standard dev for each mdv element across all points % Wing Choi 2/11/08 %glc = zeros(62,1); %glc = [.2 ;.8 ;glc]; if (nargin < 3) disp '[totalz,zscore,mdvs] = compareMultSamp(xglc,model,samps,measuredMetabolites)'; return; end if (nargin < 4) measuredMetabolites = []; end mdvs.ave = []; mdvs.stdev = []; if (isempty(xglc)) % random glucose xglc = rand(64,1); xglc = xglc/sum(xglc); xglc = idv2cdv(6)*xglc; end % generate the translation index array % can shave time by not regenerating this array on every call. xltmdv = zeros(1,4096); for i = 1:4096 xltmdv(i) = length(strrep(dec2base(i-1,2),'0','')); end % calculate mdv for samp1 and samp2 for i = 1:length(samps) samp.points = samps(i).points; mdv = calcMDVfromSamp(model,xglc,samp,measuredMetabolites); l = length(mdv.ave); mdvs.ave(1:l,i) = mdv.ave; mdvs.stdev(1:l,i) = mdv.stdev; %[mdv2] = calcMDVfromSamp(model,xglc,samp2,measuredMetabolites); %[totalz,zscore] = compareTwoMDVs(mdv1,mdv2); end totalz = 0; zscore = 0; %mdvs = mdv; return end %Here's what the function does. %Apply slvrXXfast to each point %for each field in the output, apply iso2mdv to get a much shorter vector. %store all the mdv's for each point and for each metabolite in both sets. % %Compute the mean and standard deviation of each mdv and then get a z-score % between them (=(mean1-mean2)/(sqrt(sd1^2+sd2^2))). %Add up all the z-scores (their absolute value) and have this function return % that value. % %Intuitively what we're doing here is comparing the two sets based on % how different the mdv's appear. %We're going to see if different glucose mixtures result in different values. %I'm going to rewrite part of slvrXXfast so it doesn't return every metabolite % but only those we can actually measure, but for now just make it generic. function mdv = myidv2mdv (idv,xltmdv) % generate the mdv len = length(idv); %disp(sprintf('idv is %d long',len)); mdv = zeros(1,xltmdv(len)+1); %disp(sprintf('mdv is %d long',length(mdv))); for i = 1:len idx = xltmdv(i) + 1; %disp(sprintf('idx is %d, currently on %d',idx,i)); mdv(idx) = mdv(idx) + idv(i); end return end
github
EPFL-LCSB/matTFA-master
C13ConfidenceInterval.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/C13ConfidenceInterval.m
14,161
utf_8
4b5572a4c36fbfc32729f15f709e7683
function [vs, output, v0] = C13ConfidenceInterval(v0, expdata, model, max_score, directions, majorIterationLimit) % v0 - set of flux vectors to be used as initial guesses. They may be % valid or not. % expdata - experimental data. % model - The standard model. Additional field .N (= null(S)) should also % be provided. This is a basis of the flux space. % max score - maximum allowable data fit error. % directions (optional) - ones and zeros of which reactions to compute (size = n % x 1). % OR % numbers of reactions to use aka. [1;5;7;8;200] % OR % reaction strings aka. {'GPK', 'PGL'}. Ratios are possible with this % input only. Default = [] meaning do FVA with no ratios. % majorIterationLimit (optional) - default = 10000 if nargin < 5 directions = ones(size(v0,1),1); end if isempty(directions) directions = ones(size(v0,1),1); end t_start = clock; printLevel = 3; if nargin < 6 majorIterationLimit = 1000; %max number of iterations end diffInterval = 1e-5; %gradient step size. feasibilityTolerance = max_score/20; % how close you need to be to the max score. logdirectory = strcat('temp', filesep); % isratio(i): >0 indicates not a ratio and points to reaction# % <0 indicates -numerator of ratio fraction. In this case, % denom(i) stores the denominator % denom = zeros(size(directions)); if isnumeric(directions) %cannot be an actual ratio if max(directions) == 1 isratio = find(directions); else isratio = directions; end else % might be a ratio. Gotta process strings isratio = zeros(size(directions)); for i = 1:length(directions) if findstr(directions{i}, '/') [rxn1,rest] = strtok(directions{i}, '/'); rxnID = findRxnIDs(model,rxn1); if rxnID == 0 display('unable to process rxn from list'); display(directions{i}); return; else isratio(i) = -rxnID; end rxn2 = rest(2:end); rxnID = findRxnIDs(model,rxn2); if rxnID == 0 display('unable to process rxn from list'); display(rest(2:end)); return; else denom(i) = rxnID; end else rxnID = findRxnIDs(model,directions{i}); if rxnID == 0 display('unable to process rxn from list'); display(directions{i}); return; else isratio(i) = rxnID; end end end end numdirections = length(isratio); numpoints = size(v0,2); numiterations = numdirections*numpoints*2; % total number of iterations. x0 = model.N\v0; % back substitute scores = zeros(numpoints,1); tProb.user.expdata = expdata; tProb.user.model = model; for i = 1:numpoints scores(i) = errorComputation2(x0(:,i),tProb); end % fit points if they are not currently feasible v0(:,scores> max_score) = fitC13Data(v0(:,scores > max_score),expdata,model, majorIterationLimit); if ~isfield(model, 'N') model.N = null(model.S); end x0 = model.N\v0; % back substitute % safety check: if (max(abs(model.S*v0))> 1e-6) display('v0 not quite in null space'); pause; end if(max(abs(model.N*x0 - v0)) > 1e-6) display('null basis is weird'); pause; end Name = 't2'; nalpha = size(model.N, 2); x_L = -1000*ones(nalpha,1); x_U = 1000*ones(nalpha,1); [A, b_L, b_U] = defineLinearConstraints(model); scores = zeros(numpoints,1); % compute scores for all points. for i = 1:numpoints scores(i) = errorComputation2(x0(:,i),tProb); end valid_index = scores < max_score + feasibilityTolerance; fprintf('found %d valid points\n', sum(valid_index)); x0_valid = x0(:,valid_index); x0_invalid = x0; scores_valid = scores(valid_index); % pre-compute unnecesary directions. % if checkedbefore(i) ~= 0 then direction i is redundant % if checkedbefore(i) = j then direction i and j are identical and do not % need to be recomputed. % checkedbefore(i) = j < 0 means that direction j is the same as i except % for a sign switch. checkedbefore = zeros(length(isratio),1); for i = 2:length(isratio) if(isratio(i) < 0) % meaning it actually IS a ratio and no simplification possible continue end d = objective_coefficient(isratio(i), model); for j = 1:i-1 if(isratio(j) < 0) % meaning it actually IS a ratio and no simplification possible continue end dj = objective_coefficient(isratio(j), model); if max(abs(dj - d))< 1e-4 checkedbefore(i) = j; break; elseif max(abs(dj + d))< 1e-4 checkedbefore(i) = -j; break; end end end % initialize variables; outputv = 222*ones(numiterations,1); outputexitflag = -222*ones(numiterations,1); outputfinalscore = -222*ones(numiterations,1); outputstruct = cell(numiterations,1); csense = ''; for mm = 1:length(b_L),csense(mm,1) = 'L';end for mm = 1:length(b_L),csense(mm+length(b_L),1) = 'G';end fLowBnds = zeros(length(isratio), 2); %initialize but fill in later. for rxn = 1:length(isratio) for direction = -1:2:1 if isratio(rxn) < 0 ration = objective_coefficient(-isratio(rxn),model); ratiod = objective_coefficient(denom(rxn),model); % in case RXN is a ratio Result = solveCobraNLP(... struct('lb', x_L, 'ub', x_U,... 'name', Name,... 'A', A,... 'b_L', b_L, 'b_U', b_U,... 'objFunction', 'ratioScore', 'g', 'ratioScore_grad',... 'userParams', struct(... 'ration', direction*ration, 'ratiod', ratiod,... % set direction here too. 'diff_interval', diffInterval,'useparfor', true)... ),... 'printLevel', 1, ... 'iterationLimit', 1000); else d = objective_coefficient(isratio(rxn),model); Result = solveCobraLP(... struct('A', [A;A],'b',[b_U;b_L],'csense', csense, ... 'c', direction*d, ... 'lb', x_L,'ub', x_U, ... 'osense', 1),... 'feasTol',1e-7,'optTol',1e-7); if Result.stat ~= 1 Result pause end end fLowBnds(rxn, (direction+3)/2) = direction*Result.obj; % fill in end end if ~exist (logdirectory, 'dir') if ~mkdir(logdirectory) display('unable to create logdirectory'); return; end end clear d %iterate through directions parfor itnum = 1:numiterations if exist('ttt.txt', 'file') % abort w/o crashing if file 'ttt.txt' found in current directory fprintf('quitting due to file found\n'); continue; end [rxn, direction, point] = getValues(itnum, numpoints); % translate itnum to rxn, direction and point % direction == 1 means minimize. direction == -1 means maximize % (opposite of what you might think. if checkedbefore(rxn) ~= 0 %if this reaction maps to a previous reaction, we can skip continue; end fLowBnd = fLowBnds(rxn, (direction+3)/2); %get the absolute bound in the space w/o regards to C13 constraints. fprintf('reaction %d of %d, direction %d, lowerbound %f point %d of %d\n', rxn ,length(isratio), direction, fLowBnd, point, numpoints); % short circuit if x0 already close to a bound. if isratio(rxn) > 0 di = objective_coefficient(isratio(rxn),model); obj1 = di'*x0_valid; else rationi = objective_coefficient(-isratio(rxn),model); ratiodi = objective_coefficient(denom(rxn),model); obj1 = (rationi'*x0_valid) ./ (ratiodi'*x0_valid); end if(any(abs(obj1-fLowBnd)<.0001)) display('short circuiting'); [nil, min_index] = min(obj1); outputv(itnum,1) = fLowBnd; % multiply by direction to correct sign. outputexitflag(itnum,1) = 111; outputfinalscore(itnum,1) = scores_valid(min_index); else % gotta actually do the computation. xinitial = x0_invalid(:,point); if isratio(rxn) > 0 NLPsolution = solveCobraNLP(... struct('x0', xinitial, ... 'lb', x_L, 'ub', x_U,... 'name', Name,... 'A', A, 'b_L', b_L, 'b_U', b_U,... 'd', 'errorComputation2', 'dd', 'errorComputation2_grad',... 'd_L', 0, 'd_U', max_score,... 'c', di*direction, ... % direction of optimization 'userParams', struct(... 'expdata', expdata,'model', model,'max_error', max_score,... 'diff_interval', diffInterval,'useparfor', true)... ),... 'printLevel', printLevel, ... ...%'intTol', 1e-7, ... 'iterationLimit', majorIterationLimit, ... 'logFile', strcat(logdirectory, 'ci_', num2str(rxn),'x',num2str(direction),'x', point, '.txt')); else NLPsolution = solveCobraNLP(... struct('x0', xinitial, ... 'lb', x_L, 'ub', x_U,... 'name', Name,... 'A', A, 'b_L', b_L, 'b_U', b_U,... 'd', 'errorComputation2', 'dd', 'errorComputation2_grad',... 'd_L', 0, 'd_U', max_score,... 'objFunction', 'ratioScore', 'g', 'ratioScore_grad',... 'userParams', struct(... 'expdata', expdata,'model', model,'max_error', max_score,... 'ration', direction*rationi,... 'ratiod', ratiodi,... 'diff_interval', diffInterval,'useparfor', false)... ),... 'printLevel', printLevel, ... ...%'intTol', 1e-7, ... 'iterationLimit', majorIterationLimit, ... 'logFile', strcat(logdirectory, 'ci_', num2str(rxn),'x',num2str(direction),'x', point, '.txt')); end tscore = errorComputation2(NLPsolution.full, tProb); tbest = NLPsolution.obj; fprintf('reaction %d (%d), x %d; x=%f (%f); score=%f (%f)\n', rxn, length(isratio),direction, tbest,fLowBnd, tscore, max_score) outputv(itnum,1) = direction*tbest; % multiply by direction to correct sign. outputexitflag(itnum,1) = NLPsolution.origStat; outputfinalscore(itnum,1) = tscore; outputstruct{itnum,1} = NLPsolution; end end for itnum = 1:numiterations [rxn, direction, point] = getValues(itnum,numpoints); if direction == 1; output.minv(rxn,point) = outputv(itnum); output.minexitflag(rxn,point) = outputexitflag(itnum); output.minfinalscore(rxn,point) = outputfinalscore(itnum); output.minstruct(rxn,point) = outputstruct(itnum); else output.maxv(rxn,point) = outputv(itnum); output.maxexitflag(rxn,point) = outputexitflag(itnum); output.maxfinalscore(rxn,point) = outputfinalscore(itnum); output.maxstruct(rxn,point) = outputstruct(itnum); end end for i = 1:length(isratio) if checkedbefore(i) > 0 %short circuit if seen before. output.minv(i) = output.minv(checkedbefore(i)); output.maxv(i) = output.maxv(checkedbefore(i)); output.minexitflag(i) = output.minexitflag(checkedbefore(i)); output.maxexitflag(i) = output.maxexitflag(checkedbefore(i)); output.minfinalscore(i) = output.minfinalscore(checkedbefore(i)); output.maxfinalscore(i) = output.maxfinalscore(checkedbefore(i)); output.minstruct(i) = output.minstruct(checkedbefore(i)); output.maxstruct(i) = output.maxstruct(checkedbefore(i)); elseif checkedbefore(i) < 0 output.minv(i) = -output.maxv(-checkedbefore(i)); output.maxv(i) = -output.minv(-checkedbefore(i)); output.minexitflag(i) = output.maxexitflag(-checkedbefore(i)); output.maxexitflag(i) = output.minexitflag(-checkedbefore(i)); output.minfinalscore(i) = output.maxfinalscore(-checkedbefore(i)); output.maxfinalscore(i) = output.minfinalscore(-checkedbefore(i)); output.minstruct(i) = output.maxstruct(-checkedbefore(i)); output.maxstruct(i) = output.minstruct(-checkedbefore(i)); end end vs = zeros(length(isratio), 2); for i = 1:length(isratio) validindex = output.minfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,1) = min(output.minv(i,validindex)); else vs(i,1) = 222; end validindex = output.maxfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,2) = max(output.maxv(i,validindex)); else vs(i,2) = -222; end end elapsed_time = etime(clock, t_start) return; % function [index] = getIndex(rxn, direction, point, numpoints) % % point goes from 1 .. NUMPOINTS % % rxn goes from 1 .. NUMRXNS % % direction is -1 or 1 % % index goes from 1 to NUMPOINTS*NUMRXNS*2 % % rxn = rxn - 1; % point = point -1; % direction = (direction + 1)/2; % % % index = rxn*numpoints*2 + direction*numpoints + point; % index = index+1; % % return; function [rxn, direction, point] = getValues(index, numpoints) % point goes from 1 .. NUMPOINTS % rxn goes from 1 .. NUMRXNS % direction is -1 or 1 % index goes from 1 to NUMPOINTS*NUMRXNS*2 index = index - 1; point = mod(index, numpoints); index = index - point; index = index/numpoints; direction = mod(index,2); index = index - direction; index = index/2; rxn = index; point = point +1; % remap to 1..NUMPOINTS direction = direction*2-1; % remap to -1,1 rxn = rxn+1; % remap to 1 .. number of rxns; return; % function that returns the proper objective coefficient for each reaction % takes into account the reversibility of reactinos etc. function [d] = objective_coefficient(i, model) d = zeros(length(model.lb),1); d(i) = 1; if (model.match(i)) d(model.match(i)) = -1; end d = (d'*model.N)'; % transform to null space; return
github
EPFL-LCSB/matTFA-master
runHiLoExp.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/runHiLoExp.m
10,864
utf_8
f754c1508023d127daf3b1f489af2798
function [experiment] = runHiLoExp(experiment) % runHiLoExp % takes an experiment with the following structure % and splits the sample space at the median of a target flux % solves the two spaces with a given sugar and compares the % resulting mdvs to provide a z-score. % % experiment - % model - S = the stoichiometric matrix % - rxns = array of reaction names, corresponding the S % - c = optimization target 1, or -1 % - ub,lb = upper and lower bounds of reactions % points = a #fluxes X #samples (~2000) array of the solution space % if missing or empty, will generate a sample % glcs = an array of sugars in isotopomer format, each column a separate sugar. % Should not be in MDV format. Conversion is done automatically. % will default to generate 1 random sugar if set to [] % targets = an array of cells with string for the reaction to % split on the solution space, defaults to 'PGL' % thresholds = # targets X 1 array of thresholds % metabolites = an optional parameter fed to calcMDVfromSamp.m % which only calculates the MDVs for the metabolites listed in this % array. e.g. % - optionally, metabolites can also be a structure of fragments % hilo = a #targets X #samples array of 0/1's, 0 id's the sample of % fluxes as the lo side and 1 id's the sample for the hi side. % hilo will only be calculated/recalculated if it's missing or % if the targets have been replaced using the param list % mdvs = structure of mdv results % - (name) = name of the run = t + glc# % e.g. t1, t2, glc# refers to the glc in the glcs array % - mdv = array of mdv results % - zscore = array of zscores from comparison btw the two mdvs % - totalz % Note that the split of mdvs are not stored, % also since the only time mdvs should be regen'd is when glcs % has changed, but we have no way of knowing when this happens, % the user will have to manually empty out mdvs to have it % regenerated. % zscores = array of zscores from each run, targets X glcs % rscores = array of ridge scores from each run, targets X glcs % % target is an optional string for a specific rxn to target. % if supplied, it will override and replace the targets field in the % experiment structure. % threshold is an optional number to apply on the solution space fluxes % if supplied, it will be applied to the hilo field and replace the % hilo splits. % % % outputs the experiment array. % % basically, this code will loop thru one experiment % per sugar, per target % % Wing Choi 3/14/08 if (nargin < 1) disp '[experiment] = runHiLoExp(experiment,target,threshold)'; return; end runzscore = true; %binary flag for z-scores runrscore = false; %binary flag for r-scores runkscore = false; %binary flag for k-scores %% if no model, exit with error. % if model exists, but no points % then points are generated % existing mdvs in experiment, if any, are wiped if (not(isfield(experiment,'model'))) disp 'ERROR: input structure experiment lacks the requisite model in the model field'; return; end model = experiment.model; points = []; if (isfield(experiment,'points')) points = experiment.points; end if (isempty(points)) disp 'WARN: experiment.points is empty or missing'; disp ' generating a sample and empty out mdvs'; pointSample = generateRandomSample(model,2000); points = pointSample.point; experiment.mfrac = pointSample.mf; %points = m.points; experiment.points = points; %experiment.mfrac = mf; % recalculate the mdvs since we have new points. experiment.mdvs = []; end %% if the rxns array is inverted % display error message indicating that rxns array is inverted dr = size(model.rxns,2); if (dr > 1), disp 'ERROR: rxns array is inverted'; return; end if (isfield(experiment,'metabolites')) metabolites = experiment.metabolites; else metabolites = []; end %% if no sugar, generate a random one and warn the user. % existing mdvs are wiped glcs = []; if (isfield(experiment,'glcs')) glcs = experiment.glcs; end if (isempty(glcs)) disp 'WARN: glcs not found, will generate 1 random sugar for experiment and empty out mdvs'; glcs = getRandGlc(); experiment.glcs = glcs; experiment.mdvs = []; end %% set glucose mixture name description; glcsnames = {}; for i = 1:size(glcs,2) glcsnames{1,i} = ''; glci = glcs(:,i); fglc = find(glci); for j = 1:length(fglc) if j ~=1 glcsnames{1,i} = strcat(glcsnames{1,i}, '+'); end if round(100*glci(fglc(j))) < 100 glcsnames{1,i} = strcat(glcsnames{1,i}, num2str(round(100*glci(fglc(j)))), '% '); end if fglc(j)-1 == 0 % not labeled glcsnames{1,i} = strcat(glcsnames{1,i}, 'C0'); elseif abs(log2(fglc(j)-1) - round(log2(fglc(j)-1)))<1e-8 % if it's a perfect power glcsnames{1,i} = strcat(glcsnames{1,i}, 'C', num2str(6-round(log2(fglc(j)-1))) ); elseif fglc(j)-1 == 32+16 % C12 glcsnames{1,i} = strcat(glcsnames{1,i}, 'C12'); elseif fglc(j)-1 == 63 % fully labeled glcsnames{1,i} = strcat(glcsnames{1,i}, 'CU'); else glcsnames{1,i} = strcat(glcsnames{1,i}, '#', dec2bin(fglc(j)-1, 6)); end end end experiment.glcsnames = glcsnames; %% if hilo is defined in experiment % then inform user and error out if (not(isfield(experiment,'hilo'))) disp 'ERROR: hilo field not found in input structure experiment'; return; else hilo = experiment.hilo; end ntarget = size(hilo,1); nglc = size(glcs,2); %% we don't care about the thresholds field from this point on if (not(isfield(experiment,'mdvs'))) experiment.mdvs = []; end mdvs = experiment.mdvs; if (isempty(mdvs)) disp('no mdvs found, recalculating mdvs and emptying out zscores'); mdvs = struct; for iglc = 1:nglc fprintf('MDVS on glucose %d of %d\n',iglc, nglc); glc = glcs(:,iglc); % translate sugar from isotopomer to cuomer format if abs(sum(glc)-1)>1e-6 || any(glc <0) display('invalid glc. needs to be idv'); disp(iglc) glc pause; end mdv = calcMDVfromSamp(glc,experiment.points,metabolites); name = sprintf('t%d',iglc); mdvs.(name) = mdv; end experiment.mdvs = mdvs; experiment.zscores = []; end %% regen the zscores if (not(isfield(experiment,'zscores'))) experiment.zscores = []; end zscores = experiment.zscores; if (isempty(zscores) && runzscore) disp('calculating zscores'); for iglc = 1:nglc fprintf('z-scores on glucose %d of %d\n',iglc, nglc); for itgt = 1:ntarget % target = char(targets(itgt)); hl = hilo(itgt,:); name = sprintf('t%d',iglc); mdv = mdvs.(name); [hiset,loset] = splitMDVbyTarget(mdv,hl); % if ((size(loset,1)) ~= (size(hiset,1))) % zscores(itgt,iglc) = -1; % disp('problem with the hi or lo set, cannot calculate zscore'); % continue; % end mdv1.names = mdv.names; mdv1.ave = mean(loset,2); mdv1.stdev = std(loset,0,2); mdv2.ave = mean(hiset,2); mdv2.stdev = std(hiset,0,2); [totalz,zscore] = compareTwoMDVs(mdv1,mdv2); zscores(itgt,iglc) = totalz; end end experiment.zscores = zscores; end %% regen the ridge score if (not(isfield(experiment,'rscores'))) experiment.rscores = []; end rscores = experiment.rscores; if (isempty(rscores) && runrscore) disp('calculating ridge scores'); for iglc = 1:nglc fprintf('r-scores on glucose %d of %d\n',iglc, nglc); for itgt = 1:ntarget hl = hilo(itgt,:)'; name = sprintf('t%d',iglc); mdv = mdvs.(name).mdv; rscore = score_ridge(mdv,hl); rscores(itgt,iglc) = rscore; end end experiment.rscores = rscores; end %% regen the KS score if (not(isfield(experiment,'kscores'))) experiment.kscores = []; end kscores = experiment.kscores; if (isempty(kscores) && runkscore) disp('calculating KS scores'); for iglc = 1:nglc fprintf('KS-scores on glucose %d of %d\n',iglc, nglc); for itgt = 1:ntarget hl = hilo(itgt,:)'; name = sprintf('t%d',iglc); mdv = mdvs.(name).mdv; kscore = score_KS(mdv,hl); kscores(itgt,iglc) = kscore; end end experiment.kscores = kscores; end return; end %% findIndexToTarget % % function [targetind] = findIndexToTarget(model,target) % % % Given a model, find the index to the target in the model.rxns % % d = size(model.c); % %find index to target flux % found = false; % for r = 1:d(1), % if ~isempty(findstr(char(model.rxns(r)),target)) % found = true; % break; % end % end % if (~found) % disp(sprintf('could not locate %s flux',target)); % targetind = -1; % return; % end % targetind = r; % disp(sprintf('found target flux for %s at: %d',target,targetind)); % % return % end %% splitMDVbyTarget % function [hiset,loset] = splitMDVbyTarget(mdv,hilo) % Given an mdv set and a hilo discriminator, split the % mdvset into 2 sets: a lo and hi set each with numinset cols. hiset = mdv.mdv(:,hilo==1); loset = mdv.mdv(:,~hilo); return; % nmdv = size(mdv.mdv,2); % % hisetcount = 0; % losetcount = 0; % hiset = []; % loset = []; % mdva = mdv.mdv; % mdvnan = mdv.mdvnan; % cnan = size(mdvnan,2); % % % if ((2*numinset) > nmdv) % % disp('WARN: insufficient number of points to cover split into hi and lo set'); % % end % % % % for i = 1:nmdv % if (cnan >= i) % % do nan check only if nan array is larger than i index % if (sum(isnan(mdvnan(:,i))) > 1) % continue; % end % end % if (hilo(1,i) == 1) % if (hisetcount <= numinset) % hisetcount = hisetcount + 1; % hiset(:,hisetcount) = mdva(:,i); % end % else % if (losetcount <= numinset) % losetcount = losetcount + 1; % loset(:,losetcount) = mdva(:,i); % end % end % if ((hisetcount >= numinset) && (losetcount >= numinset)) % break; % end % end % % % might have read thru the entire set but lots of nan for mdv's % if ((hisetcount < numinset) || (losetcount < numinset)) % disp(sprintf('WARN: hisetcount = %d, losetcount = %d',hisetcount,losetcount)); % end end
github
EPFL-LCSB/matTFA-master
compareTwoSamp.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/compareTwoSamp.m
3,031
utf_8
5a0c5086089c00108fbf0be445048674
function [totalz,zscore,mdv1,mdv2] = compareTwoSamp(xglc,model,samp1,samp2,measuredMetabolites) % Compare the 2 sets of samples % xglc is optional, a random sugar distribution is calculated if empty % expects samp1 and samp2 to have a field named points containing % an array of sampled points % expects model.rxns to contain a list of rxn names % measuredMetabolites is an optional parameter fed to calcMDVfromSamp.m % which only calculates the MDVs for the metabolites listed in this % array. e.g. % % totalz is the sum of all zscores % zscore is the calculated difference for each mdv element distributed % across all the points % mdv1,mdv2 each containing fields: % - mdv - the calculated mdv distribution converted from the idv % solved from each point contained in their respective samples sampX % - names - the names of the metabolites % - ave - the average of each mdv element across all of the points % - stdev - the standard dev for each mdv element across all points % Wing Choi 2/11/08 %glc = zeros(62,1); %glc = [.2 ;.8 ;glc]; if (nargin < 4) disp '[totalz,zscore,mdv1,mdv2] = compareTwoSamp(xglc,model,samp1,samp2,measuredMetabolites)'; return; end if (nargin < 5) measuredMetabolites = []; end if (isempty(xglc)) % random glucose xglc = rand(64,1); xglc = xglc/sum(xglc); xglc = idv2cdv(6)*xglc; end % generate the translation index array % can shave time by not regenerating this array on every call. xltmdv = zeros(1,4096); for i = 1:4096 xltmdv(i) = length(strrep(dec2base(i-1,2),'0','')); end % calculate mdv for samp1 and samp2 [mdv1] = calcMDVfromSamp(samp1.points,measuredMetabolites); [mdv2] = calcMDVfromSamp(samp2.points,measuredMetabolites); [totalz,zscore] = compareTwoMDVs(mdv1,mdv2); return end %Here's what the function does. %Apply slvrXXfast to each point %for each field in the output, apply iso2mdv to get a much shorter vector. %store all the mdv's for each point and for each metabolite in both sets. % %Compute the mean and standard deviation of each mdv and then get a z-score % between them (=(mean1-mean2)/(sqrt(sd1^2+sd2^2))). %Add up all the z-scores (their absolute value) and have this function return % that value. % %Intuitively what we're doing here is comparing the two sets based on % how different the mdv's appear. %We're going to see if different glucose mixtures result in different values. %I'm going to rewrite part of slvrXXfast so it doesn't return every metabolite % but only those we can actually measure, but for now just make it generic. function mdv = myidv2mdv (idv,xltmdv) % generate the mdv len = length(idv); %disp(sprintf('idv is %d long',len)); mdv = zeros(1,xltmdv(len)+1); %disp(sprintf('mdv is %d long',length(mdv))); for i = 1:len idx = xltmdv(i) + 1; %disp(sprintf('idx is %d, currently on %d',idx,i)); mdv(idx) = mdv(idx) + idv(i); end return end
github
EPFL-LCSB/matTFA-master
computeConfidenceInterval2.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/obsolete/computeConfidenceInterval2.m
9,292
utf_8
76f328a01a51b8ee184e498657e94f7e
function [vs, output, v0] = computeConfidenceInterval2(v0, expdata, model, max_score) majorIterationLimit = 2000; %max number of iterations minorIterationLimit = 1e7; % essentially infinity diffInterval = 1e-5; %gradient step size. feasibilityTolerance = max_score/20; % how close you need to be to the max score. v0 = fitC13Data(v0,expdata,model); if ~isfield(model, 'N') model.N = null(model.S); end x0 = model.N\v0; % back substitute % safety check: if (max(abs(model.S*v0))> 1e-6) display('v0 not quite in null space'); pause; end if(max(abs(model.N*x0 - v0)) > 1e-6) display('null basis is weird'); pause; end nalpha = size(model.N, 2); x_L = -1000*ones(nalpha,1); x_U = 1000*ones(nalpha,1); Name = 't2'; [A, b_L, b_U] = defineLinearConstraints(model); numpoints = size(x0,2); scores = zeros(numpoints,1); % compute scores for all points. tProb.user.expdata = expdata; tProb.user.model = model; for i = 1:numpoints scores(i) = errorComputation2(x0(:,i),tProb); end valid_index = scores < max_score + feasibilityTolerance; fprintf('found %d valid points\n', sum(valid_index)); x0_valid = x0(:,valid_index); x0_invalid = x0; scores_valid = scores(valid_index); c = []; c_L = []; c_U = []; HessPattern = []; f = 'errorComputation2'; g = 'errorComputation2_grad'; H = []; %c = 'errorComputation2'; %c_L = 0; %c_U = max_score; dc = []; d2c = []; ConsPattern = []; pSepFunc = []; x_min = []; x_max = []; f_opt = []; x_opt = []; Solver = 'snopt'; % pre-compute unnecesary directions. % if checkedbefore(i) ~= 0 then direction i is redundant % checkedbefore(i) < 0 means that the sign of all computations should be % switched. checkedbefore = zeros(length(model.lb),1); for i = 2:length(model.lb) d = objective_coefficient(i, model); for j = 1:i-1 dj = objective_coefficient(j, model); if max(abs(dj - d))< 1e-4 checkedbefore(i) = j; break; elseif max(abs(dj + d))< 1e-4 checkedbefore(i) = -j; break; end end end % initialize variables; numpoints = size(x0, 2); outputminv = 222*ones(length(model.lb), numpoints); outputminexitflag = -222*ones(length(model.lb), numpoints); outputminfinalscore = -222*ones(length(model.lb), numpoints); outputmaxv = -222*ones(length(model.lb), numpoints); outputmaxexitflag = -222*ones(length(model.lb), numpoints); outputmaxfinalscore = -222*ones(length(model.lb), numpoints); outputminstruct = cell(length(model.lb), numpoints); outputmaxstruct = cell(length(model.lb), numpoints); %iterate through directions parfor i = 1:length(model.lb) if checkedbefore(i) ~= 0 continue; end for j = -1:2:1 % max and min d = objective_coefficient(i,model)*j; lbprob = lpAssign(d, A, b_L, b_U, x_L, x_U, [], 'linear_bound', [],[],[],[],[],[],[]); lbresult = tomRun('cplex', lbprob, 0); fLowBnd = lbresult.f_k; fprintf('reaction %d of %d, direction %d, lowerbound %f\n', i,length(model.lb), j, fLowBnd); % short circuit if x0 already close to a bound. obj1 = d'*x0_valid; if(any(abs(obj1-fLowBnd)<.0001)) display('short circuiting'); [nil, index1] = min(obj1); if (j > 0) outputminv(i,:) = j*fLowBnd; % multiply by j to correct sign. outputminexitflag(i,:) = 111; outputminfinalscore(i,:) = scores_valid(index1); else outputmaxv(i,:) = j*fLowBnd; % multiply by j to correct sign. outputmaxexitflag(i,:) = 111; outputmaxfinalscore(i,:) = scores_valid(index1); end else % gotta actually do the computation. all_ds = d'*x0_invalid; [nil, index2] = sort(all_ds); % initialize temp variables to make parfor work. v = j*222*ones(1,numpoints); exitflag = -222*ones(1,numpoints); finalscore = 222*ones(1,numpoints); ostruct = cell(1,numpoints); for k = 1:length(index2) if exist('ttt.txt', 'file') fprintf('quitting due to file found\n'); continue; end xinitial = x0_invalid(:,index2(k)); % Prob = lpconAssign(d, x_L, x_U, Name, xinitial,... % A, b_L, b_U,... % c, dc, d2c, ConsPattern, c_L, c_U,... % fLowBnd, x_min, x_max, f_opt, x_opt); Prob = conAssign(f, g, H, HessPattern, x_L, x_U, Name, xinitial, ... pSepFunc, fLowBnd, ... A, b_L, b_U, c, dc, d2c, ConsPattern, c_L, c_U, ... x_min, x_max, f_opt, x_opt); %Prob.NumDiff = 2; % central diff %Prob.optParam.CentralDiff = 1e-5; %pause; Prob.user.expdata = expdata; Prob.user.model = model; Prob.user.objective = d; Prob.user.max_error = max_score; Prob.user.diff_interval = diffInterval; Prob.user.multiplier = 10; Prob.optParam.IterPrint = 0; %Prob.optParam.cTol = .1*feasibilityTolerance; Prob.PriLevOpt = 0; Prob.SOL.PrintFile = strcat('temp/snoptp', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt'); Prob.SOL.SummFile = strcat('temp/snopts', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt'); Prob.SOL.optPar(35) = majorIterationLimit; %This is major iteration count. Prob.SOL.optPar(30) = minorIterationLimit; %total iteration limit; %Prob.SOL.optPar(11) = feasibilityTolerance; % feasibility tolerance Result = tomRun(Solver, Prob, 5); tscore = errorComputation2(Result.x_k, tProb); tbest = Result.f_k; fprintf('reaction %d (%d), x %d; x=%f (%f); score=%f (%f)\n', i,length(model.lb),j, tbest,fLowBnd, tscore, max_score) v(k) = j*tbest; exitflag(k) = Result.Inform; finalscore(k) = tscore; ostruct{k} = Result; end if (j > 0) %minimizing outputminv(i,:) = v; % multiply by j to correct sign. outputminexitflag(i,:) = exitflag; outputminfinalscore(i,:) = finalscore; outputminstruct(i,:) = ostruct; else outputmaxv(i,:) = v; % multiply by j to correct sign. outputmaxexitflag(i,:) = exitflag; outputmaxfinalscore(i,:) = finalscore; outputmaxstruct(i,:) = ostruct; end end end end output.minv = outputminv; output.maxv = outputmaxv; output.minexitflag = outputminexitflag; output.maxexitflag = outputmaxexitflag; output.minfinalscore = outputminfinalscore; output.maxfinalscore = outputmaxfinalscore; output.minstruct = outputminstruct; output.maxstruct = outputmaxstruct; for i = 1:length(model.lb) if checkedbefore(i) > 0 %short circuit if seen before. output.minv(i,:) = output.minv(checkedbefore(i),:); output.maxv(i,:) = output.maxv(checkedbefore(i),:); output.minexitflag(i,:) = output.minexitflag(checkedbefore(i),:); output.maxexitflag(i,:) = output.maxexitflag(checkedbefore(i),:); output.minfinalscore(i,:) = output.minfinalscore(checkedbefore(i),:); output.maxfinalscore(i,:) = output.maxfinalscore(checkedbefore(i),:); output.minstruct(i,:) = output.minstruct(checkedbefore(i),:); output.maxstruct(i,:) = output.maxstruct(checkedbefore(i),:); elseif checkedbefore(i) < 0 output.minv(i,:) = -output.maxv(-checkedbefore(i),:); output.maxv(i,:) = -output.minv(-checkedbefore(i),:); output.minexitflag(i,:) = output.maxexitflag(-checkedbefore(i),:); output.maxexitflag(i,:) = output.minexitflag(-checkedbefore(i),:); output.minfinalscore(i,:) = output.maxfinalscore(-checkedbefore(i),:); output.maxfinalscore(i,:) = output.minfinalscore(-checkedbefore(i),:); output.minstruct(i,:) = output.maxstruct(-checkedbefore(i),:); output.maxstruct(i,:) = output.minstruct(-checkedbefore(i),:); end end vs = zeros(length(model.lb), 2); for i = 1:length(model.lb) validindex = output.minfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,1) = min(output.minv(i,validindex)); else vs(i,1) = 222; end validindex = output.maxfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,2) = max(output.maxv(i,validindex)); else vs(i,2) = -222; end end return; % function that returns the proper objective coefficient for each reaction % takes into account the reversibility of reactinos etc. function [d] = objective_coefficient(i, model) d = zeros(length(model.lb),1); d(i) = 1; if (model.match(i)) d(model.match(i)) = -1; end d = (d'*model.N)'; % transform to null space; return
github
EPFL-LCSB/matTFA-master
computeRatioConfidenceInterval.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/obsolete/computeRatioConfidenceInterval.m
6,966
utf_8
910c32ca417673f241f14c0350b9c7a3
function [vs, output, v0] = computeRatioConfidenceInterval(v0, expdata, model, max_score, ratio) % v0 - set of flux vectors to be used as initial guesses. They may be % valid or not. % expdata - experimental data. % model - The standard model. Additional field .N (= null(S)) should also % be provided. This is a basis of the flux space. % max score - maximum allowable data fit error. % ratio - which reactions to take the ratio of. positive values indicate % reactions in the numerator and negative values, reactions in the % denominator. majorIterationLimit = 2000; %max number of iterations minorIterationLimit = 1e7; % essentially infinity diffInterval = 1e-5; %gradient step size. feasibilityTolerance = max_score/20; % how close you need to be to the max score. x0 = model.N\v0; % back substitute numpoints = size(v0,2); numratios = size(ratio,2); scores = zeros(numpoints,1); tProb.user.expdata = expdata; tProb.user.model = model; for i = 1:numpoints scores(i) = errorComputation2(x0(:,i),tProb); end v0(:,scores > max_score) = fitC13Data(v0(:,scores > max_score),expdata,model); if ~isfield(model, 'N') model.N = null(model.S); end x0 = model.N\v0; % back substitute % safety check: if (max(abs(model.S*v0))> 1e-6) display('v0 not quite in null space'); pause; end if(max(abs(model.N*x0 - v0)) > 1e-6) display('null basis is weird'); pause; end nalpha = size(model.N, 2); x_L = -1000*ones(nalpha,1); x_U = 1000*ones(nalpha,1); Name = 't2'; [A, b_L, b_U] = defineLinearConstraints(model); scores = zeros(numpoints,1); % compute scores for all points. for i = 1:numpoints scores(i) = errorComputation2(x0(:,i),tProb); end valid_index = scores < max_score + feasibilityTolerance; fprintf('found %d valid points\n', sum(valid_index)); c = 'errorComputation2'; c_L = 0; c_U = max_score; dc = 'errorComputation2_grad'; d2c = []; ConsPattern = []; %pSepFunc = []; x_min = []; x_max = []; f_opt = []; x_opt = []; H = []; HessPattern = []; pSepFunc = []; fLowBnd = []; Solver = 'snopt'; outputminv = 222*ones(numratios, numpoints); outputminexitflag = -222*ones(numratios, numpoints); outputminfinalscore = -222*ones(numratios, numpoints); outputmaxv = -222*ones(numratios, numpoints); outputmaxexitflag = -222*ones(numratios, numpoints); outputmaxfinalscore = -222*ones(numratios, numpoints); outputminstruct = cell(numratios, numpoints); outputmaxstruct = cell(numratios, numpoints); %iterate through directions for i = 1:numratios %for i = 10:200 for j = -1:2:1 % max and min ration = zeros(size(objective_coefficient(1,model))); ratiod = zeros(size(objective_coefficient(1,model))); for m = 1:size(ratio,1); if(ratio(m,i) > 0) ration = ration + objective_coefficient(m,model)*j; elseif(ratio(m,i) < 0) ratiod = ratiod + objective_coefficient(m,model); end end % initialize temp variables to make parfor work. v = j*222*ones(1,numpoints); exitflag = -222*ones(1,numpoints); finalscore = 222*ones(1,numpoints); ostruct = cell(1,numpoints); for k = 1:numpoints if exist('ttt.txt', 'file') fprintf('quitting due to file found\n'); continue; end xinitial = x0(:,k); % Prob = lpconAssign(d, x_L, x_U, Name, xinitial,... % A, b_L, b_U,... % c, dc, d2c, ConsPattern, c_L, c_U,... % fLowBnd, x_min, x_max, f_opt, % x_opt); Prob = conAssign('ratioScore', 'ratioScore_grad', H, HessPattern, x_L, x_U, Name, xinitial, ... pSepFunc, fLowBnd, ... A, b_L, b_U, c, dc, d2c, ConsPattern, c_L, c_U, ... x_min, x_max, f_opt, x_opt); %Prob.NumDiff = 2; % central diff %Prob.optParam.CentralDiff = 1e-5; %pause; Prob.user.expdata = expdata; Prob.user.model = model; Prob.user.ration = ration; Prob.user.ratiod = ratiod; Prob.user.max_error = max_score; Prob.user.diff_interval = diffInterval; Prob.user.useparfor = true; Prob.optParam.IterPrint = 0; %Prob.optParam.cTol = .1*feasibilityTolerance; Prob.PriLevOpt = 1; Prob.SOL.PrintFile = strcat('temp/snoptp', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt'); Prob.SOL.SummFile = strcat('temp/snopts', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt'); Prob.SOL.optPar(35) = majorIterationLimit; %This is major iteration count. Prob.SOL.optPar(30) = minorIterationLimit; %total iteration limit; %Prob.SOL.optPar(11) = feasibilityTolerance; % feasibility tolerance Result = tomRun(Solver, Prob, 5); tscore = errorComputation2(Result.x_k, tProb); tbest = Result.f_k; fprintf('reaction %d (%d), x %d; x=%f (%f); score=%f (%f)\n', i,length(model.lb),j, tbest,fLowBnd, tscore, max_score) v(k) = j*tbest; exitflag(k) = Result.Inform; finalscore(k) = tscore; ostruct{k} = Result; end if (j > 0) %minimizing outputminv(i,:) = v; % multiply by j to correct sign. outputminexitflag(i,:) = exitflag; outputminfinalscore(i,:) = finalscore; outputminstruct(i,:) = ostruct; else outputmaxv(i,:) = v; % multiply by j to correct sign. outputmaxexitflag(i,:) = exitflag; outputmaxfinalscore(i,:) = finalscore; outputmaxstruct(i,:) = ostruct; end end end output.minv = outputminv; output.maxv = outputmaxv; output.minexitflag = outputminexitflag; output.maxexitflag = outputmaxexitflag; output.minfinalscore = outputminfinalscore; output.maxfinalscore = outputmaxfinalscore; output.minstruct = outputminstruct; output.maxstruct = outputmaxstruct; vs = zeros(numratios, 2); for i = 1:numratios validindex = output.minfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,1) = min(output.minv(i,validindex)); else vs(i,1) = 222; end validindex = output.maxfinalscore(i,:) < max_score + feasibilityTolerance; if any(validindex) vs(i,2) = max(output.maxv(i,validindex)); else vs(i,2) = -222; end end return; % function that returns the proper objective coefficient for each reaction % takes into account the reversibility of reactinos etc. function [d] = objective_coefficient(i, model) d = zeros(length(model.lb),1); d(i) = 1; if (model.match(i)) d(model.match(i)) = -1; end d = (d'*model.N)'; % transform to null space; return
github
EPFL-LCSB/matTFA-master
Combination.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/c13solver/Combination.m
1,354
utf_8
e737cd2414f521a8b1701de9c05cff10
function [out] = Combination(n,k) % produces the array of combinations possible picking k from n % adapted from Combinadics % http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx if (n < 0 || k < 0) % normally n >= k disp('Negative parameter in constructor'); return end data(k) = 0; for i = 1:k; data(i) = i; end % Combination(n,k) out.choose = getNumberCombinations(n,k); % determine the combinations for i = 1:out.choose out.all(:,i) = getCombination(n,k,i-1); end return; function [m] = getNumberCombinations(n,k) % find number of combinations by choose k items from n if (n < k) m = 0; % special case else if (n == k) m = 1; else m = factorial(n) / (factorial(k) * factorial(n-k)); end end return; function [c] = getCombination(n,k,index) c(1) = 1; x = 1; for i = 1:n if (k == 0) return; end threshold = getNumberCombinations(n-i,k-1); %disp(sprintf('index = %d, threshold = %d',index,threshold)); if (index < threshold) c(x) = i; x = x+1; k = k-1; else if (index >= threshold) index = index - threshold; end end end return;
github
EPFL-LCSB/matTFA-master
idv2mdv.m
.m
matTFA-master/ext/Cobra205_vDec2014/fluxomics/c13solver/idv2mdv.m
1,629
utf_8
4602db4ffd72989e332f08b0d92cf05f
function [out] = idv2mdv(n, fragment) % returns transofmation matrix from idv's (either Jennie's or Jan's order). % MDV = idv2mdv(log2(length(idv)))*idv; % % fragment (optional): a vector of carbons to be included. [ 0, 0, 1,1,1]' = last 3 carbons. global pseudohash1 pseudohash2 if isempty(pseudohash1) pseudohash1 = sparse(15, 2048); pseudohash2 = {}; end if nargin == 1 out = sparse(1); for i = 1:n out = [[out;sparse(1, size(out,2))] [sparse(1, size(out,2));out]]; end return; end if length(fragment) ~= n display('error in fragment length'); return; end ncarbons = sum(fragment)+1; out = sparse(ncarbons, 2^n); fragment = fragment(n:-1:1); % reverse order fragment... faster than reversing order of idv's. m = memoize(n, fragment); if ~isempty(m) out = m; return; end for i = 0:(2^n-1) t = dec2bin(i,n); t(logical(fragment)); i2 = sum(t(logical(fragment)) == '1'); out(i2+1,i+1) = 1; end memoize(n, fragment, out); return function [matrix] = memoize(n, fragment, matrix) global pseudohash1 pseudohash2 fragmentindex = 0; for i = 1:length(fragment) fragmentindex = fragmentindex*2; fragmentindex = fragment(i) + fragmentindex; end tindex = pseudohash1(n, fragmentindex); if tindex == 0 if nargin < 3 matrix = []; return; else % assign tindex = length(pseudohash2)+1; pseudohash1(n, fragmentindex) = tindex; pseudohash2{tindex} = matrix; end else matrix = pseudohash2{tindex}; return; end return
github
EPFL-LCSB/matTFA-master
createTissueSpecificModel.m
.m
matTFA-master/ext/Cobra205_vDec2014/reconstruction/createTissueSpecificModel.m
22,833
utf_8
b1e36173def8a0675727e3d42c0bb7e9
function [tissueModel,Rxns] = createTissueSpecificModel(model, ... expressionData,proceedExp,orphan,exRxnRemove,solver,options,funcModel) %createTissueSpecificModel Create draft tissue specific model from mRNA expression data % % [tissueModel,Rxns] = % createTissueSpecificModel(model,expressionData,proceedExp,orphan,exRxnRemove,solver,options,funcModel) % %INPUTS % model global recon1 model % expressionData mRNA expression Data structure % Locus Vector containing GeneIDs % Data Presence/Absence Calls % Use: (1 - Present, 0 - Absent) when proceedExp = 1 % Use: (2 - Present, 1 - Marginal, 0 - Absent) % when proceedExp = 0 % Transcript RefSeq Accession (only required if proceedExp = 0) % %OPTINAL INPUTS % proceedExp 1 - data are processed ; 0 - data need to be % processed (Default = 1) % orphan 1 - leave orphan reactions in model for Shlomi Method % 0 - remove orphan reactions % (Default = 1) % exRxnRemove Names of exchange reactions to remove % (Default = []) % solver Use either 'GIMME', 'iMAT', or 'Shlomi' to create tissue % specific model. 'Shlomi' is the same as 'iMAT' the names % are just maintained for historical purposes. % (Default = 'GIMME') % options If using GIMME, enter objectiveCol here % Default: objective function with 90% flux cutoff, % written as: [find(model.c) 0.9] % funcModel 1 - Build a functional model having only reactions % that can carry a flux (using FVA), 0 - skip this % step (Default = 0) % % %OUTPUTS % tissueModel Model produced by GIMME or iMAT, containing only % reactions carrying flux % Rxns Statistics of test % ExpressedRxns - predicted by mRNA data % UnExpressedRxns - predicted by mRNA data % unknown - unable to be predicted by mRNA % data % Upregulated - added back into model % Downregulated - removed from model % UnknownIncluded - orphans added % % NOTE: If there are multiple transcripts to one probe that have different % expression patterns the script will ask what the locus is of the % expressed and unexpressed transcripts % % Note: GIMME script matches objective functions flux, Shlomi algorithm is % based on maintaining pathway length comparable to expression data, not flux % % Aarash Bordbar 05/15/2009 % Added proceedExp, IT 10/30/09 % Adjusted manual input for alt. splice form, IT 05/27/10 % Final Corba 2.0 Version, AB 08/05/10 % Define defaults % Deal with hardcoded belief that all the genes will have human entrez % ids and the user wants to collapse alternative constructs if iscell(expressionData.Locus(1)) match_strings = true; else match_strings = false; end if ~exist('proceedExp','var') || isempty(proceedExp) proceedExp = 1; end if ~exist('solver','var') || isempty(solver) solver = 'GIMME'; end if ~exist('exRxnRemove','var') || isempty(exRxnRemove) exRxnRemove = []; end if ~exist('orphan','var') || isempty(orphan) orphan = 1; end if ~exist('funcModel','var') || isempty(funcModel) funcModel = 0; end % Extracting GPR data from model [parsedGPR,corrRxn] = extractGPRs(model); if proceedExp == 0 % Making presence/absence calls on mRNA expression data [Results,Transcripts] = charExpData(expressionData); x = ismember(Transcripts.Locus,[Transcripts.Expressed;Transcripts.UnExpressed]); unkLocus = find(x==0); AltSplice.Locus = Transcripts.Locus(unkLocus); AltSplice.Transcripts = Transcripts.Data(unkLocus); AltSplice.Expression = Transcripts.Expression(unkLocus); fprintf('There are some probes that match up with different transcripts and expression patterns\n'); fprintf('Please elucidate these discrepancies below\n'); fprintf('To do so, look up the transcript in RefSeq and enter the proper locii below\n'); cnt1 = 1; cnt2 = 1; locusNE =[]; locusE = []; for i = 1:length(AltSplice.Locus) if length(AltSplice.Transcripts{i}) < 1 elseif AltSplice.Expression(i) == 0 fprintf('Probe: %i, Transcript: %s, Expression: %i\n',AltSplice.Locus(i),AltSplice.Transcripts{i},AltSplice.Expression(i)); % locusNE(cnt1,1) = input('What is the proper locii? '); locusNE(cnt1,1) = AltSplice.Locus(i);%input('What is the proper locii? '); cnt1=cnt1+1; elseif AltSplice.Expression(i) == 1 fprintf('Probe: %i, Transcript: %s, Expression: %i\n',AltSplice.Locus(i),AltSplice.Transcripts{i},AltSplice.Expression(i)); % locusE(cnt2,1) = input('What is the proper locii? '); locusE(cnt2,1) = AltSplice.Locus(i);% Hack by Maike %input('What is the proper locii? '); cnt2=cnt2+1; end end locusP = [Results.Expressed;Transcripts.Expressed;locusE]; locusNP = [Results.UnExpressed;Transcripts.UnExpressed;locusNE]; genePresenceP = ones(length(locusP),1); genePresenceNP = zeros(length(locusNP),1); locus = [locusP;locusNP]; genePresence = [genePresenceP;genePresenceNP]; else locus = expressionData.Locus; genePresence = zeros(length(locus),1); genePresence(find(expressionData.Data(:,1))) = 1; end % Mapping probes to reactions in model [ExpressedRxns,UnExpressedRxns,unknown] = mapProbes(parsedGPR,corrRxn,locus,genePresence,match_strings); % Removing exchange reactions that are not in this specific tissue % metabolome if ~isempty(exRxnRemove) model = removeRxns(model,exRxnRemove); end nRxns = length(model.lb); % Determine reaction indices of expressed and unexpressed reactions RHindex = findRxnIDs(model,ExpressedRxns); RLindex = findRxnIDs(model,UnExpressedRxns); if (strcmp(solver, 'iMAT')) solver = 'Shlomi'; end switch solver case 'Shlomi' S = model.S; lb = model.lb; ub = model.ub; eps = 1; % Creating A matrix A = sparse(size(S,1)+2*length(RHindex)+2*length(RLindex),size(S,2)+2*length(RHindex)+length(RLindex)); [nConstr,nVar] = size(S); [m,n,s] = find(S); for i = 1:length(m) A(m(i),n(i)) = s(i); end for i = 1:length(RHindex) A(i+size(S,1),RHindex(i)) = 1; A(i+size(S,1),i+size(S,2)) = lb(RHindex(i)) - eps; A(i+size(S,1)+length(RHindex),RHindex(i)) = 1; A(i+size(S,1)+length(RHindex),i+size(S,2)+length(RHindex)+length(RLindex)) = ub(RHindex(i)) + eps; end for i = 1:length(RLindex) A(i+size(S,1)+2*length(RHindex),RLindex(i)) = 1; A(i+size(S,1)+2*length(RHindex),i+size(S,2)+length(RHindex)) = lb(RLindex(i)); A(i+size(S,1)+2*length(RHindex)+length(RLindex),RLindex(i)) = 1; A(i+size(S,1)+2*length(RHindex)+length(RLindex),i+size(S,2)+length(RHindex)) = ub(RLindex(i)); end % Creating csense csense1(1:size(S,1)) = 'E'; csense2(1:length(RHindex)) = 'G'; csense3(1:length(RHindex)) = 'L'; csense4(1:length(RLindex)) = 'G'; csense5(1:length(RLindex)) = 'L'; csense = [csense1 csense2 csense3 csense4 csense5]; % Creating lb and ub lb_y = zeros(2*length(RHindex)+length(RLindex),1); ub_y = ones(2*length(RHindex)+length(RLindex),1); lb = [lb;lb_y]; ub = [ub;ub_y]; % Creating c c_v = zeros(size(S,2),1); c_y = ones(2*length(RHindex)+length(RLindex),1); c = [c_v;c_y]; % Creating b b_s = zeros(size(S,1),1); lb_rh = lb(RHindex); ub_rh = ub(RHindex); lb_rl = lb(RLindex); ub_rl = ub(RLindex); b = [b_s;lb_rh;ub_rh;lb_rl;ub_rl]; % Creating vartype vartype1(1:size(S,2),1) = 'C'; vartype2(1:2*length(RHindex)+length(RLindex),1) = 'B'; vartype = [vartype1;vartype2]; n_int = length(vartype2); MILPproblem.A = A; MILPproblem.b = b; MILPproblem.c = c; MILPproblem.lb = lb; MILPproblem.ub = ub; MILPproblem.csense = csense; MILPproblem.vartype = vartype; MILPproblem.osense = -1; MILPproblem.x0 = []; verboseFlag = true; solution = solveCobraMILP(MILPproblem); Rxns.solution = solution; x = solution.cont; for i = 1:length(x) if abs(x(i)) < 1e-6 x(i,1) = 0; end end removed = find(x==0); % option to leave orphan reactions if orphan == 1 orphans = findorphanRxns(model); removed(find(ismember(model.rxns(removed),orphans)))=[]; end rxnRemList = model.rxns(removed); tissueModel = removeRxns(model,rxnRemList); Rxns.Expressed = ExpressedRxns; Rxns.UnExpressed = UnExpressedRxns; Rxns.unknown = unknown; x = ismember(UnExpressedRxns,tissueModel.rxns); loc = find(x); Rxns.UpRegulated = UnExpressedRxns(loc); x = ismember(ExpressedRxns,tissueModel.rxns); loc = find(x==0); Rxns.DownRegulated = ExpressedRxns(loc); x = ismember(model.rxns,[ExpressedRxns;UnExpressedRxns]); loc = find(x==0); x = ismember(tissueModel.rxns,model.rxns(loc)); loc = find(x); Rxns.UnknownIncluded = tissueModel.rxns(loc); case 'GIMME' x = ismember(model.rxns,[ExpressedRxns;UnExpressedRxns]); unk = find(x==0); expressionCol = zeros(length(model.rxns),1); for i = 1:length(unk) expressionCol(unk(i)) = -1; end for i = 1:length(RHindex) expressionCol(RHindex(i)) = 2; end if ~exist('options','var') || isempty(options) loc = find(model.c); sol = optimizeCbModel(model); options = [loc 0.9]; end cutoff = 1; [reactionActivity,reactionActivityIrrev,model2gimme,gimmeSolution] = solveGimme(model,options,expressionCol,cutoff); remove = model.rxns(find(reactionActivity == 0)); tissueModel = removeRxns(model,remove); if funcModel ==1 c = tissueModel.c; remove = []; tissueModel.c = zeros(length(tissueModel.c),1); for i = 1:length(tissueModel.rxns) tissueModel.c(i) = 1; sol1 = optimizeCbModel(tissueModel,'max'); sol2 = optimizeCbModel(tissueModel,'min'); if sol1.f == 0 & sol2.f == 0 remove = [remove tissueModel.rxns(i)]; end tissueModel.c(i) = 0; end tissueModel.c = c; tissueModel = removeRxns(tissueModel,remove); end Rxns.Expressed = ExpressedRxns; Rxns.UnExpressed = UnExpressedRxns; Rxns.unknown = unknown; x = ismember(UnExpressedRxns,tissueModel.rxns); loc = find(x); Rxns.UpRegulated = UnExpressedRxns(loc); x = ismember(ExpressedRxns,tissueModel.rxns); loc = find(x==0); Rxns.DownRegulated = ExpressedRxns(loc); x = ismember(model.rxns,[ExpressedRxns;UnExpressedRxns]); loc = find(x==0); x = ismember(tissueModel.rxns,model.rxns(loc)); loc = find(x); Rxns.UnknownIncluded = tissueModel.rxns(loc); end %% Internal Functions function [reactionActivity,reactionActivityIrrev,model2gimme,gimmeSolution] = solveGimme(model,objectiveCol,expressionCol,cutoff) nRxns = size(model.S,2); %first make model irreversible [modelIrrev,matchRev,rev2irrev,irrev2rev] = convertToIrreversible(model); nExpressionCol = size(expressionCol,1); if (nExpressionCol < nRxns) display('Warning: Fewer expression data inputs than reactions'); expressionCol(nExpressionCol+1:nRxns,:) = zeros(nRxns-nExpressionCol, size(expressionCol,2)); end nIrrevRxns = size(irrev2rev,1); expressionColIrrev = zeros(nIrrevRxns,1); for i=1:nIrrevRxns % objectiveColIrrev(i,:) = objectiveCol(irrev2rev(i,1),:); expressionColIrrev(i,1) = expressionCol(irrev2rev(i,1),1); end nObjectives = size(objectiveCol,1); for i=1:nObjectives objectiveColIrrev(i,:) = [rev2irrev{objectiveCol(i,1),1}(1,1) objectiveCol(i,2)]; end %Solve initially to get max for each objective for i=1:size(objectiveCol) %define parameters for initial solution modelIrrev.c=zeros(nIrrevRxns,1); modelIrrev.c(objectiveColIrrev(i,1),1)=1; %find max objective FBAsolution = optimizeCbModel(modelIrrev); if (FBAsolution.stat ~= 1) not_solved=1; display('Failed to solve initial FBA problem'); return end maxObjective(i)=FBAsolution.f; end model2gimme = modelIrrev; model2gimme.c = zeros(nIrrevRxns,1); for i=1:nIrrevRxns if (expressionColIrrev(i,1) > -1) %if not absent reaction if (expressionColIrrev(i,1) < cutoff) model2gimme.c(i,1) = cutoff-expressionColIrrev(i,1); end end end for i=1:size(objectiveColIrrev,1) model2gimme.lb(objectiveColIrrev(i,1),1) = objectiveColIrrev(i,2) * maxObjective(i); end gimmeSolution = optimizeCbModel(model2gimme,'min'); if (gimmeSolution.stat ~= 1) %% gimme_not_solved=1; % display('Failed to solve GIMME problem'); % return gimmeSolution.x = zeros(nIrrevRxns,1); end reactionActivityIrrev = zeros(nIrrevRxns,1); for i=1:nIrrevRxns if ((expressionColIrrev(i,1) > cutoff) | (expressionColIrrev(i,1) == -1)) reactionActivityIrrev(i,1)=1; elseif (gimmeSolution.x(i,1) > 0) reactionActivityIrrev(i,1)=2; end end %Translate reactionActivity to reversible model reactionActivity = zeros(nRxns,1); for i=1:nRxns for j=1:size(rev2irrev{i,1},2) if (reactionActivityIrrev(rev2irrev{i,1}(1,j)) > reactionActivity(i,1)) reactionActivity(i,1) = reactionActivityIrrev(rev2irrev{i,1}(1,j)); end end end function [rxnExpressed,unExpressed,unknown] = mapProbes(parsedGPR,corrRxn,locus,genePresence,match_strings) if ~exist('match_strings', 'var') || isempty(match_strings) match_strings = false; end rxnExpressed = []; unExpressed = []; unknown = []; for i = 1:size(parsedGPR,1) cnt = 0; for j = 1:size(parsedGPR,2) if length(parsedGPR{i,j}) == 0 break end cnt = cnt+1; end test = 0; for j = 1:cnt if match_strings loc = parsedGPR{i,j}; x = strmatch(loc, locus, 'exact'); else loc = str2num(parsedGPR{i,j}); loc = floor(loc); x = find(locus == loc); end if length(x) > 0 & genePresence(x) == 0 unExpressed = [unExpressed;corrRxn(i)]; test = 1; break elseif length(x) == 0 test = 2; end end if test == 0 rxnExpressed = [rxnExpressed;corrRxn(i)]; elseif test == 2 unknown = [unknown;corrRxn(i)]; end end rxnExpressed = unique(rxnExpressed); unExpressed = unique(unExpressed); unknown = unique(unknown); unknown = setdiff(unknown,rxnExpressed); unknown = setdiff(unknown,unExpressed); unExpressed = setdiff(unExpressed,rxnExpressed); function [parsedGPR,corrRxn] = extractGPRs(model) warning off all parsedGPR = []; corrRxn = []; cnt = 1; for i = 1:length(model.rxns) if length(model.grRules{i}) > 1 % Parsing each reactions gpr [parsing{1,1},parsing{2,1}] = strtok(model.grRules{i},'or'); for j = 2:1000 [parsing{j,1},parsing{j+1,1}] = strtok(parsing{j,1},'or'); if isempty(parsing{j+1,1})==1 break end end for j = 1:length(parsing) for k = 1:1000 [parsing{j,k},parsing{j,k+1}] = strtok(parsing{j,k},'and'); if isempty(parsing{j,k+1})==1 break end end end for j = 1:size(parsing,1) for k = 1:size(parsing,2) parsing{j,k} = strrep(parsing{j,k},'(',''); parsing{j,k} = strrep(parsing{j,k},')',''); parsing{j,k} = strrep(parsing{j,k},' ',''); end end for j = 1:size(parsing,1)-1 newparsing(j,:) = parsing(j,1:length(parsing(j,:))-1); end parsing = newparsing; for j = 1:size(parsing,1) for k = 1:size(parsing,2) if length(parsing{j,k}) == 0 parsing{j,k} = ''; end end end num = size(parsing,1); for j = 1:num sizeP = length(parsing(j,:)); if sizeP > size(parsedGPR,2) for k = 1:size(parsedGPR,1) parsedGPR{k,sizeP} = {''}; end end for l = 1:sizeP parsedGPR{cnt,l} = parsing(j,l); end cnt = cnt+1; end for j = 1:num corrRxn = [corrRxn;model.rxns(i)]; end clear parsing newparsing end end for i = 1:size(parsedGPR,1) for j = 1:size(parsedGPR,2) if isempty(parsedGPR{i,j}) == 1 parsedGPR{i,j} = {''}; end end end i =1 ; sizeP = size(parsedGPR,1); while i < sizeP if strcmp(parsedGPR{i,1},{''}) == 1 parsedGPR = [parsedGPR(1:i-1,:);parsedGPR(i+1:end,:)]; corrRxn = [corrRxn(1:i-1,:);corrRxn(i+1:end,:)]; sizeP = sizeP-1; i=i-1; end i = i+1; end for i = 1:size(parsedGPR,1) for j= 1:size(parsedGPR,2) parsedGPR2(i,j) = cellstr(parsedGPR{i,j}); end end parsedGPR = parsedGPR2; function [Results,Transcripts] = charExpData(ExpressionData) n = length(ExpressionData.Locus); Locus = ExpressionData.Locus; ExpThreshold = floor(0.75*size(ExpressionData.Data,2))/size(ExpressionData.Data,2); UnExpThreshold = ceil(0.25*size(ExpressionData.Data,2))/size(ExpressionData.Data,2); Results.Expressed = []; Results.UnExpressed = []; Results.AltSplice = []; Results.Total = 0; for i = 1:n if ExpressionData.Locus(i) > 0 locus = ExpressionData.Locus(i); loc = find(ExpressionData.Locus == locus); cap = length(loc)*size(ExpressionData.Data,2)*2; for j = 1:length(loc) total(j) = sum(ExpressionData.Data(loc(j),:)); ExpressionData.Locus(loc(j)) = 0; end transcripts = {}; for j = 1:length(loc) if length(ExpressionData.Transcript{loc(j)}) > 0 transcripts = [transcripts;ExpressionData.Transcript{loc(j)}]; end end if length(unique(transcripts)) <= 1 % Overall expression patterns (> 75% in binary data, Expressed) if sum(total)/cap >= ExpThreshold Results.Expressed = [Results.Expressed;locus]; % If < 25% in binary data, UnExpressed elseif sum(total)/cap <= UnExpThreshold Results.UnExpressed = [Results.UnExpressed;locus]; % Accounting for different probes and their binding positions else cntP = 0; for j = 1:length(total) % Threshold once again, 75% if total(j) >= floor(0.75*size(ExpressionData.Data,2))*2; cntP = cntP+1; end end % If 50% or more of the probes have met the threshold, % expressed if cntP/length(total) >= 0.5 Results.Expressed = [Results.Expressed;locus]; else Results.UnExpressed = [Results.UnExpressed;locus]; end end else % If different RefSeq Accession codes, different transcripts, % must be manually curated Results.AltSplice = [Results.AltSplice;locus]; end Results.Total = Results.Total+1; clear total end end % Setting up different transcripts for manual curation Transcripts.Locus = []; Transcripts.Data = {}; for i = 1:length(Results.AltSplice) num = find(Locus==Results.AltSplice(i)); transcripts = unique(ExpressionData.Transcript(num)); for j = 1:length(transcripts) Transcripts.Locus = [Transcripts.Locus;Results.AltSplice(i)]; end Transcripts.Data = [Transcripts.Data;transcripts]; end % Determining each transcripts expression using a similar threshold as % before for i = 1:length(Transcripts.Data) loc = strmatch(Transcripts.Data{i},ExpressionData.Transcript,'exact'); for j = 1:length(loc) total(j) = sum(ExpressionData.Data(loc(j),:)); ExpressionData.Locus(loc(j)) = 0; end cap = length(loc)*11*2; if sum(total)/cap >= ExpThreshold Transcripts.Expression(i,1) = 1; else Transcripts.Expression(i,1) = 0; end end % If expression of transcripts of one locus are the same, added as if no % alternative splicing occurs for simplicity Transcripts.Expressed = []; Transcripts.UnExpressed = []; mem_tran = Transcripts.Locus; for i = 1:length(Transcripts.Locus) if Transcripts.Locus(i) > 0 locus = Transcripts.Locus(i); loc = find(Transcripts.Locus==locus); sumExp = 0; for j = 1:length(loc) sumExp = sumExp+Transcripts.Expression(loc(j)); Transcripts.Locus(loc(j)) = 0; end if sumExp == 0 Transcripts.UnExpressed = [Transcripts.UnExpressed;locus]; elseif sumExp == length(loc) Transcripts.Expressed = [Transcripts.Expressed;locus]; end end end Transcripts.Locus = mem_tran;
github
EPFL-LCSB/matTFA-master
removeFieldEntriesForType.m
.m
matTFA-master/ext/Cobra205_vDec2014/reconstruction/refinement/removeFieldEntriesForType.m
7,139
utf_8
702148175917ef57ddf13c5c8740e153
function model = removeFieldEntriesForType(model, indicesToRemove, type, fieldSize, varargin) % Remove field entries at the specified indices from all fields associated % with the given type % USAGE: % model = removeFieldEntriesForType(model, indicesToRemove, type, varargin) % % INPUTS: % % model: the model to update % indicesToRemove: indices which should eb removed (either a logical array or double indices) % type: the Type of field to update one of % ('rxns','mets','comps','genes') % fieldSize: The size of the original field before % modification. This is necessary to identify fields % from which entries have to be removed. % OPTIONAL INPUTS: % varargin: Additional Options as 'ParameterName', Value pairs. Options are: % - 'excludeFields', fields which should not be % adjusted but kkept how they are. % % OUTPUT: % % modelNew: the model in which all fields associated with the % given type have the entries indicated removed. The % initial check is for the size of the field, if % multiple base fields have the same size, it is % assumed, that fields named e.g. rxnXYZ are % associated with rxns, and only those fields are % adapted along with fields which are specified in the % Model FieldDefinitions. % % .. Authors: % - Thomas Pfau June 2017, adapted to merge all fields. % - Georgios F. modification Aug 2017: There is a special case, when we have % equal number of reactions and metabolites (lines 128-144) % PossibleTypes = {'rxns','mets','comps','genes'}; parser = inputParser(); parser.addRequired('model',@(x) isfield(x,type)); parser.addRequired('indicesToRemove',@(x) islogical(x) || isnumeric(x)); parser.addRequired('type',@(x) any(ismember(PossibleTypes,x))); parser.addRequired('fieldSize',@isnumeric); parser.addParameter('excludeFields',{},@iscell); parser.parse(model,indicesToRemove,type,fieldSize,varargin{:}); fieldSize = parser.Results.fieldSize; excludeFields = parser.Results.excludeFields; if isnumeric(indicesToRemove) res = false(fieldSize,1); res(indicesToRemove) = 1; indicesToRemove = res; end %We need a special treatment for genes, i.e. if we remove genes, we need to %update all rules/gprRules if strcmp(type,'genes') removeRulesField = false; genePos = find(indicesToRemove); if ~ isfield(model,'rules') && isfield(model, 'grRules')% Only use grRules, if no rules field is present. %lets make this easy. we will simply create the rules field and %Then work on the rules field (removing that field again in the %end. model = generateRules(model); removeRulesField = true; end %update the rules fields. if isfield(model,'rules') %Rely on rules first %However, we first normalize the rules. model = normalizeRules(model); %First, eliminate all removed indices for i = 1:numel(genePos) %Replace either a trailing &, or a leading & rules = regexp(model.rules,['(?<pre>[\|&]?) *x\(' num2str(genePos(i)) '\) *(?<post>[\|&]?)'],'names'); matchingrules = find(~cellfun(@isempty, rules)); for elem = 1:numel(matchingrules) cres = rules{matchingrules(elem)}; for pos = 1:numel(cres) if isequal(cres(pos).pre,'&') model.rules(matchingrules(elem)) = regexprep(model.rules(matchingrules(elem)),[' *& *x\(' num2str(genePos(i)) '\) *([ \)])'],'$1'); elseif isequal(cres(pos).post,'&') model.rules(matchingrules(elem)) = regexprep(model.rules(matchingrules(elem)),['[ \(] *x\(' num2str(genePos(i)) '\) *& *'],'$1'); elseif isequal(cres(pos).post,'|') %Make sure its not preceded by a & model.rules(matchingrules(elem)) = regexprep(model.rules(matchingrules(elem)),['([^&]) *x\(' num2str(genePos(i)) '\) *\| *'],'$1 '); elseif isequal(cres(pos).pre,'|') %Make sure its not followed by a & model.rules(matchingrules(elem)) = regexprep(model.rules(matchingrules(elem)),[' *\| *x\(' num2str(genePos(i)) '\) *([^&])'],' $1'); else %This should only ever happen if there is only one gene. model.rules(matchingrules(elem)) = regexprep(model.rules(matchingrules(elem)),['[\( ]*x\(' num2str(genePos(i)) '\)[\( ]*'],''); end end end end %Now, replace all remaining indices. oldIndices = find(~indicesToRemove); for i = 1:numel(oldIndices) if i ~= oldIndices(i) %replace by new with an indicator that this is new. model.rules = strrep(model.rules,['x(' num2str(oldIndices(i)) ')'],['x(' num2str(i) '$)']); end end %remove the indicator. model.rules = strrep(model.rules,'$',''); if isfield(model, 'grRules') model = creategrRulesField(model); end end if removeRulesField model = rmfield(model,'rules'); end end fields = getModelFieldsForType(model, type, fieldSize); fields = setdiff(fields,excludeFields); for i = 1:numel(fields) % Lets assume, that we only have 2 dimensional fields. %%%%%%%%%%%%%%%%%%% ->->->->->->->->->->->->->->->->-> %%%%%%%%%%%%%%%% % ATTENTION: Georgios F. modification: There is a special case, when we have % equal number of reactions and metabolites if (size(model.(fields{i}),1) == fieldSize) && (size(model.(fields{i}),2) == fieldSize) && strcmp(fields{i}, 'S') if strcmp(type,'rxns') if size(model.(fields{i}),2) == fieldSize model.(fields{i}) = model.(fields{i})(:,~indicesToRemove); end elseif strcmp(type,'mets') if size(model.(fields{i}),1) == fieldSize model.(fields{i}) = model.(fields{i})(~indicesToRemove,:); end else error('Something is wrong with the definition of the stoichiometric matrix!') end else %%%%%%%%%%%%%%%%%%% -<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-< %%%%%%%%%%%%%%%% if size(model.(fields{i}),1) == fieldSize model.(fields{i}) = model.(fields{i})(~indicesToRemove,:); end if size(model.(fields{i}),2) == fieldSize model.(fields{i}) = model.(fields{i})(:,~indicesToRemove); end end end function model = normalizeRules(model) origrules = model.rules; model.rules = regexprep(model.rules,'\( *(x\([0-9]+\)) *\)','$1'); while ~all(strcmp(origrules,model.rules)) origrules = model.rules; model.rules = regexprep(model.rules,'\( *(x\([0-9]+\)) *\)','$1'); end
github
EPFL-LCSB/matTFA-master
sparseNull.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/sparseNull.m
9,145
utf_8
a10b073ba5651689e2e10fa7a5e6ca65
function N = sparseNull(S, tol) % sparseNull returns computes the sparse Null basis of a matrix % % N = sparseNull(S, tol) % % Computes a basis of the null space for a sparse matrix. For sparse % matrixes this is much faster than using null. It does however have lower % numerical accuracy. N is itself sparse and not orthonormal. So in this % way it is like using N = null(S, 'r'), except of course much faster. % % Jan Schellenberger 10/20/2009 % based on this: % http://www.mathworks.com/matlabcentral/fileexchange/11120-null-space-of-a-sparse-matrix if nargin <2 tol = 1e-9; end [SpLeft, SpRight] = spspaces(S,2, tol); N = SpRight{1}(:,SpRight{3}); N(abs(N) < tol) = 0; %%%%%%%%%%%%%% code from website. I did not write this myself. -Jan %%%% function [SpLeft, SpRight] = spspaces(A,opt,tol) % PURPOSE: finds left and right null and range space of a sparse matrix A % % --------------------------------------------------- % USAGE: [SpLeft, SpRight] = spspaces(A,opt,tol) % % INPUT: % A a sparse matrix % opt spaces to calculate % = 1: left null and range space % = 2: right null and range space % = 3: both left and right spaces % tol uses the tolerance tol when calculating % null subspaces (optional) % % OUTPUT: % SpLeft 1x4 cell. SpLeft = {} if opt =2. % SpLeft{1} an invertible matrix Q % SpLeft{2} indices, I, of rows of the matrix Q that % span the left range of the matrix A % SpLeft{3} indices, J, of rows of the matrix Q that % span the left null space of the matrix A % Q(J,:)A = 0 % SpLeft{4} inverse of the matrix Q % SpRight 1x4 cell. SpRight = {} if opt =1. % SpLeft{1} an invertible matrix Q % SpLeft{2} indices, I, of rows of the matrix Q that % span the right range of the matrix A % SpLeft{3} indices, J, of rows of the matrix Q that % span the right null space of the matrix A % AQ(:,J) = 0 % SpLeft{4} inverse of the matrix Q % % COMMENTS: % uses luq routine, that finds matrices L, U, Q such that % % A = L | U 0 | Q % | 0 0 | % % where L, Q, U are invertible matrices, U is upper triangular. This % decomposition is calculated using lu decomposition. % % This routine is fast, but can deliver inaccurate null and range % spaces if zero and nonzero singular values of the matrix A are not % well separated. % % WARNING: % right null and rang space may be very inaccurate % % Copyright (c) Pawel Kowal (2006) % All rights reserved % LREM_SOLVE toolbox is available free for noncommercial academic use only. % [email protected] if nargin<3 tol = max(max(size(A)) * norm(A,1) * eps,100*eps); end switch opt case 1 calc_left = 1; calc_right = 0; case 2 calc_left = 0; calc_right = 1; case 3 calc_left = 1; calc_right = 1; end [L,U,Q] = luq(A,0,tol); if calc_left if ~isempty(L) LL = L^-1; else LL = L; end S = max(abs(U),[],2); I = find(S>tol); if ~isempty(S) J = find(S<=tol); else J = (1:size(S,1))'; end SpLeft = {LL,I,J,L}; else SpLeft = {}; end if calc_right if ~isempty(Q) QQ = Q^-1; else QQ = Q; end S = max(abs(U),[],1); I = find(S>tol); if ~isempty(S) J = find(S<=tol); else J = (1:size(S,2))'; end SpRight = {QQ,I,J,Q}; else SpRight = {}; end function [L,U,Q] = luq(A,do_pivot,tol) % PURPOSE: calculates the following decomposition % % A = L |Ubar 0 | Q % |0 0 | % % where Ubar is a square invertible matrix % and matrices L, Q are invertible. % % --------------------------------------------------- % USAGE: [L,U,Q] = luq(A,do_pivot,tol) % INPUT: % A a sparse matrix % do_pivot = 1 with column pivoting % = 0 without column pivoting % tol uses the tolerance tol in separating zero and % nonzero values % % OUTPUT: % L,U,Q matrices % % COMMENTS: % based on lu decomposition % % Copyright (c) Pawel Kowal (2006) % All rights reserved % LREM_SOLVE toolbox is available free for noncommercial academic use only. % [email protected] [n,m] = size(A); if ~issparse(A) A = sparse(A); end %-------------------------------------------------------------------------- % SPECIAL CASES %-------------------------------------------------------------------------- if size(A,1)==0 L = speye(n); U = A; Q = speye(m); return; end if size(A,2)==0 L = speye(n); U = A; Q = speye(m); return; end %-------------------------------------------------------------------------- % LU DECOMPOSITION %-------------------------------------------------------------------------- if do_pivot [L,U,P,Q] = lu(A); Q = Q'; else [L,U,P] = lu(A); Q = speye(m); end p = size(A,1)-size(L,2); LL = [sparse(n-p,p);speye(p)]; L = [P'*L P(n-p+1:n,:)']; U = [U;sparse(p,m)]; %-------------------------------------------------------------------------- % FINDS ROWS WITH ZERO AND NONZERO ELEMENTS ON THE DIAGONAL %-------------------------------------------------------------------------- if size(U,1)==1 || size(U,2)==1 S = U(1,1); else S = diag(U); end I = find(abs(S)>tol); Jl = (1:n)'; Jl(I) = []; Jq = (1:m)'; Jq(I) = []; Ubar1 = U(I,I); Ubar2 = U(Jl,Jq); Qbar1 = Q(I,:); Lbar1 = L(:,I); %-------------------------------------------------------------------------- % ELININATES NONZEZO ELEMENTS BELOW AND ON THE RIGHT OF THE % INVERTIBLE BLOCK OF THE MATRIX U % % UPDATES MATRICES L, Q %-------------------------------------------------------------------------- if ~isempty(I) Utmp = U(I,Jq); X = Ubar1'\U(Jl,I)'; Ubar2 = Ubar2-X'*Utmp; Lbar1 = Lbar1+L(:,Jl)*X'; X = Ubar1\Utmp; Qbar1 = Qbar1+X*Q(Jq,:); Utmp = []; X = []; end %-------------------------------------------------------------------------- % FINDS ROWS AND COLUMNS WITH ONLY ZERO ELEMENTS %-------------------------------------------------------------------------- I2 = find(max(abs(Ubar2),[],2)>tol); I5 = find(max(abs(Ubar2),[],1)>tol); I3 = Jl(I2); I4 = Jq(I5); Jq(I5) = []; Jl(I2) = []; U = []; %-------------------------------------------------------------------------- % FINDS A PART OF THE MATRIX U WHICH IS NOT IN THE REQIRED FORM %-------------------------------------------------------------------------- A = Ubar2(I2,I5); %-------------------------------------------------------------------------- % PERFORMS LUQ DECOMPOSITION OF THE MATRIX A %-------------------------------------------------------------------------- [L1,U1,Q1] = luq(A,do_pivot,tol); %-------------------------------------------------------------------------- % UPDATES MATRICES L, U, Q %-------------------------------------------------------------------------- Lbar2 = L(:,I3)*L1; Qbar2 = Q1*Q(I4,:); L = [Lbar1 Lbar2 L(:,Jl)]; Q = [Qbar1; Qbar2; Q(Jq,:)]; n1 = length(I); n2 = length(I3); m2 = length(I4); U = [Ubar1 sparse(n1,m-n1);sparse(n2,n1) U1 sparse(n2,m-n1-m2);sparse(n-n1-n2,m)];
github
EPFL-LCSB/matTFA-master
ezimplot3.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/ezimplot3.m
8,154
utf_8
7bbd5c9f9dba80200fd1fb799e7c8cb3
function h = ezimplot3(varargin) % EZIMPLOT3 Easy to use 3D implicit plotter. % EZIMPLOT3(FUN) plots the function FUN(X,Y,Z) = 0 (vectorized or not) % over the default domain: % -2*PI < X < 2*PI, -2*PI < Y < 2*PI, -2*PI < Z < 2*PI. % FUN can be a string, an anonymous function handle, a .M-file handle, an % inline function or a symbolic function (see examples below) % % EZIMPLOT3(FUN,DOMAIN)plots FUN over the specified DOMAIN instead of the % default domain. DOMAIN can be vector [XMIN,XMAX,YMIN,YMAX,ZMIN,ZMAX] or % vector [A,B] (to plot over A < X < B, A < Y < B, A < Z < B). % % EZIMPLOT3(..,N) plots FUN using an N-by-N grid. The default value for % N is 60. % EZIMPLOT3(..,'color') plots FUN with color 'color'. The default value % for 'color' is 'red'. 'color' must be a valid Matlab color identifier. % % EZIMPLOT3(axes_handle,..) plots into the axes with handle axes_handle % instead of into current axes (gca). % % H = EZIMPLOT3(...) returns the handle to the patch object this function % creates. % % Example: % Plot x^3+exp(y)-cosh(z)=4, between -5 and 5 for x,y and z % % via a string: % f = 'x^3+exp(y)-cosh(z)-4' % ezimplot3(f,[-5 5]) % % via a anonymous function handle: % f = @(x,y,z) x^3+exp(y)-cosh(z)-4 % ezimplot3(f,[-5 5]) % % via a function .m file: %------------------------------% % function out = myfun(x,y,z) % out = x^3+exp(y)-cosh(z)-4; %------------------------------% % ezimplot3(@myfun,[-5 5]) or ezimplot('myfun',[-5 5]) % % via a inline function: % f = inline('x^3+exp(y)-cosh(z)-4') % ezimplot3(f,[-5 5]) % % via a symbolic expression: % syms x y z % f = x^3+exp(y)-cosh(z)-4 % ezimplot3(f,[-5 5]) % % Note: this function do not use the "ezgraph3" standard, like ezsurf, % ezmesh, etc, does. Because of this, ezimplot3 only tries to imitate that % interface. A future work must be to modify "ezgraph3" to include a % routine for implicit surfaces based on this file % % Inspired by works of: Artur Jutan UWO 02-02-98 [email protected] % Made by: Gustavo Morales UC 04-12-09 [email protected] % %%% Checking & Parsing input arguments: if ishandle(varargin{1}) cax = varargin{1}; % User selected axes handle for graphics axes(cax); args{:} = varargin{2:end}; %ensuring args be a cell array else args = varargin; end [fun domain n color] = argcheck(args{:}); %%% Generating the volumetric domain data: xm = linspace(domain(1),domain(2),n); ym = linspace(domain(3),domain(4),n); zm = linspace(domain(5),domain(6),n); [x,y,z] = meshgrid(xm,ym,zm); %%% Formatting "fun" [f_handle f_text] = fix_fun(fun); % f_handle is the anonymous f-handle for "fun" % f_text is "fun" ready to be a title %%% Evaluating "f_handle" in domain: % try fvalues = f_handle(x,y,z); % fvalues: volume data % catch ME % error('Ezimplot3:Functions', 'FUN must have no more than 3 arguments'); % end %%% Making the 3D graph of the 0-level surface of the 4D function "fun": h = patch(isosurface(x,y,z,fvalues,0)); % "patch" handles the structure... % sent by "isosurface" isonormals(x,y,z,fvalues,h)% Recalculating the isosurface normals based... % on the volume data set(h,'FaceColor',color,'EdgeColor','none'); %%% Aditional graphic details: xlabel('x');ylabel('y');zlabel('z');% naming the axis alpha(0.7) % adjusting for some transparency grid on; view([1,1,1]); axis equal; camlight; lighting gouraud %%% Showing title: title([f_text,' = 0']); % %--------------------------------------------Sub-functions HERE--- function [f dom n color] = argcheck(varargin) %ARGCHECK(arg) parses "args" to the variables "f"(function),"dom"(domain) %,"n"(grid size) and "c"(color)and TRIES to check its validity switch nargin case 0 error('Ezimplot3:Arguments',... 'At least "fun" argument must be given'); case 1 f = varargin{1}; dom = [-2*pi, 2*pi]; % default domain: -2*pi < xi < 2*pi n = 60; % default grid size color = 'red'; % default graph color case 2 f = varargin{1}; if isa(varargin{2},'double') && length(varargin{2})>1 dom = varargin{2}; n = 60; color = 'red'; elseif isa(varargin{2},'double') && length(varargin{2})==1 n = varargin{2}; dom = [-2*pi, 2*pi]; color = 'red'; elseif isa(varargin{2},'char') dom = [-2*pi, 2*pi]; n = 60; color = varargin{2}; end case 3 % If more than 2 arguments are given, it's f = varargin{1}; % assumed they are in the correct order dom = varargin{2}; n = varargin{3}; color = 'red'; % default color case 4 % If more than 2 arguments are given, it's f = varargin{1}; % assumed they are in the correct order dom = varargin{2}; n = varargin{3}; color = varargin{4}; otherwise warning('Ezimplot3:Arguments', ... 'Attempt will be made only with the 4 first arguments'); f = varargin{1}; dom = varargin{2}; n = varargin{3}; color = varargin{4}; end if length(dom) == 2 dom = repmat(dom,1,3); %domain repeated in all variables elseif length(dom) ~= 6 error('Ezimplot3:Arguments',... 'Input argument "domain" must be a row vector of size 2 or size 6'); end % %-------------------------------------------- function [f_hand f_text] = fix_fun(fun) % FIX_FUN(fun) Converts "fun" into an anonymous function of 3 variables (x,y,z) % with handle "f_hand" and a string "f_text" to use it as title types = {'char','sym','function_handle','inline'}; % cell array of 'types' type = ''; %Identifing FUN object class for i=1:size(types,2) if isa(fun,types{i}) type = types{i}; break; end end switch type case 'char' % Formatting FUN if it is char type. There's 2 possibilities: % A string with the name of the .m file if exist([fun,'.m'],'file') syms x y z; if nargin(str2func(fun)) == 3 f_sym = eval([fun,'(x,y,z)']); % evaluating FUN at the sym point (x,y,z) else error('Ezimplot3:Arguments',... '%s must be a function of 3 arguments or unknown function',fun); end f_text = strrep(char(f_sym),' ',''); % converting to char and eliminating spaces f_hand = eval(['@(x,y,z)',vectorize(f_text),';']); % converting string to anonymous f_handle else % A string with the function's expression f_hand = eval(['@(x,y,z)',vectorize(fun),';']); % converting string to anonymous f_handle f_text = strrep(fun,'.',''); f_text = strrep(f_text,' ',''); % removing vectorization & spaces end case 'sym' % Formatting FUN if it is a symbolic object f_hand = eval(['@(x,y,z)',vectorize(fun),';']); % converting string to anonymous f_handle f_text = strrep(char(fun),' ',''); % removing spaces case {'function_handle', 'inline'} % Formatting FUN if it is a function_handle or an inline object syms x y z; if nargin(fun) == 3 %&& numel(symvar(char(fun))) == 3 % Determining if # variables == 3 f_sym = fun(x,y,z); % evaluating FUN at the sym point (x,y,z) else error('Ezimplot3:Arguments',... '%s must be function of 3 arguments or unknown function',char(fun)); end f_text = strrep(char(f_sym),' ',''); % converting into string to removing spaces f_hand = eval(['@(x,y,z)',vectorize(f_text),';']); % converting string to anonymous f_handle otherwise error('First argument "fun" must be of type character, simbolic, function handle or inline'); end
github
EPFL-LCSB/matTFA-master
m2html.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/m2html/m2html.m
38,334
utf_8
9e0ccc8f5147c96ff4bde2efa2b4787b
function m2html(varargin) %M2HTML - Documentation System for Matlab M-files in HTML % M2HTML by itself generates an HTML documentation of Matlab M-files in the % current directory. HTML files are also written in the current directory. % M2HTML('PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...) % sets multiple option values. The list of option names and default values is: % o mFiles - Cell array of strings or character array containing the % list of M-files and/or directories of M-files for which an HTML % documentation will be built [ '.' ] % o htmlDir - Top level directory for generated HTML files [ '.' ] % o recursive - Process subdirectories [ on | {off} ] % o source - Include Matlab source code in the HTML documentation % [ {on} | off ] % o syntaxHighlighting - Syntax Highlighting [ {on} | off ] % o tabs - Replace '\t' (horizontal tab) in source code by n white space % characters [ 0 ... {4} ... n ] % o globalHypertextLinks - Hypertext links among separate Matlab % directories [ on | {off} ] % o todo - Create a TODO file in each directory summarizing all the % '% TODO %' lines found in Matlab code [ on | {off}] % o graph - Compute a dependency graph using GraphViz [ on | {off}] % 'dot' required, see <http://www.research.att.com/sw/tools/graphviz/> % o indexFile - Basename of the HTML index file [ 'index' ] % o extension - Extension of generated HTML files [ '.html' ] % o template - HTML template name to use [ 'blue' ] % o save - Save current state after M-files parsing in 'm2html.mat' % in directory htmlDir [ on | {off}] % o load - Load a previously saved '.mat' M2HTML state to generate HTML % files once again with possibly other options [ <none> ] % o verbose - Verbose mode [ {on} | off ] % % Examples: % >> m2html('mfiles','matlab', 'htmldir','doc'); % >> m2html('mfiles',{'matlab/signal' 'matlab/image'}, 'htmldir','doc'); % >> m2html('mfiles','matlab', 'htmldir','doc', 'recursive','on'); % >> m2html('mfiles','mytoolbox', 'htmldir','doc', 'source','off'); % >> m2html('mfiles','matlab', 'htmldir','doc', 'global','on'); % >> m2html( ... , 'template','frame', 'index','menu'); % % See also HIGHLIGHT, MDOT, TEMPLATE. % Copyright (C) 2003 Guillaume Flandin <[email protected]> % $Revision: 1.2 $Date: 2003/31/08 17:25:20 $ % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA. % Suggestions for improvement and fixes are always welcome, although no % guarantee is made whether and when they will be implemented. % Send requests to [email protected] % For tips on how to write Matlab code, see: % * MATLAB Programming Style Guidelines, by R. Johnson: % <http://www.datatool.com/prod02.htm> % * For tips on creating help for your m-files 'type help.m'. % * Matlab documentation on M-file Programming: % <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/ch10_pr9.shtml> % This function uses the Template class so that you can fully customize % the output. You can modify .tpl files in templates/blue/ or create new % templates in a new directory. % See the template class documentation for more details. % <http://www.madic.org/download/matlab/template/> % Latest information on M2HTML is available on the web through: % <http://www.artefact.tk/software/matlab/m2html/> % Other Matlab to HTML converters available on the web: % 1/ mat2html.pl, J.C. Kantor, in Perl, 1995: % <http://fresh.t-systems-sfr.com/unix/src/www/mat2html> % 2/ htmltools, B. Alsberg, in Matlab, 1997: % <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=175> % 3/ mtree2html2001, H. Pohlheim, in Perl, 1996, 2001: % <http://www.pohlheim.com/perl_main.html#matlabdocu> % 4/ MatlabToHTML, T. Kristjansson, binary, 2001: % <http://www.psi.utoronto.ca/~trausti/MatlabToHTML/MatlabToHTML.html> % 5/ Highlight, G. Flandin, in Matlab, 2003: % <http://www.madic.org/download/matlab/highlight/> % 6/ mdoc, P. Brinkmann, in Matlab, 2003: % <http://www.math.uiuc.edu/~brinkman/software/mdoc/> % 7/ Ocamaweb, Miriad Technologies, in Ocaml, 2002: % <http://ocamaweb.sourceforge.net/> % 8/ Matdoc, M. Kaminsky, in Perl, 2003: % <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3498> % 9/ Matlab itself, The Mathworks Inc, with HELPWIN and DOC %------------------------------------------------------------------------------- %- Set up options and default parameters %------------------------------------------------------------------------------- msgInvalidPair = 'Bad value for argument: ''%s'''; options = struct('verbose', 1,... 'mFiles', {{'.'}},... 'htmlDir', '.',... 'recursive', 0,... 'source', 1,... 'syntaxHighlighting', 1,... 'tabs', 4,... 'globalHypertextLinks', 0,... 'graph', 0,... 'todo', 0,... 'load', 0,... 'save', 0,... 'search', 0,... 'indexFile', 'index',... 'extension', '.html',... 'template', 'blue'); if nargin == 1 & isstruct(varargin{1}) paramlist = [ fieldnames(varargin{1}) ... struct2cell(varargin{1}) ]'; paramlist = { paramlist{:} }; else if mod(nargin,2) error('Invalid parameter/value pair arguments.'); end paramlist = varargin; end optionsnames = lower(fieldnames(options)); for i=1:2:length(paramlist) pname = paramlist{i}; pvalue = paramlist{i+1}; ind = strmatch(lower(pname),optionsnames); if isempty(ind) error(['Invalid parameter: ''' pname '''.']); elseif length(ind) > 1 error(['Ambiguous parameter: ''' pname '''.']); end switch(optionsnames{ind}) case 'verbose' if strcmpi(pvalue,'on') options.verbose = 1; elseif strcmpi(pvalue,'off') options.verbose = 0; else error(sprintf(msgInvalidPair,pname)); end case 'mfiles' if iscellstr(pvalue) options.mFiles = pvalue; elseif ischar(pvalue) options.mFiles = cellstr(pvalue); else error(sprintf(msgInvalidPair,pname)); end options.load = 0; case 'htmldir' if ischar(pvalue) if isempty(pvalue), options.htmlDir = '.'; else options.htmlDir = pvalue; end else error(sprintf(msgInvalidPair,pname)); end case 'recursive' if strcmpi(pvalue,'on') options.recursive = 1; elseif strcmpi(pvalue,'off') options.recursive = 0; else error(sprintf(msgInvalidPair,pname)); end options.load = 0; case 'source' if strcmpi(pvalue,'on') options.source = 1; elseif strcmpi(pvalue,'off') options.source = 0; else error(sprintf(msgInvalidPair,pname)); end case 'syntaxhighlighting' if strcmpi(pvalue,'on') options.syntaxHighlighting = 1; elseif strcmpi(pvalue,'off') options.syntaxHighlighting = 0; else error(sprintf(msgInvalidPair,pname)); end case 'tabs' if pvalue >= 0 options.tabs = pvalue; else error(sprintf(msgInvalidPair,pname)); end case 'globalhypertextlinks' if strcmpi(pvalue,'on') options.globalHypertextLinks = 1; elseif strcmpi(pvalue,'off') options.globalHypertextLinks = 0; else error(sprintf(msgInvalidPair,pname)); end options.load = 0; case 'graph' if strcmpi(pvalue,'on') options.graph = 1; elseif strcmpi(pvalue,'off') options.graph = 0; else error(sprintf(msgInvalidPair,pname)); end case 'todo' if strcmpi(pvalue,'on') options.todo = 1; elseif strcmpi(pvalue,'off') options.todo = 0; else error(sprintf(msgInvalidPair,pname)); end case 'load' if ischar(pvalue) try load(pvalue); catch error(sprintf('Unable to load %s.',pvalue)); end options.load = 1; [dummy options.template] = fileparts(options.template); else error(sprintf(msgInvalidPair,pname)); end case 'save' if strcmpi(pvalue,'on') options.save = 1; elseif strcmpi(pvalue,'off') options.save = 0; else error(sprintf(msgInvalidPair,pname)); end case 'search' if strcmpi(pvalue,'on') options.search = 1; elseif strcmpi(pvalue,'off') options.search = 0; else error(sprintf(msgInvalidPair,pname)); end case 'indexfile' if ischar(pvalue) options.indexFile = pvalue; else error(sprintf(msgInvalidPair,pname)); end case 'extension' if ischar(pvalue) & pvalue(1) == '.' options.extension = pvalue; else error(sprintf(msgInvalidPair,pname)); end case 'template' if ischar(pvalue) options.template = pvalue; else error(sprintf(msgInvalidPair,pname)); end otherwise error(['Invalid parameter: ''' pname '''.']); end end %------------------------------------------------------------------------------- %- Get template files location %------------------------------------------------------------------------------- s = fileparts(which(mfilename)); options.template = fullfile(s,'templates',options.template); if exist(options.template) ~= 7 error('[Template] Unknown template.'); end %------------------------------------------------------------------------------- %- Get list of M-files %------------------------------------------------------------------------------- if ~options.load mfiles = getmfiles(options.mFiles,{},options.recursive); if ~length(mfiles), fprintf('Nothing to be done.\n'); return; end if options.verbose, fprintf('Found %d M-files.\n',length(mfiles)); end mfiles = sort(mfiles); % sort list of M-files in dictionary order end %------------------------------------------------------------------------------- %- Get list of (unique) directories and (unique) names %------------------------------------------------------------------------------- if ~options.load mdirs = {}; names = {}; for i=1:length(mfiles) [mdirs{i}, names{i}] = fileparts(mfiles{i}); if isempty(mdirs{i}), mdirs{i} = '.'; end end mdir = unique(mdirs); if options.verbose, fprintf('Found %d unique Matlab directories.\n',length(mdir)); end name = names; %name = unique(names); % output is sorted %if options.verbose, % fprintf('Found %d unique Matlab files.\n',length(name)); %end end %------------------------------------------------------------------------------- %- Create output directory, if necessary %------------------------------------------------------------------------------- if isempty(dir(options.htmlDir)) %- Create the top level output directory if options.verbose fprintf('Creating directory %s...\n',options.htmlDir); end if options.htmlDir(end) == filesep, options.htmlDir(end) = []; end [pathdir, namedir] = fileparts(options.htmlDir); if isempty(pathdir) [status, msg] = mkdir(namedir); else [status, msg] = mkdir(pathdir, namedir); end if ~status, error(msg); end end %------------------------------------------------------------------------------- %- Get synopsis, H1 line, script/function, subroutines, cross-references, todo %------------------------------------------------------------------------------- if ~options.load synopsis = cell(size(mfiles)); h1line = cell(size(mfiles)); subroutine = cell(size(mfiles)); hrefs = sparse(length(mfiles),length(mfiles)); todo = struct('mfile',[],'line',[],'comment',{{}}); ismex = zeros(length(mfiles),length(mexexts)); for i=1:length(mfiles) s = mfileparse(mfiles{i}, mdirs, names, options); synopsis{i} = s.synopsis; h1line{i} = s.h1line; subroutine{i} = s.subroutine; hrefs(i,:) = s.hrefs; todo.mfile = [todo.mfile repmat(i,1,length(s.todo.line))]; todo.line = [todo.line s.todo.line]; todo.comment = {todo.comment{:} s.todo.comment{:}}; ismex(i,:) = s.ismex; end hrefs = hrefs > 0; end %------------------------------------------------------------------------------- %- Save M-filenames and cross-references for further analysis %------------------------------------------------------------------------------- matfilesave = 'm2html.mat'; if options.save if options.verbose fprintf('Saving MAT file %s...\n',matfilesave); end save(fullfile(options.htmlDir,matfilesave), ... 'mfiles', 'names', 'mdirs', 'name', 'mdir', 'options', ... 'hrefs', 'synopsis', 'h1line', 'subroutine', 'todo', 'ismex'); end %------------------------------------------------------------------------------- %- Setup the output directories %------------------------------------------------------------------------------- for i=1:length(mdir) if exist(fullfile(options.htmlDir,mdir{i})) ~= 7 ldir = splitpath(mdir{i}); for j=1:length(ldir) if exist(fullfile(options.htmlDir,ldir{1:j})) ~= 7 %- Create the output directory if options.verbose fprintf('Creating directory %s...\n',... fullfile(options.htmlDir,ldir{1:j})); end if j == 1 [status, msg] = mkdir(options.htmlDir,ldir{1}); else [status, msg] = mkdir(options.htmlDir,fullfile(ldir{1:j})); end error(msg); end end end end %------------------------------------------------------------------------------- %- Write the master index file %------------------------------------------------------------------------------- tpl_master = 'master.tpl'; tpl_master_identifier_nbyline = 4; %- Create the HTML template tpl = template(options.template,'remove'); tpl = set(tpl,'file','TPL_MASTER',tpl_master); tpl = set(tpl,'block','TPL_MASTER','rowdir','rowdirs'); tpl = set(tpl,'block','TPL_MASTER','idrow','idrows'); tpl = set(tpl,'block','idrow','idcolumn','idcolumns'); %- Open for writing the HTML master index file curfile = fullfile(options.htmlDir,[options.indexFile options.extension]); if options.verbose fprintf('Creating HTML file %s...\n',curfile); end fid = openfile(curfile,'w'); %- Set some template variables tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ... datestr(now,13)]); tpl = set(tpl,'var','MASTERPATH', './'); tpl = set(tpl,'var','DIRS', sprintf('%s ',mdir{:})); %- Print list of unique directories for i=1:length(mdir) tpl = set(tpl,'var','L_DIR',... fullurl(mdir{i},[options.indexFile options.extension])); tpl = set(tpl,'var','DIR',mdir{i}); tpl = parse(tpl,'rowdirs','rowdir',1); end %- Print full list of M-files (sorted by column) [sortnames, ind] = sort(names); m_mod = mod(length(sortnames), tpl_master_identifier_nbyline); ind = [ind zeros(1,tpl_master_identifier_nbyline-m_mod)]; m_floor = floor(length(ind) / tpl_master_identifier_nbyline); ind = reshape(ind,m_floor,tpl_master_identifier_nbyline)'; for i=1:prod(size(ind)) if ind(i) tpl = set(tpl,'var','L_IDNAME',... fullurl(mdirs{ind(i)},[names{ind(i)} options.extension])); tpl = set(tpl,'var','T_IDNAME',mdirs{ind(i)}); tpl = set(tpl,'var','IDNAME',names{ind(i)}); tpl = parse(tpl,'idcolumns','idcolumn',1); else tpl = set(tpl,'var','L_IDNAME',''); tpl = set(tpl,'var','T_IDNAME',''); tpl = set(tpl,'var','IDNAME',''); tpl = parse(tpl,'idcolumns','idcolumn',1); end if mod(i,tpl_master_identifier_nbyline) == 0 tpl = parse(tpl,'idrows','idrow',1); tpl = set(tpl,'var','idcolumns',''); end end %- Print the template in the HTML file tpl = parse(tpl,'OUT','TPL_MASTER'); fprintf(fid,'%s',get(tpl,'OUT')); fclose(fid); %------------------------------------------------------------------------------- %- Copy template files (CSS, images, ...) %------------------------------------------------------------------------------- % Get list of files d = dir(options.template); d = {d(~[d.isdir]).name}; % Copy files for i=1:length(d) [p, n, ext] = fileparts(d{i}); if ~strcmp(ext,'.tpl') % do not copy .tpl files if ~(exist(fullfile(options.htmlDir,d{i}))) if options.verbose fprintf('Copying template file %s...\n',d{i}); end [status, errmsg] = copyfile(fullfile(options.template,d{i}),... options.htmlDir); error(errmsg); end end end %------------------------------------------------------------------------------- %- Write an index for each output directory %------------------------------------------------------------------------------- tpl_mdir = 'mdir.tpl'; tpl_mdir_link = '<a href="%s">%s</a>'; dotbase = 'graph'; %- Create the HTML template tpl = template(options.template,'remove'); tpl = set(tpl,'file','TPL_MDIR',tpl_mdir); tpl = set(tpl,'block','TPL_MDIR','row-m','rows-m'); tpl = set(tpl,'block','row-m','mexfile','mex'); tpl = set(tpl,'block','TPL_MDIR','othermatlab','other'); tpl = set(tpl,'block','othermatlab','row-other','rows-other'); tpl = set(tpl,'block','TPL_MDIR','subfolder','subfold'); tpl = set(tpl,'block','subfolder','subdir','subdirs'); tpl = set(tpl,'block','TPL_MDIR','todolist','todolists'); tpl = set(tpl,'block','TPL_MDIR','graph','graphs'); tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ... datestr(now,13)]); for i=1:length(mdir) %- Open for writing each output directory index file curfile = fullfile(options.htmlDir,mdir{i},... [options.indexFile options.extension]); if options.verbose fprintf('Creating HTML file %s...\n',curfile); end fid = openfile(curfile,'w'); %- Set template fields tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]); tpl = set(tpl,'var','MASTERPATH',backtomaster(mdir{i})); tpl = set(tpl,'var','MDIR', mdir{i}); %- Display Matlab m-files, their H1 line and their Mex status tpl = set(tpl,'var','rows-m',''); for j=1:length(mdirs) if strcmp(mdirs{j},mdir{i}) tpl = set(tpl,'var','L_NAME', [names{j} options.extension]); tpl = set(tpl,'var','NAME', names{j}); tpl = set(tpl,'var','H1LINE', h1line{j}); if any(ismex(j,:)) tpl = parse(tpl,'mex','mexfile'); else tpl = set(tpl,'var','mex',''); end tpl = parse(tpl,'rows-m','row-m',1); end end %- Display other Matlab-specific files (.mat,.mdl,.p) tpl = set(tpl,'var','other',''); tpl = set(tpl,'var','rows-other',''); w = what(mdir{i}); w = w(1); w = {w.mat{:} w.mdl{:} w.p{:}}; for j=1:length(w) tpl = set(tpl,'var','OTHERFILE',w{j}); tpl = parse(tpl,'rows-other','row-other',1); end if ~isempty(w) tpl = parse(tpl,'other','othermatlab'); end %- Display subsequent directories and classes tpl = set(tpl,'var','subdirs',''); tpl = set(tpl,'var','subfold',''); d = dir(mdir{i}); d = {d([d.isdir]).name}; d = {d{~ismember(d,{'.' '..'})}}; for j=1:length(d) if ismember(fullfile(mdir{i},d{j}),mdir) tpl = set(tpl,'var','SUBDIRECTORY',... sprintf(tpl_mdir_link,... fullurl(d{j},[options.indexFile options.extension]),d{j})); else tpl = set(tpl,'var','SUBDIRECTORY',d{j}); end tpl = parse(tpl,'subdirs','subdir',1); end if ~isempty(d) tpl = parse(tpl,'subfold','subfolder'); end %- Link to the TODO list if necessary tpl = set(tpl,'var','todolists',''); if options.todo if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile)) tpl = set(tpl,'var','LTODOLIST',['todo' options.extension]); tpl = parse(tpl,'todolists','todolist',1); end end %- Link to the dependency graph if necessary tpl = set(tpl,'var','graphs',''); if options.graph tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]); tpl = parse(tpl,'graphs','graph',1); end %- Print the template in the HTML file tpl = parse(tpl,'OUT','TPL_MDIR'); fprintf(fid,'%s',get(tpl,'OUT')); fclose(fid); end %------------------------------------------------------------------------------- %- Write a TODO list file for each output directory, if necessary %------------------------------------------------------------------------------- tpl_todo = 'todo.tpl'; if options.todo %- Create the HTML template tpl = template(options.template,'remove'); tpl = set(tpl,'file','TPL_TODO',tpl_todo); tpl = set(tpl,'block','TPL_TODO','filelist','filelists'); tpl = set(tpl,'block','filelist','row','rows'); tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ... datestr(now,13)]); for i=1:length(mdir) mfilestodo = intersect(find(strcmp(mdir{i},mdirs)),todo.mfile); if ~isempty(mfilestodo) %- Open for writing each TODO list file curfile = fullfile(options.htmlDir,mdir{i},... ['todo' options.extension]); if options.verbose fprintf('Creating HTML file %s...\n',curfile); end fid = openfile(curfile,'w'); %- Set template fields tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]); tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i})); tpl = set(tpl,'var','MDIR', mdir{i}); tpl = set(tpl,'var','filelists', ''); for k=1:length(mfilestodo) tpl = set(tpl,'var','MFILE',names{mfilestodo(k)}); tpl = set(tpl,'var','rows',''); nbtodo = find(todo.mfile == mfilestodo(k)); for l=1:length(nbtodo) tpl = set(tpl,'var','L_NBLINE',... [names{mfilestodo(k)} ... options.extension ... '#l' num2str(todo.line(nbtodo(l)))]); tpl = set(tpl,'var','NBLINE',num2str(todo.line(nbtodo(l)))); tpl = set(tpl,'var','COMMENT',todo.comment{nbtodo(l)}); tpl = parse(tpl,'rows','row',1); end tpl = parse(tpl,'filelists','filelist',1); end %- Print the template in the HTML file tpl = parse(tpl,'OUT','TPL_TODO'); fprintf(fid,'%s',get(tpl,'OUT')); fclose(fid); end end end %------------------------------------------------------------------------------- %- Create a dependency graph for each output directory, if requested %------------------------------------------------------------------------------- tpl_graph = 'graph.tpl'; dot_exec = 'dot'; %dotbase defined earlier if options.graph %- Create the HTML template tpl = template(options.template,'remove'); tpl = set(tpl,'file','TPL_GRAPH',tpl_graph); tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ... datestr(now,13)]); for i=1:length(mdir) mdotfile = fullfile(options.htmlDir,mdir{i},[dotbase '.dot']); if options.verbose fprintf('Creating dependency graph %s...',mdotfile); end ind = find(strcmp(mdirs,mdir{i})); %ind = find(strncmp(mdirs,mdir{i},length(mdir{i}))); %R.F. href1 = zeros(length(ind),length(hrefs)); for j=1:length(hrefs), href1(:,j) = hrefs(ind,j); end href2 = zeros(length(ind)); for j=1:length(ind), href2(j,:) = href1(j,ind); end mdot({href2,{names{ind}},options,{mfiles{ind}}}, mdotfile); %mdot({href2,{names{ind}},options,{mfiles{ind}}},mdotfile,mdir{i});%R.F. try %- see <http://www.research.att.com/sw/tools/graphviz/> % <dot> must be in your system path: % - on Linux, modify $PATH accordingly % - on Windows, modify the environment variable PATH like this: % From the Start-menu open the Control Panel, open 'System' and activate the % panel named 'Extended'. Open the dialog 'Environment Variables'. Select the % variable 'Path' of the panel 'System Variables' and press the 'Modify button. % Then add 'C:\GraphViz\bin' to your current definition of PATH, assuming that % you did install GraphViz into directory 'C:\GraphViz'. Note that the various % paths in PATH have to be separated by a colon. Her is an example how the final % Path should look like: ...;C:\WINNT\System32;...;C:\GraphViz\bin % (Note that this should have been done automatically during GraphViz installation) eval(['!' dot_exec ' -Tcmap -Tpng ' mdotfile ... ' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.map']) ... ' -o ' fullfile(options.htmlDir,mdir{i},[dotbase '.png'])]) % use '!' rather than 'system' for backward compability catch fprintf('failed.'); end fprintf('\n'); fid = openfile(fullfile(options.htmlDir,mdir{i},... [dotbase options.extension]),'w'); tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]); tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i})); tpl = set(tpl,'var','MDIR', mdir{i}); tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']); fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r'); tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c')); fclose(fmap); tpl = parse(tpl,'OUT','TPL_GRAPH'); fprintf(fid,'%s', get(tpl,'OUT')); fclose(fid); end end %------------------------------------------------------------------------------- %- Write an HTML file for each M-file %------------------------------------------------------------------------------- %- List of Matlab keywords (output from iskeyword) matlabKeywords = {'break', 'case', 'catch', 'continue', 'elseif', 'else', ... 'end', 'for', 'function', 'global', 'if', 'otherwise', ... 'persistent', 'return', 'switch', 'try', 'while'}; %'keyboard', 'pause', 'eps', 'NaN', 'Inf' tpl_mfile = 'mfile.tpl'; tpl_mfile_code = '<a href="%s" class="code" title="%s">%s</a>'; tpl_mfile_keyword = '<span class="keyword">%s</span>'; tpl_mfile_comment = '<span class="comment">%s</span>'; tpl_mfile_string = '<span class="string">%s</span>'; tpl_mfile_aname = '<a name="%s" href="#_subfunctions" class="code">%s</a>'; tpl_mfile_line = '%04d %s\n'; %- Delimiters used in strtok: some of them may be useless (% " .), removed '.' strtok_delim = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/,:;="''%%'); %- Create the HTML template tpl = template(options.template,'remove'); tpl = set(tpl,'file','TPL_MFILE',tpl_mfile); tpl = set(tpl,'block','TPL_MFILE','pathline','pl'); tpl = set(tpl,'block','TPL_MFILE','mexfile','mex'); tpl = set(tpl,'block','TPL_MFILE','script','scriptfile'); tpl = set(tpl,'block','TPL_MFILE','crossrefcall','crossrefcalls'); tpl = set(tpl,'block','TPL_MFILE','crossrefcalled','crossrefcalleds'); tpl = set(tpl,'block','TPL_MFILE','subfunction','subf'); tpl = set(tpl,'block','subfunction','onesubfunction','onesubf'); tpl = set(tpl,'block','TPL_MFILE','source','thesource'); tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ... datestr(now,13)]); for i=1:length(mdir) for j=1:length(mdirs) if strcmp(mdirs{j},mdir{i}) curfile = fullfile(options.htmlDir,mdir{i},... [names{j} options.extension]); %- Open for writing the HTML file if options.verbose fprintf('Creating HTML file %s...\n',curfile); end fid = openfile(curfile,'w'); %- Open for reading the M-file fid2 = openfile(mfiles{j},'r'); %- Set some template fields tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]); tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i})); tpl = set(tpl,'var','MDIR', mdirs{j}); tpl = set(tpl,'var','NAME', names{j}); tpl = set(tpl,'var','H1LINE', h1line{j}); tpl = set(tpl,'var','scriptfile', ''); if isempty(synopsis{j}) tpl = set(tpl,'var','SYNOPSIS',get(tpl,'var','script')); else tpl = set(tpl,'var','SYNOPSIS', synopsis{j}); end s = splitpath(mdir{i}); tpl = set(tpl,'var','pl',''); for k=1:length(s) c = cell(1,k); for l=1:k, c{l} = filesep; end cpath = {s{1:k};c{:}}; cpath = [cpath{:}]; if ~isempty(cpath), cpath = cpath(1:end-1); end if ismember(cpath,mdir) tpl = set(tpl,'var','LPATHDIR',[repmat('../',... 1,length(s)-k) options.indexFile options.extension]); else tpl = set(tpl,'var','LPATHDIR','#'); end tpl = set(tpl,'var','PATHDIR',s{k}); tpl = parse(tpl,'pl','pathline',1); end %- Handle mex files tpl = set(tpl,'var','mex', ''); samename = dir(fullfile(mdir{i},[names{j} '.*'])); samename = {samename.name}; for k=1:length(samename) [dummy, dummy, ext] = fileparts(samename{k}); switch ext case '.c' tpl = set(tpl,'var','MEXTYPE', 'c'); case {'.cpp' '.c++' '.cxx' '.C'} tpl = set(tpl,'var','MEXTYPE', 'c++'); case {'.for' '.f' '.FOR' '.F'} tpl = set(tpl,'var','MEXTYPE', 'fortran'); end end [exts, platform] = mexexts; mexplatforms = sprintf('%s, ',platform{find(ismex(j,:))}); if ~isempty(mexplatforms) tpl = set(tpl,'var','PLATFORMS', mexplatforms(1:end-2)); tpl = parse(tpl,'mex','mexfile'); end %- Set description template field descr = ''; flagsynopcont = 0; flag_seealso = 0; while 1 tline = fgets(fid2); if ~ischar(tline), break, end tline = entity(fliplr(deblank(fliplr(tline)))); %- Synopsis line if ~isempty(strmatch('function',tline)) if ~isempty(strmatch('...',fliplr(deblank(tline)))) flagsynopcont = 1; end %- H1 line and description elseif ~isempty(strmatch('%',tline)) %- Hypertext links on the "See also" line ind = findstr(lower(tline),'see also'); if ~isempty(ind) | flag_seealso %- "See also" only in files in the same directory indsamedir = find(strcmp(mdirs{j},mdirs)); hrefnames = {names{indsamedir}}; r = deblank(tline); flag_seealso = 1; %(r(end) == ','); tline = ''; while 1 [t,r,q] = strtok(r,sprintf(' \t\n\r.,;%%')); tline = [tline q]; if isempty(t), break, end; ii = strcmpi(hrefnames,t); if any(ii) jj = find(ii); tline = [tline sprintf(tpl_mfile_code,... [hrefnames{jj(1)} options.extension],... synopsis{indsamedir(jj(1))},t)]; else tline = [tline t]; end end tline = sprintf('%s\n',tline); end descr = [descr tline(2:end)]; elseif isempty(tline) if ~isempty(descr), break, end; else if flagsynopcont if isempty(strmatch('...',fliplr(deblank(tline)))) flagsynopcont = 0; end else break; end end end tpl = set(tpl,'var','DESCRIPTION',... horztab(descr,options.tabs)); %- Set cross-references template fields: % Function called ind = find(hrefs(j,:) == 1); tpl = set(tpl,'var','crossrefcalls',''); for k=1:length(ind) if strcmp(mdirs{j},mdirs{ind(k)}) tpl = set(tpl,'var','L_NAME_CALL', ... [names{ind(k)} options.extension]); else tpl = set(tpl,'var','L_NAME_CALL', ... fullurl(backtomaster(mdirs{j}), ... mdirs{ind(k)}, ... [names{ind(k)} options.extension])); end tpl = set(tpl,'var','SYNOP_CALL', synopsis{ind(k)}); tpl = set(tpl,'var','NAME_CALL', names{ind(k)}); tpl = set(tpl,'var','H1LINE_CALL', h1line{ind(k)}); tpl = parse(tpl,'crossrefcalls','crossrefcall',1); end % Callers ind = find(hrefs(:,j) == 1); tpl = set(tpl,'var','crossrefcalleds',''); for k=1:length(ind) if strcmp(mdirs{j},mdirs{ind(k)}) tpl = set(tpl,'var','L_NAME_CALLED', ... [names{ind(k)} options.extension]); else tpl = set(tpl,'var','L_NAME_CALLED', ... fullurl(backtomaster(mdirs{j}),... mdirs{ind(k)}, ... [names{ind(k)} options.extension])); end tpl = set(tpl,'var','SYNOP_CALLED', synopsis{ind(k)}); tpl = set(tpl,'var','NAME_CALLED', names{ind(k)}); tpl = set(tpl,'var','H1LINE_CALLED', h1line{ind(k)}); tpl = parse(tpl,'crossrefcalleds','crossrefcalled',1); end %- Set subfunction template field tpl = set(tpl,'var',{'subf' 'onesubf'},{'' ''}); if ~isempty(subroutine{j}) & options.source for k=1:length(subroutine{j}) tpl = set(tpl, 'var', 'L_SUB', ['#_sub' num2str(k)]); tpl = set(tpl, 'var', 'SUB', subroutine{j}{k}); tpl = parse(tpl, 'onesubf', 'onesubfunction',1); end tpl = parse(tpl,'subf','subfunction'); end subname = extractname(subroutine{j}); %- Display source code with cross-references if options.source & ~strcmpi(names{j},'contents') fseek(fid2,0,-1); it = 1; matlabsource = ''; nbsubroutine = 1; %- Get href function names of this file indhrefnames = find(hrefs(j,:) == 1); hrefnames = {names{indhrefnames}}; %- Loop over lines while 1 tline = fgetl(fid2); if ~ischar(tline), break, end myline = ''; splitc = splitcode(entity(tline)); for k=1:length(splitc) if isempty(splitc{k}) elseif ~isempty(strmatch('function',splitc{k})) %- Subfunctions definition myline = [myline ... sprintf(tpl_mfile_aname,... ['_sub' num2str(nbsubroutine-1)],splitc{k})]; nbsubroutine = nbsubroutine + 1; elseif splitc{k}(1) == '''' myline = [myline ... sprintf(tpl_mfile_string,splitc{k})]; elseif splitc{k}(1) == '%' myline = [myline ... sprintf(tpl_mfile_comment,deblank(splitc{k}))]; elseif ~isempty(strmatch('...',splitc{k})) myline = [myline sprintf(tpl_mfile_keyword,'...')]; if ~isempty(splitc{k}(4:end)) myline = [myline ... sprintf(tpl_mfile_comment,splitc{k}(4:end))]; end else %- Look for keywords r = splitc{k}; while 1 [t,r,q] = strtok(r,strtok_delim); myline = [myline q]; if isempty(t), break, end; %- Highlight Matlab keywords & % cross-references on known functions if options.syntaxHighlighting & ... any(strcmp(matlabKeywords,t)) if strcmp('end',t) rr = fliplr(deblank(fliplr(r))); icomma = strmatch(',',rr); isemicolon = strmatch(';',rr); if ~(isempty(rr) | ~isempty([icomma isemicolon])) myline = [myline t]; else myline = [myline sprintf(tpl_mfile_keyword,t)]; end else myline = [myline sprintf(tpl_mfile_keyword,t)]; end elseif any(strcmp(hrefnames,t)) indt = indhrefnames(logical(strcmp(hrefnames,t))); flink = [t options.extension]; ii = ismember({mdirs{indt}},mdirs{j}); if ~any(ii) % take the first one... flink = fullurl(backtomaster(mdirs{j}),... mdirs{indt(1)}, flink); else indt = indt(logical(ii)); end myline = [myline sprintf(tpl_mfile_code,... flink, synopsis{indt(1)}, t)]; elseif any(strcmp(subname,t)) ii = find(strcmp(subname,t)); myline = [myline sprintf(tpl_mfile_code,... ['#_sub' num2str(ii)],... ['sub' subroutine{j}{ii}],t)]; else myline = [myline t]; end end end end matlabsource = [matlabsource sprintf(tpl_mfile_line,it,myline)]; it = it + 1; end tpl = set(tpl,'var','SOURCECODE',... horztab(matlabsource,options.tabs)); tpl = parse(tpl,'thesource','source'); else tpl = set(tpl,'var','thesource',''); end tpl = parse(tpl,'OUT','TPL_MFILE'); fprintf(fid,'%s',get(tpl,'OUT')); fclose(fid2); fclose(fid); end end end %=============================================================================== function mfiles = getmfiles(mdirs,mfiles,recursive) %- Extract M-files from a list of directories and/or M-files for i=1:length(mdirs) if exist(mdirs{i}) == 2 % M-file mfiles{end+1} = mdirs{i}; elseif exist(mdirs{i}) == 7 % Directory w = what(mdirs{i}); w = w(1); %- Sometimes an array is returned... for j=1:length(w.m) mfiles{end+1} = fullfile(mdirs{i},w.m{j}); end if recursive d = dir(mdirs{i}); d = {d([d.isdir]).name}; d = {d{~ismember(d,{'.' '..'})}}; for j=1:length(d) mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})),... mfiles,recursive); end end else fprintf('Warning: Unprocessed file %s.\n',mdirs{i}); end end %=============================================================================== function s = backtomaster(mdir) %- Provide filesystem path to go back to the root folder ldir = splitpath(mdir); s = repmat('../',1,length(ldir)); %=============================================================================== function ldir = splitpath(p) %- Split a filesystem path into parts using filesep as separator ldir = {}; p = deblank(p); while 1 [t,p] = strtok(p,filesep); if isempty(t), break; end if ~strcmp(t,'.') ldir{end+1} = t; end end if isempty(ldir) ldir{1} = '.'; % should be removed end %=============================================================================== function name = extractname(synopsis) if ischar(synopsis), synopsis = {synopsis}; end name = cell(size(synopsis)); for i=1:length(synopsis) ind = findstr(synopsis{i},'='); if isempty(ind) ind = findstr(synopsis{i},'function'); s = synopsis{i}(ind(1)+8:end); else s = synopsis{i}(ind(1)+1:end); end name{i} = strtok(s,[9:13 32 '(']); end if length(name) == 1, name = name{1}; end %=============================================================================== function f = fullurl(varargin) %- Build full url from parts (using '/' and not filesep) f = strrep(fullfile(varargin{:}),'\','/'); %=============================================================================== function str = entity(str) %- See http://www.w3.org/TR/html4/charset.html#h-5.3.2 str = strrep(str,'&','&amp;'); str = strrep(str,'<','&lt;'); str = strrep(str,'>','&gt;'); str = strrep(str,'"','&quot;'); %=============================================================================== function str = horztab(str,n) %- For browsers, the horizontal tab character is the smallest non-zero %- number of spaces necessary to line characters up along tab stops that are %- every 8 characters: behaviour obtained when n = 0. if n > 0 str = strrep(str,sprintf('\t'),blanks(n)); end
github
EPFL-LCSB/matTFA-master
qpsolng.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/glpkmex/qpsolng.m
2,447
utf_8
4b2e7f7c92565cb039eed9907693651d
% Core QP Solver. Use qpng.m instead. % % This routine solves the following optimization problem: % % min_x .5x' H x + q' x % s.t. Aeq x = beq % Ain x <= bin % % note that x0 is a feasible starting point. % % (C) Nicolo Giorgetti, 2006. function [x, lam, k, status]=qpsolng(H, q, Aeq, beq, Ain, bin, x0) nmax=200; % max number of iterations tol=1e-6; % tolerance neq=length(beq); % number of eqs nin=length(bin); % number of ineqs x=x0; n=size(x); Wact=[]; nact=0; % number of rows in Wact (only active inequalities) status=1; % problem feasible lam=zeros(neq+nin,1); k=[]; for k=1:nmax % Construct KKT K=H; r=-q-H*x; if neq > 0 % Add equality constraints A=Aeq; end if nin > 0 % Add active inequality constraints for j=1:nact i=Wact(j); if j+neq==1 A=Ain(i,:); else A=[A; Ain(i,:)]; end end end nneq=neq+nact; if nneq>0 K=[K, A'; A, zeros(nneq,nneq)]; r=[r; zeros(nneq,1)]; end y=K\r; %%%%%%%% Check this: we should use pinv instead. Possible numerical problems p=y(1:n); if norm(p)<tol % check optimality or add to work set if nact==0 x=x+p; status=1; return % successfully else lam=y(n+neq+1:n+neq+nact); [lmin,arg]=min(lam); if lmin >= 0 x=x+p; status=1; return; % successfully else % remove constraints from W nact=nact-1; for j=arg:nact Wact(j)=Wact(j+1); end end end else % x is not the minimizer in W count=nin+1; val(1:count)=1.1; for j=1:nin if Ain(j,1:n)*p > max(tol^2,1e-15) val(j)=(bin(j)-Ain(j,1:n)*x)/(Ain(j,1:n)*p); end end val(count)=1; [alpha,ind]=min(val); % this is the allowed step size x=x+alpha*p; if ind < count % there are blocking constraints, add one to W nact=nact+1; Wact(nact)=ind; end end end eq_infeas=0; in_infeas=0; if neq>0 eq_infeas = (norm(Aeq*x-beq) > rtol*(1+norm(beq))); end if nin>0 in_infeas = (any(Ain*x-bin > -rtol*(1+norm(bin)))); end if eq_infeas | in_infeas status=2; % Max iterations reached, no solution found. else status=3; % Max iterations reached but a feasible solution found. end return;
github
EPFL-LCSB/matTFA-master
qpng.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/glpkmex/qpng.m
8,266
utf_8
a76ee167df8e11072eea16b6f9407482
% Quadratic programming solver using a null-space active-set method. % % [x, obj, lambda, info] = qpng (H, q, A, b, ctype, lb, ub, x0) % % Solve the general quadratic program % % min 0.5 x'*H*x + q'*x % x % % subject to % A*x [ "=" | "<=" | ">=" ] b % lb <= x <= ub % % and given x0 as initial guess. % % ctype = An array of characters containing the sense of each constraint in the % constraint matrix. Each element of the array may be one of the % following values % 'U' Variable with upper bound ( A(i,:)*x <= b(i) ). % 'E' Fixed Variable ( A(i,:)*x = b(i) ). % 'L' Variable with lower bound ( A(i,:)*x >= b(i) ). % % status = an integer indicating the status of the solution, as follows: % 0 The problem is infeasible. % 1 The problem is feasible and convex. Global solution found. % 2 Max number of iterations reached no feasible solution found. % 3 Max number of iterations reached but a feasible solution found. % % If only 4 arguments are provided the following QP problem is solved: % % min_x .5 x'*H*x+x'*q s.t. A*x <= b % % Any bound (ctype, lb, ub, x0) may be set to the empty matrix [] % if not present. If the initial guess is feasible the algorithm is faster. % % See also: glpk. % % Copyright 2006-2007 Nicolo Giorgetti. % This file is part of GLPKMEX. % % GLPKMEX is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2, or (at your option) % any later version. % % GLPKMEX is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with GLPKMEX; see the file COPYING. If not, write to the Free % Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA. function varargout = qpng (varargin) % Inputs H=[]; q=[]; A=[]; b=[]; lb=[]; ub=[]; x0=[]; ctype=[]; % Outputs x=[]; obj=[]; lambda=[]; info=[]; if nargin < 1 disp('Quadratic programming solver using null-space active set method.'); disp('(C) 2006-2007, Nicolo Giorgetti. Version 1.0'); disp(' '); disp('Syntax: [x, obj, lambda, info] = qpng (H, q, A, b, ctype, lb, ub, x0)'); return; end if nargin<4 error('At least 4 argument are necessary'); else H=varargin{1}; q=varargin{2}; A=varargin{3}; b=varargin{4}; end if nargin>=5 ctype=varargin{5}; end if nargin>=7 lb=varargin{6}; ub=varargin{7}; end if nargin>=8 x0=varargin{8}; end if nargin>8 warning('qpng: Arguments more the 8th are omitted'); end % Checking the quadratic penalty [n,m] = size(H); if n ~= m error('qpng: Quadratic penalty matrix not square'); end if H ~= H' warning('qpng: Quadratic penalty matrix not symmetric'); H = (H + H')/2; end % Linear penalty. if isempty(q) q=zeros(n,1); else if length(q) ~= n error('qpng: The linear term has incorrect length'); end end % Constraint matrices if (isempty(A) || isempty(b)) error('qpng: Constraint matrices cannot be empty'); end [nn, n1] = size(A); if n1 ~= n error('qpng: Constraint matrix has incorrect column dimension'); end if length (b) ~= nn error ('qpng: Equality constraint matrix and vector have inconsistent dimension'); end Aeq=[]; beq=[]; Ain=[]; bin=[]; if nargin <= 4 Ain=A; bin=b; end if ~isempty(ctype) if length(ctype) ~= nn tmp=sprintf('qpng: ctype must be a char valued vector of length %d', nn); error(tmp); end indE=find(ctype=='E'); Aeq=A(indE,:); beq=b(indE,:); indU=find(ctype=='U'); Ain=A(indU,:); bin=b(indU,:); indL=find(ctype=='L'); Ain=[Ain; -A(indL,:)]; bin=[bin; -b(indL,:)]; end if ~isempty(lb) if length(lb) ~= n error('qpng: Lower bound has incorrect length'); else Ain = [Ain; -eye(n)]; bin = [bin; -lb]; end end if ~isempty(ub) if length(ub) ~= n error('qpng: Upper bound has incorrect length'); else Ain = [Ain; eye(n)]; bin = [bin; ub]; end end % Discard inequality constraints that have -Inf bounds since those % will never be active. idx = isinf(bin) & (bin > 0); bin(idx) = []; Ain(idx,:) = []; % Now we should have the following QP: % % min_x 0.5*x'*H*x + q'*x % s.t. A*x = b % Ain*x <= bin % Checking the initial guess (if empty it is resized to the % right dimension and filled with 0) if isempty(x0) x0 = zeros(n, 1); elseif length(x0) ~= n error('qpng: The initial guess has incorrect length'); end % Check if the initial guess is feasible. rtol = sqrt (eps); n_eq=size(Aeq,1); n_in=size(Ain,1); eq_infeasible=0; in_infeasible=0; if n_eq>0 eq_infeasible = (norm(Aeq*x0-beq) > rtol*(1+norm(beq))); end if n_in>0 in_infeasible = any(Ain*x0-bin > 0); end status = 1; % if (eq_infeasible | in_infeasible) % % The initial guess is not feasible. Find one by solving an LP problem. % % This function has to be improved by moving in the null space. % Atmp=[Aeq; Ain]; % btmp=[beq; bin]; % ctmp=zeros(size(Atmp,2),1); % ctype=char(['S'*ones(1,n_eq), 'U'*ones(1,n_in)]'); % [P, dummy, stat] = glpk (ctmp, Atmp, btmp, [], [], ctype); % % if (stat == 180 | stat == 181 | stat == 151) % x0=P; % else % % The problem is infeasible % status = 0; % end % % end if (eq_infeasible | in_infeasible) % The initial guess is not feasible. % First define xbar that is feasible with respect to the equality % constraints. if (eq_infeasible) if (rank(Aeq) < n_eq) error('qpng: Equality constraint matrix must be full row rank') end xbar = pinv(Aeq) * beq; else xbar = x0; end % Check if xbar is feasible with respect to the inequality % constraints also. if (n_in > 0) res = Ain * xbar - bin; if any(res > 0) % xbar is not feasible with respect to the inequality % constraints. Compute a step in the null space of the % equality constraints, by solving a QP. If the slack is % small, we have a feasible initial guess. Otherwise, the % problem is infeasible. if (n_eq > 0) Z = null(Aeq); if (isempty(Z)) % The problem is infeasible because A is square and full % rank, but xbar is not feasible. info = 0; end end if info % Solve an LP with additional slack variables to find % a feasible starting point. gamma = eye(n_in); if (n_eq > 0) Atmp = [Ain*Z, gamma]; btmp = -res; else Atmp = [Ain, gamma]; btmp = bin; end ctmp = [zeros(n-n_eq, 1); ones(n_in, 1)]; lb = [-Inf*ones(n-n_eq,1); zeros(n_in,1)]; ub = []; ctype = repmat ('L', n_in, 1); [P, dummy, status] = glpk (ctmp, Atmp, btmp, lb, ub, ctype); if ((status == 180 | status == 181 | status == 151) & all (abs (P(n-n_eq+1:end)) < rtol * (1 + norm (btmp)))) % We found a feasible starting point if (n_eq > 0) x0 = xbar + Z*P(1:n-n_eq); else x0 = P(1:n); end else % The problem is infeasible info = 0; end end else % xbar is feasible. We use it a starting point. x0 = xbar; end else % xbar is feasible. We use it a starting point. x0 = xbar; end end if status % The initial (or computed) guess is feasible. % We call the solver. t=cputime; [x, lambda, iter, status]=qpsolng(H, q, Aeq, beq, Ain, bin, x0); time=cputime-t; else iter = 0; x = x0; lambda = []; time=0; end varargout{1}= x; varargout{2}= 0.5 * x' * H * x + q' * x; %obj varargout{3}= lambda; info=struct('status', status, 'solveiter', iter, 'time', time); varargout{4}=info;
github
EPFL-LCSB/matTFA-master
glpk.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/glpkmex/glpk.m
20,365
utf_8
d8e67c6977ba79760299289ebfca225f
% Matlab MEX interface for the GLPK library % % [xopt, fmin, status, extra] = glpk (c, a, b, lb, ub, ctype, vartype, % sense, param) % % Solve an LP/MILP problem using the GNU GLPK library. Given three % arguments, glpk solves the following standard LP: % % min C'*x subject to A*x <= b % % but may also solve problems of the form % % [ min | max ] C'*x % subject to % A*x [ "=" | "<=" | ">=" ] b % x >= LB % x <= UB % % Input arguments: % c = A column array containing the objective function coefficients. % % A = A matrix containing the constraints coefficients. % % b = A column array containing the right-hand side value for each constraint % in the constraint matrix. % % lb = An array containing the lower bound on each of the variables. If % lb is not supplied (or an empty array) the default lower bound for the variables is % minus infinite. % % ub = An array containing the upper bound on each of the variables. If % ub is not supplied (or an empty array) the default upper bound is assumed to be % infinite. % % ctype = An array of characters containing the sense of each constraint in the % constraint matrix. Each element of the array may be one of the % following values % 'F' Free (unbounded) variable (the constraint is ignored). % 'U' Variable with upper bound ( A(i,:)*x <= b(i)). % 'S' Fixed Variable (A(i,:)*x = b(i)). % 'L' Variable with lower bound (A(i,:)*x >= b(i)). % 'D' Double-bounded variable (A(i,:)*x >= -b(i) and A(i,:)*x <= b(i)). % % vartype = A column array containing the types of the variables. % 'C' Continuous variable. % 'I' Integer variable % 'B' Binary variable % % sense = If sense is 1, the problem is a minimization. If sense is % -1, the problem is a maximization. The default value is 1. % % param = A structure containing the following parameters used to define the % behavior of solver. Missing elements in the structure take on default % values, so you only need to set the elements that you wish to change % from the default. % % Integer parameters: % msglev (default: 1) % Level of messages output by solver routines: % 0 - No output. % 1 - Error messages only. % 2 - Normal output. % 3 - Full output (includes informational messages). % % scale (default: 1). Scaling option: % 0 - No scaling. % 1 - Equilibration scaling. % 2 - Geometric mean scaling, then equilibration scaling. % 3 - Geometric then Equilibrium scaling % 4 - Round to nearest power of 2 scaling % % dual (default: 0). Dual simplex option: % 0 - Do not use the dual simplex. % 1 - If initial basic solution is dual feasible, use % the dual simplex. % 2- Use two phase dual simplex, or if primal simplex % if dual fails % % price (default: 1). Pricing option (for both primal and dual simplex): % 0 - Textbook pricing. % 1 - Steepest edge pricing. % % r_test (default: 1). Ratio test Technique: % 0 - stardard (textbook) % 1 - Harris's two-pass ratio test % % round (default: 0). Solution rounding option: % % 0 - Report all primal and dual values "as is". % 1 - Replace tiny primal and dual values by exact zero. % % itlim (default: -1). Simplex iterations limit. % If this value is positive, it is decreased by one each % time when one simplex iteration has been performed, and % reaching zero value signals the solver to stop the search. % Negative value means no iterations limit. % % itcnt (default: 200). Output frequency, in iterations. % This parameter specifies how frequently the solver sends % information about the solution to the standard output. % % presol (default: 1). If this flag is set, the routine % lpx_simplex solves the problem using the built-in LP presolver. % Otherwise the LP presolver is not used. % % lpsolver (default: 1) Select which solver to use. % If the problem is a MIP problem this flag will be ignored. % 1 - Revised simplex method. % 2 - Interior point method. % 3 - Simplex method with exact arithmatic. % % branch (default: 2). Branching heuristic option (for MIP only): % 0 - Branch on the first variable. % 1 - Branch on the last variable. % 2 - Branch on the most fractional variable. % 3 - Branch using a heuristic by Driebeck and Tomlin. % % btrack (default: 2). Backtracking heuristic option (for MIP only): % 0 - Depth first search. % 1 - Breadth first search. % 2 - best local bound % 3 - Backtrack using the best projection heuristic. % % pprocess (default: 2) Pre-processing technique option ( for MIP only ): % 0 - disable preprocessing % 1 - perform preprocessing for root only % 2 - perform preprocessing for all levels % % usecuts (default: 1). ( for MIP only ): % glp_intopt generates and adds cutting planes to % the MIP problem in order to improve its LP relaxation % before applying the branch&bound method % 0 -> all cuts off % 1 -> Gomoy's mixed integer cuts % 2 -> Mixed integer rounding cuts % 3 -> Mixed cover cuts % 4 -> Clique cuts % 5 -> all cuts % % binarize (default: 0 ) Binarizeation option ( for mip only ): % ( used only if presolver is enabled ) % 0 -> do not use binarization % 1 -> replace general integer variables by binary ones % % save (default: 0). If this parameter is nonzero save a copy of % the original problem to file. You can specify the % file name and format by using the 'savefilename' and 'savefiletype' % parameters (see in String Parameters Section here below). % If previous parameters are not defined the original problem % is saved with CPLEX LP format in the default file "outpb.lp". % % mpsinfo (default: 1) If this is set, % the interface writes to file several comment cards, % which contains some information about the problem. % Otherwise the routine writes no comment cards. % % mpsobj ( default: 2) This parameter tells the % routine how to output the objective function row: % 0 - never output objective function row % 1 - always output objective function row % 2 - output objective function row if the problem has % no free rows % % mpsorig (default: 0) If this is set, the % routine uses the original symbolic names of rows and % columns. Otherwise the routine generates plain names % using ordinal numbers of rows and columns. % % mpswide (default: 1) If this is set, the % routine uses all data fields. Otherwise the routine % keeps fields 5 and 6 empty. % % mpsfree (default: 0) If this is set, the routine % omits column and vector names every time when possible % (free style). Otherwise the routine never omits these % names (pedantic style). % % % Real parameters: % relax (default: 0.07). Relaxation parameter used % in the ratio test. If it is zero, the textbook ratio test % is used. If it is non-zero (should be positive), Harris' % two-pass ratio test is used. In the latter case on the % first pass of the ratio test basic variables (in the case % of primal simplex) or reduced costs of non-basic variables % (in the case of dual simplex) are allowed to slightly violate % their bounds, but not more than relax*tolbnd or relax*toldj % (thus, relax is a percentage of tolbnd or toldj). % % tolbnd (default: 10e-7). Relative tolerance used % to check ifthe current basic solution is primal feasible. % It is not recommended that you change this parameter % unless you have a detailed understanding of its purpose. % % toldj (default: 10e-7). Absolute tolerance used to % check if the current basic solution is dual feasible. It % is not recommended that you change this parameter unless % you have a detailed understanding of its purpose. % % tolpiv (default: 10e-9). Relative tolerance used % to choose eligible pivotal elements of the simplex table. % It is not recommended that you change this parameter % unless you have a detailed understanding of its purpose. % % objll ( default: -DBL_MAX). Lower limit of the % objective function. If on the phase II the objective % function reaches this limit and continues decreasing, the % solver stops the search. This parameter is used in the % dual simplex method only. % % objul (default: +DBL_MAX). Upper limit of the % objective function. If on the phase II the objective % function reaches this limit and continues increasing, % the solver stops the search. This parameter is used in % the dual simplex only. % % tmlim (default: -1.0). Searching time limit, in % seconds. If this value is positive, it is decreased each % time when one simplex iteration has been performed by the % amount of time spent for the iteration, and reaching zero % value signals the solver to stop the search. Negative % value means no time limit. % % outdly (default: 0.0). Output delay, in seconds. % This parameter specifies how long the solver should % delay sending information about the solution to the standard % output. Non-positive value means no delay. % % tolint (default: 10e-5). Relative tolerance used % to check if the current basic solution is integer % feasible. It is not recommended that you change this % parameter unless you have a detailed understanding of % its purpose. % % tolobj (default: 10e-7). Relative tolerance used % to check if the value of the objective function is not % better than in the best known integer feasible solution. % It is not recommended that you change this parameter % unless you have a detailed understanding of its purpose. % % mipgap (default: 0.0) The relative mip gap tolerance. If the % relative mip gap for currently known best integer feasible % solution falls below this tolerance, the solver terminates % the search. This allows obtaining suboptimal interger % feasible solutions if solving the problem to optimality % takes too long. % % String Parameters: % savefilename (default: "outpb"). Specify the name to use to % save the original problem. MEX interface looks for % this parameter if 'save' parameter is set to 1. If % no name is provided "outpb" will be used. % savefiletype (default: CPLEX format). Specify the format type % used to save the file. Only the following options % are allowed: % 'fixedmps' - fixed MPS format (.mps). % 'freemps' - free MPS format (.mps). % 'cplex' - CPLEX LP format (.lp). % 'plain' - plain text (.txt). % % Output values: % xopt = The optimizer (the value of the decision variables at the optimum). % % fopt = The optimum value of the objective function. % % status = Status of the optimization. % 1 solution is undefined % 2 solution is feasible % 3 solution is infeasible % 4 no feasible solution exists % 5 solution is optimal % 6 solution is unbounded % % If an error occurs, status will contain one of the following % codes. % Simplex method: % 101 invalid basis % 102 singular matrix % 103 ill-conditioned matrix % 104 invalid bounds % 105 solver failed % 106 objective lower limit reached % 107 objective upper limit reached % 108 iteration limit exceeded % 109 time limit exceeded % 110 no primal feasible solution % % Interior point method, mixed integer problem: % 204 Unable to start the search. % 205 Objective function lower limit reached. % 206 Objective function upper limit reached. % 207 Iterations limit exhausted. % 208 Time limit exhausted. % 209 No feasible solution. % 210 Numerical instability. % 211 Problems with basis matrix. % 212 No convergence (interior). % 213 No primal feasible solution (LP presolver). % 214 No dual feasible solution (LP presolver). % % extra = A data structure containing the following fields: % lambda - Dual variables. % redcosts - Reduced Costs. % time - Time (in seconds) used for solving LP/MIP problem. % mem - Memory (in Kbytes) used for solving LP/MIP problem. % % Example: % % c = [10, 6, 4]'; % a = [ 1, 1, 1; % 10, 4, 5; % 2, 2, 6]; % b = [100, 600, 300]'; % lb = [0, 0, 0]'; % ub = []; % ctype = "UUU"; % vartype = "CCC"; % s = -1; % % param.msglev = 1; % param.itlim = 100; % % [xmin, fmin, status, extra] = ... % glpk (c, a, b, lb, ub, ctype, vartype, s, param); % % See also: qpng. % % Copyright 2005-2007 Nicolo' Giorgetti % Email: Nicolo' Giorgetti <giorgetti __at __ ieee.org> % updated by Niels Klitgord March 2009 % Email: Niels Klitgord <niels __at__ bu.edu> % This file is part of GLPKMEX. % % GLPKMEX is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2, or (at your option) % any later version. % % This part of code is distributed with the FURTHER condition that it % can be linked to the Matlab libraries and/or use it inside the Matlab % environment. % % GLPKMEX is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with GLPKMEX; see the file COPYING. If not, write to the Free % Software Foundation, 59 Temple Place - Suite 330, Boston, MA % 02111-1307, USA. function [xopt,fmin,status,extra] = glpk (c,a,b,lb,ub,ctype,vartype,sense,param) % If there is no input output the version and syntax if (nargin < 3 || nargin > 9) disp('GLPK Matlab interface. Version: 2.7'); disp('(C) 2001-2007, Nicolo'' Giorgetti.'); disp('Maintained by Niels Klitgord'); disp(' '); disp('Syntax: [xopt,fopt,status,extra]=glpk(c,a,b,lb,ub,ctype,vartype,sense,param)'); return; end if (all(size(c) > 1) || ~isreal(c) || ischar(c)) error('C must be a real vector'); end % clears glpkcc mex function from memory to deal with param bug % this is because params not specificly set default to the last used rather % than internal defaults for some reason.... clear glpkcc; nx = length (c); % 1) Force column vector. c = c(:); % 2) Matrix constraint if (isempty(a)) error('A cannot be an empty matrix'); end [nc, nxa] = size(a); if (~isreal(a) || nxa ~= nx) tmp=sprintf('A must be a real valued %d by %d matrix', nc, nx); error(tmp); return; end % 3) RHS if (isempty(b)) error('B cannot be an empty vector'); end if (~isreal(b) || length(b) ~= nc) tmp=sprintf('B must be a real valued %d by 1 vector', nc); error (tmp); return; end % 4) Vector with the lower bound of each variable if (nargin > 3) if (isempty(lb)) lb = repmat(-Inf, nx, 1); elseif (~isreal(lb) || all(size(lb) > 1) || length(lb) ~= nx) tmp=sprintf('LB must be a real valued %d by 1 column vector', nx); error (tmp); return; end else lb = -Inf*ones(nx, 1); end % 5) Vector with the upper bound of each variable if (nargin > 4) if (isempty(ub)) ub = repmat(Inf, nx, 1); elseif (~isreal(ub) || all(size(ub) > 1) || length(ub) ~= nx) tmp=sprintf('UB must be a real valued %d by 1 column vector', nx); error (tmp); return; end else ub = repmat(Inf, nx, 1); end % 6) Sense of each constraint if (nargin > 5) if (isempty (ctype)) ctype = repmat('U', nc, 1); elseif (~ischar(ctype) || all(size(ctype) > 1) || length(ctype) ~= nc) tmp=sprintf('CTYPE must be a char valued vector of length %d', nc); error(tmp); return; else for i=1:length(ctype) switch(ctype(i)) case {'f','F'}, % do nothing case {'u','U'}, % do nothing case {'s','S'}, % do nothing case {'l','L'}, % do nothing case {'d','D'}, % do nothing otherwise tmp=sprintf('CTYPE must contain only F, U, S, L, or D'); error(tmp); end end end else ctype= repmat('U', nc, 1); end % 7) Vector with the type of variables if (nargin > 6) if isempty(vartype) vartype = repmat('C', nx, 1); elseif (~ischar(vartype) || all(size(vartype) > 1) || length (vartype) ~= nx) tmp=sprintf('VARTYPE must be a char valued vector of length %d', nx); error(tmp); return; else for i=1:length(vartype) switch(vartype(i)) case {'c','C'}, % do nothing case {'i','I'}, % do nothing case {'b','B'}, % do nothing otherwise tmp=sprintf('VARTYPE must contain only C, I or B'); error(tmp); end end end else % As default we consider continuous vars vartype = repmat('C', nx, 1); end % 8) Sense of optimization if (nargin >7) if isempty(sense) sense=1; elseif (ischar(sense) || all(size(sense) > 1) || ~isreal(sense)) tmp=sprintf('SENSE must be an integer value'); error(tmp); elseif sense>=0 sense=1; else sense=-1; end else sense=1; end % 9) Parameters vector if (nargin > 8) if (~isstruct(param)) error('PARAM must be a structure'); end else if str2double(version('-release'))<36 param =struct; else param = struct([]); end end [xopt, fmin, status, extra] = glpkcc(c, a, b, lb, ub, ctype, vartype, sense, param);
github
EPFL-LCSB/matTFA-master
glpkmex.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/glpkmex/glpkmex.m
3,052
utf_8
33b5f8ff88c0469e04a4e77cd09ef9da
% ***OBSOLETE*** GLPKMEX interface. Use glpk instead. % % [xmin,fmin,status,extra]=glpkmex(sense,c,a,b,ctype,lb,ub,vartype,param,lp,solver,save) % % This function is provided for compatibility with the old Matlab % interface to the GNU GLPK library. You should use the glpk function % instead. % % See also: glpk, qpng. % % Copyright 2001-2007, Nicolo' Giorgetti % This file is part of GLPKMEX. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2, or (at your option) % any later version. % % This part of code is distributed with the FURTHER condition that it is % possible to link it to the Matlab libraries and/or use it inside the Matlab % environment. % % GLPKMEX is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with GLPKMEX; see the file COPYING. If not, write to the Free % Software Foundation, 59 Temple Place - Suite 330, Boston, MA % 02111-1307, USA. function [xopt, fopt, status, extra] = glpkmex (varargin) % If there is no input output the version and syntax if (nargin < 4 || nargin > 11) disp('***OLD*** GLPK Matlab interface.'); disp('(C) 2001-2007, Nicolo'' Giorgetti.'); disp(' '); disp('[xopt,fopt,status,extra] = glpkmex(sense,c,a,b,ctype,lb,ub,vartype,param,lpsolver,savepb'); return; end % reorder args: % % glpkmex glpk % % 1 sense c % 2 c a % 3 a b % 4 b lb % 5 ctype ub % 6 lb ctype % 7 ub vartype % 8 vartype sense % 9 param param % 10 lpsolver % 11 savepb sense = varargin{1}; c = varargin{2}; a = varargin{3}; b = varargin{4}; nx = length (c); if (nargin > 4) ctype = varargin{5}; else ctype = repmat ('U', nx, 1); end if (nargin > 5) lb = varargin{6}; else lb = repmat (-Inf, nx, 1); end if (nargin > 6) ub = varargin{7}; else ub = repmat (Inf, nx, 1); end if (nargin > 7) vartype = varargin{8}; else vartype = repmat ('C', nx, 1); end if (nargin > 8) param = varargin{9}; else param = struct (); end if (nargin > 9 && ~isfield(param, 'lpsolver')) param.lpsolver = varargin{10}; end if (nargin > 10 && ~isfield(param, 'save')) param.save = varargin{11}; end if (nargout == 0) glpk (c, a, b, lb, ub, ctype, vartype, sense, param); elseif (nargout == 1) xopt = glpk (c, a, b, lb, ub, ctype, vartype, sense, param); elseif (nargout == 2) [xopt, fopt] = glpk (c, a, b, lb, ub, ctype, vartype, sense, param); elseif (nargout == 3) [xopt, fopt, status] = ... glpk (c, a, b, lb, ub, ctype, vartype, sense, param); else [xopt, fopt, status, extra] = ... glpk (c, a, b, lb, ub, ctype, vartype, sense, param); end
github
EPFL-LCSB/matTFA-master
isBindingInstalled.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/isBindingInstalled.m
3,030
utf_8
fd7bfb0254686f102c3dfc6170e65038
function installed = isBindingInstalled() % installed = isBindingInstalled() % % Returns % % 1. installed = % - 1 if the libSBML executables are installed % - 0 otherwise % % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> installed = 1; if (~exist('OCTAVE_VERSION')) filename = fullfile(tempdir, 'test.xml'); outFile = fullfile(tempdir, 'test-out.xml'); else if isWindows() filename = fullfile(pwd, 'test.xml'); outFile = [tempdir, 'temp', filesep, 'test-out.xml']; else filename = fullfile(pwd, 'test.xml'); outFile = [tempdir, 'test-out.xml']; end; end; writeTempFile(filename); try M = TranslateSBML(filename); catch installed = 0; return; end; if (installed == 1) try OutputSBML(M, outFile, 1); catch installed = 0; return; end; end; delete(filename); delete(outFile); % % % Is this windows % Mac OS X 10.7 Lion returns true for a call to ispc() % since we were using that to distinguish between windows and macs we need % to catch this % ------------------------------------------------------------------------ function y = isWindows() y = 1; if isunix() y = 0; return; end; if ismac() y = 0; return; end; if ~ispc() message = sprintf('\n%s\n%s\n', ... 'Unable to determine the type of operating system in use.', ... 'Please contact [email protected] to help resolve this problem.'); error(message); end; % write out a temporary file function writeTempFile(filename) fout = fopen(filename, 'w'); fprintf(fout, '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n'); fprintf(fout, '<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" '); fprintf(fout, 'level=\"3\" version=\"1\">\n'); fprintf(fout, ' <model/>\n</sbml>\n'); fclose(fout);
github
EPFL-LCSB/matTFA-master
install.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/install.m
9,088
utf_8
881213623382d9ea90f52aa2142f33e7
function install % install % % 1. reports whether the libsbml binding is installed % 2. adds the toolbox dirctories to the Path %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % ========================================================================= % Main loop. % ========================================================================= disp(sprintf('\nInstalling the SBMLToolbox.\n')); [matlab_octave, bit64] = check_system(); disp(sprintf('\nChecking for libSBML %s binding\n', matlab_octave)); if isBindingInstalled() == 1 disp(sprintf('libSBML %s binding found and working\n', matlab_octave)); else disp(sprintf('libSBML %s binding not found\n\n%s\n%s\n%s', matlab_octave, ... 'NOTE: This is not a fatal error.', ... 'You will not be able to import or export SBML but can still use the toolbox', ... 'to create and manipulate MATLAB_SBML structures')); end; % add the current directory and all subdirectories to the MATLAB search % path ToolboxPath = genpath(pwd); addpath(ToolboxPath); s = savepath; if (s ~= 0) disp(sprintf('\nInstallation failed\n%s', ... 'The directories were not added to the Path')); else disp(sprintf('\nInstallation successful')); end; % ========================================================================= % Support functions. % ========================================================================= % % Assess our computing environment. % ------------------------------------------------------------------------- function [matlab_octave, bit64] = check_system() disp('* Doing preliminary checks of runtime environment ...'); if (~exist('OCTAVE_VERSION')) matlab_octave = 'MATLAB'; disp(' - This appears to be MATLAB and not Octave.'); else matlab_octave = 'Octave'; disp(' - This appears to be Octave and not MATLAB.'); end; bit64 = 32; if ispc() if strcmp(computer(), 'PCWIN64') == 1 bit64 = 64; disp(sprintf(' - %s reports the OS is Windows 64-bit.', matlab_octave)); else disp(sprintf(' - %s reports the OS is Windows 32-bit.', matlab_octave)); end; elseif ismac() if strcmp(computer(), 'MACI64') == 1 bit64 = 64; disp(sprintf(' - %s reports the OS is 64-bit MacOS.', matlab_octave)); else % Reading http://www.mathworks.com/help/techdoc/ref/computer.html % it is still not clear to me what a non-64-bit MacOS will report. % Let's not assume the only other alternative is 32-bit, since we % actually don't care here. Let's just say "macos". % disp(sprintf(' - %s reports the OS is MacOS.', matlab_octave)); end; elseif isunix() if strcmp(computer(), 'GLNXA64') == 1 bit64 = 64; disp(sprintf(' - %s reports the OS is 64-bit Linux.', matlab_octave)); else disp(sprintf(' - %s reports the OS is 32-bit Linux.', matlab_octave)); end; end; % % Assess our location in the file system. % ------------------------------------------------------------------------- % Possible values returned: % LOCATION: % 'installed' -> installation directory % 'source' -> libsbml source tree % % WRITEACCESS: % 1 -> we can write in this directory % 0 -> we can't write in this directory % function [location, writeAccess, in_installer] = check_location(matlab_octave, ... functioning) myDisp('* Trying to establish our location ...', functioning); % This is where things get iffy. There are a lot of possibilities, and % we have to resort to heuristics. % % Linux and Mac: we look for 2 possibilities % - installation dir ends in "libsbml/bindings/matlab" % Detect it by looking for ../../VERSION.txt. % Assume we're in .../share/libsbml/bindings/matlab and that our % library is in .../lib/ % % - source dir ends in "libsbml/src/bindings/matlab" % Detect it by looking for ../../../VERSION.txt. % Assume our library is in ../../ % in_installer = 0; [remain, first] = fileparts(pwd); if strcmpi(matlab_octave, 'matlab') if ~strcmp(first, 'matlab') if ~ispc() error_incorrect_dir('matlab'); else in_installer = 1; end; else myDisp(' - We are in the libSBML subdirectory for Matlab.', functioning); end; else if ~strcmp(first, 'octave') if ~ispc() error_incorrect_dir('octave'); else in_installer = 1; end; else myDisp(' - We are in the libSBML subdirectory for Octave.', functioning); end; end; location = ''; % if in_installer == 1 then we are in the windows installer but in % path provided by the user % checking further is pointless if (in_installer == 0) [above_bindings, bindings] = fileparts(remain); if exist(fullfile(above_bindings, 'VERSION.txt')) myDisp(' - We appear to be in the installation target directory.', functioning); in_installer = 1; if ispc() location = above_bindings; else location = 'installed'; end; else [libsbml_root, src] = fileparts(above_bindings); if exist(fullfile(libsbml_root, 'Makefile.in')) myDisp(' - We appear to be in the libSBML source tree.', functioning); if ispc() location = libsbml_root; else location = 'source'; end; else if ispc() % we might be in the windows installer but in a location the user chose % for the bindings % Makefile.in will not exist in this directory if (exist([pwd, filesep, 'Makefile.in']) == 0) in_installer = 1; else % We don't know where we are. if strcmpi(matlab_octave, 'MATLAB') error_incorrect_dir('matlab'); else error_incorrect_dir('octave'); end; end; else % We don't know where we are. if strcmpi(matlab_octave, 'MATLAB') error_incorrect_dir('matlab'); else error_incorrect_dir('octave'); end; end; end; end; end; % if we are in the windows installer but in a location the user chose % for the bindings % we need the user to tell use the root directory for the rest of libsbml % unless we are already functioning if (ispc() && functioning == 0 && in_installer == 1 && isempty(location)) count = 1; while(exist(location, 'dir') == 0 && count < 3) location = input(sprintf('%s: ', ... 'Please enter the location of the top-level libsbml directory'), 's'); count = count + 1; end; if (exist(location, 'dir') == 0) error('Failed to find libsbml directory'); end; end; % Test that it looks like we have the expected pieces in this directory. % We don't want to assume particular paths, because we might be % getting run from the libSBML source tree or the installed copy of % the matlab bindings sources. So, we test for just a couple of % things: the tail of the name of the directory in which this file is % located (should be either "matlab" or "octave") and the presence of % another file, "OutputSBML.c", which became part of libsbml at the % same time this new build scheme was introduced. our_name = sprintf('%s.m', mfilename); other_name = 'OutputSBML.c'; if ~exist(fullfile(pwd, our_name), 'file') ... || ~exist(fullfile(pwd, other_name), 'file') error_incorrect_dir('matlab'); end; % Check whether we have write access to this directory. fid = fopen('temp.txt', 'w'); writeAccess = 1; if fid == -1 myDisp(' - We do not have write access here -- will write elsewhere.', functioning); writeAccess = 0; else myDisp(' - We have write access here! That makes us happy.', functioning); fclose(fid); delete('temp.txt'); end;
github
EPFL-LCSB/matTFA-master
isBindingFbcEnabled.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/fbc_package/isBindingFbcEnabled.m
2,265
utf_8
8cb0fb5729183cd42636bc97918fb7e8
function fbcEnabled = isBindingFbcEnabled() % fbcEnabled = isBindingFbcEnabled() % % Returns % % 1. fbcEnabled = % - 1 if the executables are enabled with fbc support % - 0 otherwise % % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % assume not enabled fbcEnabled = 0; if isBindingInstalled() == 0 return; end; if (isoctave() == '0') filename = fullfile(tempdir, 'fbc.xml'); else filename = fullfile(pwd, 'fbc.xml'); end; writeTempFile(filename); try [m, e] = TranslateSBML(filename, 1, 0); if (length(e) == 0 && isfield(m, 'fbc_version') == 1 ) fbcEnabled = 1; end; delete(filename); catch delete(filename); return end; function writeTempFile(filename) fout = fopen(filename, 'w'); fprintf(fout, '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n'); fprintf(fout, '<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" '); fprintf(fout, 'xmlns:fbc=\"http://www.sbml.org/sbml/level3/version1/fbc/version1\" '); fprintf(fout, 'level=\"3\" version=\"1\" fbc:required=\"true\">\n'); fprintf(fout, ' <model/>\n</sbml>\n'); fclose(fout);
github
EPFL-LCSB/matTFA-master
bind_isSBML_Model.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Validate_MATLAB_SBML_Structures/bind_isSBML_Model.m
139,862
utf_8
6b19c286b430b99baed148584e663c49
function [valid, message] = isValidSBML_Model(SBMLStructure) % [valid, message] = isValidSBML_Model(SBMLModel) % % Takes % % 1. SBMLModel, an SBML Model structure % % Returns % % 1. valid = % - 1, if the structure represents % a MATLAB_SBML Model structure of the appropriate % level and version % - 0, otherwise % 2. a message explaining any failure % % *NOTE:* The fields present in a MATLAB_SBML Model structure of the appropriate % level and version can be found using getModelFieldnames(level, version) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2011 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> %check the input arguments are appropriate if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; if ~isempty(SBMLStructure) if isfield(SBMLStructure, 'SBML_level') level = SBMLStructure.SBML_level; else level = 3; end; if isfield(SBMLStructure, 'SBML_version') version = SBMLStructure.SBML_version; else version = 1; end; else level = 3; version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_MODEL'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_MODEL', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; %check that any nested structures are appropriate % functionDefinitions if (valid == 1 && level > 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.functionDefinition)) [valid, message] = isSBML_FunctionDefinition( ... SBMLStructure.functionDefinition(index), ... level, version); index = index + 1; end; end; % unitDefinitions if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.unitDefinition)) [valid, message] = isSBML_UnitDefinition( ... SBMLStructure.unitDefinition(index), ... level, version); index = index + 1; end; end; % compartments if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.compartment)) [valid, message] = isSBML_Compartment(SBMLStructure.compartment(index), ... level, version); index = index + 1; end; end; % species if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.species)) [valid, message] = isSBML_Species(SBMLStructure.species(index), ... level, version); index = index + 1; end; end; % compartmentTypes if (valid == 1 && level == 2 && version > 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.compartmentType)) [valid, message] = isSBML_CompartmentType(SBMLStructure.compartmentType(index), ... level, version); index = index + 1; end; end; % speciesTypes if (valid == 1 && level == 2 && version > 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.speciesType)) [valid, message] = isSBML_SpeciesType(SBMLStructure.speciesType(index), ... level, version); index = index + 1; end; end; % parameter if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.parameter)) [valid, message] = isSBML_Parameter(SBMLStructure.parameter(index), ... level, version); index = index + 1; end; end; % initialAssignment if (valid == 1 && (level > 2 || (level == 2 && version > 1))) index = 1; while (valid == 1 && index <= length(SBMLStructure.initialAssignment)) [valid, message] = isSBML_InitialAssignment( ... SBMLStructure.initialAssignment(index), ... level, version); index = index + 1; end; end; % rule if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.rule)) [valid, message] = isSBML_Rule(SBMLStructure.rule(index), ... level, version); index = index + 1; end; end; % constraints if (valid == 1 && (level > 2 || (level == 2 && version > 1))) index = 1; while (valid == 1 && index <= length(SBMLStructure.constraint)) [valid, message] = isSBML_Constraint( ... SBMLStructure.constraint(index), ... level, version); index = index + 1; end; end; % reaction if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.reaction)) [valid, message] = isSBML_Reaction(SBMLStructure.reaction(index), ... level, version); index = index + 1; end; end; % event if (valid == 1 && level > 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.event)) [valid, message] = isSBML_Event(SBMLStructure.event(index), ... level, version); index = index + 1; end; end; % report failure if (valid == 0) message = sprintf('Invalid Model structure\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_AlgebraicRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_ALGEBRAIC_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_ALGEBRAIC_RULE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid AlgebraicRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_AssignmentRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_ASSIGNMENT_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (level > 1) if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else % check L1 types typecode = SBMLStructure.typecode; cvr = strcmp(typecode, 'SBML_COMPARTMENT_VOLUME_RULE'); pr = strcmp(typecode, 'SBML_PARAMETER_RULE'); scr = strcmp(typecode, 'SBML_SPECIES_CONCENTRATION_RULE'); if (cvr ~= 1 && pr ~= 1 && scr ~= 1) valid = 0; message = 'typecode mismatch'; return; elseif (strcmp(SBMLStructure.type, 'scalar') ~= 1) valid = 0; message = 'expected scalar type'; return; end; end; else valid = 0; message = 'missing typecode'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames(typecode, level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid AssignmentRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Compartment(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_COMPARTMENT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_COMPARTMENT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Compartment\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_CompartmentType(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_COMPARTMENT_TYPE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_COMPARTMENT_TYPE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid CompartmentType\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_CompartmentVolumeRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_COMPARTMENT_VOLUME_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_COMPARTMENT_VOLUME_RULE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid CompartmentVolumeRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Constraint(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_CONSTRAINT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_CONSTRAINT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Constraint\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Delay(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_DELAY'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_DELAY', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Delay\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Event(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_EVENT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_EVENT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; %check that any nested structures are appropriate % eventAssignments if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.eventAssignment)) [valid, message] = isSBML_EventAssignment( ... SBMLStructure.eventAssignment(index), ... level, version); index = index + 1; end; end; % trigger/delay/priority % these are level and version dependent if (valid == 1) if (level == 2 && version > 2) if (length(SBMLStructure.trigger) > 1) valid = 0; message = 'multiple trigger elements encountered'; elseif (length(SBMLStructure.delay) > 1) valid = 0; message = 'multiple delay elements encountered'; end; if (valid == 1 && length(SBMLStructure.trigger) == 1) [valid, message] = isSBML_Trigger(SBMLStructure.trigger, level, version); end; if (valid == 1 && length(SBMLStructure.delay) == 1) [valid, message] = isSBML_Delay(SBMLStructure.delay, level, version); end; elseif (level > 2) if (length(SBMLStructure.trigger) > 1) valid = 0; message = 'multiple trigger elements encountered'; elseif (length(SBMLStructure.delay) > 1) valid = 0; message = 'multiple delay elements encountered'; elseif (length(SBMLStructure.priority) > 1) valid = 0; message = 'multiple priority elements encountered'; end; if (valid == 1 && length(SBMLStructure.trigger) == 1) [valid, message] = isSBML_Trigger(SBMLStructure.trigger, level, version); end; if (valid == 1 && length(SBMLStructure.delay) == 1) [valid, message] = isSBML_Delay(SBMLStructure.delay, level, version); end; if (valid == 1 && length(SBMLStructure.priority) == 1) [valid, message] = isSBML_Priority(SBMLStructure.priority, level, version); end; end; end; % report failure if (valid == 0) message = sprintf('Invalid Event\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_EventAssignment(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_EVENT_ASSIGNMENT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_EVENT_ASSIGNMENT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid EventAssignment\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_FunctionDefinition(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_FUNCTION_DEFINITION'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_FUNCTION_DEFINITION', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid FunctionDefinition\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_InitialAssignment(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_INITIAL_ASSIGNMENT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_INITIAL_ASSIGNMENT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid InitialAssignment\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_KineticLaw(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_KINETIC_LAW'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_KINETIC_LAW', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; %check that any nested structures are appropriate % parameters if (valid == 1 && level < 3) index = 1; while (valid == 1 && index <= length(SBMLStructure.parameter)) [valid, message] = isSBML_Parameter(SBMLStructure.parameter(index), ... level, version); index = index + 1; end; end; %check that any nested structures are appropriate % localParameters if (valid == 1 && level > 2) index = 1; while (valid == 1 && index <= length(SBMLStructure.localParameter)) [valid, message] = isSBML_LocalParameter(SBMLStructure.localParameter(index), ... level, version); index = index + 1; end; end; % report failure if (valid == 0) message = sprintf('Invalid KineticLaw\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_LocalParameter(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_LOCAL_PARAMETER'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_LOCAL_PARAMETER', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid LocalParameter\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_ModifierSpeciesReference(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_MODIFIER_SPECIES_REFERENCE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_MODIFIER_SPECIES_REFERENCE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid ModifierSpeciesReference\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Parameter(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_PARAMETER'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_PARAMETER', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Parameter\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_ParameterRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_PARAMETER_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_PARAMETER_RULE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid ParameterRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Priority(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_PRIORITY'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_PRIORITY', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Priority\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_RateRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_RATE_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (level > 1) if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else % check L1 types typecode = SBMLStructure.typecode; cvr = strcmp(typecode, 'SBML_COMPARTMENT_VOLUME_RULE'); pr = strcmp(typecode, 'SBML_PARAMETER_RULE'); scr = strcmp(typecode, 'SBML_SPECIES_CONCENTRATION_RULE'); if (cvr ~= 1 && pr ~= 1 && scr ~= 1) valid = 0; message = 'typecode mismatch'; return; elseif (strcmp(SBMLStructure.type, 'rate') ~= 1) valid = 0; message = 'expected rate type'; return; end; end; else valid = 0; message = 'missing typecode'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames(typecode, level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid RateRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Reaction(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_REACTION'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_REACTION', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; %check that any nested structures are appropriate % reactants if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.reactant)) [valid, message] = isSBML_SpeciesReference(SBMLStructure.reactant(index), ... level, version); index = index + 1; end; end; % products if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.product)) [valid, message] = isSBML_SpeciesReference(SBMLStructure.product(index), ... level, version); index = index + 1; end; end; % modifiers if (valid == 1 && level > 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.modifier)) [valid, message] = isSBML_ModifierSpeciesReference( ... SBMLStructure.modifier(index), ... level, version); index = index + 1; end; end; % kineticLaw if (valid == 1 && length(SBMLStructure.kineticLaw) == 1) [valid, message] = isSBML_KineticLaw(SBMLStructure.kineticLaw, level, version); end; % report failure if (valid == 0) message = sprintf('Invalid Reaction\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Rule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; if ~isempty(SBMLStructure) if isfield(SBMLStructure, 'typecode') typecode = SBMLStructure.typecode; else valid = 0; message = 'missing typecode'; return; end; else typecode = 'SBML_ASSIGNMENT_RULE'; end; switch (typecode) case 'SBML_ALGEBRAIC_RULE' [valid, message] = isSBML_AlgebraicRule(SBMLStructure, level, version); case 'SBML_ASSIGNMENT_RULE' [valid, message] = isSBML_AssignmentRule(SBMLStructure, level, version); case 'SBML_COMPARTMENT_VOLUME_RULE' [valid, message] = isSBML_CompartmentVolumeRule(SBMLStructure, level, version); case 'SBML_PARAMETER_RULE' [valid, message] = isSBML_ParameterRule(SBMLStructure, level, version); case 'SBML_RATE_RULE' [valid, message] = isSBML_RateRule(SBMLStructure, level, version); case 'SBML_SPECIES_CONCENTRATION_RULE' [valid, message] = isSBML_SpeciesConcentrationRule(SBMLStructure, level, version); case 'SBML_RULE' [valid, message] = checkRule(SBMLStructure, level, version); otherwise valid = 0; message = 'Incorrect rule typecode'; end; function [valid, message] = checkRule(SBMLStructure, level, version) message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getAlgebraicRuleFieldnames(level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Rule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Species(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_SPECIES'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_SPECIES', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Species\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_SpeciesConcentrationRule(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_SPECIES_CONCENTRATION_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_SPECIES_CONCENTRATION_RULE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid SpeciesConcentrationRule\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_SpeciesReference(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_SPECIES_REFERENCE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_SPECIES_REFERENCE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid SpeciesReference\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_SpeciesType(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_SPECIES_TYPE'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_SPECIES_TYPE', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid SpeciesType\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_StoichiometryMath(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_STOICHIOMETRY_MATH'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_STOICHIOMETRY_MATH', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid StoichiometryMath\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Trigger(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_TRIGGER'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_TRIGGER', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Trigger\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_Unit(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_UNIT'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_UNIT', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Unit\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [valid, message] = isSBML_UnitDefinition(varargin) %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_UNIT_DEFINITION'; if (valid == 1 && ~isempty(SBMLStructure)) if isfield(SBMLStructure, 'typecode') if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; return; end; else valid = 0; message = 'missing typecode field'; return; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getFieldnames('SBML_UNIT_DEFINITION', level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; %check that any nested structures are appropriate % unit if (valid == 1) index = 1; while (valid == 1 && index <= length(SBMLStructure.unit)) [valid, message] = isSBML_Unit(SBMLStructure.unit(index), ... level, version); index = index + 1; end; end; % report failure if (valid == 0) message = sprintf('Invalid UnitDefinition\n%s\n', message); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function valid = isValidLevelVersionCombination(level, version) valid = 1; if ~isIntegralNumber(level) error('level must be an integer'); elseif ~isIntegralNumber(version) error('version must be an integer'); end; if (level < 1 || level > 3) error('current SBML levels are 1, 2 or 3'); end; if (level == 1) if (version < 1 || version > 2) error('SBMLToolbox supports versions 1-2 of SBML Level 1'); end; elseif (level == 2) if (version < 1 || version > 4) error('SBMLToolbox supports versions 1-4 of SBML Level 2'); end; elseif (level == 3) if (version ~= 1) error('SBMLToolbox supports only version 1 of SBML Level 3'); end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function value = isIntegralNumber(number) value = 0; integerClasses = {'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}; % since the function isinteger does not exist in MATLAB Rel 13 % this is not used %if (isinteger(number)) if (ismember(class(number), integerClasses)) value = 1; elseif (isnumeric(number)) % if it is an integer if (number == fix(number)) value = 1; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getAlgebraicRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'type', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getAssignmentRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getCompartmentFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'name', ... 'volume', ... 'units', ... 'outside', ... 'isSetVolume', ... }; nNumberFields = 8; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'spatialDimensions', ... 'size', ... 'units', ... 'outside', ... 'constant', ... 'isSetSize', ... 'isSetVolume', ... }; nNumberFields = 13; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'compartmentType', ... 'spatialDimensions', ... 'size', ... 'units', ... 'outside', ... 'constant', ... 'isSetSize', ... 'isSetVolume', ... }; nNumberFields = 14; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'compartmentType', ... 'spatialDimensions', ... 'size', ... 'units', ... 'outside', ... 'constant', ... 'isSetSize', ... 'isSetVolume', ... }; nNumberFields = 15; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'compartmentType', ... 'spatialDimensions', ... 'size', ... 'units', ... 'outside', ... 'constant', ... 'isSetSize', ... 'isSetVolume', ... }; nNumberFields = 15; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'spatialDimensions', ... 'size', ... 'units', ... 'constant', ... 'isSetSize', ... 'isSetSpatialDimensions', ... }; nNumberFields = 13; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getCompartmentTypeFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... }; nNumberFields = 6; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... }; nNumberFields = 7; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... }; nNumberFields = 7; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getCompartmentVolumeRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'type', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 4) SBMLfieldnames = []; nNumberFields = 0; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getConstraintFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... 'message', ... }; nNumberFields = 7; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... 'message', ... }; nNumberFields = 7; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... 'message', ... }; nNumberFields = 7; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... 'message', ... }; nNumberFields = 7; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getDelayFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getEventAssignmentFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'variable', ... 'math', ... }; nNumberFields = 6; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'variable', ... 'sboTerm', ... 'math', ... }; nNumberFields = 7; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'variable', ... 'math', ... }; nNumberFields = 7; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'variable', ... 'math', ... }; nNumberFields = 7; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'variable', ... 'math', ... }; nNumberFields = 7; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getEventFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'trigger', ... 'delay', ... 'timeUnits', ... 'eventAssignment', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'trigger', ... 'delay', ... 'timeUnits', ... 'sboTerm', ... 'eventAssignment', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'trigger', ... 'delay', ... 'eventAssignment', ... }; nNumberFields = 10; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'useValuesFromTriggerTime', ... 'trigger', ... 'delay', ... 'eventAssignment', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'useValuesFromTriggerTime', ... 'trigger', ... 'delay', ... 'priority', ... 'eventAssignment', ... }; nNumberFields = 12; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getFieldnames(typecode, ... level, version) done = 1; switch (typecode) case {'SBML_ALGEBRAIC_RULE', 'AlgebraicRule', 'algebraicRule'} fhandle = str2func('getAlgebraicRuleFieldnames'); case {'SBML_ASSIGNMENT_RULE', 'AssignmentRule', 'assignmentRule'} fhandle = str2func('getAssignmentRuleFieldnames'); case {'SBML_COMPARTMENT', 'Compartment', 'compartment'} fhandle = str2func('getCompartmentFieldnames'); case {'SBML_COMPARTMENT_TYPE', 'CompartmentType', 'compartmentType'} fhandle = str2func('getCompartmentTypeFieldnames'); case {'SBML_COMPARTMENT_VOLUME_RULE', 'CompartmentVolumeRule', 'compartmentVolumeRule'} fhandle = str2func('getCompartmentVolumeRuleFieldnames'); case {'SBML_CONSTRAINT', 'Constraint', 'constraint'} fhandle = str2func('getConstraintFieldnames'); case {'SBML_DELAY', 'Delay', 'delay'} fhandle = str2func('getDelayFieldnames'); case {'SBML_EVENT', 'Event', 'event'} fhandle = str2func('getEventFieldnames'); case {'SBML_EVENT_ASSIGNMENT', 'EventAssignment', 'eventAssignment'} fhandle = str2func('getEventAssignmentFieldnames'); case {'SBML_FUNCTION_DEFINITION', 'FunctionDefinition', 'functionDefinition'} fhandle = str2func('getFunctionDefinitionFieldnames'); case {'SBML_INITIAL_ASSIGNMENT', 'InitialAssignment', 'initialAssignment'} fhandle = str2func('getInitialAssignmentFieldnames'); case {'SBML_KINETIC_LAW', 'KineticLaw', 'kineticLaw'} fhandle = str2func('getKineticLawFieldnames'); case {'SBML_LOCAL_PARAMETER', 'LocalParameter', 'localParameter'} fhandle = str2func('getLocalParameterFieldnames'); case {'SBML_MODEL', 'Model', 'model'} fhandle = str2func('getModelFieldnames'); case {'SBML_MODIFIER_SPECIES_REFERENCE', 'ModifierSpeciesReference', 'modifierSpeciesReference'} fhandle = str2func('getModifierSpeciesReferenceFieldnames'); case {'SBML_PARAMETER', 'Parameter', 'parameter'} fhandle = str2func('getParameterFieldnames'); case {'SBML_PARAMETER_RULE', 'ParameterRule', 'parameterRule'} fhandle = str2func('getParameterRuleFieldnames'); case {'SBML_PRIORITY', 'Priority', 'priority'} fhandle = str2func('getPriorityFieldnames'); case {'SBML_RATE_RULE', 'RateRule', 'ruleRule'} fhandle = str2func('getRateRuleFieldnames'); case {'SBML_REACTION', 'Reaction', 'reaction'} fhandle = str2func('getReactionFieldnames'); case {'SBML_SPECIES', 'Species', 'species'} fhandle = str2func('getSpeciesFieldnames'); case {'SBML_SPECIES_CONCENTRATION_RULE', 'SpeciesConcentrationRule', 'speciesConcentrationRule'} fhandle = str2func('getSpeciesConcentrationRuleFieldnames'); case {'SBML_SPECIES_REFERENCE', 'SpeciesReference', 'speciesReference'} fhandle = str2func('getSpeciesReferenceFieldnames'); case {'SBML_SPECIES_TYPE', 'SpeciesType', 'speciesType'} fhandle = str2func('getSpeciesTypeFieldnames'); case {'SBML_STOICHIOMETRY_MATH', 'StoichiometryMath', 'stoichiometryMath'} fhandle = str2func('getStoichiometryMathFieldnames'); case {'SBML_TRIGGER', 'Trigger', 'trigger'} fhandle = str2func('getTriggerFieldnames'); case {'SBML_UNIT', 'Unit', 'unit'} fhandle = str2func('getUnitFieldnames'); case {'SBML_UNIT_DEFINITION', 'UnitDefinition', 'unitDefinition'} fhandle = str2func('getUnitDefinitionFieldnames'); otherwise done = 0; end; if done == 1 [SBMLfieldnames, nNumberFields] = feval(fhandle, level, version); else switch (typecode) case {'SBML_FBC_FLUXBOUND', 'FluxBound', 'fluxBound'} fhandle = str2func('getFluxBoundFieldnames'); case {'SBML_FBC_FLUXOBJECTIVE', 'FluxObjective', 'fluxObjective'} fhandle = str2func('getFluxObjectiveFieldnames'); case {'SBML_FBC_OBJECTIVE', 'Objective', 'objective'} fhandle = str2func('getObjectiveFieldnames'); case {'SBML_FBC_MODEL', 'FBCModel'} fhandle = str2func('getFBCModelFieldnames'); case {'SBML_FBC_SPECIES', 'FBCSpecies'} fhandle = str2func('getFBCSpeciesFieldnames'); otherwise error('%s\n%s', ... 'getFieldnames(typecode, level, version', ... 'typecode not recognised'); end; [SBMLfieldnames, nNumberFields] = feval(fhandle, level, version, 1); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getFunctionDefinitionFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'math', ... }; nNumberFields = 7; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'math', ... }; nNumberFields = 8; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'math', ... }; nNumberFields = 8; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'math', ... }; nNumberFields = 8; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'math', ... }; nNumberFields = 8; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getInitialAssignmentFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'symbol', ... 'math', ... }; nNumberFields = 7; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'symbol', ... 'math', ... }; nNumberFields = 7; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'symbol', ... 'math', ... }; nNumberFields = 7; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'symbol', ... 'math', ... }; nNumberFields = 7; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getKineticLawFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'formula', ... 'parameter', ... 'timeUnits', ... 'substanceUnits', ... }; nNumberFields = 7; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'math', ... 'parameter', ... 'timeUnits', ... 'substanceUnits', ... }; nNumberFields = 9; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'math', ... 'parameter', ... 'sboTerm', ... }; nNumberFields = 8; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'math', ... 'parameter', ... }; nNumberFields = 8; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'math', ... 'parameter', ... }; nNumberFields = 8; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... 'localParameter', ... }; nNumberFields = 7; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getLocalParameterFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'value', ... 'units', ... 'isSetValue', ... }; nNumberFields = 10; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getModelFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'unitDefinition', ... 'compartment', ... 'species', ... 'parameter', ... 'rule', ... 'reaction', ... }; nNumberFields = 12; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'id', ... 'functionDefinition', ... 'unitDefinition', ... 'compartment', ... 'species', ... 'parameter', ... 'rule', ... 'reaction', ... 'event', ... }; nNumberFields = 16; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'id', ... 'sboTerm', ... 'functionDefinition', ... 'unitDefinition', ... 'compartmentType', ... 'speciesType', ... 'compartment', ... 'species', ... 'parameter', ... 'initialAssignment', ... 'rule', ... 'constraint', ... 'reaction', ... 'event', ... }; nNumberFields = 21; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'id', ... 'sboTerm', ... 'functionDefinition', ... 'unitDefinition', ... 'compartmentType', ... 'speciesType', ... 'compartment', ... 'species', ... 'parameter', ... 'initialAssignment', ... 'rule', ... 'constraint', ... 'reaction', ... 'event', ... }; nNumberFields = 21; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'id', ... 'sboTerm', ... 'functionDefinition', ... 'unitDefinition', ... 'compartmentType', ... 'speciesType', ... 'compartment', ... 'species', ... 'parameter', ... 'initialAssignment', ... 'rule', ... 'constraint', ... 'reaction', ... 'event', ... }; nNumberFields = 21; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'SBML_level', ... 'SBML_version', ... 'name', ... 'id', ... 'sboTerm', ... 'functionDefinition', ... 'unitDefinition', ... 'compartment', ... 'species', ... 'parameter', ... 'initialAssignment', ... 'rule', ... 'constraint', ... 'reaction', ... 'event', ... 'substanceUnits', ... 'timeUnits', ... 'lengthUnits', ... 'areaUnits', ... 'volumeUnits', ... 'extentUnits', ... 'conversionFactor', ... }; nNumberFields = 26; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getModifierSpeciesReferenceFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'species', ... }; nNumberFields = 5; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'species', ... 'id', ... 'name', ... 'sboTerm', ... }; nNumberFields = 8; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... }; nNumberFields = 8; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... }; nNumberFields = 8; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... }; nNumberFields = 8; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getParameterFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'name', ... 'value', ... 'units', ... 'isSetValue', ... }; nNumberFields = 7; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'value', ... 'units', ... 'constant', ... 'isSetValue', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'value', ... 'units', ... 'constant', ... 'sboTerm', ... 'isSetValue', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'value', ... 'units', ... 'constant', ... 'isSetValue', ... }; nNumberFields = 11; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'value', ... 'units', ... 'constant', ... 'isSetValue', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'value', ... 'units', ... 'constant', ... 'isSetValue', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getParameterRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'type', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 4) SBMLfieldnames = []; nNumberFields = 0; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getPriorityFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getRateRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getReactionFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'name', ... 'reactant', ... 'product', ... 'kineticLaw', ... 'reversible', ... 'fast', ... }; nNumberFields = 9; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'reactant', ... 'product', ... 'modifier', ... 'kineticLaw', ... 'reversible', ... 'fast', ... 'isSetFast', ... }; nNumberFields = 13; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'reactant', ... 'product', ... 'modifier', ... 'kineticLaw', ... 'reversible', ... 'fast', ... 'sboTerm', ... 'isSetFast', ... }; nNumberFields = 14; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'reactant', ... 'product', ... 'modifier', ... 'kineticLaw', ... 'reversible', ... 'fast', ... 'isSetFast', ... }; nNumberFields = 14; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'reactant', ... 'product', ... 'modifier', ... 'kineticLaw', ... 'reversible', ... 'fast', ... 'isSetFast', ... }; nNumberFields = 14; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'reactant', ... 'product', ... 'modifier', ... 'kineticLaw', ... 'reversible', ... 'fast', ... 'isSetFast', ... 'compartment', ... }; nNumberFields = 15; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'type', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getSpeciesConcentrationRuleFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'type', ... 'formula', ... 'variable', ... 'species', ... 'compartment', ... 'name', ... 'units', ... }; nNumberFields = 10; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 4) SBMLfieldnames = []; nNumberFields = 0; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getSpeciesFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'name', ... 'compartment', ... 'initialAmount', ... 'units', ... 'boundaryCondition', ... 'charge', ... 'isSetInitialAmount', ... 'isSetCharge', ... }; nNumberFields = 11; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'compartment', ... 'initialAmount', ... 'initialConcentration', ... 'substanceUnits', ... 'spatialSizeUnits', ... 'hasOnlySubstanceUnits', ... 'boundaryCondition', ... 'charge', ... 'constant', ... 'isSetInitialAmount', ... 'isSetInitialConcentration', ... 'isSetCharge', ... }; nNumberFields = 18; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'speciesType', ... 'compartment', ... 'initialAmount', ... 'initialConcentration', ... 'substanceUnits', ... 'spatialSizeUnits', ... 'hasOnlySubstanceUnits', ... 'boundaryCondition', ... 'charge', ... 'constant', ... 'isSetInitialAmount', ... 'isSetInitialConcentration', ... 'isSetCharge', ... }; nNumberFields = 19; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'speciesType', ... 'compartment', ... 'initialAmount', ... 'initialConcentration', ... 'substanceUnits', ... 'hasOnlySubstanceUnits', ... 'boundaryCondition', ... 'charge', ... 'constant', ... 'isSetInitialAmount', ... 'isSetInitialConcentration', ... 'isSetCharge', ... }; nNumberFields = 19; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'speciesType', ... 'compartment', ... 'initialAmount', ... 'initialConcentration', ... 'substanceUnits', ... 'hasOnlySubstanceUnits', ... 'boundaryCondition', ... 'charge', ... 'constant', ... 'isSetInitialAmount', ... 'isSetInitialConcentration', ... 'isSetCharge', ... }; nNumberFields = 19; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'compartment', ... 'initialAmount', ... 'initialConcentration', ... 'substanceUnits', ... 'hasOnlySubstanceUnits', ... 'boundaryCondition', ... 'constant', ... 'isSetInitialAmount', ... 'isSetInitialConcentration', ... 'conversionFactor', ... }; nNumberFields = 17; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getSpeciesReferenceFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'species', ... 'stoichiometry', ... 'denominator', ... }; nNumberFields = 6; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'species', ... 'stoichiometry', ... 'denominator', ... 'stoichiometryMath', ... }; nNumberFields = 8; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'species', ... 'id', ... 'name', ... 'sboTerm', ... 'stoichiometry', ... 'stoichiometryMath', ... }; nNumberFields = 10; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... 'stoichiometry', ... 'stoichiometryMath', ... }; nNumberFields = 10; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... 'stoichiometry', ... 'stoichiometryMath', ... }; nNumberFields = 10; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'species', ... 'id', ... 'name', ... 'stoichiometry', ... 'constant', ... 'isSetStoichiometry', ... }; nNumberFields = 11; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getSpeciesTypeFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... }; nNumberFields = 6; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... }; nNumberFields = 7; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... }; nNumberFields = 7; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getStoichiometryMathFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; end; elseif (level == 3) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getTriggerFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (level == 2) if (version == 1) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 2) SBMLfieldnames = []; nNumberFields = 0; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'math', ... }; nNumberFields = 6; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'persistent', ... 'initialValue', ... 'math', ... }; nNumberFields = 8; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getUnitDefinitionFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'name', ... 'unit', ... }; nNumberFields = 5; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'unit', ... }; nNumberFields = 7; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'name', ... 'id', ... 'unit', ... }; nNumberFields = 7; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'unit', ... }; nNumberFields = 8; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'unit', ... }; nNumberFields = 8; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'name', ... 'id', ... 'unit', ... }; nNumberFields = 8; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [SBMLfieldnames, nNumberFields] = getUnitFieldnames(level, ... version) if (~isValidLevelVersionCombination(level, version)) error ('invalid level/version combination'); end; if (level == 1) SBMLfieldnames = { 'typecode', ... 'notes', ... 'annotation', ... 'kind', ... 'exponent', ... 'scale', ... }; nNumberFields = 6; elseif (level == 2) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'kind', ... 'exponent', ... 'scale', ... 'multiplier', ... 'offset', ... }; nNumberFields = 9; elseif (version == 2) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'kind', ... 'exponent', ... 'scale', ... 'multiplier', ... }; nNumberFields = 8; elseif (version == 3) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'kind', ... 'exponent', ... 'scale', ... 'multiplier', ... }; nNumberFields = 9; elseif (version == 4) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'kind', ... 'exponent', ... 'scale', ... 'multiplier', ... }; nNumberFields = 9; end; elseif (level == 3) if (version == 1) SBMLfieldnames = { 'typecode', ... 'metaid', ... 'notes', ... 'annotation', ... 'sboTerm', ... 'kind', ... 'exponent', ... 'scale', ... 'multiplier', ... }; nNumberFields = 9; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
EPFL-LCSB/matTFA-master
isSBML_Rule.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Validate_MATLAB_SBML_Structures/isSBML_Rule.m
4,719
utf_8
82221b39c9f485c76bc0c4cb4425712d
function [valid, message] = isSBML_Rule(varargin) % [valid, message] = isSBML_Rule(SBMLRule, level, version(optional)) % % Takes % % 1. SBMLRule, an SBML Rule structure % 2. level, an integer representing an SBML level % 3. version (optional), an integer representing an SBML version % % Returns % % 1. valid = % - 1, if the structure represents % a MATLAB_SBML Rule structure of the appropriate % level and version % - 0, otherwise % 2. a message explaining any failure % % *NOTE:* the optional version defaults to a value of 1 % % *NOTE:* The fields present in a MATLAB_SBML Rule structure of the appropriate % level and version can be found using getRuleFieldnames(level, version) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> %check the input arguments are appropriate if (nargin < 2 || nargin > 3) error('wrong number of input arguments'); end; SBMLStructure = varargin{1}; if (length(SBMLStructure) > 1) valid = 0; message = 'cannot deal with arrays of structures'; return; end; level = varargin{2}; if (nargin == 3) version = varargin{3}; else version = 1; end; isValidLevelVersionCombination(level, version); message = ''; if ~isempty(SBMLStructure) if isfield(SBMLStructure, 'typecode') typecode = SBMLStructure.typecode; else valid = 0; message = 'missing typecode'; return; end; else typecode = 'SBML_ASSIGNMENT_RULE'; end; switch (typecode) case 'SBML_ALGEBRAIC_RULE' [valid, message] = isSBML_AlgebraicRule(SBMLStructure, level, version); case 'SBML_ASSIGNMENT_RULE' [valid, message] = isSBML_AssignmentRule(SBMLStructure, level, version); case 'SBML_COMPARTMENT_VOLUME_RULE' [valid, message] = isSBML_CompartmentVolumeRule(SBMLStructure, level, version); case 'SBML_PARAMETER_RULE' [valid, message] = isSBML_ParameterRule(SBMLStructure, level, version); case 'SBML_RATE_RULE' [valid, message] = isSBML_RateRule(SBMLStructure, level, version); case 'SBML_SPECIES_CONCENTRATION_RULE' [valid, message] = isSBML_SpeciesConcentrationRule(SBMLStructure, level, version); case 'SBML_RULE' [valid, message] = checkRule(SBMLStructure, level, version); otherwise valid = 0; message = 'Incorrect rule typecode'; end; function [valid, message] = checkRule(SBMLStructure, level, version) message = ''; % check that argument is a structure valid = isstruct(SBMLStructure); % check the typecode typecode = 'SBML_RULE'; if (valid == 1 && ~isempty(SBMLStructure)) if (strcmp(typecode, SBMLStructure.typecode) ~= 1) valid = 0; message = 'typecode mismatch'; end; end; % if the level and version fields exist they must match if (valid == 1 && isfield(SBMLStructure, 'level') && ~isempty(SBMLStructure)) if ~isequal(level, SBMLStructure.level) valid = 0; message = 'level mismatch'; end; end; if (valid == 1 && isfield(SBMLStructure, 'version') && ~isempty(SBMLStructure)) if ~isequal(version, SBMLStructure.version) valid = 0; message = 'version mismatch'; end; end; % check that structure contains all the necessary fields [SBMLfieldnames, numFields] = getAlgebraicRuleFieldnames(level, version); if (numFields ==0) valid = 0; message = 'invalid level/version'; end; index = 1; while (valid == 1 && index <= numFields) valid = isfield(SBMLStructure, char(SBMLfieldnames(index))); if (valid == 0); message = sprintf('%s field missing', char(SBMLfieldnames(index))); end; index = index + 1; end; % report failure if (valid == 0) message = sprintf('Invalid Rule\n%s\n', message); end;
github
EPFL-LCSB/matTFA-master
AnalyseSpecies.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/AnalyseSpecies.m
14,715
utf_8
8b6973e0bfad96e3ccee4c6adb214328
function Species = AnalyseSpecies(SBMLModel) % [analysis] = AnalyseSpecies(SBMLModel) % % Takes % % 1. SBMLModel, an SBML Model structure % % Returns % % 1. a structure detailing the species and how they are manipulated % within the model % % % *EXAMPLE:* % % Using the model from toolbox/Test/test-data/algebraicRules.xml % % analysis = AnalyseSpecies(m) % % analysis = % % 1x5 struct array with fields: % Name % constant % boundaryCondition % initialValue % hasAmountOnly % isConcentration % compartment % ChangedByReaction % KineticLaw % ChangedByRateRule % RateRule % ChangedByAssignmentRule % AssignmentRule % InAlgebraicRule % AlgebraicRule % ConvertedToAssignRule % ConvertedRule % % analysis(1) = % % % Name: {'S1'} % constant: 0 % boundaryCondition: 0 % initialValue: 0.0300 % hasAmountOnly: 0 % isConcentration: 0 % compartment: 'compartment' % ChangedByReaction: 1 % KineticLaw: {' - (k*S1)'} % ChangedByRateRule: 0 % RateRule: '' % ChangedByAssignmentRule: 0 % AssignmentRule: '' % InAlgebraicRule: 1 % AlgebraicRule: {{1x1 cell}} % ConvertedToAssignRule: 0 % ConvertedRule: '' % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> if (~isValidSBML_Model(SBMLModel)) error('AnalyseSpecies(SBMLModel)\n%s', 'argument must be an SBMLModel structure'); end; if length(SBMLModel.species) == 0 Species = []; return; end; [name, KineticLaw] = GetRateLawsFromReactions(SBMLModel); [n, RateRule] = GetRateLawsFromRules(SBMLModel); [n, AssignRule] = GetSpeciesAssignmentRules(SBMLModel); [n, AlgRules] = GetSpeciesAlgebraicRules(SBMLModel); [n, Values] = GetSpecies(SBMLModel); % create the output structure for i = 1:length(SBMLModel.species) Species(i).Name = name(i); % species Type if (SBMLModel.SBML_level == 2 && SBMLModel.SBML_version > 1) if exist('OCTAVE_VERSION') if isempty(SBMLModel.species(i).speciesType) Species(i).speciesType = ''; else Species(i).speciesType = SBMLModel.species(i).speciesType; end; else Species(i).speciesType = SBMLModel.species(i).speciesType; end; end; % boundary condition and constant bc = SBMLModel.species(i).boundaryCondition; if (SBMLModel.SBML_level > 1) const = SBMLModel.species(i).constant; else const = 0; end; Species(i).constant = const; Species(i).boundaryCondition = bc; %initial value / amount/ concentration Species(i).initialValue = Values(i); if (SBMLModel.SBML_level > 1) comp = Model_getCompartmentById(SBMLModel, SBMLModel.species(i).compartment); if (comp.spatialDimensions == 0) Species(i).hasAmountOnly = 1; else if (SBMLModel.species(i).hasOnlySubstanceUnits == 1) Species(i).hasAmountOnly = 1; else Species(i).hasAmountOnly = 0; end; end; if (SBMLModel.species(i).isSetInitialConcentration == 0 ... && SBMLModel.species(i).isSetInitialAmount == 0) % value is set by rule/assignment thus will be concentration % unless the compartment is 0D or species hasOnlySubstanceUnits if (comp.spatialDimensions == 0 ... || SBMLModel.species(i).hasOnlySubstanceUnits == 1) Species(i).isConcentration = 0; else Species(i).isConcentration = 1; end; elseif (SBMLModel.species(i).isSetInitialAmount == 1) % species has a value given as amount % but if overridden by assignment it will be in conc if (abs(SBMLModel.species(i).initialAmount - Values(i)) > 1e-16) Species(i).isConcentration = 1; else Species(i).isConcentration = 0; end; else % here species has a value given as concentration % if comp is 0D or species hasOnlySubstanceUnits this is not % correct and needs to be converted if (comp.spatialDimensions == 0 ... || SBMLModel.species(i).hasOnlySubstanceUnits == 1) Species(i).isConcentration = 0; if isnan(comp.size) Species(i).initialvalue = NaN; else Species(i).initialValue = Values(i)/comp.size; end; else Species(i).isConcentration = 1; end; end; else % level 1 species were in amounts Species(i).isConcentration = 0; end; Species(i).compartment = SBMLModel.species(i).compartment; if (strcmp(KineticLaw(i), '0')) Species(i).ChangedByReaction = 0; Species(i).KineticLaw = ''; else Species(i).ChangedByReaction = 1; Species(i).KineticLaw = KineticLaw(i); end; if (strcmp(RateRule(i), '0')) Species(i).ChangedByRateRule = 0; Species(i).RateRule = ''; else Species(i).ChangedByRateRule = 1; Species(i).RateRule = RateRule(i); end; if (strcmp(AssignRule(i), '0')) Species(i).ChangedByAssignmentRule = 0; Species(i).AssignmentRule = ''; else Species(i).ChangedByAssignmentRule = 1; Species(i).AssignmentRule = AssignRule(i); end; if (strcmp(AlgRules(i), '0')) Species(i).InAlgebraicRule = 0; Species(i).AlgebraicRule = ''; else Species(i).InAlgebraicRule = 1; Species(i).AlgebraicRule = AlgRules(i); end; if ((Species(i).constant == 0) ... && (Species(i).ChangedByReaction == 0) ... && (Species(i).ChangedByRateRule == 0) ... && (Species(i).ChangedByAssignmentRule == 0)) if (Species(i).InAlgebraicRule == 1) Species(i).ConvertedToAssignRule = 1; Rule = Species(i).AlgebraicRule{1}; % need to look at whether rule contains a user definined % function FunctionIds = Model_getFunctionIds(SBMLModel); for f = 1:length(FunctionIds) if (matchFunctionName(char(Rule), FunctionIds{f})) Rule = SubstituteFunction(char(Rule), SBMLModel.functionDefinition(f)); end; end; SubsRule = SubsAssignmentRules(SBMLModel, char(Rule)); Species(i).ConvertedRule = Rearrange(SubsRule, name{i}); else Species(i).ConvertedToAssignRule = 0; Species(i).ConvertedRule = ''; end; elseif ((isnan(Species(i).initialValue)) ... && (Species(i).InAlgebraicRule == 1) ... && (Species(i).ChangedByAssignmentRule == 0)) error ('The model is over parameterised and the simulation cannot make decisions regarding rules'); else Species(i).ConvertedToAssignRule = 0; Species(i).ConvertedRule = ''; end; end; function form = SubsAssignmentRules(SBMLModel, rule) [species, AssignRule] = GetSpeciesAssignmentRules(SBMLModel); form = rule; % bracket the species to be replaced for i = 1:length(species) if (matchName(rule, species{i})) if (~strcmp(AssignRule{i}, '0')) form = strrep(form, species{i}, strcat('(', species{i}, ')')); end; end; end; for i = 1:length(species) if (matchName(rule, species{i})) if (~strcmp(AssignRule{i}, '0')) form = strrep(form, species{i}, AssignRule{i}); end; end; end; function output = Arrange(formula, x, vars) ops = '+-'; f = LoseWhiteSpace(formula); operators = ismember(f, ops); OpIndex = find(operators == 1); %-------------------------------------------------- % divide formula up into elements seperated by +/- if (OpIndex(1) == 1) % leading sign i.e. +x-y NumElements = length(OpIndex); j = 2; index = 2; else NumElements = length(OpIndex) + 1; j = 1; index = 1; end; for i = 1:NumElements-1 element = ''; while (j < OpIndex(index)) element = strcat(element, f(j)); j = j+1; end; Elements{i} = element; j = j + 1; index = index + 1; end; % get last element j = OpIndex(end)+1; element = ''; while (j <= length(f)) element = strcat(element, f(j)); j = j+1; end; Elements{NumElements} = element; %-------------------------------------------------- % check whether element contains x % if does keep on lhs else move to rhs changing sign output = ''; lhs = 1; for i = 1:NumElements if (matchName(Elements{i}, x)) % element contains x LHSElements{lhs} = Elements{i}; if (OpIndex(1) == 1) LHSOps(lhs) = f(OpIndex(i)); elseif (i == 1) LHSOps(lhs) = '+'; else LHSOps(lhs) = f(OpIndex(i-1)); end; lhs = lhs + 1; elseif (i == 1) % first element does not contain x if (OpIndex(1) == 1) if (strcmp(f(1), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else % no sign so + output = strcat(output, '-'); end; output = strcat(output, Elements{i}); else % element not first and does not contain x if (OpIndex(1) == 1) if (strcmp(f(OpIndex(i)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else if (strcmp(f(OpIndex(i-1)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; end; output = strcat(output, Elements{i}); end; end; %------------------------------------------------------ % look at remaining LHS for i = 1:length(LHSElements) Mult{i} = ParseElement(LHSElements{i}, x); end; if (length(LHSElements) == 1) % only one element with x % check signs and multipliers if (strcmp(LHSOps(1), '-')) output = strcat('-(', output, ')'); end; if (~strcmp(Mult{1}, '1')) output = strcat(output, '/', Mult{1}); end; else divisor = ''; if (strcmp(LHSOps(1), '+')) divisor = strcat(divisor, '(', Mult{1}); else divisor = strcat(divisor, '(-', Mult{1}); end; for i = 2:length(LHSElements) divisor = strcat(divisor, LHSOps(i), Mult{i}); end; divisor = strcat(divisor, ')'); output = strcat('(', output, ')/', divisor); end; function multiplier = ParseElement(element, x) % assumes that the element is of the form n*x/m % and returns n/m in simplest form if (strcmp(element, x)) multiplier = '1'; return; end; VarIndex = matchName(element, x); MultIndex = strfind(element, '*'); DivIndex = strfind(element, '/'); if (isempty(MultIndex)) MultIndex = 1; end; if (isempty(DivIndex)) DivIndex = length(element); end; if ((DivIndex < MultIndex) ||(VarIndex < MultIndex) || (VarIndex > DivIndex)) error('Cannot deal with formula in this form; %s', element); end; n = ''; m = ''; for i = 1:MultIndex-1 n = strcat(n, element(i)); end; if (isempty(n)) n = '1'; end; for i = DivIndex+1:length(element) m = strcat(m, element(i)); end; if (isempty(m)) m = '1'; end; % if both m and n represenet numbers then they can be simplified Num_n = str2num(n); Num_m = str2num(m); if (~isempty(Num_n) && ~isempty(Num_m)) multiplier = num2str(Num_n/Num_m); else if (strcmp(m, '1')) multiplier = n; else multiplier = strcat(n, '/', m); end; end; function y = LoseWhiteSpace(charArray) % LoseWhiteSpace(charArray) takes an array of characters % and returns the array with any white space removed % %---------------------------------------------------------------- % EXAMPLE: % y = LoseWhiteSpace(' exa mp le') % y = 'example' % %------------------------------------------------------------ % check input is an array of characters if (~ischar(charArray)) error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters'); end; %------------------------------------------------------------- % get the length of the array NoChars = length(charArray); %------------------------------------------------------------- % create an array that indicates whether the elements of charArray are % spaces % e.g. WSpace = isspace(' v b') = [1, 1, 0, 1, 0] % and determine how many WSpace = isspace(charArray); NoSpaces = sum(WSpace); %----------------------------------------------------------- % rewrite the array to leaving out any spaces % remove any numbers from the array of symbols if (NoSpaces > 0) NewArrayCount = 1; for i = 1:NoChars if (~isspace(charArray(i))) y(NewArrayCount) = charArray(i); NewArrayCount = NewArrayCount + 1; end; end; else y = charArray; end;
github
EPFL-LCSB/matTFA-master
WriteODEFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/WriteODEFunction.m
29,879
utf_8
9d231760d2c9e73dd506f73078e5a7da
function WriteODEFunction(varargin) % WriteODEFunction(SBMLModel, name(optional)) % % Takes % % 1. SBMLModel, an SBML Model structure % 2. name, an optional string representing the name of the ode function to be used % % Outputs % % 1. a file 'name.m' defining a function that defines the ode equations of % the model for use with the ode solvers % (if no name supplied the model id will be used) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> switch (nargin) case 0 error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'must have at least one argument'); case 1 SBMLModel = varargin{1}; filename = ''; case 2 SBMLModel = varargin{1}; filename = varargin{2}; otherwise error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'does not take more than two arguments'); end; % check input is an SBML model if (~isValidSBML_Model(SBMLModel)) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'first argument must be an SBMLModel structure'); end; % ------------------------------------------------------------- % check that we can deal with the model % for i=1:length(SBMLModel.parameter) % if (SBMLModel.parameter(i).constant == 0) % error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with varying parameters'); % end; % end; if SBMLModel.SBML_level > 2 if ~isempty(SBMLModel.conversionFactor) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with conversion factors'); end; for i=1:length(SBMLModel.species) if ~isempty(SBMLModel.species(i).conversionFactor) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with conversion factors'); end; end; end; for i=1:length(SBMLModel.compartment) if (SBMLModel.compartment(i).constant == 0) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with varying compartments'); end; end; % if (length(SBMLModel.species) == 0) % error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with models with no species'); % end; for i=1:length(SBMLModel.event) if exist('OCTAVE_VERSION') && length(SBMLModel.event) > 0 error('Octave cannot deal with events'); end; if (~isempty(SBMLModel.event(i).delay)) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with delayed events'); end; if SBMLModel.SBML_level > 2 if (~isempty(SBMLModel.event(i).priority)) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with event priorities'); end; if (~isempty(SBMLModel.event(i).trigger) && ... (SBMLModel.event(i).trigger.initialValue == 1 || SBMLModel.event(i).trigger.persistent == 1)) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with persistent trigger'); end; end; end; for i=1:length(SBMLModel.reaction) if (SBMLModel.reaction(i).fast == 1) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with fast reactions'); end; end; if (length(SBMLModel.compartment) > 1) error('WriteODEFunction(SBMLModel, (optional) filename)\n%s', 'Cannot deal with multiple compartments'); end; if (SBMLModel.SBML_level > 1 && ~isempty(SBMLModel.time_symbol)) for i=1:length(SBMLModel.rule) if (strcmp(SBMLModel.rule(i).typecode, 'SBML_ASSIGNMENT_RULE')) if (~isempty(matchName(SBMLModel.rule(i).formula, SBMLModel.time_symbol))) error('Cannot deal with time in an assignment rule'); end; end; end; end; if (SBMLModel.SBML_level > 1 && ~isempty(SBMLModel.delay_symbol)) for i=1:length(SBMLModel.rule) if (strcmp(SBMLModel.rule(i).typecode, 'SBML_ASSIGNMENT_RULE')) if (~isempty(matchName(SBMLModel.rule(i).formula, SBMLModel.delay_symbol))) error('Cannot deal with delay in an assignment rule'); end; end; end; end; %-------------------------------------------------------------- % get information from the model [ParameterNames, ParameterValues] = GetAllParametersUnique(SBMLModel); [VarParams, VarInitValues] = GetVaryingParameters(SBMLModel); NumberParams = length(VarParams); NumberSpecies = length(SBMLModel.species); if NumberSpecies > 0 Species = AnalyseSpecies(SBMLModel); Speciesnames = GetSpecies(SBMLModel); end; if NumberParams > 0 Parameters = AnalyseVaryingParameters(SBMLModel); end; if length(SBMLModel.compartment) > 0 [CompartmentNames, CompartmentValues] = GetCompartments(SBMLModel); else CompartmentNames = []; end; if (NumberParams + NumberSpecies) == 0 error('Cannot detect any variables'); end; if (SBMLModel.SBML_level > 1) NumEvents = length(SBMLModel.event); NumFuncs = length(SBMLModel.functionDefinition); % version 2.0.2 adds the time_symbol field to the model structure % need to check that it exists if (isfield(SBMLModel, 'time_symbol')) if (~isempty(SBMLModel.time_symbol)) timeVariable = SBMLModel.time_symbol; else timeVariable = 'time'; end; else timeVariable = 'time'; end; if ((SBMLModel.SBML_level == 2 &&SBMLModel.SBML_version > 1) || ... (SBMLModel.SBML_level > 2)) if (length(SBMLModel.constraint) > 0) error('Cannot deal with constraints.'); end; end; else NumEvents = 0; NumFuncs = 0; timeVariable = 'time'; end; %--------------------------------------------------------------- % get the name/id of the model Name = ''; if (SBMLModel.SBML_level == 1) Name = SBMLModel.name; else if (isempty(SBMLModel.id)) Name = SBMLModel.name; else Name = SBMLModel.id; end; end; if (~isempty(filename)) Name = filename; elseif (length(Name) > 63) Name = Name(1:60); end; fileName = strcat(Name, '.m'); %-------------------------------------------------------------------- % open the file for writing fileID = fopen(fileName, 'w'); % write the function declaration % if no events and using octave if (exist('OCTAVE_VERSION') && NumEvents == 0) fprintf(fileID, 'function xdot = %s(x_values, %s)\n', Name, timeVariable); else fprintf(fileID, 'function xdot = %s(%s, x_values)\n', Name, timeVariable); end; % need to add comments to output file fprintf(fileID, '%% function %s takes\n', Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%% either\t1) no arguments\n'); fprintf(fileID, '%% \t and returns a vector of the initial values\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% or \t2) time - the elapsed time since the beginning of the reactions\n'); fprintf(fileID, '%% \t x_values - vector of the current values of the variables\n'); fprintf(fileID, '%% \t and returns a vector of the rate of change of value of each of the variables\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% %s can be used with MATLABs odeN functions as \n', Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%%\t[t,x] = ode23(@%s, [0, t_end], %s)\n', Name, Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%%\t\t\twhere t_end is the end time of the simulation\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%%The variables in this model are related to the output vectors with the following indices\n'); fprintf(fileID, '%%\tIndex\tVariable name\n'); for i = 1:NumberSpecies fprintf(fileID, '%%\t %u \t %s\n', i, char(Species(i).Name)); end; for i = 1:NumberParams fprintf(fileID, '%%\t %u \t %s\n', i+NumberSpecies, char(VarParams{i})); end; fprintf(fileID, '%%\n'); % write the variable vector fprintf(fileID, '%%--------------------------------------------------------\n'); fprintf(fileID, '%% output vector\n\n'); fprintf(fileID, 'xdot = zeros(%u, 1);\n', NumberSpecies+NumberParams); % write the compartment values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% compartment values\n\n'); for i = 1:length(CompartmentNames) fprintf(fileID, '%s = %g;\n', CompartmentNames{i}, CompartmentValues(i)); end; % write the parameter values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% parameter values\n\n'); for i = 1:length(ParameterNames) fprintf(fileID, '%s = %g;\n', ParameterNames{i}, ParameterValues(i)); end; % write the initial concentration values for the species fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% initial values of variables - these may be overridden by assignment rules\n'); fprintf(fileID, '%% NOTE: any use of initialAssignments has been considered in calculating the initial values\n\n'); fprintf(fileID, 'if (nargin == 0)\n'); % if time symbol is used in any subsequent formula it is undeclared % for the initial execution of the function % which would only happen when time = 0 fprintf(fileID, '\n\t%% initial time\n'); fprintf(fileID, '\t%s = 0;\n', timeVariable); fprintf(fileID, '\n\t%% initial values\n'); for i = 1:NumberSpecies if (Species(i).isConcentration == 1) fprintf(fileID, '\t%s = %g;\n', char(Species(i).Name), Species(i).initialValue); elseif (Species(i).hasAmountOnly == 1) fprintf(fileID, '\t%s = %g;\n', char(Species(i).Name), Species(i).initialValue); else fprintf(fileID, '\t%s = %g/%s;\n', char(Species(i).Name), Species(i).initialValue, Species(i).compartment); end; end; for i = 1:NumberParams fprintf(fileID, '\t%s = %g;\n', char(Parameters(i).Name), Parameters(i).initialValue); end; fprintf(fileID, '\nelse\n'); fprintf(fileID, '\t%% floating variable values\n'); for i = 1:NumberSpecies fprintf(fileID, '\t%s = x_values(%u);\n', char(Species(i).Name), i); end; for i = 1:NumberParams fprintf(fileID, '\t%s = x_values(%u);\n', char(Parameters(i).Name), i+NumberSpecies); end; fprintf(fileID, '\nend;\n'); % write assignment rules fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% assignment rules\n'); AssignRules = Model_getListOfAssignmentRules(SBMLModel); for i = 1:length(AssignRules) rule = WriteRule(AssignRules(i)); fprintf(fileID, '%s\n', rule); end; % write algebraic rules fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% algebraic rules\n'); for i = 1:NumberSpecies if (Species(i).ConvertedToAssignRule == 1) fprintf(fileID, '%s = %s;\n', char(Species(i).Name), Species(i).ConvertedRule); end; end; for i = 1:NumberParams if (Parameters(i).ConvertedToAssignRule == 1) fprintf(fileID, '%s = %s;\n', char(Parameters(i).Name), Parameters(i).ConvertedRule); end; end; % write code to calculate concentration values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% calculate concentration values\n\n'); fprintf(fileID, 'if (nargin == 0)\n'); fprintf(fileID, '\n\t%% initial values\n'); % need to catch any initial concentrations that are not set % and case where an initial concentration is set but is incosistent with a % later rule for i = 1:NumberSpecies if (Species(i).ChangedByAssignmentRule == 0) % not set by rule - use value given if (isnan(Species(i).initialValue)) error('WriteODEFunction(SBMLModel)\n%s', 'species concentration not provided or assigned by rule'); else if (Species(i).isConcentration == 1) fprintf(fileID, '\txdot(%u) = %g;\n', i, Species(i).initialValue); elseif (Species(i).hasAmountOnly == 1) fprintf(fileID, '\txdot(%u) = %g;\n', i, Species(i).initialValue); else fprintf(fileID, '\txdot(%u) = %g/%s;\n', i, Species(i).initialValue, Species(i).compartment); end; % fprintf(fileID, '\txdot(%u) = %g;\n', i, Species(i).initialValue); end; else % initial concentration set by rule fprintf(fileID, '\txdot(%u) = %s;\n', i, char(Species(i).Name)); end; end; % for NumSpecies % parameters for i = 1:NumberParams if (Parameters(i).ChangedByAssignmentRule == 0 && Parameters(i).ConvertedToAssignRule == 0) % not set by rule - use value given if (isnan(Parameters(i).initialValue)) error('WriteODEFunction(SBMLModel)\n%s', 'parameter not provided or assigned by rule'); else fprintf(fileID, '\txdot(%u) = %g;\n', i+NumberSpecies, Parameters(i).initialValue); end; else % initial concentration set by rule fprintf(fileID, '\txdot(%u) = %s;\n', i+NumberSpecies, char(Parameters(i).Name)); end; end; % for NumParams fprintf(fileID, '\nelse\n'); fprintf(fileID, '\n\t%% rate equations\n'); NeedToOrderArray = 0; for i = 1:NumberSpecies if (Species(i).ChangedByReaction == 1) % need to look for piecewise functions if (isempty(matchFunctionName(char(Species(i).KineticLaw), 'piecewise'))) if (Species(i).hasAmountOnly == 0) Array{i} = sprintf('\txdot(%u) = (%s)/%s;\n', i, char(Species(i).KineticLaw), Species(i).compartment); else Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(Species(i).KineticLaw)); end; else var = sprintf('xdot(%u)', i); Array{i} = WriteOutPiecewise(var, char(Species(i).KineticLaw)); end; elseif (Species(i).ChangedByRateRule == 1) % a rule will be in concentration by default % if (Species(i).isConcentration == 1) Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(Species(i).RateRule)); % else % Array{i} = sprintf('\txdot(%u) = (%s)*%s;\n', i, char(Species(i).RateRule), Species(i).compartment); % end; % Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(Species(i).RateRule)); elseif (Species(i).ChangedByAssignmentRule == 1) % here no rate law has been provided by either kinetic law or rate % rule - need to check whether the species is in an % assignment rule which may impact on the rate %%% Checking for a piecewise in the assignment rule and %%% handling it %%% Change made by Sumant Turlapati, Entelos, Inc. on June 8th, 2005 if (isempty(matchFunctionName(char(Species(i).AssignmentRule), 'piecewise'))) DifferentiatedRule = DifferentiateRule(char(Species(i).AssignmentRule), Speciesnames, SBMLModel); Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(DifferentiatedRule)); NeedToOrderArray = 1; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% TO DO NESTED PIECEWISE Args = DealWithPiecewise(char(Species(i).AssignmentRule)); DiffRule1 = DifferentiateRule(char(Args{1}), Speciesnames, SBMLModel); DiffRule2 = DifferentiateRule(char(Args{3}), Speciesnames, SBMLModel); Array{i} = sprintf('\tif (%s) \n\t\txdot(%d) = %s;\n\telse\n\t\txdot(%u) = %s;\n\tend;\n', ... Args{2}, i, char(DiffRule1), i, char(DiffRule2)); % NeedToOrderArray = 1; end; %DifferentiatedRule = DifferentiateRule(char(Species(i).AssignmentRule), Speciesnames); %Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(DifferentiatedRule)); %NeedToOrderArray = 1; elseif (Species(i).ConvertedToAssignRule == 1) % here no rate law has been provided by either kinetic law or rate % rule - need to check whether the species is in an % algebraic rule which may impact on the rate DifferentiatedRule = DifferentiateRule(char(Species(i).ConvertedRule), Speciesnames, SBMLModel); Array{i} = sprintf('\txdot(%u) = %s;\n', i, char(DifferentiatedRule)); NeedToOrderArray = 1; else % not set by anything Array{i} = sprintf('\txdot(%u) = 0;\n', i); end; end; % for Numspecies for i = 1:NumberParams if (Parameters(i).ChangedByRateRule == 1) Array{i+NumberSpecies} = sprintf('\txdot(%u) = %s;\n', i+NumberSpecies, char(Parameters(i).RateRule)); elseif (Parameters(i).ChangedByAssignmentRule == 1) if (isempty(matchFunctionName(char(Parameters(i).AssignmentRule), 'piecewise'))) DifferentiatedRule = DifferentiateRule(char(Parameters(i).AssignmentRule), VarParams, SBMLModel); Array{i+NumberSpecies} = sprintf('\txdot(%u) = %s;\n', i+NumberSpecies, char(DifferentiatedRule)); NeedToOrderArray = 1; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% TO DO NESTED PIECEWISE Args = DealWithPiecewise(char(Parameters(i).AssignmentRule)); DiffRule1 = DifferentiateRule(char(Args{1}), VarParams, SBMLModel); DiffRule2 = DifferentiateRule(char(Args{3}), VarParams, SBMLModel); Array{i+NumberSpecies} = sprintf('\tif (%s) \n\t\txdot(%d) = %s;\n\telse\n\t\txdot(%u) = %s;\n\tend;\n', ... Args{2}, i+NumberSpecies, char(DiffRule1), i+NumberSpecies, char(DiffRule2)); % NeedToOrderArray = 1; end; elseif (Parameters(i).ConvertedToAssignRule == 1) % here no rate law has been provided by either kinetic law or rate % rule - need to check whether the species is in an % algebraic rule which may impact on the rate DifferentiatedRule = DifferentiateRule(char(Parameters(i).ConvertedRule), VarParams, SBMLModel); Array{i+NumberSpecies} = sprintf('\txdot(%u) = %s;\n', i+NumberSpecies, char(DifferentiatedRule)); NeedToOrderArray = 1; else % not set by anything Array{i+NumberSpecies} = sprintf('\txdot(%u) = 0;\n', i+NumberSpecies); end; end; % for Numparams % need to check that assignments are made in appropriate order % deals with rules that have been differentiated where xdot may occur on % both sides of an equation if (NeedToOrderArray == 1) Array = OrderArray(Array); end; if (NumberSpecies + NumberParams) > 0 for i = 1:length(Array) fprintf(fileID, '%s', Array{i}); end; end; fprintf(fileID, '\nend;\n'); % ----------------------------------------------------------------- if (NumEvents > 0) % write two additional files for events WriteEventHandlerFunction(SBMLModel, Name); WriteEventAssignmentFunction(SBMLModel, Name); end; % ------------------------------------------------------------------ % put in any function definitions if (NumFuncs > 0) fprintf(fileID, '\n\n%%---------------------------------------------------\n%%Function definitions\n\n'); for i = 1:NumFuncs Name = SBMLModel.functionDefinition(i).id; Elements = GetArgumentsFromLambdaFunction(SBMLModel.functionDefinition(i).math); fprintf(fileID, '%%function %s\n\n', Name); fprintf(fileID, 'function returnValue = %s(', Name); for j = 1:length(Elements)-1 if (j == length(Elements)-1) fprintf(fileID, '%s', Elements{j}); else fprintf(fileID, '%s, ', Elements{j}); end; end; if (isempty(matchFunctionName(Elements{end}, 'piecewise'))) fprintf(fileID, ')\n\nreturnValue = %s;\n\n\n', Elements{end}); else pw = WriteOutPiecewise('returnValue', Elements{end}); fprintf(fileID, ')\n\n%s\n\n', pw); end; end; end; fclose(fileID); %-------------------------------------------------------------------------- function y = WriteRule(SBMLRule) y = ''; switch (SBMLRule.typecode) case 'SBML_ASSIGNMENT_RULE' if (isempty(matchFunctionName(char(SBMLRule.formula), 'piecewise'))) y = sprintf('%s = %s;', SBMLRule.variable, SBMLRule.formula); else var = sprintf('%s', SBMLRule.variable); y = WriteOutPiecewise(var, char(SBMLRule.formula)); end; case 'SBML_SPECIES_CONCENTRATION_RULE' y = sprintf('%s = %s;', SBMLRule.species, SBMLRule.formula); case 'SBML_PARAMETER_RULE' y = sprintf('%s = %s;', SBMLRule.name, SBMLRule.formula); case 'SBML_COMPARTMENT_VOLUME_RULE' y = sprintf('%s = %s;', SBMLRule.compartment, SBMLRule.formula); otherwise error('No assignment rules'); end; %-------------------------------------------------------------------------- function formula = DifferentiateRule(f, SpeciesNames, model) if (model.SBML_level > 1 && ~isempty(model.time_symbol)) if (~isempty(matchName(f, model.time_symbol))) error('Cannot deal with time in an assignment rule'); end; end; if (~isempty(matchFunctionName(f, 'piecewise'))) error('Cannot deal with nested piecewise in an assignment rule'); end; % if the formula contains a functionDefinition % need to get rid of it first for i=1:length(model.functionDefinition) id = model.functionDefinition(i).id; if (~isempty(matchFunctionName(f, id))) f = SubstituteFunction(f, model.functionDefinition(i)); % remove surrounding brackets if (strcmp(f(1), '(') && strcmp(f(end), ')')) f = f(2:end-1); end; end; end; Brackets = PairBrackets(f); Dividers = '+-'; Divide = ismember(f, Dividers); % dividers between brackets do not count if (Brackets ~= 0) [NumPairs,y] = size(Brackets); for i = 1:length(Divide) if (Divide(i) == 1) for j = 1:NumPairs if ((i > Brackets(j,1)) && (i < Brackets(j, 2))) Divide(i) = 0; end; end; end; end; end; Divider = ''; NoElements = 1; element = ''; for i = 1:length(f) if (Divide(i) == 0) element = strcat(element, f(i)); else Divider = strcat(Divider, f(i)); Elements{NoElements} = element; NoElements = NoElements + 1; element = ''; end; % catch last element if (i == length(f)) Elements{NoElements} = element; end; end; for i = 1:NoElements % check whether element contains a species name % need to catch case where element is number and % species names use numbers eg s3 element '3' found = 0; for j = 1:length(SpeciesNames) % j = 1; A = matchName(Elements{i}, SpeciesNames{j}); if (~isempty(A)) if (length(Elements{i}) == length(SpeciesNames{j})) found = 1; % exact match else % need to check what has been found poscharAfter = A(1) + length(SpeciesNames{j}); poscharBefore = A(1) - 1; if (poscharBefore > 0) charBefore = Elements{i}(poscharBefore); else charBefore = '*'; end; if (poscharAfter <= length(Elements{i})) charAfter = Elements{i}(poscharAfter); else charAfter = '*'; end; if ((charBefore == '*' || charBefore == '/') && ... (charAfter == '*' || charAfter == '/')) found = 1; end; end; if (found == 1) break; end; end; end; if (found == 0) % this element does not contain a species Elements{i} = strrep(Elements{i}, Elements{i}, '0'); else % this element does contain a species %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % WHAT IF MORE THAN ONE SPECIES % for moment assume this would not happen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Power = strfind(Elements{i}, '^'); if (~isempty(Power)) Number = ''; Digits = isstrprop(Elements{i}, 'digit'); k = Power+1; while ((k < (length(Elements{i})+1)) & (Digits(k) == 1)) Number = strcat(Number, Elements{i}(k)); k = k + 1; end; Index = str2num(Number); Replace = sprintf('%u * %s^%u*xdot(%u)', Index, SpeciesNames{j}, Index-1, j); Initial = sprintf('%s^%u', SpeciesNames{j}, Index); Elements{i} = strrep(Elements{i}, Initial, Replace); else Replace = sprintf('xdot(%u)', j); Elements{i} = strrep(Elements(i), SpeciesNames{j}, Replace); end; end; end; % put the formula back together formula = ''; for i = 1:NoElements-1 formula = strcat(formula, Elements{i}, Divider(i)); end; formula = strcat(formula, Elements{NoElements}); %-------------------------------------------------------------------------- % function to put rate assignments in appropriate order % eg % xdot(2) = 3 % xdot(1) = 3* xdot(2) function Output = OrderArray(Array) % if (length(Array) > 9) % error('cannot deal with more than 10 species yet'); % end; NewArrayIndex = 1; TempArrayIndex = 1; TempArray2Index = 1; NumberInNewArray = 0; NumberInTempArray = 0; NumberInTempArray2 = 0; TempArray2 = {}; % put any formula withoutxdot on RHS into new array for i = 1:length(Array) if (length(strfind(Array{i}, 'xdot'))> 2) % xdot occurs more than once % put in temp array TempArray{TempArrayIndex} = Array{i}; TempArrayIndices(TempArrayIndex) = i; % update TempArrayIndex = TempArrayIndex + 1; NumberInTempArray = NumberInTempArray + 1; elseif (length(strfind(Array{i}, 'xdot'))==2) % if it is piecewise it will be of form if x xdot() = else xdot() % so xdot will occur twice but not necessarily on RHS if (length(strfind(Array{i}, 'if (')) == 1 ... && strfind(Array{i}, 'if (') < 3) % put in New array NewArray{NewArrayIndex} = Array{i}; NewArrayIndices(NewArrayIndex) = i; % update NewArrayIndex = NewArrayIndex + 1; NumberInNewArray = NumberInNewArray + 1; else TempArray{TempArrayIndex} = Array{i}; TempArrayIndices(TempArrayIndex) = i; % update TempArrayIndex = TempArrayIndex + 1; NumberInTempArray = NumberInTempArray + 1; % error('cannot deal with this function %s', Array{i}); end; else % no xdot on RHS % put in New array NewArray{NewArrayIndex} = Array{i}; NewArrayIndices(NewArrayIndex) = i; % update NewArrayIndex = NewArrayIndex + 1; NumberInNewArray = NumberInNewArray + 1; end; end; while (NumberInTempArray > 0) % go thru temp array for i = 1:NumberInTempArray % find positions of xdot Xdot = strfind(TempArray{i}, 'xdot'); % check whether indices of xdot on RHS are already in new array Found = 0; for j = 2:length(Xdot) Number = str2num(TempArray{i}(Xdot(j)+5)); if (sum(ismember(NewArrayIndices, Number)) == 1) Found = 1; else Found = 0; end; end; % if all have been found put in new array if (Found == 1) % put in New array NewArray{NewArrayIndex} = TempArray{i}; NewArrayIndices(NewArrayIndex) = TempArrayIndices(i); % update NewArrayIndex = NewArrayIndex + 1; NumberInNewArray = NumberInNewArray + 1; else % put in temp array2 TempArray2{TempArray2Index} = TempArray{i}; TempArray2Indices(TempArray2Index) = TempArrayIndices(i); % update TempArray2Index = TempArray2Index + 1; NumberInTempArray2 = NumberInTempArray2 + 1; end; end; %Realloctate temp arrays if (~isempty(TempArray2)) TempArray = TempArray2; TempArrayIndices = TempArray2Indices; NumberInTempArray = NumberInTempArray2; TempArray2Index = 1; NumberInTempArray2 = 0; else NumberInTempArray = 0; end; end; % of while NumInTempArray > 0 Output = NewArray; function output = WriteOutPiecewise(var, formula) Arguments = DealWithPiecewise(formula); if (strfind('piecewise', Arguments{2})) error('Cant do this yet!'); end; Text1{1} = sprintf('\n\tif (%s)', Arguments{2}); if (matchFunctionName(Arguments{1}, 'piecewise')) Text1{2} = WriteOutPiecewise(var, Arguments{1}); else Text1{2} = sprintf('\n\t\t%s = %s;', var, Arguments{1}); end; Text1{3} = sprintf('\n\telse'); if (matchFunctionName('piecewise', Arguments{3})) Text1{4} = WriteOutPiecewise(var, Arguments{3}); else Text1{4} = sprintf('\n\t\t%s = %s;\n\tend;\n', var, Arguments{3}); end; output = Text1{1}; for (i = 2:4) output = strcat(output, Text1{i}); end;
github
EPFL-LCSB/matTFA-master
WriteEventAssignmentFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/WriteEventAssignmentFunction.m
9,101
utf_8
0b45ac0f8184fe7240a489b6399337d3
function WriteEventAssignmentFunction(SBMLModel, Name) % WriteEventAssignmentFunction(SBMLModel, name) % % Takes % % 1. SBMLModel, an SBML Model structure % 2. name, a string representing the name of the ode function being used % % Outputs % % 1. a file 'name_eventAssign.m' defining a function that assigns values following an event % (for use with the event option of MATLABs ode solvers) % % *NOTE:* This function is called from WriteODEFunction when a model with % events is encountered. %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % check input is an SBML model if (~isValidSBML_Model(SBMLModel)) error('WriteEventAssignmentFunction(SBMLModel)\n%s', 'argument must be an SBMLModel structure'); end; % ------------------------------------------------------------- % get information from the model % get information from the model [ParameterNames, ParameterValues] = GetAllParametersUnique(SBMLModel); [VarParams, VarInitValues] = GetVaryingParameters(SBMLModel); NumberParams = length(VarParams); [SpeciesNames, SpeciesValues] = GetSpecies(SBMLModel); NumberSpecies = length(SBMLModel.species); VarNames = [SpeciesNames, VarParams]; VarValues = [SpeciesValues, VarInitValues]; NumberVars = NumberSpecies + NumberParams; NumFuncs = length(SBMLModel.functionDefinition); Species = AnalyseSpecies(SBMLModel); Params = AnalyseVaryingParameters(SBMLModel); %--------------------------------------------------------------- % get the name/id of the model % Name = ''; % if (SBMLModel.SBML_level == 1) % Name = SBMLModel.name; % else % if (isempty(SBMLModel.id)) % Name = SBMLModel.name; % else % Name = SBMLModel.id; % end; % end; % version 2.0.2 adds the time_symbol field to the model structure % need to check that it exists if (isfield(SBMLModel, 'time_symbol')) if (~isempty(SBMLModel.time_symbol)) timeVariable = SBMLModel.time_symbol; else timeVariable = 'time'; end; else timeVariable = 'time'; end; Name = strcat(Name, '_eventAssign'); fileName = strcat(Name, '.m'); %-------------------------------------------------------------------- % open the file for writing fileID = fopen(fileName, 'w'); % write the function declaration fprintf(fileID, 'function Values = %s(%s, VarValues, eventNo)\n', Name, timeVariable); % need to add comments to output file fprintf(fileID, '%% function %s takes\n', Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%% current simulation time\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% vector of current species values\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% the number of the event that has triggered\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% and returns the values assigned by an event assignment\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% %s should be used with MATLABs odeN functions\n', Name); fprintf(fileID, '%% and called to reinitialise values when an event has stopped the integration\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '\n'); % write the parameter values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% parameter values\n\n'); for i = 1:length(ParameterNames) fprintf(fileID, '%s = %g;\n', ParameterNames{i}, ParameterValues(i)); end; % write the current species concentrations fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% floating variables\n'); for i = 1:NumberVars fprintf(fileID, '%s = VarValues(%u);\n', VarNames{i}, i); end; % write the event assignments fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% event assignments\n\n'); fprintf(fileID, 'switch(eventNo)\n'); for i = 1:length(SBMLModel.event) fprintf(fileID, '\tcase %u\n', i); for j = 1:length(SBMLModel.event(i).eventAssignment) % if a variable being assigned occurs in the math of a subsequent event % assignment the value should be the original assignment = SBMLModel.event(i).eventAssignment(j).math; for s=1:NumberVars if (~isempty(matchName(SBMLModel.event(i).eventAssignment(j).math, VarNames{s}))) speciesV = sprintf('VarValues(%u)', s); assignment = strrep(assignment, VarNames{s}, speciesV); end; end; fprintf(fileID, '\t\t%s = %s;\n', SBMLModel.event(i).eventAssignment(j).variable, assignment); end; end; fprintf(fileID, '\totherwise\nend;\n'); % write assignment rules fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% assignment rules\n'); AssignRules = Model_getListOfAssignmentRules(SBMLModel); for i = 1:length(AssignRules) rule = WriteRule(AssignRules(i)); fprintf(fileID, '%s\n', rule); end; % write algebraic rules fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% algebraic rules\n'); for i = 1:NumberSpecies if (Species(i).ConvertedToAssignRule == 1) fprintf(fileID, '%s = %s;\n', char(Species(i).Name), Species(i).ConvertedRule); end; end; for i = 1:NumberParams if (Params(i).ConvertedToAssignRule == 1) fprintf(fileID, '%s = %s;\n', char(Params(i).Name), Params(i).ConvertedRule); end; end; % output values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% output values\n\n'); for i = 1:NumberVars fprintf(fileID, 'Values(%u) = %s;\n', i, VarNames{i}); end; % put in any function definitions if (NumFuncs > 0) fprintf(fileID, '\n\n%%---------------------------------------------------\n%%Function definitions\n\n'); for i = 1:NumFuncs Name = SBMLModel.functionDefinition(i).id; Elements = GetArgumentsFromLambdaFunction(SBMLModel.functionDefinition(i).math); fprintf(fileID, '%%function %s\n\n', Name); fprintf(fileID, 'function returnValue = %s(', Name); for j = 1:length(Elements)-1 if (j == length(Elements)-1) fprintf(fileID, '%s', Elements{j}); else fprintf(fileID, '%s, ', Elements{j}); end; end; fprintf(fileID, ')\n\nreturnValue = %s;\n\n\n', Elements{end}); end; end; fclose(fileID); %-------------------------------------------------------------------------- function y = WriteRule(SBMLRule) y = ''; switch (SBMLRule.typecode) case 'SBML_ASSIGNMENT_RULE' if (isempty(matchFunctionName(char(SBMLRule.formula), 'piecewise'))) y = sprintf('%s = %s;', SBMLRule.variable, SBMLRule.formula); else var = sprintf('%s', SBMLRule.variable); y = WriteOutPiecewise(var, char(SBMLRule.formula)); end; case 'SBML_SPECIES_CONCENTRATION_RULE' y = sprintf('%s = %s;', SBMLRule.species, SBMLRule.formula); case 'SBML_PARAMETER_RULE' y = sprintf('%s = %s;', SBMLRule.name, SBMLRule.formula); case 'SBML_COMPARTMENT_VOLUME_RULE' y = sprintf('%s = %s;', SBMLRule.compartment, SBMLRule.formula); otherwise error('No assignment rules'); end; %------------------------------------------------------------------------------ function output = WriteOutPiecewise(var, formula) Arguments = DealWithPiecewise(formula); if (strfind('piecewise', Arguments{2})) error('Cant do this yet!'); end; Text1{1} = sprintf('\n\tif (%s)', Arguments{2}); if (matchFunctionName(Arguments{1}, 'piecewise')) Text1{2} = WriteOutPiecewise(var, Arguments{1}); else Text1{2} = sprintf('\n\t\t%s = %s;', var, Arguments{1}); end; Text1{3} = sprintf('\n\telse'); if (strfind('piecewise', Arguments{3})) Text1{4} = WriteOutPiecewise(var, Arguments{3}); else Text1{4} = sprintf('\n\t\t%s = %s;\n\tend;\n', var, Arguments{3}); end; output = Text1{1}; for (i = 2:4) output = strcat(output, Text1{i}); end;
github
EPFL-LCSB/matTFA-master
AnalyseVaryingParameters.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/AnalyseVaryingParameters.m
10,969
utf_8
eadb1635027fd7b7829377f0df6f9f66
function VaryingParameters = AnalyseVaryingParameters(SBMLModel) % [analysis] = AnalyseVaryingParameters(SBMLModel) % % Takes % % 1. SBMLModel, an SBML Model structure % % Returns % % 1. a structure detailing any parameters that are not constant and how they are manipulated % within the model % % *EXAMPLE:* % % Using the model from toolbox/Test/test-data/algebraicRules.xml % % analysis = AnalyseVaryingParameters(m) % % analysis = % Name: {'s2'} % initialValue: 4 % ChangedByRateRule: 0 % RateRule: '' % ChangedByAssignmentRule: 0 % AssignmentRule: '' % InAlgebraicRule: 1 % AlgebraicRule: {{1x1 cell}} % ConvertedToAssignRule: 1 % ConvertedRule: '-(-S2-S3)' %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> if (~isValidSBML_Model(SBMLModel)) error('AnalyseVaryingParameters(SBMLModel)\n%s', ... 'argument must be an SBMLModel structure'); end; VaryingParameters = []; if length(SBMLModel.parameter) == 0 return; end; [names, Values] = GetVaryingParameters(SBMLModel); [n, AssignRule] = GetParameterAssignmentRules(SBMLModel); [n, RateRule] = GetParameterRateRules(SBMLModel); [n, AlgRules] = GetParameterAlgebraicRules(SBMLModel); % create the output structure index = 1; for i = 1:length(SBMLModel.parameter) % skip constant parameters if SBMLModel.parameter(i).constant == 1 continue; end; VaryingParameters(index).Name = names(index); VaryingParameters(index).initialValue = Values(index); if (strcmp(RateRule(i), '0')) VaryingParameters(index).ChangedByRateRule = 0; VaryingParameters(index).RateRule = ''; else VaryingParameters(index).ChangedByRateRule = 1; VaryingParameters(index).RateRule = RateRule(i); end; if (strcmp(AssignRule(i), '0')) VaryingParameters(index).ChangedByAssignmentRule = 0; VaryingParameters(index).AssignmentRule = ''; else VaryingParameters(index).ChangedByAssignmentRule = 1; VaryingParameters(index).AssignmentRule = AssignRule(i); end; if (strcmp(AlgRules(i), '0')) VaryingParameters(index).InAlgebraicRule = 0; VaryingParameters(index).AlgebraicRule = ''; else VaryingParameters(index).InAlgebraicRule = 1; VaryingParameters(index).AlgebraicRule = AlgRules(i); end; if ((VaryingParameters(index).ChangedByRateRule == 0) && (VaryingParameters(index).ChangedByAssignmentRule == 0)) if (VaryingParameters(index).InAlgebraicRule == 1) VaryingParameters(index).ConvertedToAssignRule = 1; Rule = VaryingParameters(index).AlgebraicRule{1}; % need to look at whether rule contains a user definined % function FunctionIds = Model_getFunctionIds(SBMLModel); for f = 1:length(FunctionIds) if (matchFunctionName(char(Rule), FunctionIds{f})) Rule = SubstituteFunction(char(Rule), SBMLModel.functionDefinition(f)); end; end; SubsRule = SubsAssignmentRules(SBMLModel, char(Rule)); VaryingParameters(index).ConvertedRule = Rearrange(SubsRule, names{index}); else VaryingParameters(index).ConvertedToAssignRule = 0; VaryingParameters(index).ConvertedRule = ''; end; else VaryingParameters(index).ConvertedToAssignRule = 0; VaryingParameters(index).ConvertedRule = ''; end; index = index + 1; end; function form = SubsAssignmentRules(SBMLModel, rule) [VaryingParameters, AssignRule] = GetParameterAssignmentRules(SBMLModel); form = rule; % bracket the VaryingParameters to be replaced for i = 1:length(VaryingParameters) if (matchName(rule, VaryingParameters{i})) if (~strcmp(AssignRule{i}, '0')) form = strrep(form, VaryingParameters{i}, strcat('(', VaryingParameters{i}, ')')); end; end; end; for i = 1:length(VaryingParameters) if (matchName(rule, VaryingParameters{i})) if (~strcmp(AssignRule{i}, '0')) form = strrep(form, VaryingParameters{i}, AssignRule{i}); end; end; end; function output = Arrange(formula, x, vars) ops = '+-'; f = LoseWhiteSpace(formula); operators = ismember(f, ops); OpIndex = find(operators == 1); %-------------------------------------------------- % divide formula up into elements seperated by +/- if (OpIndex(1) == 1) % leading sign i.e. +x-y NumElements = length(OpIndex); j = 2; index = 2; else NumElements = length(OpIndex) + 1; j = 1; index = 1; end; for i = 1:NumElements-1 element = ''; while (j < OpIndex(index)) element = strcat(element, f(j)); j = j+1; end; Elements{i} = element; j = j + 1; index = index + 1; end; % get last element j = OpIndex(end)+1; element = ''; while (j <= length(f)) element = strcat(element, f(j)); j = j+1; end; Elements{NumElements} = element; %-------------------------------------------------- % check whether element contains x % if does keep on lhs else move to rhs changing sign output = ''; lhs = 1; for i = 1:NumElements if (matchName(Elements{i}, x)) % element contains x LHSElements{lhs} = Elements{i}; if (OpIndex(1) == 1) LHSOps(lhs) = f(OpIndex(i)); elseif (i == 1) LHSOps(lhs) = '+'; else LHSOps(lhs) = f(OpIndex(i-1)); end; lhs = lhs + 1; elseif (i == 1) % first element does not contain x if (OpIndex(1) == 1) if (strcmp(f(1), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else % no sign so + output = strcat(output, '-'); end; output = strcat(output, Elements{i}); else % element not first and does not contain x if (OpIndex(1) == 1) if (strcmp(f(OpIndex(i)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else if (strcmp(f(OpIndex(i-1)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; end; output = strcat(output, Elements{i}); end; end; %------------------------------------------------------ % look at remaining LHS for i = 1:length(LHSElements) Mult{i} = ParseElement(LHSElements{i}, x); end; if (length(LHSElements) == 1) % only one element with x % check signs and multipliers if (strcmp(LHSOps(1), '-')) output = strcat('-(', output, ')'); end; if (~strcmp(Mult{1}, '1')) output = strcat(output, '/', Mult{1}); end; else divisor = ''; if (strcmp(LHSOps(1), '+')) divisor = strcat(divisor, '(', Mult{1}); else divisor = strcat(divisor, '(-', Mult{1}); end; for i = 2:length(LHSElements) divisor = strcat(divisor, LHSOps(i), Mult{i}); end; divisor = strcat(divisor, ')'); output = strcat('(', output, ')/', divisor); end; function multiplier = ParseElement(element, x) % assumes that the element is of the form n*x/m % and returns n/m in simplest form if (strcmp(element, x)) multiplier = '1'; return; end; VarIndex = matchName(element, x); MultIndex = strfind(element, '*'); DivIndex = strfind(element, '/'); if (isempty(MultIndex)) MultIndex = 1; end; if (isempty(DivIndex)) DivIndex = length(element); end; if ((DivIndex < MultIndex) ||(VarIndex < MultIndex) || (VarIndex > DivIndex)) error('Cannot deal with formula in this form: %s', element); end; n = ''; m = ''; for i = 1:MultIndex-1 n = strcat(n, element(i)); end; if (isempty(n)) n = '1'; end; for i = DivIndex+1:length(element) m = strcat(m, element(i)); end; if (isempty(m)) m = '1'; end; % if both m and n represenet numbers then they can be simplified Num_n = str2num(n); Num_m = str2num(m); if (~isempty(Num_n) && ~isempty(Num_m)) multiplier = num2str(Num_n/Num_m); else if (strcmp(m, '1')) multiplier = n; else multiplier = strcat(n, '/', m); end; end; function y = LoseWhiteSpace(charArray) % LoseWhiteSpace(charArray) takes an array of characters % and returns the array with any white space removed % %---------------------------------------------------------------- % EXAMPLE: % y = LoseWhiteSpace(' exa mp le') % y = 'example' % %------------------------------------------------------------ % check input is an array of characters if (~ischar(charArray)) error('LoseWhiteSpace(input)\n%s', 'input must be an array of characters'); end; %------------------------------------------------------------- % get the length of the array NoChars = length(charArray); %------------------------------------------------------------- % create an array that indicates whether the elements of charArray are % spaces % e.g. WSpace = isspace(' v b') = [1, 1, 0, 1, 0] % and determine how many WSpace = isspace(charArray); NoSpaces = sum(WSpace); %----------------------------------------------------------- % rewrite the array to leaving out any spaces % remove any numbers from the array of symbols if (NoSpaces > 0) NewArrayCount = 1; for i = 1:NoChars if (~isspace(charArray(i))) y(NewArrayCount) = charArray(i); NewArrayCount = NewArrayCount + 1; end; end; else y = charArray; end;
github
EPFL-LCSB/matTFA-master
WriteEventHandlerFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/WriteEventHandlerFunction.m
12,176
utf_8
f5fbcd1778a9be55b55816f0d6e020a8
function WriteEventHandlerFunction(SBMLModel, Name) % WriteEventHandlerFunction(SBMLModel, name) % % Takes % % 1. SBMLModel, an SBML Model structure % 2. name, a string representing the name of the ode function being used % % Outputs % % 1. a file 'name_events.m' defining a function that tests whether events % have been triggered % (for use with the event option of MATLABs ode solvers) % % *NOTE:* This function is called from WriteODEFunction when a model with % events is encountered. %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % check input is an SBML model if (~isValidSBML_Model(SBMLModel)) error('WriteEventHandlerFunction(SBMLModel)\n%s', 'argument must be an SBMLModel structure'); end; % ------------------------------------------------------------- % get information from the model [ParameterNames, ParameterValues] = GetAllParametersUnique(SBMLModel); [VarParams, VarInitValues] = GetVaryingParameters(SBMLModel); NumberParams = length(VarParams); [SpeciesNames, SpeciesValues] = GetSpecies(SBMLModel); NumberSpecies = length(SBMLModel.species); VarNames = [SpeciesNames, VarParams]; VarValues = [SpeciesValues, VarInitValues]; NumberVars = NumberSpecies + NumberParams; arrayVariable = 'var1'; if ismember(arrayVariable, VarNames) arrayVariable = 'xyz_var1'; end; if ismember(arrayVariable, VarNames) error ('Unbelievable clash of variable names between model and event handling functions'); end; %--------------------------------------------------------------- % get the name/id of the model % Name = ''; % if (SBMLModel.SBML_level == 1) % Name = SBMLModel.name; % else % if (isempty(SBMLModel.id)) % Name = SBMLModel.name; % else % Name = SBMLModel.id; % end; % end; % version 2.0.2 adds the time_symbol field to the model structure % need to check that it exists if (isfield(SBMLModel, 'time_symbol')) if (~isempty(SBMLModel.time_symbol)) timeVariable = SBMLModel.time_symbol; else timeVariable = 'time'; end; else timeVariable = 'time'; end; if (min(VarValues) == 0) degree = 1; else degree = round(log10(min(VarValues))); end; tol = 1e-10 * power(10, degree); Name = strcat(Name, '_events'); fileName = strcat(Name, '.m'); %-------------------------------------------------------------------- % open the file for writing fileID = fopen(fileName, 'w'); % write the function declaration fprintf(fileID, 'function [value,isterminal,direction] = %s(%s, %s)\n', ... Name, timeVariable, arrayVariable); % need to add comments to output file fprintf(fileID, '%% function %s takes\n', Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%%\t1) current elapsed time of integration\n'); fprintf(fileID, '%%\t2) vector of current output values\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% and stops the integration if the value calculated is zero\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%% %s should be used with MATLABs odeN functions as \n', Name); fprintf(fileID, '%% the events function option\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '%%\ti.e. options = odeset(''Events'', @%s)\n', Name); fprintf(fileID, '%%\n'); fprintf(fileID, '%%\t[t,x] = ode23(@function, [0, t_end], function, options)\n'); fprintf(fileID, '%%\n'); fprintf(fileID, '\n'); fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% constant for use with < or >\neps = %g;\n\n', tol); % write the parameter values fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% parameter values\n\n'); for i = 1:length(ParameterNames) fprintf(fileID, '%s = %g;\n', ParameterNames{i}, ParameterValues(i)); end; % write the current species concentrations fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% floating variables\n'); for i = 1:NumberVars fprintf(fileID, '%s = %s(%u);\n', VarNames{i}, arrayVariable, i); end; % write the events fprintf(fileID, '\n%%--------------------------------------------------------\n'); fprintf(fileID, '%% events - point at which value will return 0\n\n'); numOfFunctions = 0 ; fprintf(fileID, 'value = ['); for i = 1:length(SBMLModel.event) [Funcs, Ignored] = ParseTriggerFunction(SBMLModel.event(i).trigger,[]); for j = 1:length(Funcs) numOfFunctions = numOfFunctions + 1; %fprintf(1, '%s\n', Funcs{j}); if ((i > 1) || (j > 1)) fprintf(fileID, ', %s', Funcs{j}); else fprintf(fileID, '%s', Funcs{j}); end; end; end; fprintf(fileID, '];\n'); fprintf(fileID, '\n%%stop integration\n'); fprintf(fileID, 'isterminal = [1'); for i = 2:numOfFunctions fprintf(fileID, ', 1'); end; fprintf(fileID, '];\n\n'); % this may depend on model fprintf(fileID, '%%set direction at which event should be looked for\n'); fprintf(fileID, 'direction = [-1'); for i = 2:numOfFunctions fprintf(fileID, ', -1'); end; fprintf(fileID, '];\n\n'); fclose(fileID); %-------------------------------------------------------------------------- % other functions function [FunctionStrings, Trigger] = ParseTriggerFunction(Trigger, FunctionStrings) %fprintf(1,'parsing: %s\n', Trigger); if (isstruct(Trigger)) Trigger = LoseLeadingWhiteSpace(Trigger.math); else Trigger = LoseLeadingWhiteSpace(Trigger); end; % trigger has the form function(function(variable,constant), function(v,c)) % need to isolate each OpenBracket = strfind(Trigger, '('); Func = Trigger(1:OpenBracket-1); Trigger = Trigger(OpenBracket+1:length(Trigger)); %fprintf(1,'got function: %s\n', Func); switch (Func) case 'and' [FunctionStrings, Trigger] = ParseTwoArgumentsAndClose(Trigger, FunctionStrings); case 'or' [FunctionStrings, Trigger] = ParseTwoArgumentsAndClose(Trigger, FunctionStrings); case 'lt' [left, right, Trigger] = ParseTwoNumericArgumentsAndClose(Trigger); FunctionString = sprintf('(%s) - (%s) + eps', left, right); FunctionStrings{length(FunctionStrings)+1} = FunctionString; case 'le' [left, right, Trigger] = ParseTwoNumericArgumentsAndClose(Trigger); FunctionString = sprintf('(%s) - (%s) + eps', left, right); FunctionStrings{length(FunctionStrings)+1} = FunctionString; case 'gt' [left, right, Trigger] = ParseTwoNumericArgumentsAndClose(Trigger); FunctionString = sprintf('(%s) - (%s) + eps', right, left); FunctionStrings{length(FunctionStrings)+1} = FunctionString; case 'ge' [left, right, Trigger] = ParseTwoNumericArgumentsAndClose(Trigger); FunctionString = sprintf('(%s) - (%s) + eps', right, left); FunctionStrings{length(FunctionStrings)+1} = FunctionString; otherwise error(sprintf('unrecognised function %s in trigger', Func)); end; function [FunctionStrings, Trigger] = ParseTwoArgumentsAndClose(Trigger, FunctionStrings) %fprintf(1, 'In ParseTwoArgumentsAndClose parsing: %s\n', Trigger); [FunctionStrings, Trigger] = ParseTriggerFunction(Trigger, FunctionStrings); comma = strfind(Trigger, ','); [FunctionStrings, Trigger] = ParseTriggerFunction(Trigger(comma+1:length(Trigger)), FunctionStrings); closeBracket = strfind(Trigger, ')'); Trigger = Trigger(closeBracket+1:length(Trigger)); function [left, right, Trigger] = ParseTwoNumericArgumentsAndClose(Trigger) [left, Trigger] = ParseNumericFunction(Trigger); comma = strfind(Trigger, ','); [right, Trigger] = ParseNumericFunction(Trigger(comma+1:length(Trigger))); closeBracket = strfind(Trigger, ')'); Trigger = Trigger(closeBracket+1:length(Trigger)); function [func, Trigger] = ParseNumericFunction(Trigger) %fprintf(1,'In ParseNumericFunction parsing: %s\n', Trigger); openBracket = strfind(Trigger, '('); comma = strfind(Trigger, ','); closeBracket = strfind(Trigger, ')'); if (isempty(openBracket) || (length(comma)~=0 && comma(1) < openBracket(1)) ... || (length(closeBracket)~=0 && closeBracket(1) < openBracket(1))) % simple case where no nesting if (length(comma)~=0 && comma(1) < closeBracket(1)) % terminated by comma func = Trigger(1:comma(1)-1); Trigger = Trigger(comma(1):length(Trigger)); else if (length(closeBracket)~=0) % terminated by close bracket func = Trigger(1:closeBracket(1)-1); Trigger=Trigger(closeBracket(1):length(Trigger)); else func=Trigger; Trigger=''; end; end; else % nested case func = Trigger(1:openBracket-1); Trigger = Trigger(openBracket+1:length(Trigger)); [subfunc, Trigger] = ParseNumericFunction(Trigger); func = sprintf('%s(%s', func, subfunc); Trigger = LoseLeadingWhiteSpace(Trigger); comma = strfind(Trigger, ','); while (length(comma) ~= 0 && comma(1) == 1) [subfunc, Trigger] = ParseNumericFunction(Trigger); func = sprintf('%s,%s', func, subfunc); Trigger = LoseLeadingWhiteSpace(Trigger); comma = strfind(Trigger, ','); end func=sprintf('%s)',func); closeBracket=strfind(Trigger, ')'); Trigger = Trigger(closeBracket(1)+1:length(Trigger)); end; %fprintf(1,'at end of ParseNumericFunction function: %s\n', func); %fprintf(1,'at end of ParseNumericFunction parsing: %s\n', Trigger); function y = LoseLeadingWhiteSpace(charArray) % LoseLeadingWhiteSpace(charArray) takes an array of characters % and returns the array with any leading white space removed % %---------------------------------------------------------------- % EXAMPLE: % y = LoseLeadingWhiteSpace(' example') % y = 'example' % %------------------------------------------------------------ % check input is an array of characters if (~ischar(charArray)) error('LoseLeadingWhiteSpace(input)\n%s', 'input must be an array of characters'); end; %------------------------------------------------------------- % get the length of the array NoChars = length(charArray); %------------------------------------------------------------- % determine the number of leading spaces % create an array that indicates whether the elements of charArray are % spaces % e.g. WSpace = isspace(' v b') = [1, 1, 0, 1, 0] WSpace = isspace(charArray); % find the indices of elements that are 0 % no spaces equals the index of the first zero minus 1 % e.g. Zeros = find(WSpace == 0) = [3,5] % NoSpaces = 2; Zeros = find(WSpace == 0); if (isempty(Zeros)) NoSpaces = 0; else NoSpaces = Zeros(1)-1; end; %----------------------------------------------------------- % if there is leading white spaces rewrite the array to leave these out if (NoSpaces > 0) for i = 1: NoChars-NoSpaces y(i) = charArray(i+NoSpaces); end; else y = charArray; end;
github
EPFL-LCSB/matTFA-master
SolveODEFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Simulation/SolveODEFunction.m
13,085
utf_8
f779f53ab96b648094f18c546b0837c7
function [t, data] = SolveODEFunction(varargin) % SolveODEFunction(varargin) % % Takes % % 1. a MATLAB_SBML model structure (required argument) % 2. time limit (default = 10) % 3. number of time steps (default lets the solver decide) % 4. a flag to indicate whether to output species values in amount/concentration % 1 amount, 0 concentration (default) % 5. a flag to indicate whether to output the simulation data as % a comma separated variable (csv) file % 1 output 0 no output (default) % 6. a filename (this is needed if WriteODEFunction was used with a % filename) % % Returns % % 1. an array of time values % 2. an array of the values of variables at each time point; species will % be in concentration or amount as specified by input arguments % % Outputs % % 1. a file 'name.csv' with the data results (if the flag to output such a % file is set to 1. % % *NOTE:* the results are generated using ode45 solver (MATLAB) or lsode % (Octave) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % get inputs if (nargin < 1) error('SolveODEFunction(SBMLModel, ...)\n%s', 'must have at least one argument'); elseif (nargin > 6) error('SolveODEFunction(SBMLModel, ...)\n%s', 'cannot have more than six arguments'); end; % first argument SBMLModel = varargin{1}; % check first input is an SBML model if (~isValidSBML_Model(SBMLModel)) error('SolveODEFunction(SBMLModel)\n%s', 'first argument must be an SBMLModel structure'); end; % put in default values Time_limit = 10; NoSteps = -1; outAmt = 0; outCSV = 1; if (SBMLModel.SBML_level == 1) Name = SBMLModel.name; else Name = SBMLModel.id; end; if (length(Name) > 63) Name = Name(1:60); end; switch nargin case 2 Time_limit = varargin{2}; case 3 Time_limit = varargin{2}; NoSteps = varargin{3}; case 4 Time_limit = varargin{2}; NoSteps = varargin{3}; outAmt = varargin{4}; case 5 Time_limit = varargin{2}; NoSteps = varargin{3}; outAmt = varargin{4}; outCSV = varargin{5}; case 6 Time_limit = varargin{2}; NoSteps = varargin{3}; outAmt = varargin{4}; outCSV = varargin{5}; if ~isempty(varargin{6}) Name = varargin{6}; end; end; % check values are sensible if ((length(Time_limit) ~= 1) || (~isnumeric(Time_limit))) error('SolveODEFunction(SBMLModel, time)\n%s', ... 'time must be a single real number indicating a time limit'); end; if ((length(NoSteps) ~= 1) || (~isnumeric(NoSteps))) error('SolveODEFunction(SBMLModel, time, steps)\n%s', ... 'steps must be a single real number indicating the number of steps'); end; if (~isIntegralNumber(outAmt) || outAmt < 0 || outAmt > 1) error('SolveODEFunction(SBMLModel, time, steps, concFlag)\n%s', ... 'concFlag must be 0 or 1'); end; if (~isIntegralNumber(outCSV) || outCSV < 0 || outCSV > 1) error('SolveODEFunction(SBMLModel, time, steps, concFlag, csvFlag)\n%s', ... 'csvFlag must be 0 or 1'); end; if (~ischar(Name)) error('SolveODEFunction(SBMLModel, time, steps, concFlag, csvFlag, name)\n%s', ... 'name must be a string'); end; fileName = strcat(Name, '.m'); %-------------------------------------------------------------- % check that a .m file of this name exists % check whether file exists fId = fopen(fileName); if (fId == -1) if (nargin < 6) error('SolveODEFunction(SBMLModel)\n%s\n%s', ... 'You must use WriteODEFunction to output an ode function for this', ... 'model before using this function'); else error('SolveODEFunction(SBMLModel)\n%s', 'You have not used this filename with WriteODEFunction'); end; else fclose(fId); end; %------------------------------------------------------------ % calculate values to use in iterative process if (NoSteps ~= -1) delta_t = Time_limit/NoSteps; Time_span = [0:delta_t:Time_limit]; else Time_span = [0, Time_limit]; end; %-------------------------------------------------------------- % get variables from the model [VarParams, VarInitValues] = GetVaryingParameters(SBMLModel); NumberParams = length(VarParams); [SpeciesNames, SpeciesValues] = GetSpecies(SBMLModel); NumberSpecies = length(SBMLModel.species); VarNames = [SpeciesNames, VarParams]; NumVars = NumberSpecies + NumberParams; %--------------------------------------------------------------- % get function handle fhandle = str2func(Name); % get initial conditions InitConds = feval(fhandle); % set the tolerances of the odesolver to appropriate values RelTol = min(InitConds(find(InitConds > 0))) * 1e-4; if isempty(RelTol) RelTol = 1e-6; end; if (RelTol > 1e-6) RelTol = 1e-6; end; AbsTol = RelTol * 1e-4; if exist('OCTAVE_VERSION') [t, data] = runSimulationOctave(RelTol, AbsTol, fhandle, Time_span, InitConds); else if Model_getNumEvents(SBMLModel) == 0 [t, data] = runSimulation(RelTol, AbsTol, fhandle, Time_span, InitConds); else [t, data] = runEventSimulation(Name, NumVars, RelTol, AbsTol, fhandle, Time_span, InitConds); end; end; if (outAmt == 1) data = calculateAmount(SBMLModel, t, data); end; if (outCSV == 1) outputData(t, data, Name, VarNames); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TimeCourse, VarsCourse] = runSimulation(RelTol, AbsTol, ... fhandle, Time_span, InitConds) options = odeset('RelTol', RelTol, 'AbsTol', AbsTol); [TimeCourse, VarsCourse] = runSimulator(options, fhandle, Time_span, InitConds); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TimeCourse, VarsCourse] = runEventSimulation(Name, NumVars, RelTol, AbsTol, ... fhandle, Time_span, InitConds) eventName = strcat(Name, '_events'); afterEvent = strcat(Name, '_eventAssign'); eventHandle = str2func(eventName); AfterEventHandle = str2func(afterEvent); options = odeset('Events', eventHandle, 'RelTol', RelTol, 'AbsTol', AbsTol); TimeCourse = []; VarsCourse = []; while ((~isempty(Time_span)) && (Time_span(1) < Time_span(end))) [TimeCourse, VarsCourse, InitConds, Time_span] = ... runEventSimulator(options, fhandle, Time_span, ... InitConds, TimeCourse, VarsCourse, NumVars, ... AfterEventHandle, Time_span(end)); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TimeCourse, VarsCourse, InitConds, Time_span] ... = runEventSimulator(options, fhandle, Time_span, InitConds, TimeCourse, ... VarsCourse, NumVars, AfterEventHandle, Time_limit) [TimeCourseA, VarsCourseA, eventTime, ab, eventNo] = ode45(fhandle, Time_span, InitConds, options); % need to catch case where the time span entered was two sequential % times from the original time-span % e.g. original Time_span = [0, 0.1, ..., 4.9, 5.0] % Time_span = [4.9, 5.0] % % ode solver will output points between if (length(Time_span) == 2) NewTimeCourse = [TimeCourseA(1); TimeCourseA(end)]; TimeCourseA = NewTimeCourse; for i = 1:NumVars NewVar(1,i) = VarsCourseA(1, i); NewVar(2,i) = VarsCourseA(end, i); end; VarsCourseA = NewVar; end; % store current values of the varaiables at the time simulation ended for i = 1:NumVars CurrentValues(i) = VarsCourseA(end, i); end; % if we are not at the end of the time span remove the last point from % each if (TimeCourseA(end) ~= Time_span(end)) TimeCourseA = TimeCourseA(1:length(TimeCourseA)-1); for i = 1:NumVars VarsCourseB(:,i) = VarsCourseA(1:end-1, i); end; else VarsCourseB = VarsCourseA; end; % adjust the time span Time_spanA = Time_span - TimeCourseA(length(TimeCourseA)); Time_span_new = Time_spanA((find(Time_spanA==0)+1): length(Time_spanA)); Time_span = []; Time_span = Time_span_new + TimeCourseA(length(TimeCourseA)); % if time span has not finished get new initial conditions % need to integrate from the time the event stopped the solver to the % next starting point to determine the new initial conditions if (~isempty(Time_span)) InitConds = runCatchUpSimulation(AfterEventHandle, eventTime(end), ... CurrentValues, eventNo(end), Time_span(1), Time_limit, options, fhandle, NumVars); end; % add the values from this iteration TimeCourse = [TimeCourse;TimeCourseA]; VarsCourse = [VarsCourse;VarsCourseB]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function InitConds = runCatchUpSimulation(AfterEventHandle, eventTime, ... CurrentValues, eventNo, endTime, Time_limit, options, fhandle, NumVars) CurrentValues = feval(AfterEventHandle, eventTime, CurrentValues, eventNo); [t,NewValues, eventTime, ab, eventNo] = ode45(fhandle, ... [eventTime, endTime], CurrentValues, options); if ~isempty(eventTime) % an event has been triggered in this small time span for i = 1:NumVars CurrentValues(i) = NewValues(end, i); end; InitConds = runCatchUpSimulation(AfterEventHandle, eventTime(end), ... CurrentValues, eventNo(end), endTime, Time_limit, options, fhandle, NumVars); else for i = 1:NumVars InitConds(i) = NewValues(length(NewValues), i); end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TimeCourse, VarsCourse] = runSimulator(options, fhandle, ... Time_span, InitConds) [TimeCourse, VarsCourse] = ode45(fhandle, Time_span, InitConds, options); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TimeCourse, VarsCourse] = runSimulationOctave(RelTol, AbsTol, ... fhandle, Time_span, InitConds) lsode_options('relative tolerance', RelTol); lsode_options('absolute tolerance', AbsTol); VarsCourse = lsode(fhandle, InitConds, Time_span); TimeCourse = Time_span; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function amtData = calculateAmount(SBMLModel, TimeCourse, SpeciesCourse) [compartments, comp_values] = GetCompartments(SBMLModel); allOnes = 1; for i=1:length(comp_values) if comp_values(i) ~= 1 allOnes = 0; end; end; amtData = SpeciesCourse; if allOnes == 1 return; else for i = 1:length(TimeCourse) for j = 1:length(SBMLModel.species) % if the species hasOnlySubstanceUnits then it is already in amount if (SBMLModel.species(j).hasOnlySubstanceUnits == 1) amtData(i, j) = SpeciesCourse(i, j); else % need to deal with mutliple compartments comp = Model_getCompartmentById(SBMLModel, SBMLModel.species(j).compartment); comp_size = comp.size; % catch any anomalies if (isnan(comp_size)) comp_size = 1; end; amtData(i, j) = SpeciesCourse(i,j)*comp_size; end; end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function outputData(TimeCourse, VarsCourse, Name, Vars) fileName = strcat(Name, '.csv'); %-------------------------------------------------------------------- % open the file for writing fileID = fopen(fileName, 'w'); numVars = length(Vars); numdata = size(VarsCourse); if (numVars ~= numdata(2)) || (length(TimeCourse) ~= numdata(1)) error ('%s\n%s', 'Incorrect numbers of data points from simulation', ... 'Please report the problem to libsbml-team @caltech.edu') end; % write the header fprintf(fileID, 'time'); for i = 1: length(Vars) fprintf(fileID, ',%s', Vars{i}); end; fprintf(fileID, '\n'); % write each time course step values for i = 1:length(TimeCourse) fprintf(fileID, '%0.5g', TimeCourse(i)); for j = 1:length(Vars) fprintf(fileID, ',%1.16g', VarsCourse(i,j)); end; fprintf(fileID, '\n'); end; fclose(fileID);
github
EPFL-LCSB/matTFA-master
SubstituteFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Convenience/SubstituteFunction.m
5,155
utf_8
66c788cb09b115ecfad961f50a6ac138
function Formula = SubstituteFunction(OriginalFormula, SBMLFunctionDefinition) % newExpression = SubstituteFunction(expression, SBMLFunctionDefinition) % % Takes % % 1. expression, a string representation of a math expression % 2. SBMLFunctionDefinition, an SBML FunctionDefinition structure % % Returns % % 1. newExpression % - the string representation of the expression when any instances of the % functionDefinition have been substituted % - an empty string if the functiondefinition is not in the original % expression % % *EXAMPLE:* % % Consider fD to be an SBMLFunctionDefinition % with id = 'g' and math = 'lambda(x,x+0.5)' % % formula = SubstituteFormula('g(y)', fD) % % formula = 'y+0.5' % % % formula = SubstituteFormula('h(y)', fD) % % formula = '' % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> %check arguments are appropriate if (~isstruct(SBMLFunctionDefinition)) error(sprintf('%s', ... 'first argument must be an SBML functionDefinition structure')); end; [sbmlLevel, sbmlVersion] = GetLevelVersion(SBMLFunctionDefinition); if (~ischar(OriginalFormula)) error('SubstituteFunction(OriginalFormula, SBMLFunctionDefinition)\n%s', 'first argument must be a character array containing the id of the function definition'); elseif (~isSBML_FunctionDefinition(SBMLFunctionDefinition, sbmlLevel, sbmlVersion)) error('SubstituteFunction(OriginalFormula, SBMLFunctionDefinition)\n%s', 'second argument must be an SBML function definition structure'); end; OriginalFormula = LoseWhiteSpace(OriginalFormula); startPoint = matchFunctionName(OriginalFormula, SBMLFunctionDefinition.id); if (isempty(startPoint)) Formula = ''; return; end; ElementsOfFuncDef = GetArgumentsFromLambdaFunction(SBMLFunctionDefinition.math); % get the arguments of the application of the formula Formula = ''; index = length(startPoint); StartFunctionInFormula = startPoint(index); j = StartFunctionInFormula + length(SBMLFunctionDefinition.id); pairs = PairBrackets(OriginalFormula); for i=1:length(pairs) if (pairs(i, 1) == j) endPt = pairs(i, 2); break; end; end; [NoElements, ElementsInFormula] = GetElementsOfFunction(OriginalFormula(j:endPt)); OriginalFunction = ''; for i = StartFunctionInFormula:endPt OriginalFunction = strcat(OriginalFunction, OriginalFormula(i)); end; % check got right number if (NoElements ~= length(ElementsOfFuncDef) - 1) error('SubstituteFunction(OriginalFormula, SBMLFunctionDefinition)\n%s', 'mismatch in number of arguments between formula and function'); end; % check that same arguments have not been used for i = 1:NoElements for j = 1:NoElements if (strcmp(ElementsInFormula{i}, ElementsOfFuncDef{j})) newElem = strcat(ElementsInFormula{i}, '_new'); ElementsOfFuncDef{j} = newElem; ElementsOfFuncDef{end} = strrep(ElementsOfFuncDef{end}, ElementsInFormula{i}, newElem); end; end; end; % replace the arguments in function definition with those in the formula FuncFormula = '('; FuncFormula = strcat(FuncFormula, ElementsOfFuncDef{end}); FuncFormula = strcat(FuncFormula, ')'); for i = 1:NoElements FuncFormula = strrep(FuncFormula, ElementsOfFuncDef{i}, ElementsInFormula{i}); end; Formula = strrep(OriginalFormula, OriginalFunction, FuncFormula); % if the function occurred more than once if (index - 1) > 0 Formula = SubstituteFunction(Formula, SBMLFunctionDefinition); end; function [NoElements, ElementsInFormula] = GetElementsOfFunction(OriginalFormula); j = 2; c = OriginalFormula(j); element = ''; NoElements = 1; ElementsInFormula = {}; while (j < length(OriginalFormula)) if (strcmp(c, ',')) ElementsInFormula{NoElements} = element; element = ''; NoElements = NoElements + 1; else element = strcat(element, c); end; j = j + 1; c = OriginalFormula(j); end; ElementsInFormula{NoElements} = element;
github
EPFL-LCSB/matTFA-master
RemoveDuplicates.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Convenience/RemoveDuplicates.m
2,898
utf_8
46f7aade9e3235449589d381f0890c24
function y = RemoveDuplicates(FullArray) % newArray = RemoveDuplicates(array) % % Takes % % 1. array, any array % % Returns % % 1. the array with any duplicate entries removed % % *EXAMPLE:* % % newArray = RemoveDuplicates([2, 3, 4, 3, 2, 5]) % newArray = [2, 3, 4, 5] % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % check whether array is a column vector [size_x, size_y] = size(FullArray); if (size_y == 1 && size_x ~= 1) y = RemoveDuplicatesColumn(FullArray); return; end; %------------------------------------------------------------- % find number of elements in existing array NoElements = length(FullArray); if (NoElements == 0) y = []; return; end; % copy first element of the array to the new array newArrayIndex = 1; NewArray(1) = FullArray(1); %loop through all elements % if they do not already exist in new array copy them into it for i = 2:NoElements element = FullArray(i); if (~ismember(element, NewArray)) newArrayIndex = newArrayIndex + 1; NewArray(newArrayIndex) = element; end; end; y = NewArray; function y = RemoveDuplicatesColumn(FullArray) % RemoveDuplicatesCell takes column vector % and returns it with any duplicates removed % find number of elements in existing array [NoElements, x] = size(FullArray); % copy first element of the array to the new array newArrayIndex = 1; NewArray(1,x) = FullArray(1); %loop through all elements % if they already exist in new array do not copy for i = 2:NoElements element = FullArray(i); if (~ismember(element, NewArray)) newArrayIndex = newArrayIndex + 1; NewArray(newArrayIndex,x) = element; end; end; y = NewArray;
github
EPFL-LCSB/matTFA-master
Rearrange.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Convenience/Rearrange.m
11,479
utf_8
6ed57da4458b9e994a775fa3c990b46f
function output = Rearrange(formula, x) % output = Rearrange(expression, name) % % Takes % % 1. expression, a string representation of a math expression % 2. name, a string representing the name of a variable % % Returns % % 1. the expression rearranged in terms of the variable % % *EXAMPLE:* % % output = Rearrange('X + Y - Z', 'X') % % output = '-Y+Z' % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> f = LoseWhiteSpace(formula); if (~isempty(strfind(f, '+-'))) f = strrep(f, '+-', '-'); end; if (~isempty(strfind(f, '-+'))) f = strrep(f, '-+', '-'); end; % if x is not in the formula just return the formula if (~ismember(f, x)) output = f; return; end; % if there are brackets these need to switch sides of the equation % "intact" ie x+(y+z) rearranges to x = -(y+z) brackets = PairBrackets(f); num = 0; if (length(brackets)>1) [num, m] = size(brackets); for b=1:num group{b} = f(brackets(1): brackets(2)); if (sum(ismember(group{b}, x)) > 0) error('Cannot deal with formula in this form: %s', f); end; newvar{b} = strcat('var', num2str(b)); f = strrep(f, group{b}, newvar{b}); end; end; ops = '+-'; operators = ismember(f, ops); OpIndex = find(operators == 1); if(~isempty(OpIndex)) %-------------------------------------------------- % divide formula up into elements seperated by +/- if (OpIndex(1) == 1) % leading sign i.e. +x-y NumElements = length(OpIndex); j = 2; index = 2; else NumElements = length(OpIndex) + 1; j = 1; index = 1; end; for i = 1:NumElements-1 element = ''; while (j < OpIndex(index)) element = strcat(element, f(j)); j = j+1; end; Elements{i} = element; j = j + 1; index = index + 1; end; % get last element j = OpIndex(end)+1; element = ''; while (j <= length(f)) element = strcat(element, f(j)); j = j+1; end; Elements{NumElements} = element; else NumElements = 0; LHSElements{1} = f; LHSOps(1) = '+'; end; %-------------------------------------------------- % check whether element contains x % if does keep on lhs else move to rhs changing sign output = ''; lhs = 1; for i = 1:NumElements if (matchName(Elements{i}, x)) % element contains x LHSElements{lhs} = Elements{i}; if (OpIndex(1) == 1) LHSOps(lhs) = f(OpIndex(i)); elseif (i == 1) LHSOps(lhs) = '+'; else LHSOps(lhs) = f(OpIndex(i-1)); end; lhs = lhs + 1; elseif (i == 1) % first element does not contain x if (OpIndex(1) == 1) if (strcmp(f(1), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else % no sign so + output = strcat(output, '-'); end; output = strcat(output, Elements{i}); else % element not first and does not contain x if (OpIndex(1) == 1) if (strcmp(f(OpIndex(i)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; else if (strcmp(f(OpIndex(i-1)), '-')) output = strcat(output, '+'); else output = strcat(output, '-'); end; end; output = strcat(output, Elements{i}); end; end; %------------------------------------------------------ % look at remaining LHS for i = 1:length(LHSElements) [Mult{i}, invert(i)] = ParseElement(LHSElements{i}, x); end; operators = '+-/*^'; if (length(LHSElements) == 1) % only one element with x % check signs and multipliers if (strcmp(LHSOps(1), '-')) output = strcat('-(', output, ')'); end; if (~strcmp(Mult{1}, '1')) if (isempty(output)) if (invert(1) == 0) output = '0'; end; else if (sum(ismember(Mult{1}, '/')) > 0) if (invert(1) == 0) output = strcat(output, '*(', Invert(Mult{1}, x), ')'); else output = strcat('(', Mult{1}, ')*(', Invert(output, x), ')'); end; else output = strcat(output, '/', Mult{1}); end; end; end; else if (isempty(output)) if (invert == 0) output = '0'; end; else divisor = ''; if (strcmp(LHSOps(1), '+')) divisor = strcat(divisor, '(', Mult{1}); else divisor = strcat(divisor, '(-', Mult{1}); end; for i = 2:length(LHSElements) divisor = strcat(divisor, LHSOps(i), Mult{i}); end; divisor = strcat(divisor, ')'); if (sum(ismember(output, operators)) > 0) output = strcat('(', output, ')/', divisor); else output = strcat(output, '/', divisor); end; end; end; % replaced substituted vars for b=1:num output = strrep(output, newvar{b}, group{b}); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [multiplier, invert] = ParseElement(element, x) if (strcmp(element, x)) multiplier = '1'; invert = 0; return; end; multipliers = strfind(element, '*'); if (length(multipliers) > 2) error('Too many multipliers'); end; VarIndex = matchName(element, x); if (isempty(multipliers)) MultIndex = 1; else if (length(multipliers) == 1) MultIndex = multipliers(1); else if (VarIndex > multipliers(2)) MultIndex = multipliers(2); else MultIndex = multipliers(1); end; end; end; DivIndex = strfind(element, '/'); if (isempty(DivIndex)) DivIndex = length(element); end; % if we have x/5*b if (DivIndex < MultIndex) MultIndex = 1; end; % if we have b/x if (VarIndex > DivIndex) [element, noinvert] = Invert(element, x); multiplier = ParseElement(element, x); if (noinvert == 0) multiplier = Invert(multiplier, x); invert = 1; else invert = 0; end; return; end; % if we have x*c if (VarIndex < MultIndex) element = SwapMultiplier(element, x); [multiplier, invert] = ParseElement(element, x); return; end; if ((DivIndex < MultIndex) ||(VarIndex < MultIndex) || (VarIndex > DivIndex)) error('Cannot deal with formula in this form: %s', element); end; n = ''; m = ''; for i = 1:MultIndex-1 if (element(i) ~= '(' && element(i) ~= ')') n = strcat(n, element(i)); end; end; if (isempty(n)) n = '1'; end; for i = DivIndex+1:length(element) m = strcat(m, element(i)); end; if (isempty(m)) m = '1'; end; % if both m and n represenet numbers then they can be simplified Num_n = str2num(n); Num_m = str2num(m); if (~isempty(Num_n) && ~isempty(Num_m)) multiplier = num2str(Num_n/Num_m); else if (strcmp(m, '1')) multiplier = n; else multiplier = strcat(n, '/', m); end; end; invert = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [y, noinvert] = Invert(formula, x) % need to consider a/x*b % which is really (b*a)/x operators = '+-/*^'; noinvert = 0; divider = strfind(formula, '/'); if (length(divider) > 1) error('Too many divide signs'); end; if (isempty(divider)) nominator = formula; denominator = '1'; else nominator = formula(1:divider-1); denominator = formula(divider+1:end); end; if (~IsSingleBracketed(denominator)) multiplier = strfind(denominator, '*'); if (length(multiplier) > 1) error('Too may multiplication signs'); end; if (~isempty(multiplier)) lhs = denominator(1:multiplier-1); rhs = denominator(multiplier+1:end); if (sum(ismember(nominator, operators)) > 0) if (IsSingleBracketed(nominator)) nominator = strcat(nominator, '*', rhs); else nominator = strcat('(', nominator, ')*', rhs); end; else nominator = strcat(nominator, '*', rhs); end; denominator = lhs; end; end; % if x is now part of the nominator dont invert if (matchName(nominator, x)) if (sum(ismember(nominator, operators)) > 0) if (IsSingleBracketed(nominator)) y = strcat(nominator, '/'); else y = strcat ('(', nominator, ')/'); end; else y = strcat(nominator, '/'); end; if (sum(ismember(denominator, operators)) > 0) if (IsSingleBracketed(denominator)) y = strcat(y, denominator); else y = strcat(y, '(', denominator, ')'); end; else y = strcat(y, denominator); end; noinvert = 1; else if (sum(ismember(denominator, operators)) > 0) if (IsSingleBracketed(denominator)) y = strcat(denominator, '/'); else y = strcat ('(', denominator, ')/'); end; else y = strcat(denominator, '/'); end; if (sum(ismember(nominator, operators)) > 0) if (IsSingleBracketed(nominator)) y = strcat(y, nominator); else y = strcat(y, '(', nominator, ')'); end; else y = strcat(y, nominator); end; end; %y = strcat('(', denominator, ')/(', nominator, ')'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = IsSingleBracketed(formula) y = 0; Open = strfind(formula, '('); if (isempty(Open) || length(Open)> 1) return; end; if (Open ~= 1) return; end; len = length(formula); Close = strfind(formula, ')'); if (length(Close)> 1) return; end; if (Close ~= len) return; end; y = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = SwapMultiplier(formula, x) % formula will have only * and / % x will occur before both % * will occur before / index = matchName(formula, x); start = index(1); index = strfind(formula, '*'); multiplier = index(1); nextop = 0; if (length(index) > 1) nextop = index(2); end; index = strfind(formula, '/'); if (length(index) > 0) end_after = index(1)-1; else if (nextop > 0) end_after = nextop-1; else end_after = length(formula); end; end; replace = ''; for i = multiplier+1:end_after replace = strcat(replace, formula(i)); end; newformula = replace; newformula = strcat(newformula, '*'); newformula = strcat(newformula, x); for i = end_after+1:length(formula) newformula = strcat(newformula, formula(i)); end; y = newformula;
github
EPFL-LCSB/matTFA-master
propagateLevelVersion.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/MATLAB_SBML_Structure_Functions/structFieldnames/propagateLevelVersion.m
2,729
utf_8
ac0c57fde5be4302fbf3241c14e3787e
function model = propagateLevelVersion(SBMLModel) % SBMLModel = propagateLevelVersion(SBMLModel) % % Takes % % 1. SBMLModel, an SBML Model structure % % Returns % % 1. the SBML Model structure with level and version fields added to all % sub structures % % *NOTE:* This function facilitates keeping track of the level and version % of sub objects within a model %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> %get level and version and check the input arguments are appropriate if ~isValidSBML_Model(SBMLModel) error('first argument must be an SBMLModel structure'); end; level = SBMLModel.SBML_level; version = SBMLModel.SBML_version; model = addLV('SBML_MODEL', SBMLModel, level, version); function model = addLV(typecode, model, level, version) fields = getFieldnames(typecode, level, version); for i=1:length(fields) subcomp = getfield(model, fields{i}); if isstruct(subcomp) if length(subcomp) > 0 model = setfield(model, fields{i}, addLevelVersion(subcomp, level, version)); end; end; end; function retStr = addLevelVersion(substr, level, version) if length(substr) == 1 retStr = addLevelVersionStruct(substr, level, version); retStr = addLV(substr.typecode, retStr, level, version); else for i=1:length(substr) retStr(i) = addLevelVersionStruct(substr(i), level, version); retStr(i) = addLV(substr(i).typecode, retStr(i), level, version); end; end; function retStr = addLevelVersionStruct(substr, level, version) retStr = substr; retStr.level = level; retStr.version = version;
github
EPFL-LCSB/matTFA-master
testObject.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/MATLAB_SBML_Structure_Functions/Test/testObject.m
10,178
utf_8
7294eab33dbb7ea5880923e3769a8072
function [fail, num, message] = testObject(obj, attributes, component, fail, num, message) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % different cases which indicate what type of attribute is being tested % 1 string % 2 sboTerm - ie integer with unset value = -1 % 3 double whose unset value is NaN % 4 double - always set % 5 boolean - with issetvalue % 6 int - always set % 7 boolean - no issetvalue % 8 L1RuleType - always set % 9 another structure - test add functions % 10 SBMLlevel/version - always set - ignore % if no attributes obj should be empty if length(attributes) == 0 if (~isempty(obj)) fail = fail + 1; num = num + 1; m = sprintf('create%s created an invalid object', component); disp(m); message{length(message)+1} = m; end; end; %remove any fbc prefix for i = 1:length(attributes) name = attributes{i}{1}; if length(name) > 4 if strcmp(name(1:4), 'Fbc_') attributes{i}{1} = strcat(upper(name(5:5)), name(6:end)); end; end; end; for i = 1:length(attributes) switch (attributes{i}{2}) case 7 f = 0; case 9 [f, m] = testEmpty(component, attributes{i}{1}, obj); case {4, 6, 8, 10} [f, m] = testAlwaysSet(component, attributes{i}{1}, obj); otherwise [f, m] = testIsNotSet(component, attributes{i}{1}, obj); end; num = num + 1; if f > 0 fail = fail + f; disp(m); message{length(message)+1} = m; end; end; for i = 1:length(attributes) [f, m] = testSet(component, attributes{i}{1}, obj, attributes{i}{2}); num = num + 3; if f > 0 fail = fail + f; disp(m); len = length(message); for j = 1:length(m) message{len+j} = m{j}; end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fail, message] = testEmpty(component, attribute, obj) message = {}; singles = {'KineticLaw', 'Trigger', 'Delay', 'Priority', 'StoichiometryMath'}; if isIn(singles, attribute) fhandle = sprintf('%s_isSet%s', component, attribute); else fhandle = sprintf('%s_getNum%ss', component, attribute); end; result = feval(fhandle, obj); if result == 0 fail = 0; else fail = 1; message{1} = sprintf('%s should return 0', fhandle); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fail, message] = testIsNotSet(component, attribute, obj) message = {}; fhandle = sprintf('%s_isSet%s', component, attribute); result = feval(fhandle, obj); if result == 0 fail = 0; else fail = 1; message{1} = sprintf('%s_isSet%s should return 0', component, attribute); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fail, message] = testAlwaysSet(component, attribute, obj) message = {}; fhandle = sprintf('%s_isSet%s', component, attribute); result = feval(fhandle, obj); if result == 1 fail = 0; else fail = 1; message{1} = sprintf('%s_isSet%s should return 1', component, attribute); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fail, message] = testSet(component, attribute, obj, type) testStr = 'abc'; testDouble = 3.3; testInt = 2; testBool = 1; testL1RuleType = 'rate'; message = {}; fail = 0; if (type == 9) [fail, message] = testAdd(component, attribute, obj); return; elseif (type == 10) % level/version return; end; fhandle_isSet = sprintf('%s_isSet%s', component, attribute); fhandle_set = sprintf('%s_set%s', component, attribute); fhandle_get = sprintf('%s_get%s', component, attribute); fhandle_unset = sprintf('%s_unset%s', component, attribute); % set and test that attribute is set switch (type) case 1 obj = feval(fhandle_set, obj, testStr); case 2 obj = feval(fhandle_set, obj, testInt); case 3 obj = feval(fhandle_set, obj, testDouble); case 4 obj = feval(fhandle_set, obj, testDouble); case 5 obj = feval(fhandle_set, obj, testBool); case 6 obj = feval(fhandle_set, obj, testInt); case 7 obj = feval(fhandle_set, obj, testBool); case 8 obj = feval(fhandle_set, obj, testL1RuleType); otherwise end; switch (type) case 7 result = 1; otherwise result = feval(fhandle_isSet, obj); end; if result ~= 1 fail = fail + 1; m = sprintf('%s_set%s failed', component, attribute); message{length(message)+1} = m; end; %get the attribute and check it is correct result = feval(fhandle_get, obj); switch (type) case 1 if ~strcmp(result, testStr) fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 2 if result ~= testInt fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 3 if result ~= testDouble fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 4 if result ~= testDouble fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 5 if result ~= testBool fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 6 if result ~= testInt fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 7 if result ~= testBool fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; case 8 if ~strcmp(result, testL1RuleType) fail = fail + 1; m = sprintf('%s_get%s failed', component, attribute); message{length(message)+1} = m; end; otherwise end; % unset and check it is unset switch (type) case {4, 6, 7, 8} result = 0; otherwise obj = feval(fhandle_unset, obj); result = feval(fhandle_isSet, obj); end; if result ~= 0 fail = fail + 1; m = sprintf('%s_unset%s failed', component, attribute); message{length(message)+1} = m; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fail, message] = testAdd(component, attribute, obj) fail = 0; message = {}; singles = {'KineticLaw', 'Trigger', 'Delay', 'Priority', 'StoichiometryMath'}; if isIn(singles, attribute) single = 1; else single = 0; end; if strcmp(attribute, 'Rule') fhandle_create = 'AlgebraicRule_create'; elseif strcmp(attribute, 'Product') || strcmp(attribute, 'Reactant') fhandle_create = 'SpeciesReference_create'; elseif strcmp(attribute, 'Modifier') fhandle_create = 'ModifierSpeciesReference_create'; else fhandle_create = sprintf('%s_create', attribute); end; fhandle_get = sprintf('%s_get%s', component, attribute); if single == 1 fhandle_set = sprintf('%s_set%s', component, attribute); fhandle_isset = sprintf('%s_isSet%s', component, attribute); fhandle_unset = sprintf('%s_unset%s', component, attribute); else fhandle_set = sprintf('%s_add%s', component, attribute); fhandle_isset = sprintf('%s_getNum%ss', component, attribute); fhandle_getLO = sprintf('%s_getListOf%ss', component, attribute); end; fhandle_createSub = sprintf('%s_create%s', component, attribute); if strcmp(obj.typecode, 'SBML_MODEL') newObj = feval(fhandle_create, obj.SBML_level, obj.SBML_version); else newObj = feval(fhandle_create, obj.level, obj.version); end; % add new obj and check is now set obj = feval(fhandle_set, obj, newObj); result = feval(fhandle_isset, obj); if result == 1 fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_set); end; % get the obj and test if single == 1 returnObj = feval(fhandle_get, obj); else returnObj = feval(fhandle_get, obj, 1); end; if areIdentical(returnObj, newObj) fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_set); end; % test unset single obj if single obj = feval(fhandle_unset, obj); result = feval(fhandle_isset, obj); if result == 0 fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_unset); end; else obj = feval(fhandle_set, obj, newObj); lo = feval(fhandle_getLO, obj); result = length(lo); if result == 2 fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_getLO); end; end; % test create if single obj = feval(fhandle_createSub, obj); result = feval(fhandle_isset, obj); if result == 1 fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_createSub); end; else obj = feval(fhandle_createSub, obj); lo = feval(fhandle_getLO, obj); result = length(lo); if result == 3 fail = 0; else fail = 1; message{1} = sprintf('%s failed', fhandle_createSub); end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function value = isIn(array, thing) value = sum(ismember(array, thing));
github
EPFL-LCSB/matTFA-master
Model_getListOfByTypecode.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/MATLAB_SBML_Structure_Functions/Model/Model_getListOfByTypecode.m
3,470
utf_8
3ee51ba7a44c4697be5cce017e9c2346
function array = Model_getListOfByTypecode(SBMLModel, SBMLTypecode) % listOf = Model_getListOfByTypecode(SBMLModel, typecode) % % Takes % % 1. SBMLModel, an SBML Model structure % 2. typecode; a string representing the typecode of SBML ListOf structure % % Returns % % 1. the SBML ListOf structure that has this typecode % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % check that input is correct if (~isValidSBML_Model(SBMLModel)) error(sprintf('%s\n%s', 'Model_getListOfByTypecode(SBMLModel, SBMLTypecode)', 'first argument must be an SBML model structure')); elseif (~CheckTypecode(SBMLTypecode)) error(sprintf('%s\n%s', 'Model_getListOfByTypecode(SBMLModel, SBMLTypecode)', 'second argument must be a string representing an SBML typecode')); end; switch (SBMLTypecode) case 'SBML_FUNCTION_DEFINITION' array = SBMLModel.functionDefinition; case 'SBML_UNIT_DEFINITION' array = SBMLModel.unitDefinition; case 'SBML_COMPARTMENT' array = SBMLModel.compartment; case 'SBML_SPECIES' array = SBMLModel.species; case 'SBML_PARAMETER' array = SBMLModel.parameter; case {'SBML_ASSIGNMENT_RULE', 'SBML_ALGEBRAIC_RULE', 'SBML_RATE_RULE', 'SBML_SPECIES_CONCENTRATION_RULE', 'SBML_COMPARTMENT_VOLUME_RULE', 'SBML_PARAMETER_RULE'} array = SBMLModel.rule; case 'SBML_REACTION' array = SBMLModel.reaction; case 'SBML_EVENT' array = SBMLModel.event; otherwise array = []; end; %------------------------------------------------------------------------------------ function value = CheckTypecode(SBMLTypecode) % % CheckTypecode % takes a string representing an SBMLTypecode % and returns 1 if it is a valid typecode and 0 otherwise % % value = CheckTypecode('SBMLTypecode') ValidTypecodes = {'SBML_COMPARTMENT', 'SBML_EVENT', 'SBML_FUNCTION_DEFINITION', 'SBML_PARAMETER', 'SBML_REACTION', 'SBML_SPECIES', ... 'SBML_UNIT_DEFINITION', 'SBML_ASSIGNMENT_RULE', 'SBML_ALGEBRAIC_RULE', 'SBML_RATE_RULE', 'SBML_SPECIES_CONCENTRATION_RULE', ... 'SBML_COMPARTMENT_VOLUME_RULE', 'SBML_PARAMETER_RULE'}; value = 1; if (~ischar(SBMLTypecode)) value = 0; elseif (~ismember(SBMLTypecode, ValidTypecodes)) value = 0; end;
github
EPFL-LCSB/matTFA-master
GetRateLawsFromReactions.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/AccessModel/GetRateLawsFromReactions.m
17,010
utf_8
e123fc8f39c36d33d5ef39991f08688a
function [Species, RateLaws] = GetRateLawsFromReactions(SBMLModel) % [species, rateLaws] = GetRateLawsFromReactions(SBMLModel) % % Takes % % 1. SBMLModel; an SBML Model structure % % Returns % % 1. an array of strings representing the identifiers of all species % 2. an array of % % - the character representation of the rate law established from any reactions % that determines the particular species % - '0' if the particular species is not a reactant/product in any reaction % % *EXAMPLE:* % % model has 4 species (s1, s2, s3, s4) % and 2 reactions; s1 -> s2 with kineticLaw 'k1*s1' % s2 -> s3 with kineticLaw 'k2*s2' % % [species, rateLaws] = GetRateLawsFromReactions(model) % % species = ['s1', 's2', 's3', 's4'] % rateLaws = {'-k1*s1', 'k1*s1-k2*s2', 'k2*s2', '0'} % %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2012 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> % check input is an SBML model if (~isValidSBML_Model(SBMLModel)) error('GetRateLawsFromReactions(SBMLModel)\n%s', 'input must be an SBMLModel structure'); end; %-------------------------------------------------------------- % get information from the model Species = GetSpecies(SBMLModel); NumberSpecies = length(SBMLModel.species); NumReactions = length(SBMLModel.reaction); % for each species loop through each reaction and determine whether the species % takes part and in what capacity for i = 1:NumberSpecies output = ''; % if species is a boundary condition (or constant in level 2 % no rate law is required boundary = SBMLModel.species(i).boundaryCondition; if (SBMLModel.SBML_level > 1) constant = SBMLModel.species(i).constant; else constant = -1; end; if (boundary == 1) output = '0'; elseif (constant ==1) output = '0'; else %determine which reactions it occurs within for j = 1:NumReactions SpeciesRole = DetermineSpeciesRoleInReaction(SBMLModel.species(i), SBMLModel.reaction(j)); %-------------------------------------------------------------- % check that reaction has a kinetic law if (isempty(SBMLModel.reaction(j).kineticLaw)) error('GetRateLawsFromReactions(SBMLModel)\n%s', 'NO KINETIC LAW SUPPLIED'); end; %-------------------------------------------------------------- if (SBMLModel.SBML_level < 3) kineticLawMath = SBMLModel.reaction(j).kineticLaw.formula; else kineticLawMath = SBMLModel.reaction(j).kineticLaw.math; end; TotalOccurences = 0; % record numbers of occurences of species as reactant/product % and check that we can deal with reaction if (sum(SpeciesRole)>0) NoReactants = SpeciesRole(2); NoProducts = SpeciesRole(1); TotalOccurences = NoReactants + NoProducts; %-------------------------------------------------------------- % check that a species does not occur twice on one side of the % reaction if (NoReactants > 1 || NoProducts > 1) error('GetRateLawsFromReactions(SBMLModel)\n%s', 'SPECIES OCCURS MORE THAN ONCE ON ONE SIDE OF REACTION'); end; %-------------------------------------------------------------- % check that reaction has a kinetic law formula if (isempty(SBMLModel.reaction(j).kineticLaw)) error('GetRateLawsFromReactions(SBMLModel)\n%s', 'NO KINETIC LAW SUPPLIED'); end; %-------------------------------------------------------------- end; % species has been found in this reaction while (TotalOccurences > 0) % % add the kinetic law to the output for this species if(NoProducts > 0) % Deal with case where parameter is defined within the reaction % and thus the reaction name has been appended to the parameter % name in the list in case of repeated use of same name Param_Name = GetParameterFromReaction(SBMLModel.reaction(j)); if (~isempty(Param_Name)) ReviseParam_Name = GetParameterFromReactionUnique(SBMLModel.reaction(j)); formula = Substitute(Param_Name, ReviseParam_Name, kineticLawMath); else formula = kineticLawMath; end; % put in stoichiometry if ((SBMLModel.SBML_level == 2 && SBMLModel.SBML_version > 1) ... || SBMLModel.SBML_level == 3) stoichiometry = SBMLModel.reaction(j).product(SpeciesRole(4)).stoichiometry; else stoichiometry = SBMLModel.reaction(j).product(SpeciesRole(4)).stoichiometry/double(SBMLModel.reaction(j).product(SpeciesRole(4)).denominator); end; if ((SBMLModel.SBML_level == 2) && (~isempty(SBMLModel.reaction(j).product(SpeciesRole(4)).stoichiometryMath))) if (SBMLModel.SBML_version < 3) output = sprintf('%s + (%s) * (%s)', output, SBMLModel.reaction(j).product(SpeciesRole(4)).stoichiometryMath, formula); else output = sprintf('%s + (%s) * (%s)', output, SBMLModel.reaction(j).product(SpeciesRole(4)).stoichiometryMath.math, formula); end; elseif (SBMLModel.SBML_level == 3) % level 3 stoichiometry may be assigned by % rule/initialAssignment which will override any % stoichiometry value if (~isempty(SBMLModel.reaction(j).product(SpeciesRole(4)).id)) rule = Model_getAssignmentRuleByVariable(SBMLModel, SBMLModel.reaction(j).product(SpeciesRole(4)).id); rrule = Model_getRateRuleByVariable(SBMLModel, SBMLModel.reaction(j).product(SpeciesRole(4)).id); ia = Model_getInitialAssignmentBySymbol(SBMLModel, SBMLModel.reaction(j).product(SpeciesRole(4)).id); if ~isempty(rule) output = sprintf('%s + (%s) * (%s)', output, rule.formula, formula); elseif ~isempty(ia) output = sprintf('%s + (%s) * (%s)', output, ia.math, formula); elseif ~isempty(rrule) error('Cannot deal with stoichiometry in a rate rule'); elseif ~isnan(stoichiometry) if (stoichiometry == 1) output = sprintf('%s + (%s)', output, formula); else output = sprintf('%s + %g * (%s)', output, stoichiometry, formula); end; else error('Cannot determine stoichiometry'); end; elseif isnan(stoichiometry) error ('Cannot determine stoichiometry'); else if (stoichiometry == 1) output = sprintf('%s + (%s)', output, formula); else output = sprintf('%s + %g * (%s)', output, stoichiometry, formula); end; end; else % if stoichiometry = 1 no need to include it in formula if (stoichiometry == 1) output = sprintf('%s + (%s)', output, formula); else output = sprintf('%s + %g * (%s)', output, stoichiometry, formula); end; end; NoProducts = NoProducts - 1; elseif (NoReactants > 0) % Deal with case where parameter is defined within the reaction % and thus the reaction name has been appended to the parameter % name in the list in case of repeated use of same name Param_Name = GetParameterFromReaction(SBMLModel.reaction(j)); if (~isempty(Param_Name)) ReviseParam_Name = GetParameterFromReactionUnique(SBMLModel.reaction(j)); formula = Substitute(Param_Name, ReviseParam_Name, kineticLawMath); else formula = kineticLawMath; end; % put in stoichiometry if ((SBMLModel.SBML_level == 2 && SBMLModel.SBML_version > 1) ... || SBMLModel.SBML_level == 3) stoichiometry = SBMLModel.reaction(j).reactant(SpeciesRole(5)).stoichiometry; else stoichiometry = SBMLModel.reaction(j).reactant(SpeciesRole(5)).stoichiometry/double(SBMLModel.reaction(j).reactant(SpeciesRole(5)).denominator); end; if ((SBMLModel.SBML_level == 2) && (~isempty(SBMLModel.reaction(j).reactant(SpeciesRole(5)).stoichiometryMath))) if (SBMLModel.SBML_version < 3) output = sprintf('%s - (%s) * (%s)', output, SBMLModel.reaction(j).reactant(SpeciesRole(5)).stoichiometryMath, formula); else output = sprintf('%s - (%s) * (%s)', output, SBMLModel.reaction(j).reactant(SpeciesRole(5)).stoichiometryMath.math, formula); end; elseif (SBMLModel.SBML_level == 3) % level 3 stoichiometry may be assigned by % rule/initialAssignment which will override any % stoichiometry value if (~isempty(SBMLModel.reaction(j).reactant(SpeciesRole(5)).id)) rule = Model_getAssignmentRuleByVariable(SBMLModel, SBMLModel.reaction(j).reactant(SpeciesRole(5)).id); rrule = Model_getRateRuleByVariable(SBMLModel, SBMLModel.reaction(j).reactant(SpeciesRole(5)).id); ia = Model_getInitialAssignmentBySymbol(SBMLModel, SBMLModel.reaction(j).reactant(SpeciesRole(5)).id); if ~isempty(rule) output = sprintf('%s - (%s) * (%s)', output, rule.formula, formula); elseif ~isempty(ia) output = sprintf('%s - (%s) * (%s)', output, ia.math, formula); elseif ~isempty(rrule) error('Cannot deal with stoichiometry in a rate rule'); elseif ~isnan(stoichiometry) if (stoichiometry == 1) output = sprintf('%s - (%s)', output, formula); else output = sprintf('%s - %g * (%s)', output, stoichiometry, formula); end; else error('Cannot determine stoichiometry'); end; elseif isnan(stoichiometry) error ('Cannot determine stoichiometry'); else if (stoichiometry == 1) output = sprintf('%s - (%s)', output, formula); else output = sprintf('%s - %g * (%s)', output, stoichiometry, formula); end; end; else % if stoichiometry = 1 no need to include it in formula if (stoichiometry == 1) output = sprintf('%s - (%s)', output, formula); else output = sprintf('%s - %g * (%s)', output, stoichiometry, formula); end; end; NoReactants = NoReactants - 1; end; TotalOccurences = TotalOccurences - 1; end; % while found > 0 end; % for NumReactions end; % if boundary condition % finished looking for this species % record rate law and loop to next species % rate = 0 if no law found if (isempty(output)) RateLaws{i} = '0'; else RateLaws{i} = output; end; end; % for NumberSpecies if NumberSpecies == 0 RateLaws = {}; end; function y = Substitute(InitialCharArray, ReplacementParams, Formula) % Allowed = {'(',')','*','/','+','-','^', ' ', ','}; if exist('OCTAVE_VERSION') [g,b,c,e] = regexp(Formula, '[,+/*\^()-]'); len = length(Formula); a{1} = Formula(1:b(1)-1); for i=2:length(b) a{i} = Formula(b(i-1)+1:b(i)-1); end; i = length(b)+1; a{i} = Formula(b(i-1)+1:len); else [a,b,c,d,e] = regexp(Formula, '[,+*/()-]', 'split'); end; num = length(a); for i=1:length(InitialCharArray) for j=1:num if strcmp(a(j), InitialCharArray{i}) a(j) = regexprep(a(j), a(j), ReplacementParams{i}); end; end; end; Formula = ''; for i=1:num-1 Formula = strcat(Formula, char(a(i)), char(e(i))); end; Formula = strcat(Formula, char(a(num))); y = Formula; % % get the number of parameters to be replced % NumberParams = length(InitialCharArray); % % % % want these in order of shortest to longest % % since shorter may be subsets of longer % % ie. 'alpha' is a subset of 'alpha1' % % % determine length of each parameter % for i = 1:NumberParams % NoCharsInParam(i) = length(InitialCharArray{i}); % end; % % % create an array of the index of the shortest to longest % [NoCharsInParam, Index] = sort(NoCharsInParam); % % % rewrite the arrays of parameters from shortest to longest % for i = 1:NumberParams % OrderedCharArray{i} = InitialCharArray{Index(i)}; % OrderedReplacements{i} = ReplacementParams{Index(i)}; % end; % % RevisedFormula = Formula; % % for i = NumberParams:-1:1 % % before replacing a character need to check that it is not part of a % % word etc % NumOccurences = length(findstr(OrderedCharArray{i}, RevisedFormula)); % for j = 1:NumOccurences % k = findstr(OrderedCharArray{i}, RevisedFormula); % if (k(j) == 1) % before = ' '; % else % before = RevisedFormula(k(j)-1); % end; % if ((k(j)+length(OrderedCharArray{i})) < length(RevisedFormula)) % after = RevisedFormula(k(j)+length(OrderedCharArray{i})); % else % after = ' '; % end; % % octave does not match ' ' using ismember % if ((ismember(after, Allowed) || (after == Allowed{8})) ... % && (ismember(before, Allowed) || (before == Allowed{8}))) % RevisedFormula = regexprep(RevisedFormula, OrderedCharArray{i}, ... % OrderedReplacements{i}, j); % end; % end; % end; % % y = RevisedFormula; %
github
EPFL-LCSB/matTFA-master
TestFunction.m
.m
matTFA-master/ext/Cobra205_vDec2014/external/toolboxes/SBMLToolbox-4.1.0/toolbox/Test/TestFunction.m
4,751
utf_8
20ffcfa9c79433da3fc9998246d20dd8
function y = TestFunction(varargin) %<!--------------------------------------------------------------------------- % This file is part of SBMLToolbox. Please visit http://sbml.org for more % information about SBML, and the latest version of SBMLToolbox. % % Copyright (C) 2009-2011 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK % % Copyright (C) 2006-2008 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. University of Hertfordshire, Hatfield, UK % % Copyright (C) 2003-2005 jointly by the following organizations: % 1. California Institute of Technology, Pasadena, CA, USA % 2. Japan Science and Technology Agency, Japan % 3. University of Hertfordshire, Hatfield, UK % % SBMLToolbox is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published by % the Free Software Foundation. A copy of the license agreement is provided % in the file named "LICENSE.txt" included with this software distribution. %----------------------------------------------------------------------- --> y = 0; if (nargin < 3) error('Need at least 3 inputs'); end; func = varargin{1}; fhandle = str2func(func); number_in = varargin{2}; number_out = varargin{3}; if (nargin < 3+number_in+number_out) error('incorrect number of arguments'); end; start_out = 4 + number_in; fail = 0; switch number_out case 0 switch number_in case 1 [a] = feval(fhandle, varargin{4}); case 2 [a] = feval(fhandle, varargin{4}, varargin{5}); case 3 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}); case 4 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}, varargin{7}); end; fail = fail + ~testEquality(a); case 1 switch number_in case 1 [a] = feval(fhandle, varargin{4}); case 2 [a] = feval(fhandle, varargin{4}, varargin{5}); case 3 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}); case 4 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}, varargin{7}); end; fail = fail + ~testEquality(a, varargin{start_out}); case 2 switch number_in case 1 [a, b] = feval(fhandle, varargin{4}); case 2 [a, b] = feval(fhandle, varargin{4}, varargin{5}); case 3 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}); case 4 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}, varargin{7}); end; fail = fail + ~testEquality(a, varargin{start_out}); fail = fail + ~testEquality(b, varargin{start_out+1}); case 3 switch number_in case 1 [a, b, c] = feval(fhandle, varargin{4}); case 2 [a, b, c] = feval(fhandle, varargin{4}, varargin{5}); case 3 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}); case 4 [a] = feval(fhandle, varargin{4}, varargin{5}, varargin{6}, varargin{7}); end; fail = fail + ~testEquality(a, varargin{start_out}); fail = fail + ~testEquality(b, varargin{start_out+1}); fail = fail + ~testEquality(c, varargin{start_out+2}); otherwise error('too many output'); end; if (fail > 0) y = 1; end; function y = testEquality(array1, array2) y = isequal(array1, array2); if y == 1 return; elseif length(array1) ~= length(array2) y = 0; return; elseif issparse(array1) array1_full = full(array1); array2_full = full(array2); y = testEquality(array1_full, array2_full); else y = 1; i = 1; % check whether we are dealing with a nan which will always fail equality while (y == 1 && i <= length(array1)) if ~isstruct(array1) if isnan(array1(i)) y = isnan(array2(i)); else y = isequal(array1(i), array2(i)); end; else fields = fieldnames(array1(i)); j = 1; while( y == 1 && j <= length(fields)) ff1 = getfield(array1(i), fields{j}); ff2 = getfield(array2(i), fields{j}); if (iscell(ff1)) ff1 = ff1{1}; ff2 = ff2{1}; end; if isnan(ff1) y = isnan(ff2); else y = isequal(ff1, ff2); end; j = j+1; end; end; i = i + 1; end; end;
github
EPFL-LCSB/matTFA-master
sampleScatterMatrix.m
.m
matTFA-master/ext/Cobra205_vDec2014/sampling/sampleScatterMatrix.m
4,767
utf_8
58deec35b12aa4bb50273bc36cd3f221
function sampleScatterMatrix(rxnNames,model,sample,nPoints,fontSize,dispRFlag,rxnNames2) %sampleScatterMatrix Draws a scatterplot matrix with pairwise scatterplots %for multiple reactions % % sampleScatterMatrix(rxnNames,model,sample,nPoints,dispRFlag,rxnNames2) % %INPUTS % rxnNames Cell array of reaction names to be plotted % model Model structure % sample Samples to be analyzed (nRxns x nSamples) % %OPTIONAL INPUTS % nPoints How many sample points to plot (Default 100) % fontSize Font size for labels (Default calculated based on % number of reactions) % dispRFlag Display correlation coefficients (Default false) % rxnNames2 Optional second set of reaction names % % Examples of usage: % % 1) sampleScatterMatrix({'PFK','PYK','PGL'},model,sample); % Plots the scatterplots only between the three reactions listed - % histograms for each reaction will be on the diagonal % % 2) sampleScatterMatrix({'PFK','PYK','PGL'},model,sample,100,10,true,{'ENO','TPI'); % Plots the scatterplots between each of the first set of reactions and % each of the second set of reactions. No histograms will be shown. % % Markus Herrgard 9/14/06 [isInModel,rxnInd] = ismember(rxnNames,model.rxns); rxnNames = rxnNames(isInModel); rxnInd = rxnInd(isInModel); nRxns = length(rxnNames); if (nargin < 4) nPoints = 100; end if (nargin < 6) dispRFlag = false; end if (nargin > 6) [isInModel2,rxnInd2] = ismember(rxnNames2,model.rxns); rxnNames2 = rxnNames2(isInModel2); rxnInd2 = rxnInd2(isInModel2); nRxns2 = length(rxnNames2); twoSetsFlag = true; else nRxns2 = nRxns; rxnNames2 = rxnNames; twoSetsFlag = false; end if (twoSetsFlag) nRxns = nRxns+1; nRxns2 = nRxns2+1; end if (nargin < 5) nPanels = nRxns*nRxns2; fontSize = 10+ceil(50/sqrt(nPanels)); end height = 0.8/nRxns; width = 0.8/nRxns2; fontSize = 10; clf h = waitbar(0,'Drawing scatterplots ...'); for i = 1:nRxns for j = 1:nRxns2 waitbar(((i-1)*nRxns+j)/(nRxns*nRxns2),h); left = 0.1+(j-1)*width; bottom = 0.9-i*height; if (twoSetsFlag) if (i == 1 & j == 1) else %subplot(nRxns,nRxns2,(i-1)*nRxns2+j); subplot('position',[left bottom width height]); if (j >1 & i >1) sampleScatterPlot(sample,rxnInd2(j-1),rxnInd(i-1),nPoints,fontSize,dispRFlag); elseif (i == 1) sampleHistInternal(sample,rxnInd2(j-1),fontSize); elseif (j == 1) sampleHistInternal(sample,rxnInd(i-1),fontSize); end if (i == 1) title(rxnNames2{j-1},'FontSize',fontSize); end if (j == 1) ylabel(rxnNames{i-1},'FontSize',fontSize); end end else if (j == i) %subplot(nRxns,nRxns2,(i-1)*nRxns2+j); subplot('position',[left bottom width height]); sampleHistInternal(sample,rxnInd(i),fontSize); elseif (j > i) %subplot(nRxns,nRxns2,(i-1)*nRxns2+j); subplot('position',[left bottom width height]); sampleScatterPlot(sample,rxnInd(j),rxnInd(i),nPoints,fontSize,dispRFlag); end if (i == 1) title(rxnNames2{j},'FontSize',fontSize); end if (j == nRxns2) set(gca,'YAxisLocation','right'); ylabel(rxnNames{i},'FontSize',fontSize); end end end end close(h); function sampleScatterPlot(sample,id1,id2,nPoints,fontSize,dispRFlag) selPts = randperm(size(sample,2)); selPts = selPts(1:nPoints); plot(sample(id1,selPts),sample(id2,selPts),'r.'); set(gca,'YTickLabel',[]); set(gca,'XTickLabel',[]); maxx = max(sample(id1,:)); maxy = max(sample(id2,:)); minx = min(sample(id1,:)); miny = min(sample(id2,:)); axis([minx maxx miny maxy]); % Display correlation coefficients if (dispRFlag) r = corrcoef(sample(id1,:)',sample(id2,:)'); %h = text(minx+0.66*(maxx-minx),miny+0.2*(maxy-miny),num2str(round(100*r(1,2))/100)); %set(h,'FontSize',fontSize-5); xlabel(num2str(round(100*r(1,2))/100),'FontSize',fontSize-5); end function sampleHistInternal(sample,id,fontSize) [n,bins] = hist(sample(id,:),30); if (exist('smooth')) plot(bins,smooth(bins,n')/sum(n')); else plot(bins,n'/sum(n')); end maxx = max(bins); minx = min(bins); set(gca,'XTick',linspace(minx,maxx,4)); set(gca,'XTickLabel',round(10*linspace(minx,maxx,4))/10); set(gca,'YTickLabel',[]); set(gca,'FontSize',fontSize-5); axis tight
github
EPFL-LCSB/matTFA-master
verifyPoints.m
.m
matTFA-master/ext/Cobra205_vDec2014/sampling/verifyPoints.m
1,925
utf_8
51f9f4c742a6369a2be6b835d274e08f
% function [errorsA, errorsLUB] = verifyPoints(sampleStruct) function [errorsA, errorsLUB, stuckPoints] = verifyPoints(sampleStruct) %verifyPoints Verify that a set of points are in the solutoin space of sampleStruct. % Typically, this method would be called to check a set of warmup points or % points generated via gpSampler. Also verifies if points moved from % warmup points. % % function [errorsA, errorsLUB, stuckPoints] = verifyPoints(sampleStruct) % %INPUT % sampleStruct LPProblem containing points and warmup points % %OUTPUTS % errorsA Row index of the constraint in sampleStruct that % is not consistent with the given points % errorsLUB Upper and lower bounds of the constraint + tolerance % stuckPoints Index of points which did not move. % % Author: Ellen Tsai 2007 % Richard Que (12/1/09) Combined with checkWP.m %check to see if warmup points moved [warmupPts, points] = deal(sampleStruct.warmupPts, sampleStruct.points); n=size(points,2); len=size(n,1); stuckPoints=zeros(0,1); for i=1:n len(i,1)=norm(warmupPts(:,i)-points(:,i)); if len(i,1)<10 stuckPoints=[stuckPoints; i]; end end minL = min(len); %check to see if points are within solution space [A,b,csense]=deal(sampleStruct.A,sampleStruct.b,sampleStruct.csense); t=.01; %tolerance npoints = size(points, 2); LHS = A*points; EIndex = (csense == 'E'); LIndex = (csense == 'L'); GIndex = (csense == 'G'); [errorsL(:,1), errorsL(:,2)] = find(LHS(LIndex,:) - b(LIndex)* ones(1, npoints) > t); [errorsG(:,1), errorsG(:,2)] = find(b(GIndex)* ones(1, npoints) - LHS(GIndex,:) > t); [errorsE(:,1), errorsE(:,2)] = find( abs(LHS(EIndex,:) - b(EIndex)* ones(1, npoints)) > t); errorsUB = find(points > sampleStruct.ub*ones(1,npoints) + t); errorsLB = find(points < sampleStruct.lb*ones(1,npoints) - t); errorsA = [errorsL; errorsG; errorsE]; errorsLUB = [errorsLB; errorsUB]; end
github
EPFL-LCSB/matTFA-master
gpSampler_tFBAVersiontUsed.m
.m
matTFA-master/ext/Cobra205_vDec2014/sampling/gpSampler_tFBAVersiontUsed.m
12,932
utf_8
e82b2581d217d3925c1a3fa2c4ff003e
function [sampleStructOut, mixedFrac] = gpSampler(sampleStruct, nPoints, bias, maxTime, maxSteps, threads, nPointsCheck) %gpSampler Samples an arbitrary linearly constrained space using a fixed %number of points that are moved in parallel % % [sampleStructOut, mixedFraction] = gpSampler(sampleStruct, nPoints, bias, maxTime, maxSteps) % % The space is defined by % A x <=,==,>= b % lb <= x <= ub % %INPUTS % sampleStruct Structure describing the space to be sampled and % previous point sets % A LHS matrix (optionally, if not A script checks for S) % b RHS vector % lb Lower bound % ub Upper bound % csense Constraint type for each row in A ('G', 'L', 'E') % warmupPoints Set of warmup points (optional, generated by default) % points Currently sampled points (optional) % %OPTIONAL INPUTS % nPoints Number of points used in sampling % (default = 2*nRxns or 5000 whichever is greater) % bias % method Biasing distribution: 'uniform', 'normal' % index The reaction indexes which to bias (nBias total) % param nBias x 2 matrix of parameters (for uniform it's min % max, for normal it's mu, sigma). % maxTime Maximum time alloted for the sampling in seconds % (default 600 s, pass an empty number [] to set maxSteps instead) % maxSteps Maximum number of steps to take (default 1e10). Sampler % will run until either maxStep or maxTime is reached. % Set maxStep or maxTime to 0 and no sampling will occur % (only warmup points generated). % threads number of threads the sampler will use. If you have a % dual core machine, you can set it to 2 etc. The speed % up is almost linear w/ the number of cores. % If using this feature and 2009a or newer, a futher % speedup can be obtained by starting matlab from the % command line by "typing matlab -singleCompThread" % New feature: if threads < 0, use distributed toolbox. % nPointsCheck Checks that minimum number of points (2*nRxns) are % used. (Default = true). % %OUTPUT % sampleStructOut The sampling structure with some extra fields. % mixedFract The fraction mixed (relative to the warmupPts). A value of 1 % means not mixed at all. A value of .5 means completely mixed. %% Parameter Processing / error checking sampleStructOut = 0; % in case of returning early mixedFrac = 1; % in case of returning early if nargin < 2 nPoints = 5000; end if nargin < 3 bias = []; end if ~isempty(bias) if ~isfield (bias, 'method') display('bias does not have a method set'); return; end end if nargin < 4 || (isempty(maxTime) && isempty(maxSteps)) maxTime = 10*60; % 10 minutes end if (nargin < 5) || isempty(maxSteps) % Max time takes precedence maxSteps = 1e10; else % Set max steps instead of max time if (isempty(maxTime)) maxTime = 1e10; end end if nargin < 6 || isempty(threads) threads = 1; end if nargin < 7, nPointsCheck = true; end % Sanity checking if (~ isfield (sampleStruct, 'A')) if isfield(sampleStruct, 'S') display('A set to S'); sampleStruct.A = sampleStruct.S; else display('A and/or S not set'); return; end end if (~ isfield (sampleStruct, 'b')) sampleStruct.b = zeros(size(sampleStruct.A,1), 1); display('Warning: b not set. Defaulting to zeros'); end if (~ isfield (sampleStruct, 'csense')) sampleStruct.csense(1:size(sampleStruct.A,1)) = 'E'; display('Warning: csense not set. Defaulting to all Equality constraints'); end if (~isfield (sampleStruct, 'lb')) display('lb not set'); return; end if (~isfield (sampleStruct, 'ub')) display('ub not set'); return; end %% internal data generation % make internal structure [A, b, csense, lb, ub] = deal(sampleStruct.A, sampleStruct.b, sampleStruct.csense, sampleStruct.lb, sampleStruct.ub); % constInd = (lb == ub); % constVal = lb(constInd); % Aconst = A(:,constInd); % b = b - Aconst*constVal; % A = A(:,~constInd); % lb = lb(~constInd); % ub = ub(~constInd); % [sampleStruct.A, sampleStruct.b, sampleStruct.csense, sampleStruct.lb, sampleStruct.ub] = deal(A, b, csense, lb, ub); [rA, dimx] = size(A); if (~ isfield(sampleStruct, 'internal')) Anew = sparse(0, dimx); Cnew = sparse(0, dimx); Bnew = zeros(rA, 1); Dnew = zeros(rA, 1); rAnew = 0; rCnew = 0 ; for i = 1:size(A, 1) switch csense(i) case 'E' rAnew = rAnew+1; Anew(rAnew,:) = A(i,:); Bnew(rAnew,:) = b(i); case 'G' rCnew=rCnew+1; Cnew(rCnew,:) = -A(i,:); Dnew(rCnew,:) = -b(i); case 'L' rCnew=rCnew+1; Cnew(rCnew,:) = A(i,:); Dnew(rCnew,:) = b(i); otherwise display ('whoops. csense can only contain E, G, or L') return; end end %Anew = Anew(1:rAnew,:); Bnew = Bnew(1:rAnew,:); Dnew = Dnew(1:rCnew,:); % calculate offset if find(Bnew ~= 0) offset = Anew\Bnew; else offset = zeros(size(Anew,2), 1); end % rescale Bnew, Dnew Boffset = Bnew - Anew*offset; if (max(abs(Boffset)) > .0000000001) display('whoops. It looks like the offset calculation made a mistake. this should be zero.'); max(abs(Boffset)) return; end Doffset = Dnew - Cnew*offset; lbnew = lb - offset; ubnew = ub - offset; sampleStruct.internal.offset = offset; sampleStruct.internal.Anew = Anew; sampleStruct.internal.Cnew = Cnew; sampleStruct.internal.Dnew = Doffset; sampleStruct.internal.lbnew = lbnew; sampleStruct.internal.ubnew = ubnew; if (isfield(sampleStruct, 'warmupPts')) sampleStruct = rmfield(sampleStruct, 'warmupPts'); end if ~isempty(bias) sampleStruct.internal.fixed = bias.index; else sampleStruct.internal.fixed = []; end end %% Generate warmup points if (~ isfield(sampleStruct, 'warmupPts') ) fprintf('Generating warmup points\n'); % warmupPts = warmup(sampleStruct, nPoints, bias); warmupPts = createHRWarmup(sampleStruct, nPoints, false, bias, nPointsCheck); sampleStruct.warmupPts = warmupPts; if (isfield(sampleStruct, 'points')) sampleStruct = rmfield(sampleStruct, 'points'); end if (isfield(sampleStruct, 'bias')) sampleStruct = rmfield(sampleStruct, 'bias'); end sampleStruct.steps = 0; save sampleStructTmp sampleStruct else fprintf('Warmup points already present.\n'); % save sampleStructTmp sampleStruct end %% Do actual sampling fprintf('Sampling\n'); if(maxTime > 0 && maxSteps > 0) if threads < 0 %uses distributed toolbox. sampleStruct = ACHRSamplerDistributedGeneral(sampleStruct, ceil(maxSteps/50), 50, maxTime); else sampleStruct = ACHRSamplerParallelGeneral(sampleStruct, ceil(maxSteps/50), 50, maxTime, threads); end mixedFrac = mixFraction(sampleStruct.points, sampleStruct.warmupPts, sampleStruct.internal.fixed); else mixedFrac = 1; end sampleStructOut = sampleStruct; return; %% warmup Point generator function warmupPts = warmup(sampleProblem, nPoints, bias) dimX = size(sampleProblem.A, 2); warmupPts = zeros(dimX, nPoints); [LPproblem.A,LPproblem.b,LPproblem.lb,LPproblem.ub,LPproblem.csense,LPproblem.osense] = ... deal(sampleProblem.A,sampleProblem.b,sampleProblem.lb,sampleProblem.ub,sampleProblem.csense,1); % Generate the correct parameters for the biasing reactions if ~isempty(bias) if (~ismember(bias.method,{'uniform','normal'})) error('Biasing method not implemented'); end for k = 1:size(bias.index) ind = bias.index(k); % Find upper & lower bounds for bias rxns to ensure that no % problems arise with values out of bounds LPproblem.c = zeros(size(LPproblem.A,2),1); LPproblem.c(ind) = 1; LPproblem.osense = -1; sol = solveCobraLP(LPproblem); maxFlux = sol.obj; LPproblem.osense = 1; sol = solveCobraLP(LPproblem); minFlux = sol.obj; if strcmp(bias.method, 'uniform') upperBias = bias.param(k,2); lowerBias = bias.param(k,1); if (upperBias > maxFlux || upperBias < minFlux) upperBias = maxFlux; disp('Invalid bias bounds - using default bounds instead'); end if (lowerBias < minFlux || lowerBias > maxFlux) lowerBias = minFlux; disp('Invalid bias bounds - using default bounds instead'); end bias.param(k,1) = lowerBias; bias.param(k,2) = upperBias; elseif strcmp(bias.method, 'normal') biasMean = bias.param(k,1); if (biasMean > maxFlux || biasMean < minFlux) bias.param(k,1) = (minFlux + maxFlux)/2; disp('Invalid bias mean - using default mean instead'); end biasFluxMin(k) = minFlux; biasFluxMax(k) = maxFlux; end end end %Generate the points i = 1; while i <= nPoints/2 if mod(i,10) ==0 fprintf('%d\n',2*i); end if ~isempty(bias) for k = 1:size(bias.index) ind = bias.index(k); if strcmp(bias.method, 'uniform') diff = bias.param(k,2) - bias.param(k,1); fluxVal = diff*rand() + bias.param(k,1); elseif strcmp(bias.method, 'normal') valOK = false; % Try until get points inside the space while (~valOK) fluxVal = randn()*bias.param(k,2)+bias.param(k,1); if (fluxVal <= biasFluxMax(k) && fluxVal >= biasFluxMin(k)) valOK = true; end end end LPproblem.lb(ind) = 0.99999999*fluxVal; LPproblem.ub(ind) = 1.00000001*fluxVal; end end % Pick the next flux to optimize, cycles though each reaction % alternates minimization and maximization for each cycle LPproblem.c = rand(dimX, 1)-.5; validFlag = true; for maxMin = [1, -1] % Set the objective function if i <= dimX % LPproblem.c = rand(dimX, 1)-.5; LPproblem.c(i) = 5000; end LPproblem.osense = maxMin; % Determine the max or min for the rxn sol = solveCobraLP(LPproblem); x = sol.full; if maxMin == 1 sol1 = sol; else sol2 = sol; end status = sol.stat; if status ~= 1 display ('invalid solution') validFlag = false; display(status) pause; end % Move points to within bounds x(x > LPproblem.ub) = LPproblem.ub(x > LPproblem.ub); x(x < LPproblem.lb) = LPproblem.lb(x < LPproblem.lb); % Store point % For non-random points just store a min/max point if (maxMin == 1) warmupPts(:,2*i-1) = x; else warmupPts(:,2*i) = x; end end if validFlag %postprocess(LPproblem, sol1, sol2) i = i+1; end end centerPoint = mean(warmupPts,2); % Move points in if isempty(bias) warmupPts = warmupPts*.33 + .67*centerPoint*ones(1,nPoints); else warmupPts = warmupPts*.99 + .01*centerPoint*ones(1,nPoints); end % Permute point order % if (permFlag) % [nRxns,nPoints] = size(warmupPts); % warmupPts = warmupPts(:,randperm(nPoints)); % end return; %% post processing for better warmup point generation. % function out = postprocess(LPproblem, sol1, sol2) % x1 = sol1.full; % x2 = sol2.full; % closetoboundary(LPproblem, x1) % closetoboundary(LPproblem, x2) % % separation = sol2.obj - sol1.obj; % if separation < .00001 % disp('low separation'); % pause; % end % LPproblem.A = [LPproblem.A; LPproblem.c]; % LPproblem.b(end+1) = sol1.obj + separation*.1; % Lpproblem.csense(end+1) = 'L'; % % % % pause; % out = 2; % % return; % function counter = closetoboundary(LPproblem, sol) % etol = 1e-5; % counter = 0; % counter = counter + sum(LPproblem.A((LPproblem.csense == 'G'),:)*sol - LPproblem.b(LPproblem.csense =='G') < etol) % counter = counter + sum(LPproblem.b(LPproblem.csense =='L') - LPproblem.A((LPproblem.csense == 'L'),:)*sol < etol) % counter = counter + sum(LPproblem.ub - sol < etol) % counter = counter + sum(sol - LPproblem.lb < etol) % return;
github
EPFL-LCSB/matTFA-master
ACHRSamplerParallelGeneral.m
.m
matTFA-master/ext/Cobra205_vDec2014/sampling/ACHRSamplerParallelGeneral.m
13,226
utf_8
a57266feeacacc3b5068e1cf4d95fc38
function [sampleStruct] = ACHRSamplerParallelGeneral(sampleStruct,nLoops,stepsPerPoint, maxtime, proc, fdirectory) % ACHRSamplerParallelGeneral Artificial Centering Hit-and-Run sampler with in place (memory) point % managmenet % % sampleStruct = ACHRSamplerParallelGeneral(sampleStruct,nLoops,stepsPerPoint) % %INPUTS % sampleStruct Sampling structure % nLoops Number of iterations % stepsPerPoint Number of sampler steps per point saved % maxtime Amount of time to spend on calculation (in seconds) % %OPTIONAL INPUTS % proc Number of processes if > 0. Otherwise, the proces #. % fdirectory Do not use this parameter when calling function directly. % %OUTPUT % sampleStruct Sampling structure with sample points % % Jan Schellenberger 1/29/07 % (vaguely) based on code by: % Markus Herrgard, Gregory Hannum, Ines Thiele, Nathan Price 4/14/06 warning off MATLAB:divideByZero; %proc == 0 means master %proc greater than 1 means slave. if nargin < 5 % not parallel at all. parallel = 0; proc = 0; elseif nargin >= 5 && proc == 1 % not parallel (explicit) parallel = 0; proc = 0; else % parallel. parallel = 1; if proc < 0 % an indication that this is a slave process proc = -proc; else % indicator that you are a master process numproc = proc; proc = 0; % clear all files that may exist delete('xxMasterfil*.mat'); delete('xxRound*.mat'); delete('xxRoundDonePrint*.mat'); delete('xxRoundAck*.mat'); delete('xxDoneRound*.mat'); delete('xxDoneP*.mat'); delete('xxGlobalDone*.mat*'); end end % Minimum allowed distance to the closest constraint maxMinTol = 1e-10; % Ignore directions where u is really small uTol = 1e-10; safetycheck = false; % checks the direction of u for fixed directions. totalStepCount = 0; t0 = clock; if proc == 0 % if master thread if( ~ isfield(sampleStruct, 'points')) points = sampleStruct.warmupPts; % start with warmup points else points = sampleStruct.points; % continue with points end offset = sampleStruct.internal.offset; [dimX,nPoints] = size(points); points = points - offset*ones(1, nPoints); ub = sampleStruct.internal.ubnew; lb = sampleStruct.internal.lbnew; A = sampleStruct.internal.Anew; C = sampleStruct.internal.Cnew; D = sampleStruct.internal.Dnew; fixed = union(sampleStruct.internal.fixed,find(ub==lb)); if (~isfield(sampleStruct.internal,'N')) if size(A,1)==0 N=[]; sampleStruct.internal.N=N; else if issparse(A) N = null(full(A)); else N = null(A); end sampleStruct.internal.N = N; end else N = sampleStruct.internal.N; end movable = (1:dimX)'; movable(fixed) = []; if safetycheck Nsmall = null(full(A(:, movable))); else Nsmall = []; end % Find the center of the space centerPoint = mean(points, 2); fidErr = fopen('ACHRParallelError.txt','w'); pointRange = 1:nPoints; totalloops = nLoops; if parallel blah = 1; display('saving master file.'); save('xxMasterfile', 'ub', 'lb', 'A', 'C', 'D', 'fixed', 'N', 'movable', 'Nsmall', 'numproc', 'nPoints' ); display('finished saving master file. spawning processes'); for i = 1:(numproc - 1) % goes from 1 to 7 if proc == 8 command = strcat('matlab -singleCompThread -automation -nojvm -r ACHRSamplerParallelGeneral([],',num2str(nLoops),',',num2str(stepsPerPoint),',0,', num2str(-i) ,',''' ,pwd, ''');exit; &' ); display(command) system(command); end display('finished spawning processes'); end end if proc > 0 %slave threads only cd (fdirectory); load('xxMasterfile', 'ub', 'lb', 'A', 'C', 'D', 'fixed', 'N', 'movable', 'Nsmall', 'numproc', 'nPoints'); blah = 1; end for i = 1:nLoops if parallel % this whole block only gets executed in parallel mode. if proc == 0 %master thread does this. % save points display(strcat('distributing points round ', num2str(i))); save(strcat('xxRound', num2str(i)), 'points', 'centerPoint'); save(strcat('xxRoundDonePrint', num2str(i)), 'blah'); display(strcat('finished distributing points round ', num2str(i))); else % if slave threads do this. display(strcat('reading in points round ', num2str(i))); while exist(strcat('xxRoundDonePrint', num2str(i), '.mat'), 'file') ~= 2; % wait for other thread to finish. %display(strcat('waiting for round ', num2str(i))); fprintf(1, '.'); if exist('xxGlobalDone.mat', 'file') == 2 exit; end pause(.25); end fprintf(1,'\nloading files four next round.\n'); try load(strcat('xxRound', num2str(i)), 'points', 'centerPoint'); % load actual points catch pause(15) % for some reason at round 64 it needs extra time to load load(strcat('xxRound', num2str(i)), 'points', 'centerPoint'); % load actual points end save(strcat('xxRoundAck', num2str(i),'x', num2str(proc) ), 'blah'); % save acknowledgement display(strcat('finished reading input and acknowledgment sent ', num2str(i))); end % divide up points. master thread (proc = 0) gets first chunk. pointRange = subparts(nPoints, numproc, proc); end % actual sampling over pointRange for pointCount = pointRange % Create the random step size vector randVector = rand(stepsPerPoint,1); prevPoint = points(:,pointCount); curPoint = prevPoint; if mod(pointCount,200) == 0 display(pointCount); end saveCoords = prevPoint(fixed); for stepCount = 1:stepsPerPoint % Pick a random warmup point randPointID = ceil(nPoints*rand); randPoint = points(:,randPointID); % Get a direction from the center point to the warmup point u = (randPoint-centerPoint); if ~isempty(fixed) % no need to reproject if there are no fixed reactions. %ubefore = u; if safetycheck u(movable) = Nsmall * (Nsmall' * u(movable)); end %uafter = u; u(fixed) = 0; % takes care of biasing. end u = u/norm(u); % Figure out the distances to upper and lower bounds distUb = (ub - prevPoint); distLb = (prevPoint - lb); distD = (D-C*prevPoint); % Figure out positive and negative directions posDirn = (u > uTol); negDirn = (u < -uTol); move = C*u; posDirn2 = (move > uTol); negDirn2 = (move < -uTol); % Figure out all the possible maximum and minimum step sizes maxStepTemp = distUb./u; minStepTemp = -distLb./u; StepD = distD./move; maxStepVec = [maxStepTemp(posDirn);minStepTemp(negDirn);StepD(posDirn2 )]; minStepVec = [minStepTemp(posDirn);maxStepTemp(negDirn);StepD(negDirn2 )]; % Figure out the true max & min step sizes maxStep = min(maxStepVec); minStep = max(minStepVec); % Find new direction if we're getting too close to a constraint if (abs(minStep) < maxMinTol && abs(maxStep) < maxMinTol) || (minStep > maxStep) fprintf('Warning small step: %f %f\n',minStep,maxStep); continue; end % Pick a rand out of list_of_rands and use it to get a random % step distance stepDist = minStep + randVector(stepCount)*(maxStep-minStep); %fprintf('%d %d %d %f %f\n',i,pointCount,stepCount,minStep,maxStep); % Advance to the next point curPoint = prevPoint + stepDist*u; % Reproject the current point into the null space if mod (stepCount, 25) == 0 if ~isempty(N) curPoint = N* (N' * curPoint); end curPoint(fixed) = saveCoords; end % Print out amount of constraint violation if (mod(totalStepCount,1000)==0) && proc == 0 % only do for master thread fprintf(fidErr,'%10.8f\t%10.8f\t',max(curPoint-ub),max(lb-curPoint)); end % Move points inside the space if reprojection causes problems overInd = (curPoint > ub); underInd = (curPoint < lb); if (sum(overInd)>0) || (sum(underInd)>0) curPoint(overInd) = ub(overInd); curPoint(underInd) = lb(underInd); end % Print out amount of constraint violation if (mod(totalStepCount,1000) == 0) && proc == 0 % only do for master thread fprintf(fidErr,'%10.8f\n',full(max(max(abs(A*curPoint))))); end prevPoint = curPoint; % Count the total number of steps totalStepCount = totalStepCount + 1; end % Steps per point % Final reprojection if ~isempty(N) curPoint = N* (N' * curPoint); end curPoint(fixed) = saveCoords; centerPoint = centerPoint + (curPoint - points(:,pointCount))/nPoints; % only swapping one point... it's trivial. % Swap current point in set of points. points(:,pointCount) = curPoint; end % Points per cycle if parallel % do this block if in parallel mode (regather points) if proc == 0 % if master % look for acknowledgements. display(strcat ('waiting for acknowledgement', num2str(i))); donewaiting = 0; while ~donewaiting donewaiting = 1; for k = 1:(numproc-1); if exist(strcat('xxRoundAck',num2str(i), 'x', num2str(k),'.mat'), 'file') ~= 2 donewaiting = 0; end end %display('waiting for acknowledgement'); fprintf(1, '.'); pause(.25) end % all other processes have received their information. delete temporary files. fprintf(1, '\n'); for k = 1:(numproc-1) delete (strcat('xxRoundAck', num2str(i), 'x', num2str(k), '.mat')); end delete(strcat('xxRound', num2str(i), '.mat')); delete(strcat('xxRoundDonePrint', num2str(i), '.mat')); % look for return values. display(strcat ('waiting for return files ', num2str(i))); donewaiting = 0; while ~donewaiting donewaiting = 1; for k = 1:(numproc-1); if exist(strcat('xxDoneP',num2str(i), 'x', num2str(k),'.mat'), 'file') ~= 2 donewaiting = 0; end end pause(.25) fprintf(1,'.'); end fprintf(1, '\nAll processes finished. reading\n'); for k = 1:(numproc-1) load (strcat('xxDoneRound', num2str(i), 'x', num2str(k)), 'points2'); r2 = subparts(nPoints, numproc, k); points(:,r2) = points2; delete (strcat('xxDoneRound', num2str(i), 'x', num2str(k), '.mat') ); delete (strcat('xxDoneP',num2str(i), 'x', num2str(k), '.mat')); end centerPoint = mean(points, 2); % recalculate center point after gathering all data. display(strcat('done with round ', num2str(i))); else % if slave points2 = points(:, pointRange); save (strcat('xxDoneRound', num2str(i), 'x', num2str(proc)), 'points2'); save (strcat('xxDoneP',num2str(i), 'x', num2str(proc)), 'blah'); end end t1 = clock(); fprintf('%10.0f s %d steps\n',etime(t1, t0),i*stepsPerPoint); if etime(t1, t0) > maxtime && proc == 0 % only master thread can terminate due to time limits. totalloops = i; break; end end if proc > 0 % slave threads terminate here. return; end points = points + offset*ones(1, nPoints); sampleStruct.points = points; if ~ isfield(sampleStruct, 'steps') sampleStruct.steps = 0; end sampleStruct.steps = sampleStruct.steps + stepsPerPoint*totalloops; % flag for all other handles to terminate. if parallel save('xxGlobalDone', 'blah'); delete('xxMaster*.mat'); end fclose(fidErr); function out = subparts(nPoints, n, k) out = (floor(nPoints*k/n)+1) : (floor(nPoints*(k+1)/n)); return
github
EPFL-LCSB/matTFA-master
generateSUXMatrix.m
.m
matTFA-master/ext/Cobra205_vDec2014/gapFilling/growthExpMatch/generateSUXMatrix.m
3,883
utf_8
7765018ced7286373cb6eabb2a70249c
function MatricesSUX =generateSUXMatrix(model,dictionary, KEGGFilename, KEGGBlackList, compartment, addModel) % generateSUXMatrix creates the matrices for matlab smiley -- > combines S, U % (KEGG), X (transport) % % MatricesSUX =generateSUXMatrix(model,CompAbr, KEGGID, % KEGGFilename, compartment) % % model model structure % CompAbr List of compounds abreviation (non-compartelized) % KEGGID List of KEGGIDs for compounds in CompAbr % KEGGFilename File name containing KEGG database % KEGGBlackList % compartment [c] --> transport from cytoplasm [c] to extracellulat space % [e] (default), [p] creates transport from [c] to [p] and from [p] to [c], % if '' - no exchange reactions/transport will be added to the matrix. % addModel model structure, containing an additional matrix or model % that should be combined with SUX matrix.% Note that the naming of metabolites in this matrix has to be identical to % model naming. Also, the list should be unique. % % 11-10-07 IT % if nargin < 6 addModel = ''; end if nargin < 5 compartment = '[c]'; end if nargin < 4 KEGGBlackList = {}; end if nargin < 3 KEGGFilename = '11-20-08-KEGG-reaction.lst'; end % checks if model.mets has () or [] for compartment, or adds cytosol to % compounds if no compartment is specified model = CheckMetName(model); % create KEGG Matrix - U KEGG = createUniversalReactionModel(KEGGFilename, KEGGBlackList); KEGG = transformKEGG2Model(KEGG,dictionary); %merge all 3 matrixes % 1. S with U model.RxnSubsystem = model.subSystems; KEGG.RxnSubsystem = KEGG.subSystems; [model_SU] = mergeTwoModels(model,KEGG,1); % Adds an additional matrix if given as input % Note that the naming of metabolites in this matrix has to be identical to % model naming. Also, the list should be unique. if isstruct(addModel) addModel = CheckMetName(addModel); [model_SU] = mergeTwoModels(model_SU,addModel,1); end if ~isempty(compartment) ExchangeRxnMatrix = createXMatrix(model_SU.mets,1,compartment); % 2. SU with X ExchangeRxnMatrix.RxnSubsystem = ExchangeRxnMatrix.subSystems; %model_SU.RxnSubsystem = model_SU.subSystems; [MatricesSUX] = mergeTwoModels(model_SU,ExchangeRxnMatrix,1); % creates a vector assigning the origin of the reactions to the parentfprintf(1,'Converting merged model into an irreversible model...'); else MatricesSUX=model_SU; end MatricesSUX.rxnGeneMat(length(MatricesSUX.rxns),length(MatricesSUX.genes))=0; MatricesSUX.rxnGeneMat = sparse(MatricesSUX.rxnGeneMat); MatricesSUX = convertToIrreversible(MatricesSUX); % MatrixPart indicates in which area of MatricesSUX the model reactions, % kegg reactions, and exchange/transport reactions are located (ie. 1 - % model, 2 - kegg, 3 - X) tmp=find(model.rev); MatricesSUX.MatrixPart(1:length(model.rxns)+length(tmp),1)=1; % model reactions MatricesSUX.MatrixPart(length(MatricesSUX.MatrixPart)+1:length(MatricesSUX.MatrixPart)+length(KEGG.rxns)+length(find(KEGG.rev)),1)=2;%KEGG DB reactions MatricesSUX.MatrixPart(length(MatricesSUX.MatrixPart)+1:length(MatricesSUX.rxns),1)=3; %exchange and transport reactions function model = CheckMetName(model) % checks if model.mets has () or [] for compartment if ~isempty(strfind(model.mets,'(c)')) ||~isempty(strfind(model.mets,'(e)')) for i = 1 :length(model.mets) model.mets{i} = regexprep(model.mets{i},'(','['); model.mets{i} = regexprep(model.mets{i},')',']'); end end % fixes metabolites names if no compartment has been added to metabolites. % It assumes that the metabolites without compartment are in the cytosol for i = 1 :length(model.mets) if isempty(regexp(model.mets{i},'\(\w\)')) && isempty(regexp(model.mets{i},'\[\w\]')) model.mets{i} = strcat(model.mets{i},'[c]'); end end
github
EPFL-LCSB/matTFA-master
growthExpMatch.m
.m
matTFA-master/ext/Cobra205_vDec2014/gapFilling/growthExpMatch/growthExpMatch.m
6,053
utf_8
7b4d9288dec14e0b4979d70ba9f64043
function [solution]=growthExpMatch(model, KEGGFilename, compartment, iterations, dictionary, logFile, threshold) %growExpMatch run the growthExpMatch algorythm % % [solution]=growthExpMatch(model, KEGGFilename, compartment, iterations, dictionary, logFile, threshold) % %INPUTS % model COBRA model structure % KEGGFilename File name containing Kegg database (.lst file with list of % reactions: each listing is reaction name followed by colon % followed by the reaction formula) % compartment [c] --> transport from cytoplasm [c] to extracellulat space % [e] (default), [p] creates transport from [c] to [p] % and from [p] to [c] % iterations Number of iterations to run % dictionary n x 2 cell array of metabolites names for conversion from % Kegg ID's to the compound abbreviations from BiGG database % (1st column is compound abb. (non-compartmenalized) and % 2nd column is Kegg ID) Both columns are the same length. % %OPTINAL INPUTS % logFile solution is printed in this file (name of reaction added and % flux of that particular reaction) (Default = GEMLog.txt) % % threshold threshold number for biomass reaction; model is considered % to be growing when the flux of the biomass reaction is % above threshold. (Default = 0.05) % %OUTPUT % solution MILP solution that consists of the continuous solution, integer % solution, objective value, stat, full solution, and % imported reactions % % %%Procedure to run SMILEY: %(1) obtain all input files (ie. model, CompAbr, and KeggID are from BiGG, KeggList is from Kegg website) %(2) remove desired reaction from model with removeRxns, or set the model % on a particular Carbon or Nitrogen source %(3) create an SUX Matrix by using the function MatricesSUX = % generateSUXMatrix(model,dictionary, KEGGFilename,compartment) %(4) run it through SMILEY using [solution,b,solInt]=Smiley(MatricesSUX) %(5) solution.importedRxns contains the solutions to all iterations % % MILPproblem % A LHS matrix % b RHS vector % c Objective coeff vector % lb Lower bound vector % ub Upper bound vector % osense Objective sense (-1 max, +1 min) % csense Constraint senses, a string containting the constraint sense for % each row in A ('E', equality, 'G' greater than, 'L' less than). % vartype Variable types % x0 Initial solution % Based on IT 11/2008 % Edited by xx if nargin<2 MatricesSUX= model; iterations=2; else MatricesSUX = generateSUXMatrix(model,dictionary, KEGGFilename,compartment); end if nargin <6 logFile='GEMLog'; end if nargin <7 threshold= 0.05; end MatricesSUXori = MatricesSUX; startKegg = find(MatricesSUX.MatrixPart ==2, 1, 'first'); stopKegg = find(MatricesSUX.MatrixPart ==2, 1, 'last'); lengthKegg = stopKegg -startKegg +1; startEx = find(MatricesSUX.MatrixPart ==3, 1, 'first'); stopEx = find(MatricesSUX.MatrixPart ==3, 1, 'last'); lengthEx = stopEx -startEx +1; if isempty(lengthEx) lengthEx = 0; end vmax = 1000; [a,b]=size(MatricesSUX.S); cols = b + lengthKegg + lengthEx; rows = a + lengthKegg + lengthEx; [i1,j1,s1] = find(MatricesSUX.S); % Kegg %add rows i2a=(a+1:a+lengthKegg)'; j2a=(startKegg:stopKegg)'; s2a=ones(lengthKegg,1); %add cols i2b=(a+1:a+lengthKegg)'; j2b=(b+1:b+lengthKegg)'; s2b=-vmax*ones(lengthKegg,1); %Exchange %add rows i3a=(a+lengthKegg+1:rows)'; j3a=(startEx:stopEx)'; s3a=ones(lengthEx,1); %add cols i3b=(a+lengthKegg+1:rows)'; j3b=(b+lengthKegg+1:cols)'; s3b=-vmax*ones(lengthEx,1); if isempty(MatricesSUX.c); disp('No biomass reaction found'); else biomass_rxn_loc = find(MatricesSUX.c); end i = [i1;i2a;i2b;i3a;i3b;rows+1]; j=[j1;j2a;j2b;j3a;j3b;biomass_rxn_loc]; s=[s1;s2a;s2b;s3a;s3b;1]; MatricesSUX.A = sparse(i,j,s); MatricesSUX.b = zeros(size(MatricesSUX.A,1),1); %%% Set the threshold to 0.05 %%% MatricesSUX.b(size(MatricesSUX.A,1),1) = threshold; MatricesSUX.cOuter = zeros(size(MatricesSUX.A,2),1); MatricesSUX.cOuter(b+1:b+lengthKegg)=1; MatricesSUX.cOuter(b+lengthKegg+1:cols)=2.1; MatricesSUX.csense(1:a)='E'; MatricesSUX.csense(a+1:rows)='L'; MatricesSUX.csense(rows+1) = 'G'; MatricesSUX.lb(b+1:cols)=0; MatricesSUX.ub(b+1:cols)=1; MatricesSUX.rxns(b+1:cols)=strcat(MatricesSUX.rxns(startKegg:stopEx),'dummy'); MatricesSUX.MatrixPart(b+1:cols)=4; Int= find(MatricesSUX.MatrixPart>=4); spy(MatricesSUX.A) x0=zeros(size(MatricesSUX.A,2),1); solInt=zeros(length(Int),1); %%% setting the MILPproblem %%% vartype(b+1:cols) = 'B'; vartype(1:b) = 'C'; MILPproblem.A = MatricesSUX.A; MILPproblem.b = MatricesSUX.b; MILPproblem.c = MatricesSUX.cOuter; MILPproblem.lb = MatricesSUX.lb; MILPproblem.ub = MatricesSUX.ub; MILPproblem.csense = MatricesSUX.csense; MILPproblem.osense = 1; MILPproblem.vartype = vartype; MILPproblem.x0 = x0; for i = 1: iterations solution = solveCobraMILP(MILPproblem); if(solution.obj~=0) solInt(:,i+1)=solution.int; printSolutionGEM(MatricesSUX, solution,logFile,i); MILPproblem.A(rows+i+1,j2b(1):cols) = solInt(:,i+1)'; MILPproblem.b(rows+i+1) = sum(solInt(:,i+1))-.1; MILPproblem.csense(rows+i+1) = 'L'; % save([logFile '_solution_' num2str(i)]); end solution.importedRxns = findImportedReactions(solInt, MatricesSUX); tmp=find(solution.cont); for j=1:length(tmp) if(tmp(j)>=Int(1)) MILPproblem.ub(tmp(j))=solution.cont(tmp(j));%%% end end if (solution.stat~=1) break end end printSolutionGEM(MatricesSUX, solution); function importedRxns = findImportedReactions(solInt, MatricesSUX) importedRxns= {}; stopModel = find((MatricesSUX.MatrixPart ==1), 1, 'last'); for i = 1: size(solInt,2)-1 [x,y] = find(solInt(:, i+1)); for j = 1: size(x) importedRxns{i, j} = MatricesSUX.rxns(stopModel + x(j)); MatricesSUX.rxns(stopModel + x(j)); end end
github
CollinGuo/GoDec_plus-master
SpectralClustering.m
.m
GoDec_plus-master/SpectralClustering.m
1,247
utf_8
21c3ecc5345706307b629c9e01180798
%-------------------------------------------------------------------------- % This function takes an adjacency matrix of a graph and computes the % clustering of the nodes using the spectral clustering algorithm of % Ng, Jordan and Weiss. % CMat: NxN adjacency matrix % n: number of groups for clustering % groups: N-dimensional vector containing the memberships of the N points % to the n groups obtained by spectral clustering %-------------------------------------------------------------------------- % Copyright @ Ehsan Elhamifar, 2012 %-------------------------------------------------------------------------- function groups = SpectralClustering(CKSym,n) warning off; N = size(CKSym,1); MAXiter = 1000; % Maximum number of iterations for KMeans REPlic = 20; % Number of replications for KMeans % Normalized spectral clustering according to Ng & Jordan & Weiss % using Normalized Symmetric Laplacian L = I - D^{-1/2} W D^{-1/2} DN = diag( 1./sqrt(sum(CKSym)+eps) ); LapN = speye(N) - DN * CKSym * DN; [uN,sN,vN] = svd(LapN); kerN = vN(:,N-n+1:N); for i = 1:N kerNS(i,:) = kerN(i,:) ./ norm(kerN(i,:)+eps); end groups = kmeans(kerNS,n,'maxiter',MAXiter,'replicates',REPlic,'EmptyAction','singleton');
github
walid1992/AndroidSpeexDenoise-master
echo_diagnostic.m
.m
AndroidSpeexDenoise-master/app/src/main/jni/libspeexdsp/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
brennankoopman/MTE204_Robot_Arm_Control-master
Jacobian.m
.m
MTE204_Robot_Arm_Control-master/Jacobian.m
575
utf_8
7231c1c63fd0e284853ed024883d2ea1
% calculates the jacobian based on the joint angles function J = Jacobian(q); len = [0 1 1]; dx1 = -(len(2)*cos(q(2)) + len(3)*cos(q(2)-q(3)))*sin(q(1)); dx2 = (-len(2)*sin(q(2))-len(3)*sin(q(2)-q(3)))*cos(q(1)); dx3 = (len(3)*sin(q(2)-q(3)))*cos(q(1)); dy1 = (len(2)*cos(q(2))+len(3)*cos(q(2)-q(3)))*cos(q(1)); dy2 = (-len(2)*sin(q(2))-len(3)*sin(q(2)-q(3)))*sin(q(1)); dy3 = len(3)*sin(q(2)-q(3))*sin(q(1)); dz1 = 0; dz2 = len(2)*cos(q(2))+len(3)*cos(q(2)-q(3)); dz3 = -len(3)*cos(q(2)-q(3)); J = [dx1,dx2,dx3; dy1,dy2,dy3; dz1,dz2,dz3];
github
brennankoopman/MTE204_Robot_Arm_Control-master
timeOutputTest.m
.m
MTE204_Robot_Arm_Control-master/timeOutputTest.m
2,015
utf_8
4d5da938ce78aadae33aca4b8d618470
%{ %this times the numerical method verses n subintervals, the calculations in this function are the major ones a real %time system would need to operate with our mething method q - the initial position in angles of deg t - the target position in cartesian coords, col vesctor Jerr - the end case error on the Jacobian transpose method n = number of steps you break the linear movement into %} function time = timeOutputTest(q, t, Jerr, n) tic %this records the innitial time stamp for the time trials q = q*(pi/180); Q = [q,zeros(3,n)]; %list of all angles for each target point starting at the initial position Points = sectionPath(t,q,n); %CALCULATES THE ANGLES FOR EACH STEP POINT USING THE JACOBIAN TRANSPOSE METHOD for a = 1:n Q(:,a+1) = getQ( Points(:,a+1), Q(:,a),Jerr); % ERROR of Jerr end dQ = [zeros(3,n)]; %list of all differential angles cPoints = [Points(:,1)]; %list of points, with 100 points for each arc, ie target point, here we just set the first entry the initial position for a = 1:n %for each jump in angles dQ(:,a+1) = Q(:,a+1) - Q(:,a); %finds the change in angle needed for this step %it turns out that the rotations dont linearlize nicely when a path crosses %the refrence axis, since the change in angle from 350 -> 10 should be 20, % NOT -340, thus a single dq value cannot exceed 180 deg, as the smaller % rotation value is preffered. note that angles are in RADIANS if( abs(dQ(1,a))>pi) dQ(1,a)= dQ(1,a)-2*pi*sign(dQ(1,a)); %takes the opposite of the sign of your dQ * 360, and adds your dQ to find your opposite rotation end if( abs(dQ(2,a))>pi) dQ(2,a) = dQ(2,a)-2*pi*sign(dQ(2,a)); end if( abs(dQ(3,a))>pi) dQ(3,a) = dQ(3,a)-2*pi*sign(dQ(3,a)); end end %csvwrite('dQ.csv', transpose(dQ)); %csvwrite('Q.csv', transpose(Q)); time = toc; %return time stamp for the time the method took
github
brennankoopman/MTE204_Robot_Arm_Control-master
armFunction_midJoint.m
.m
MTE204_Robot_Arm_Control-master/armFunction_midJoint.m
387
utf_8
ef5a3716f0aca41119ee61b2002b8ec0
%this function calculates the postion of the midjoint with the inputs of %q, which is the joint angles of the arm %P is the reference point of the arm in 3D space, typically (0,0,0) function [smid] = armFunction_midJoint (q, P) len = [0;1;1]; y = (len(2)*cos(q(2)))*sin(q(1)) - P(1); x = (len(2)*cos(q(2)))*cos(q(1)) - P(2); z = len(2)*sin(q(2)) - P(3); smid = [x;y;z]; endfunction
github
brennankoopman/MTE204_Robot_Arm_Control-master
armFunction.m
.m
MTE204_Robot_Arm_Control-master/armFunction.m
458
utf_8
af0cc0db3ec240f263d95ab51ab4835f
%this function calculates the postion of the end effector with the inputs of %q, which is the joints angles of the arm %P is the reference point of the arm in 3D space, typically (0,0,0) function s = armFunction(q, P) len = [0 1 1]; x = (len(2)*cos(q(2)) + len(3)*cos(q(2)-q(3)))*cos(q(1)) - P(1); % x y = (len(2)*cos(q(2)) + len(3)*cos(q(2)-q(3)))*sin(q(1)) - P(2); % y z = (len(2)*sin(q(2)) + len(3)*sin(q(2)-q(3))) - P(3); % z s = [x;y;z];
github
brennankoopman/MTE204_Robot_Arm_Control-master
sectionPath.m
.m
MTE204_Robot_Arm_Control-master/sectionPath.m
764
utf_8
fc563b76c2ae1de650cea01e7498cf4d
%{ Version = Test this version will be used for the analysis of the time efficiency of the algorithm this function will take any linear path between s and t, and break it up into an efficient number of smaller steps in order to make the path as straight as possible %} %t is the target position, q is the initial position given in its angles %n = number of steps %sNew is a list of new positions to be outputted function sNew = sectionPath(t, qi, n) s = armFunction( qi, [0;0;0]); e = t - s; %n is the number of substeps we have per movement eN = e / n; sNew = [s,zeros(3, n)]; %set the first value to the initial position for a = 1:n sNew(:,a+1) = sNew(:,a) + eN; %the size of sNew is 3 x n+1 end end
github
zeakey/edgeval-master
checkNumArgs.m
.m
edgeval-master/utils/checkNumArgs.m
3,796
utf_8
726c125c7dc994c4989c0e53ad4be747
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % Helper utility for checking numeric vector arguments. % % Runs a number of tests on the numeric array x. Tests to see if x has all % integer values, all positive values, and so on, depending on the values % for intFlag and signFlag. Also tests to see if the size of x matches siz % (unless siz==[]). If x is a scalar, x is converted to a array simply by % creating a matrix of size siz with x in each entry. This is why the % function returns x. siz=M is equivalent to siz=[M M]. If x does not % satisfy some criteria, an error message is returned in er. If x satisfied % all the criteria er=''. Note that error('') has no effect, so can use: % [ x, er ] = checkNumArgs( x, ... ); error(er); % which will throw an error only if something was wrong with x. % % USAGE % [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % % INPUTS % x - numeric array % siz - []: does not test size of x % - [if not []]: intended size for x % intFlag - -1: no need for integer x % 0: error if non integer x % 1: error if non odd integers % 2: error if non even integers % signFlag - -2: entires of x must be strictly negative % -1: entires of x must be negative % 0: no contstraints on sign of entries in x % 1: entires of x must be positive % 2: entires of x must be strictly positive % % OUTPUTS % x - if x was a scalar it may have been replicated into a matrix % er - contains error msg if anything was wrong with x % % EXAMPLE % a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er) % % See also NARGCHK % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] xname = inputname(1); er=''; if( isempty(siz) ); siz = size(x); end; if( length(siz)==1 ); siz=[siz siz]; end; % first check that x is numeric if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end; % if x is a scalar, simply replicate it. xorig = x; if( length(x)==1); x = x(ones(siz)); end; % regardless, must have same number of x as n if( length(siz)~=ndims(x) || ~all(size(x)==siz) ) er = ['has size = [' num2str(size(x)) '], ']; er = [er 'which is not the required size of [' num2str(siz) ']']; er = createErrMsg( xname, xorig, er ); return; end % check that x are the right type of integers (unless intFlag==-1) switch intFlag case 0 if( ~all(mod(x,1)==0)) er = 'must have integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 1 if( ~all(mod(x,2)==1)) er = 'must have odd integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 2 if( ~all(mod(x,2)==0)) er = 'must have even integer entries'; er = createErrMsg( xname, xorig, er ); return; end; end; % check sign of entries in x (unless signFlag==0) switch signFlag case -2 if( ~all(x<0)) er = 'must have strictly negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case -1 if( ~all(x<=0)) er = 'must have negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case 1 if( ~all(x>=0)) er = 'must have positive entries'; er = createErrMsg( xname, xorig, er ); return; end; case 2 if( ~all(x>0)) er = 'must have strictly positive entries'; er = createErrMsg( xname, xorig, er ); return; end end function er = createErrMsg( xname, x, er ) if(numel(x)<10) er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.']; else er = ['Numeric input argument ' xname ' ' er '.']; end
github
zeakey/edgeval-master
edgesEvalDir.m
.m
edgeval-master/utils/edgesEvalDir.m
5,852
utf_8
b708b92045eaa75fa68d09e169447bb6
function varargout = edgesEvalDir( varargin ) % Calculate edge precision/recall results for directory of edge images. % % Enhanced replacement for boundaryBench() from BSDS500 code: % http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/ % Uses same format for results and is fully compatible with boundaryBench. % Given default prms results are *identical* to boundaryBench with the % additional 9th output of R50 (recall at 50% precision). % % The odsF/P/R/T are results at the ODS (optimal dataset scale). % The oisF/P/R are results at the OIS (optimal image scale). % Naming convention: P=precision, R=recall, F=2/(1/P+1/R), T=threshold. % % In addition to the outputs, edgesEvalDir() creates three files: % eval_bdry_img.txt - per image OIS results [imgId T R P F] % eval_bdry_thr.txt - per threshold ODS results [T R P F] % eval_bdry.txt - complete results (*re-ordered* copy of output) % These files are identical to the ones created by boundaryBench. % % USAGE % [odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50] = edgesEvalDir( prms ) % [ODS,~,~,~,OIS,~,~,AP,R50] = edgesEvalDir( prms ) % % INPUTS % prms - parameters (struct or name/value pairs) % .resDir - ['REQ'] dir containing edge detection results (.png) % .gtDir - ['REQ'] dir containing ground truth (.mat) % .pDistr - [{'type','parfor'}] parameters for fevalDistr % .cleanup - [0] if true delete temporary files % .thrs - [99] number or vector of thresholds for evaluation % .maxDist - [.0075] maximum tolerance for edge match % .thin - [1] if true thin boundary maps % % OUTPUTS % odsF/P/R/T - F-measure, precision, recall and threshold at ODS % oisF/P/R - F-measure, precision, and recall at OIS % AP - average precision % R50 - recall at 50% precision % % EXAMPLE % % See also edgesEvalImg, edgesEvalPlot % % Structured Edge Detection Toolbox Version 3.01 % Code written by Piotr Dollar, 2014. % Licensed under the MSR-LA Full Rights License [see license.txt] % get additional parameters dfs={ 'resDir','REQ', 'gtDir','REQ', 'pDistr',{{'type','parfor'}}, ... 'cleanup',0, 'thrs',99, 'maxDist',.0075, 'thin',1 }; p=getPrmDflt(varargin,dfs,1); resDir=p.resDir; gtDir=p.gtDir; evalDir=[resDir '-eval/']; if(~exist(evalDir,'dir')), mkdir(evalDir); end % check if results already exist, if so load and return fNm = fullfile(evalDir,'eval_bdry.txt'); if(exist(fNm,'file')), R=dlmread(fNm); R=mat2cell2(R,[1 8]); varargout=R([4 3 2 1 7 6 5 8]); if(nargout<=8), return; end; R=dlmread(fullfile(evalDir,'eval_bdry_thr.txt')); P=R(:,3); R=R(:,2); [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); varargout=[varargout R50]; return; end % perform evaluation on each image (this part can be very slow) assert(exist(resDir,'dir')==7); assert(exist(gtDir,'dir')==7); ids=dir(fullfile(gtDir,'*.mat')); ids={ids.name}; n=length(ids); do=false(1,n); jobs=cell(1,n); res=cell(1,n); for i=1:n, id=ids{i}(1:end-4); res{i}=fullfile(evalDir,[id '_ev1.txt']); do(i)=~exist(res{i},'file'); im1=fullfile(resDir,[id '.png']); gt1=fullfile(gtDir,[id '.mat']); jobs{i}={im1,gt1,'out',res{i},'thrs',p.thrs,'maxDist',p.maxDist,... 'thin',p.thin}; if(0), edgesEvalImg(jobs{i}{:}); end end fevalDistr('edgesEvalImg',jobs(do),p.pDistr{:}); % collect evaluation results I=dlmread(res{1}); T=I(:,1); Z=zeros(numel(T),1); cntR=Z; sumR=Z; cntP=Z; sumP=Z; oisCntR=0; oisSumR=0; oisCntP=0; oisSumP=0; scores=zeros(n,5); for i=1:n % load image results and accumulate I = dlmread(res{i}); cntR1=I(:,2); cntR=cntR+cntR1; sumR1=I(:,3); sumR=sumR+sumR1; cntP1=I(:,4); cntP=cntP+cntP1; sumP1=I(:,5); sumP=sumP+sumP1; % compute OIS scores for image [R,P,F] = computeRPF(cntR1,sumR1,cntP1,sumP1); [~,k]=max(F); [oisR1,oisP1,oisF1,oisT1] = findBestRPF(T,R,P); scores(i,:) = [i oisT1 oisR1 oisP1 oisF1]; % oisCnt/Sum will be used to compute dataset OIS scores oisCntR=oisCntR+cntR1(k); oisSumR=oisSumR+sumR1(k); oisCntP=oisCntP+cntP1(k); oisSumP=oisSumP+sumP1(k); end % compute ODS R/P/F and OIS R/P/F [R,P,F] = computeRPF(cntR,sumR,cntP,sumP); [odsR,odsP,odsF,odsT] = findBestRPF(T,R,P); [oisR,oisP,oisF] = computeRPF(oisCntR,oisSumR,oisCntP,oisSumP); % compute AP/R50 (interpolating 100 values, has minor bug: should be /101) if(0), R=[0; R; 1]; P=[1; P; 0]; F=[0; F; 0]; T=[1; T; 0]; end [~,k]=unique(R); k=k(end:-1:1); R=R(k); P=P(k); T=T(k); F=F(k); AP=0; if(numel(R)>1), AP=interp1(R,P,0:.01:1); AP=sum(AP(~isnan(AP)))/100; end [~,o]=unique(P); R50=interp1(P(o),R(o),max(P(o(1)),.5)); % write results to disk varargout = {odsF,odsP,odsR,odsT,oisF,oisP,oisR,AP,R50}; writeRes(evalDir,'eval_bdry_img.txt',scores); writeRes(evalDir,'eval_bdry_thr.txt',[T R P F]); writeRes(evalDir,'eval_bdry.txt',[varargout{[4 3 2 1 7 6 5 8]}]); % optionally perform cleanup if( p.cleanup ), delete([evalDir '/*_ev1.txt']); delete([resDir '/*.png']); rmdir(resDir); end end function [R,P,F] = computeRPF(cntR,sumR,cntP,sumP) % compute precision, recall and F measure given cnts and sums R=cntR./max(eps,sumR); P=cntP./max(eps,sumP); F=2*P.*R./max(eps,P+R); end function [bstR,bstP,bstF,bstT] = findBestRPF(T,R,P) % linearly interpolate to find best thr for optimizing F if(numel(T)==1), bstT=T; bstR=R; bstP=P; bstF=2*P.*R./max(eps,P+R); return; end A=linspace(0,1,100); B=1-A; bstF=-1; for j = 2:numel(T) Rj=R(j).*A+R(j-1).*B; Pj=P(j).*A+P(j-1).*B; Tj=T(j).*A+T(j-1).*B; Fj=2.*Pj.*Rj./max(eps,Pj+Rj); [f,k]=max(Fj); if(f>bstF), bstT=Tj(k); bstR=Rj(k); bstP=Pj(k); bstF=f; end end end function writeRes( alg, fNm, vals ) % write results to disk k=size(vals,2); fNm=fullfile(alg,fNm); fid=fopen(fNm,'w'); if(fid==-1), error('Could not open file %s for writing.',fNm); end frmt=repmat('%10g ',[1 k]); frmt=[frmt(1:end-1) '\n']; fprintf(fid,frmt,vals'); fclose(fid); end
github
zeakey/edgeval-master
fevalDistr.m
.m
edgeval-master/utils/fevalDistr.m
11,227
utf_8
7e4d5077ef3d7a891b2847cb858a2c6c
function [out,res] = fevalDistr( funNm, jobs, varargin ) % Wrapper for embarrassingly parallel function evaluation. % % Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs % should be a cell array of length nJob and each job should be a cell array % of parameters to pass to funNm. funNm must be a function in the path and % must return a single value (which may be a dummy value if funNm writes % results to disk). Different forms of parallelization are supported % depending on the hardware and Matlab toolboxes available. The type of % parallelization is determined by the parameter 'type' described below. % % type='LOCAL': jobs are executed using a simple "for" loop. This implies % no parallelization and is the default fallback option. % % type='PARFOR': jobs are executed using a "parfor" loop. This option is % only available if the Matlab *Parallel Computing Toolbox* is installed. % Make sure to setup Matlab workers first using "matlabpool open". % % type='DISTR': jobs are executed on the Caltech cluster. Distributed % queuing system must be installed separately. Currently this option is % only supported on the Caltech cluster but could easily be installed on % any Linux cluster as it requires only SSH and a shared filesystem. % Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and % determines cluster machines used (e.g. pLaunch={48,401:408}). % % type='COMPILED': jobs are executed locally in parallel by first compiling % an executable and then running it in background. This option requires the % *Matlab Compiler* to be installed (but does NOT require the Parallel % Computing Toolbox). Compiling can take 1-10 minutes, so use this option % only for large jobs. (On Linux alter startup.m by calling addpath() only % if ~isdeployed, otherwise will get error about "CTF" after compiling). % Note that relative paths will not work after compiling so all paths used % by funNm must be absolute paths. % % type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster. % Similar to type='COMPILED', except after compiling, the executable is % queued to the HPC cluster where all computation occurs. This option % likewise requires the *Matlab Compiler*. Paths to data, etc., must be % absolute paths and available from HPC cluster. Parameter pLaunch must % have two fields 'scheduler' and 'shareDir' that define the HPC Server. % Extra parameters in pLaunch add finer control, see fedWinhpc for details. % For example, at MSR one possible cluster is defined by scheduler = % 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'. % Note call to 'job submit' from Matlab will hang unless pwd is saved % (simply call 'job submit' from cmd prompt and enter pwd). % % USAGE % [out,res] = fevalDistr( funNm, jobs, [varargin] ) % % INPUTS % funNm - name of function that will process jobs % jobs - [1xnJob] cell array of parameters for each job % varargin - additional params (struct or name/value pairs) % .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc' % .pLaunch - [] extra params for type='distr' or type='winhpc' % .group - [1] send jobs in batches (only relevant if type='distr') % % OUTPUTS % out - 1 if jobs completed successfully % res - [1xnJob] cell array containing results of each job % % EXAMPLE % % Note: in this case parallel versions are slower since conv2 is so fast % n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end % tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc, % tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc, % tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc % [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1)) % % See also matlabpool mcc % % Piotr's Computer Vision Matlab Toolbox Version 3.26 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] dfs={'type','local','pLaunch',[],'group',1}; [type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2); if(isempty(jobs)), res=cell(1,0); out=1; return; end switch lower(type) case 'local', [out,res]=fedLocal(funNm,jobs,store); case 'parfor', [out,res]=fedParfor(funNm,jobs,store); case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store); case 'compiled', [out,res]=fedCompiled(funNm,jobs,store); case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store); otherwise, error('unkown type: ''%s''',type); end end function [out,res] = fedLocal( funNm, jobs, store ) % Run jobs locally using for loop. nJob=length(jobs); res=cell(1,nJob); out=1; tid=ticStatus('collecting jobs'); for i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; tocStatus(tid,i/nJob); end end function [out,res] = fedParfor( funNm, jobs, store ) % Run jobs locally using parfor loop. nJob=length(jobs); res=cell(1,nJob); out=1; parfor i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; end end function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store ) % Run jobs using Linux queuing system. if(~exist('controller.m','file')) msg='distributed queuing not installed, switching to type=''local''.'; warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG> end nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:}); if( group>1 ) nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0; for i=1:nJobGrp, k1=min(nJob,k+group); jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr'; end jids=controller('jobsAdd',nJob,funNm,jobs); k=0; fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs'); while( 1 ) jids1=controller('jobProbe',jids); if(isempty(jids1)), pause(.1); continue; end jid=jids1(1); [r,err]=controller('jobRecv',jid); if(~isempty(err)), disp('ABORTING'); out=0; break; end k=k+1; if(store), res{jid==jids}=r; end tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end; controller('closeQueue'); end function [out,res] = fedCompiled( funNm, jobs, store ) % Run jobs locally in background in parallel using compiled code. nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{}); cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0; Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs'); while( 1 ) % launch jobs until queue is full (q==Q) or all jobs launched (i==nJob) while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i); if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0); else system2([cmd int2str2(i,10) ' &'],0); end end % collect completed jobs (k1 of them), release queue slots done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1; for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH> end function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store ) % Run jobs using Windows HPC Server. nJob=length(jobs); res=cell(1,nJob); dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',... 'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000}; p = getPrmDflt(pLaunch,dfs,1); tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions); for i=1:nJob, jobSave(tDir,jobs{i},i); end hpcSubmit(funNm,1:nJob,tDir,p); k=0; ticId=ticStatus('collecting jobs'); while( 1 ) done=jobFileIds(tDir,'done'); k=k+length(done); for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH> end function tids = hpcSubmit( funNm, ids, tDir, pLaunch ) % Helper: send jobs w given ids to HPC cluster. n=length(ids); tids=cell(1,n); if(n==0), return; end; scheduler=[' /scheduler:' pLaunch.scheduler ' ']; m=system2(['cluscfg view' scheduler],0); minCores=(hpcParse(m,'total number of nodes',1) - ... hpcParse(m,'Unreachable nodes',1) - 1)*8; minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]); m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ... '/priority:' int2str(pLaunch.priority)],1); jid=hpcParse(m,'created job, id',0); s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e); if(p), jid1=[jid '.1']; else jid1=jid; end for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ... int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ... '.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id]; if(p), ids1='*'; n=1; else ids1=int2str2(ids); end if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80)); end function v = hpcParse( msg, key, tonum ) % Helper: extract val corresponding to key in hpc msg. t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2)); keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys)); if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end if(tonum==1), v=str2double(v); return; end v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split')); if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000; end function tDir = jobSetup( rtDir, funNm, executable, mccOptions ) % Helper: prepare by setting up temporary dir and compiling funNm t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15); tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir); if(~isempty(executable) && exist(executable,'file')) fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir); else t=clock; fprintf('Compiling (this may take a while)...\n'); [~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:}); t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t); if(~isempty(executable)), copyfile([tDir filesep f e],executable); end end end function ids = jobFileIds( tDir, type ) % Helper: get list of job files ids on disk of given type fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs); ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end end function jobSave( tDir, job, ind ) %#ok<INUSL> % Helper: save job to temporary file for use with fevalDistrDisk() save([tDir int2str2(ind,10) '-in'],'job'); end function r = jobLoad( tDir, ind, store ) % Helper: load job and delete temporary files from fevalDistrDisk() f=[tDir int2str2(ind,10)]; if(store), r=load([f '-out']); r=r.r; else r=[]; end fs={[f '-done'],[f '-in.mat'],[f '-out.mat']}; delete(fs{:}); pause(.1); for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN> warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG> delete(fs{i}); pause(5); k=k+1; if(k>12), break; end; end; end end function msg = system2( cmd, show ) % Helper: wraps system() call if(show), disp(cmd); end [status,msg]=system(cmd); msg=msg(1:end-1); if(status), error(msg); end if(show), disp(msg); end end
github
isamabdullah88/Visual-Inertial-Odometry-master
integrateIMU.m
.m
Visual-Inertial-Odometry-master/SourceCode/Functions/integrateIMU.m
3,116
utf_8
26979cd3549c449c0e7ca5da743e2957
function[xUpdate] = integrateIMU(xPrev, a, omega, dt, g_w) %INTEGRATEIMUSTREAM Integrate IMU stream and return state and covariance %estimates %The state is given by : %x =[p_I_G q_IG v_I_G b_g b_a]; %Set noise to 0 noise_params.sigma_g = 0; noise_params.sigma_a = 0; noise_params.sigma_bg = 0; noise_params.sigma_ba = 0; noise_params.tau = 10^12; %Calculate xDot w = getWhiteNoise(noise_params); %RK4 Integration % Given x' = f(x), RK4 integration proceeds as follows : % x(n + 1) = x(n) + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4); where % k1 = f(x); % k2 = f(x + dt / 2 * k1) % k3 = f(x + dt / 2 * k2) % k4 = f(x + dt * k3) k = {}; k_coeffs =[1 0.5 0.5 1]; b_coeffs =[1 / 6 1 / 3 1 / 3 1 / 6]; %RK4 %b_coeffs =[1 0 0 0]; %Forward Euler k{1} = getxDot(xPrev, omega, a, w, noise_params, g_w); for i_k = 2 : 4 xTemp.p_I_G = xPrev.p_I_G + (k{i_k - 1}.p_I_G) * k_coeffs(i_k) * dt; xTemp.q_IG = xPrev.q_IG + (k{i_k - 1}.q_IG) * k_coeffs(i_k) * dt; %Possibly renormalize here xTemp.v_I_G = xPrev.v_I_G + (k{i_k - 1}.v_I_G) * k_coeffs(i_k) * dt; xTemp.b_g = xPrev.b_g + (k{i_k - 1}.b_g) * k_coeffs(i_k) * dt; xTemp.b_a = xPrev.b_a + (k{i_k - 1}.b_a) * k_coeffs(i_k) * dt; k{i_k} = getxDot(xTemp, omega, a, w, noise_params, g_w); end xUpdate.p_I_G = xPrev.p_I_G + dt * (b_coeffs(1) * k{1}.p_I_G + b_coeffs(2) * k{2}.p_I_G + b_coeffs(3) * k{3}.p_I_G + b_coeffs(4) * k{4}.p_I_G); xUpdate.v_I_G = xPrev.v_I_G + dt * (b_coeffs(1) * k{1}.v_I_G + b_coeffs(2) * k{2}.v_I_G + b_coeffs(3) * k{3}.v_I_G + b_coeffs(4) * k{4}.v_I_G); xUpdate.b_g = xPrev.b_g + dt * (b_coeffs(1) * k{1}.b_g + b_coeffs(2) * k{2}.b_g + b_coeffs(3) * k{3}.b_g + b_coeffs(4) * k{4}.b_g); xUpdate.b_a = xPrev.b_a + dt * (b_coeffs(1) * k{1}.b_a + b_coeffs(2) * k{2}.b_a + b_coeffs(3) * k{3}.b_a + b_coeffs(4) * k{4}.b_a); xUpdate.q_IG = quat_normalize(xPrev.q_IG + dt * (b_coeffs(1) * k{1}.q_IG + b_coeffs(2) * k{2}.q_IG + b_coeffs(3) * k{3}.q_IG + b_coeffs(4) * k{4}.q_IG)); %Note the renormalization %Non linear kinematics % x - state % w - noise vector % omega, a - ang. rates and accels. % tau - time constant for accelerometer bias function xdot = getxDot(x, omega, a, w, noise_params, g_w) xdot.p_I_G = x.v_I_G; xdot.q_IG = 0.5 * omegaMat(omega, zeros(3, 1), x.b_g) * x.q_IG; xdot.v_I_G = rotmat_from_quat(quat_normalize(x.q_IG)) * (a - x.b_a) + rotmat_from_quat(quat_normalize(x.q_IG)) * g_w; xdot.b_g = zeros(3, 1); xdot.b_a = zeros(3, 1); end %White noise vector function w = getWhiteNoise(sigma_params) w.w_g = sigma_params.sigma_g. * randn(3, 1); w.w_a = sigma_params.sigma_a. * randn(3, 1); w.w_bg = sigma_params.sigma_bg. * randn(3, 1); w.w_ba = sigma_params.sigma_ba. * randn(3, 1); end %Quaternion kinematic matrix function bigOmega = omegaMat(omega_meas, w_g, b_g) %Is it + w_g or - w_g? Does it matter? omega_true = omega_meas + w_g - b_g; ox = omega_true(1); oy = omega_true(2); oz = omega_true(3); bigOmega =[0 - ox - oy - oz; ... ox 0 oz - oy; oy - oz 0 ox; oz oy - ox 0;]; %See technical note on quaternions by Sola. Page 6. %This formulation assumes that the quaternion has the scalar part %at the start end end
github
isamabdullah88/Visual-Inertial-Odometry-master
calcGNPosEstTODO.m
.m
Visual-Inertial-Odometry-master/SourceCode/Functions/calcGNPosEstTODO.m
2,592
utf_8
79942d6dfc17224ece353c06cb16e2a5
function[p_f_G, cost, RCOND] = calcGNPosEst(camState, observations, noiseParams) %CALCGNPOSEST Calculate the position estimate of the feature using Gauss %Newton optimization % INPUT : % observations : 2xM matrix of pixel values of the current landmark % camStates : Cell array of M structs of camera poses % camera : intrinsic calibration % OUTPUT : % p_f_G : 3x1 feature vector in the global frame %K is not needed if we assume observations are not pixels but x' = (u - %c_u) / f_u %K =[camera.f_u 0 camera.c_u; 0 camera.f_v camera.c_v; 0 0 1]; %% Actual Problem %Get initial estimate through intersection %Use the first 2 camStates CnInd = length(camState); C_1n = quatToRotMat(camState{CnInd}.q_CG)' * quatToRotMat(camState{1}.q_CG); % t_21_1 = quatToRotMat(camState{secondViewIdx}.q_CG) * (camState{secondViewIdx}.p_C_G - camState{1}.p_C_G); t_1n_1 = quatToRotMat(camState{1}.q_CG) * (camState{CnInd}.p_C_G - camState{1}.p_C_G); p_f1_1_bar = triangulate(observations( :, 1), observations( : , CnInd), C_1n, t_1n_1); x0 =[p_f1_1_bar(1) / p_f1_1_bar(3); p_f1_1_bar(2) / p_f1_1_bar(3); 1 / p_f1_1_bar(3)]; [params, cost] = lsqnonlin(@objFn, double(x0)); p_f_G = params; RCOND = 1; %% The Objective Function function r = objFn(beta) % beta =[X, Y, Z]of the feature position in global frame. These % are our parameters to estimate % r = f(X, beta) - Y : These are the list of residuals for all the % data points lastInd = length(camState); for i = 2 : lastInd C_1i = quatToRotMat(camState{i}.q_CG)' * quatToRotMat(camState{i}.q_CG); % t_i1_1 = quatToRotMat(camState{1}.q_CG) * (camState{i}.p_C_G - camState{1}.p_C_G); t_i1_1 = quatToRotMat(camState{1}.q_CG) * (camState{i}.p_C_G - camState{1}.p_C_G); % C1 = C_1i( : , 1); C2 = C_1i( : , 2); C3 = C_1i( : , 3); % B1 = beta(1); B2 = beta(2); B3 = beta(3); % X1 = t_i1_1(1); X2 = t_i1_1(2); X3 = t_i1_1(3); % Calculate f(X, B) fXBVec = C_1i * (beta - (t_i1_1 * beta(3))); f1XB = fXBVec(1) / fXBVec(3); f2XB = fXBVec(2) / fXBVec(3); % Compute residual of norms fXB =[f1XB, f2XB]; obs = double(observations( : , i)); y =[obs(1), obs(2)]; r(i - 1) = norm(y - fXB); end end function[p_f1_1] = triangulate(obs1, obs2, C_12, t_21_1) % triangulate Triangulates 3D points from two sets of feature vectors and a % a frame - to - frame transformation %Calculate unit vectors v_1 =[obs1;1]; v_2 =[obs2;1]; v_1 = v_1 / norm(v_1); v_2 = v_2 / norm(v_2); A =[v_1 - C_12 * v_2]; b = t_21_1; % disp(b); scalar_consts = A\b; p_f1_1 = scalar_consts(1) * v_1; end end
github
isamabdullah88/Visual-Inertial-Odometry-master
match.m
.m
Visual-Inertial-Odometry-master/SourceCode/Functions/match.m
1,927
utf_8
f7d5bf4c2b0a7056954aaa41a7ab575e
% num = match(image1, image2) % % This function reads two images, finds their SIFT features, and % displays lines connecting the matched keypoints. A match is accepted % only if its distance is less than distRatio times the distance to the % second closest match. % It returns the number of matches displayed. % % Example : match('scene.pgm', 'book.pgm'); function num = match(image1, image2) % Find SIFT keypoints for each image [im1, des1, loc1] = sift(image1); [im2, des2, loc2] = sift(image2); % For efficiency in Matlab, it is cheaper to compute dot products between % unit vectors rather than Euclidean distances. Note that the ratio of % angles (acos of dot products of unit vectors) is a close approximation % to the ratio of Euclidean distances for small angles. % % distRatio : Only keep matches in which the ratio of vector angles from the % nearest to second nearest neighbor is less than distRatio. distRatio = 0.6; % For each descriptor in the first image, select its match to second image. des2t = des2'; % Precompute matrix transpose for i = 1 : size(des1, 1) dotprods = des1(i, : ) * des2t; % Computes vector of dot products [vals, indx] = sort(acos(dotprods)); % Take inverse cosine and sort results % Check if nearest neighbor has angle less than distRatio times 2nd. if (vals(1) < distRatio * vals(2)) match(i) = indx(1); else match(i) = 0; end end % Create a new image showing the two images side by side. im3 = appendimages(im1, im2); % Show a figure with lines joining the accepted matches. figure('Position', [100 100 size(im3, 2) size(im3, 1)]); colormap('gray'); imagesc(im3); hold on; cols1 = size(im1, 2); for i = 1 : size(des1, 1) if (match(i) > 0) line([loc1(i, 2) loc2(match(i), 2)+ cols1], ... [loc1(i, 1) loc2(match(i), 1)], 'Color', 'c'); end end hold off; num = sum(match > 0); fprintf('Found %d matches.\n', num);
github
isamabdullah88/Visual-Inertial-Odometry-master
loadImuData.m
.m
Visual-Inertial-Odometry-master/SourceCode/Functions/loadImuData.m
1,522
utf_8
376c7c00df767b65f51449e0d08648eb
function[ imuData, gpsData, velocity ] = loadImuData( imuDir ) %loadImuData loads the imu data from kitti dataset in required format i.e. %gyro, accelerometer and timestamps fileDir =[imuDir ' / data /']; fileNames = dir(fullfile(fileDir, ' * .txt')); dateStrings = loadTimestamps(imuDir); len = size(dateStrings, 1); wgs84 = wgs84Ellipsoid('meters'); % seperating required data for i = 1 : len dataF = dlmread([fileDir ' /' fileNames(i).name]); tmpGps = dataF(1 : 3); gpsLatLong(i, : ) = tmpGps; [x, y, z] = geodetic2ecef(wgs84, tmpGps(1), tmpGps(2), tmpGps(3)); gpsData(i, : ) = [x, y, z]; acc(i, : ) = [dataF(12), dataF(13), dataF(14)]; omega(i, : ) = dataF(18 : 20); velocity(i, : ) = [dataF(9), dataF(10), dataF(11)]; end imuData.acc = acc; imuData.omega = omega; % Subtract GPS from first value and plot ground truth gpsData( : , 1) = gpsData( : , 1) - gpsData(1, 1); gpsData( : , 2) = gpsData( : , 2) - gpsData(1, 2); gpsData( : , 3) = gpsData( : , 3) - gpsData(1, 3); % tGPS = toGlobalCoords(gpsData); % % tGPS = gpsData; % figure; line(tGPS( :, 1), tGPS( : , 2), tGPS( : , 3), 'Color', 'm'); % title('Ground Truth GPS in x - y - z plot'); % xlabel('pos X'); ylabel('pos Y'); zlabel('pos Z'); % converting from date to time for i = 1 : len dataTs(i) = dateToTime(datenum(dateStrings(i))); end imuData.dT = diff(dataTs); %%% Function to convert data to time -------------------------------------- function t = dateToTime(date) t = (date - 719529) * 86400; %# 719529 == datenum(1970, 1, 1) end end
github
isamabdullah88/Visual-Inertial-Odometry-master
loadCalibrationCamToCam.m
.m
Visual-Inertial-Odometry-master/SourceCode/Utils/loadCalibrationCamToCam.m
1,837
utf_8
ab070dd26d9e2df2f7739d6d203c4547
function calib = loadCalibrationCamToCam(filename) % open file fid = fopen(filename, 'r'); if fid < 0 calib =[]; return; end % read corner distance calib.cornerdist = readVariable(fid, 'corner_dist', 1, 1); % read all cameras (maximum : 100) for cam = 1 : 100 % read variables S_ = readVariable(fid, ['S_' num2str(cam - 1, '%02d')], 1, 2); K_ = readVariable(fid, ['K_' num2str(cam - 1, '%02d')], 3, 3); D_ = readVariable(fid, ['D_' num2str(cam - 1, '%02d')], 1, 5); R_ = readVariable(fid, ['R_' num2str(cam - 1, '%02d')], 3, 3); T_ = readVariable(fid, ['T_' num2str(cam - 1, '%02d')], 3, 1); S_rect_ = readVariable(fid, ['S_rect_' num2str(cam - 1, '%02d')], 1, 2); R_rect_ = readVariable(fid, ['R_rect_' num2str(cam - 1, '%02d')], 3, 3); P_rect_ = readVariable(fid, ['P_rect_' num2str(cam - 1, '%02d')], 3, 4); % calibration for this cam completely found? if isempty(S_) || isempty(K_) || isempty(D_) || isempty(R_) || isempty(T_) break; end % write calibration calib.S{cam} = S_; calib.K{cam} = K_; calib.D{cam} = D_; calib.R{cam} = R_; calib.T{cam} = T_; % if rectification available if ~ isempty(S_rect_) && ~ isempty(R_rect_) && ~ isempty(P_rect_) calib.S_rect{cam} = S_rect_; calib.R_rect{cam} = R_rect_; calib.P_rect{cam} = P_rect_; end end % close file fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A = readVariable(fid, name, M, N) % rewind fseek(fid, 0, 'bof'); % search for variable identifier success = 1; while success > 0 [str, success] = fscanf(fid, '%s', 1); if strcmp(str, [name ' :']) break; end end % return if variable identifier not found if ~ success A = []; return; end % fill matrix A = zeros(M, N); for m = 1 : M for n = 1 : N [val, success] = fscanf(fid, '%f', 1); if success A(m, n) = val; else A =[]; return; end end end
github
isamabdullah88/Visual-Inertial-Odometry-master
loadCalibrationRigid.m
.m
Visual-Inertial-Odometry-master/SourceCode/Utils/loadCalibrationRigid.m
834
utf_8
f52ca08e93a8e8441acb81012628dfa4
function Tr = loadCalibrationRigid(filename) % open file fid = fopen(filename, 'r'); if fid < 0 error(['ERROR : Could not load : ' filename]); end % read calibration R = readVariable(fid, 'R', 3, 3); T = readVariable(fid, 'T', 3, 1); Tr =[R T;0 0 0 1]; % close file fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function A = readVariable(fid, name, M, N) % rewind fseek(fid, 0, 'bof'); % search for variable identifier success = 1; while success > 0 [str, success] = fscanf(fid, '%s', 1); if strcmp(str, [name ' :']) break; end end % return if variable identifier not found if ~ success A = []; return; end % fill matrix A = zeros(M, N); for m = 1 : M for n = 1 : N [val, success] = fscanf(fid, '%f', 1); if success A(m, n) = val; else A =[]; return; end end end
github
isamabdullah88/Visual-Inertial-Odometry-master
simCamera.m
.m
Visual-Inertial-Odometry-master/Gauss Newton Simulation/simCamera.m
1,700
utf_8
25bcc63217dba70a35b10547d459fb33
function[ obs, camStates ] = simCamera( C1_p_f, camera, C1_p_C2, thetas, n ) %simCamera simulates a camera of n frames given the parameters and returns 2D feature %coordinates in each frame % C1_p_f : 3D position coordinates of feature in C1, which would be % tracked in sub - sequent camera frames % camera : The camera parameter matrix % thetas : List of angles of each frame with respect to first frame % n : The number of frames in which it is to track % C1_p_Ci : List of poses of each frame from first frame % obs : 2Xn matrix. Each column contains 3D coordinates of feature in % each frame % poseC1 : 3D poses of each camera frame in C1 % Note : The maximum number of frames would only be, in which the feature % does not go out of view. % Poses of i frame in C1 C1_p_Ci = C1_p_C2; K = camera.K; tmpP = K *[C1_p_f; 1]; obs( :, 1) = [tmpP(1) / tmpP(3); tmpP(2) / tmpP(3)]; for i = 1 : n % camStates{i}.q_CG = (angle2quat(0, thetas(i), 0, 'XYZ'))'; camStates{i}.q_CG =[0;0;0;1]; if (i == 1) camStates{i}.p_C_G =[0;0;0]; else camStates{i}.p_C_G = C1_p_Ci; % Translating camera Ci from Ci - 1 C1_p_Ci = C1_p_Ci + C1_p_C2; end C_C1_Ci = rotMat(thetas(i)); % 3D feature pos in Ci Ci_p_f = C_C1_Ci * (C1_p_f - camStates{i}.p_C_G); % 2D pos of feature in Ci tmpPi = K *[Ci_p_f; 1]; obs( : , i + 1) = [tmpPi(1) / tmpPi(3); tmpPi(2) / tmpPi(3)]; end % Coverting pixel coordinates to 'ideal' coordinates obs(1, : ) = (obs(1, : ) - camera.px) / camera.mx; obs(2, : ) = (obs(2, : ) - camera.py) / camera.my; function C_C1_C2 = rotMat(theta) C_C1_C2 =[cosd(theta) 0 sind(theta); 0 1 0 - sind(theta) 0 cosd(theta)]; end end
github
epilepsyecosystem/1stplace_notsorandomanymore-master
spatFilt.m
.m
1stplace_notsorandomanymore-master/Andriy/code/spatFilt.m
1,113
utf_8
9e5d17114745661029930c1558855096
%James Ethridge , Will Weaver %Spatial filtering function. Returns the filtered signal Y. % %Inputs: %x: the input matrix where M rows are the channels and N columns are the % time bins % %coef: the entire P' matrix of filter coefficients % %dimm: the number of dimensions the filter should attemp to reduce the % output vector space to function Y = spatFilt(x, coef, dimm) [m n] = size(coef); %check for valid dimensions if(m<dimm) disp('Cannot reduce to a higher dimensional space!'); return end %instantiate filter matrix Ptild = zeros(dimm,n); %create the n-dimensional filter by sorting i=0; for d = 1:dimm if(mod(d,2)==0) Ptild(d,:) = coef(m-i,:); i=i+1; else Ptild(d,:) = coef(1+i,:); end end %get length of input signal T = length(x); %instantiate output matrix Y=zeros(dimm,T); %filtering for d = 1:dimm for t = 1:T Y(d,t) = dot(Ptild(d,:),x(:,t)); end end return
github
epilepsyecosystem/1stplace_notsorandomanymore-master
sub_pos.m
.m
1stplace_notsorandomanymore-master/Andriy/code/sub_pos.m
496
utf_8
12fb7f8d85bca88f653bf530a3e02f07
% % Stephen Faul % 21st July 2004 % % SUB_POS: returns the starting positions of each subband of the % resultant vector from wt % % input: data_len -- the length of the original signal % num_coeffs -- the number of filter coefficients (2*order for Daubechie % % output: pos -- vector of the starting positions of each subband % function pos = sub_pos(data_len,num_coeffs) for i=1:num_coeffs pos(i)=data_len/(2^i)+1; end pos(i+1)=1;