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
Brain-Modulation-Lab/bml-master
permutationTest.m
.m
bml-master/stat/permutationTest.m
7,376
utf_8
835d2df86b9402893d58e70d59cca7b7
% [p, observeddifference, effectsize] = permutationTest(sample1, sample2, permutations [, varargin]) % % Permutation test (aka randomisation test), testing for a difference % in means between two samples. % % In: % sample1 - vector of measurements from one (experimental) sample % sample2 - vector of measurements from a second (control) sample % permutations - the number of permutations % % Optional (name-value pairs): % sidedness - whether to test one- or two-sided: % 'both' - test two-sided (default) % 'smaller' - test one-sided, alternative hypothesis is that % the mean of sample1 is smaller than the mean of % sample2 % 'larger' - test one-sided, alternative hypothesis is that % the mean of sample1 is larger than the mean of % sample2 % exact - whether or not to run an exact test, in which all possible % combinations are considered. this is only feasible for % relatively small sample sizes. the 'permutations' argument % will be ignored for an exact test. (1|0, default 0) % plotresult - whether or not to plot the distribution of randomised % differences, along with the observed difference (1|0, % default: 0) % showprogress - whether or not to show a progress bar. if 0, no bar % is displayed; if showprogress > 0, the bar updates % every showprogress-th iteration. % % Out: % p - the resulting p-value % observeddifference - the observed difference between the two % samples, i.e. mean(sample1) - mean(sample2) % effectsize - the effect size, Hedges' g % % Usage example: % >> permutationTest(rand(1,100), rand(1,100)-.25, 10000, ... % 'plotresult', 1, 'showprogress', 250) % % Copyright 2015-2018, 2021 Laurens R Krol % Team PhyPA, Biological Psychology and Neuroergonomics, % Berlin Institute of Technology % 2021-01-13 lrk % - Replaced effect size calculation with Hedges' g, from Hedges & Olkin % (1985), Statistical Methods for Meta-Analysis (p. 78, formula 3), % Orlando, FL, USA: Academic Press. % 2020-07-14 lrk % - Added version-dependent call to hist/histogram % 2019-02-01 lrk % - Added short description % - Increased the number of bins in the plot % 2018-03-15 lrk % - Suppressed initial MATLAB:nchoosek:LargeCoefficient warning % 2018-03-14 lrk % - Added exact test % 2018-01-31 lrk % - Replaced calls to mean() with nanmean() % 2017-06-15 lrk % - Updated waitbar message in first iteration % 2017-04-04 lrk % - Added progress bar % 2017-01-13 lrk % - Switched to inputParser to parse arguments % 2016-09-13 lrk % - Caught potential issue when column vectors were used % - Improved plot % 2016-02-17 toz % - Added plot functionality % 2015-11-26 First version % 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 3 of the License, or % (at your option) 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, see <http://www.gnu.org/licenses/>. function [p, observeddifference, effectsize] = permutationTest(sample1, sample2, permutations, varargin) % parsing input p = inputParser; addRequired(p, 'sample1', @isnumeric); addRequired(p, 'sample2', @isnumeric); addRequired(p, 'permutations', @isnumeric); addParamValue(p, 'sidedness', 'both', @(x) any(validatestring(x,{'both', 'smaller', 'larger'}))); addParamValue(p, 'exact' , 0, @isnumeric); addParamValue(p, 'plotresult', 0, @isnumeric); addParamValue(p, 'showprogress', 0, @isnumeric); parse(p, sample1, sample2, permutations, varargin{:}) sample1 = p.Results.sample1; sample2 = p.Results.sample2; permutations = p.Results.permutations; sidedness = p.Results.sidedness; exact = p.Results.exact; plotresult = p.Results.plotresult; showprogress = p.Results.showprogress; % enforcing row vectors if iscolumn(sample1), sample1 = sample1'; end if iscolumn(sample2), sample2 = sample2'; end allobservations = [sample1, sample2]; observeddifference = nanmean(sample1) - nanmean(sample2); pooledstd = sqrt( ( (numel(sample1)-1)*std(sample1)^2 + (numel(sample2)-1)*std(sample2)^2 ) / ( numel(allobservations)-2 ) ); effectsize = observeddifference / pooledstd; w = warning('off', 'MATLAB:nchoosek:LargeCoefficient'); if ~exact && permutations > nchoosek(numel(allobservations), numel(sample1)) warning(['the number of permutations (%d) is higher than the number of possible combinations (%d);\n' ... 'consider running an exact test using the ''exact'' argument'], ... permutations, nchoosek(numel(allobservations), numel(sample1))); end warning(w); if showprogress, w = waitbar(0, 'Preparing test...', 'Name', 'permutationTest'); end if exact % getting all possible combinations allcombinations = nchoosek(1:numel(allobservations), numel(sample1)); permutations = size(allcombinations, 1); end % running test randomdifferences = zeros(1, permutations); if showprogress, waitbar(0, w, sprintf('Permutation 1 of %d', permutations), 'Name', 'permutationTest'); end for n = 1:permutations if showprogress && mod(n,showprogress) == 0, waitbar(n/permutations, w, sprintf('Permutation %d of %d', n, permutations)); end % selecting either next combination, or random permutation if exact, permutation = [allcombinations(n,:), setdiff(1:numel(allobservations), allcombinations(n,:))]; else, permutation = randperm(length(allobservations)); end % dividing into two samples randomSample1 = allobservations(permutation(1:length(sample1))); randomSample2 = allobservations(permutation(length(sample1)+1:length(permutation))); % saving differences between the two samples randomdifferences(n) = nanmean(randomSample1) - nanmean(randomSample2); end if showprogress, delete(w); end % getting probability of finding observed difference from random permutations if strcmp(sidedness, 'both') p = (length(find(abs(randomdifferences) > abs(observeddifference)))+1) / (permutations+1); elseif strcmp(sidedness, 'smaller') p = (length(find(randomdifferences < observeddifference))+1) / (permutations+1); elseif strcmp(sidedness, 'larger') p = (length(find(randomdifferences > observeddifference))+1) / (permutations+1); end % plotting result if plotresult figure; if verLessThan('matlab', '8.4') % MATLAB R2014a and earlier hist(randomdifferences, 20); else % MATLAB R2014b and later histogram(randomdifferences, 20); end hold on; xlabel('Random differences'); ylabel('Count') od = plot(observeddifference, 0, '*r', 'DisplayName', sprintf('Observed difference.\nEffect size: %.2f,\np = %f', effectsize, p)); legend(od); end end
github
Brain-Modulation-Lab/bml-master
bml_annot_consolidate.m
.m
bml-master/annot/bml_annot_consolidate.m
5,342
utf_8
ad62572c50564017216b36c6c8bb9e89
function cons = bml_annot_consolidate(cfg, annot) % BML_ANNOT_CONSOLIDATE returns a consolidated annotation table % % Use as % cons = bml_annot_consolidate(cfg, annot); % cons = bml_annot_consolidate(annot); % % The first argument cfg is a configuration structure, which can contain % the following field: % cfg.criterion - function handle: consolidation criteria. This function should % accept a table of candidate annotations to consolidate and % return a true or false. % defaults to @(x) (x.starts(end) <= max(x.ends(1:(end-1)))) % that is, a row is consolidated with the previous if the % starts time of the row is smaller than the largest ends time % of the previous rows. % cfg.description - string: description of the output annot table % cfg.additive - cellstr with names of variables to be treated as additive % defaults to empty % cfg.groupby - cellstr indicating name of column of annot by which to group % the rows before consolidating. If missing no grouping is % done. % % Returns a annotation table with the folloing variables: % cons_duration - sum of the consolidated durations % id_starts - first original id of the consolidated row % id_ends - last original id of the consolidated row % cons_n - number of consolidated rows % cons_group - consolidation group id, only if groupby was specified % % EXAMPLES % ======== % % %detecting stretches of constant depth in neuroomega % cfg=[]; % cfg.criterion = @(x) (length(unique(x.depth))==1) && (abs((max(x.ends)-min(x.starts))-sum(x.duration))<10e-3); % neuro_cons_depth = bml_annot_consolidate(cfg,info_neuroomega); % % %grouping annotations in fours % cfg=[]; % cfg.criterion = @(x) height(x)<=4 % grouped_annot = bml_annot_consolidate(cfg,annot); if nargin == 1 annot = bml_annot_table(cfg,[],inputname(1)); cfg = []; elseif nargin == 2 annot = bml_annot_table(annot,[],inputname(2)); else error('incorrect number of arguments in call to bml_annot_consolidate'); end description = bml_getopt(cfg,'description', ['cons_' annot.Properties.Description]); criterion = bml_getopt(cfg,'criterion',[]); additive = bml_getopt(cfg,'additive',{}); groupby = bml_getopt(cfg,'groupby',[]); if isempty(annot) cons = annot; return end if isempty(criterion) fprintf('consolidating by default overlap/contiguity criterion\n') criterion = @(x) (x.starts(end) <= max(x.ends(1:(end-1)))); end if ~isa(criterion, 'function_handle') error('''criterion'' should be a function handle'); end %ToDo: allow grouping by several variables if isempty(groupby) annot.groupby_=ones(height(annot),1); groupby = {'groupby_'}; groups={1}; else if sum(strcmp(annot.Properties.VariableNames, groupby))~=1 error('groupby should match one (and only one) column of annot'); end groups = unique(annot{:,groupby}); end cons = table(); for g=1:numel(groups) if iscellstr(groups(g)) annot_g = annot(strcmp(annot{:,groupby},groups(g)),:); else annot_g = annot(annot{:,groupby}==groups{g},:); end i=1; j=1; tmp=collapse_table_rows(annot_g(1,:),additive); cons_g = cell2table(cell(0,width(tmp))); cons_g.Properties.VariableNames = tmp.Properties.VariableNames; if height(annot_g)<=1 cons_g = collapse_table_rows(annot_g,additive); cons_g.id=[]; cons_g = bml_annot_table(cons_g,description); cons = [cons; cons_g]; continue end while i<=height(annot_g) if j==1 curr_s=collapse_table_rows(annot_g(i,:),additive); end merge_s = annot_g(i:(i+j),:); if criterion(merge_s) curr_s = collapse_table_rows(merge_s,additive); j = j + 1; if i + j > height(annot_g) cons_g = [cons_g; curr_s]; i = height(annot_g)+1; end else cons_g = [cons_g;curr_s]; i = i + j; j = 1; if i == height(annot_g) %adding last register curr_s = collapse_table_rows(annot_g(i,:),additive); cons_g = [cons_g; curr_s]; i = height(annot_g)+1; end end end cons = [cons; cons_g]; end cons.id=[]; cons = bml_annot_table(cons,description); if any(strcmp('groupby_',cons.Properties.VariableNames)) cons.groupby_ = []; end function collapsed = collapse_table_rows(merge_s,additive) % % Private function. Collapses a table to a record collapsed = table(... min(merge_s.starts),... max(merge_s.ends),... sum(merge_s.duration),... min(merge_s.id),... max(merge_s.id),... length(merge_s.id),... 'VariableNames',{'starts','ends','cons_duration','id_starts','id_ends','cons_n'}); vars = setdiff(merge_s.Properties.VariableNames,[collapsed.Properties.VariableNames,additive]); row=[]; for i=1:length(vars) merge_s_var_i = merge_s.(vars{i}); if iscell(merge_s_var_i) && numel(merge_s_var_i)==1 && isempty(merge_s_var_i{1}) row.(vars{i}) = {[]}; else uval = unique(merge_s_var_i); if length(uval)==1 row.(vars{i}) = uval; elseif iscell(uval) row.(vars{i}) = {[]}; elseif isa(uval,'datetime') row.(vars{i}) = NaT; else row.(vars{i}) = nan; end end end %dealing with additive vars for i=1:length(additive) uval = sum(merge_s.(additive{i})); row.(vars{i}) = uval; end collapsed = [collapsed, struct2table(row)];
github
Brain-Modulation-Lab/bml-master
bml_coding2annot.m
.m
bml-master/annot/bml_coding2annot.m
28,895
utf_8
752f7b7b1cda1913994d1d7a52186e1f
function annot = bml_coding2annot(cfg) % BML_CODING2ANNOT creates annotation table from CodingMatrix % % Use as % annot = bml_codingmatrix2annot(cfg) % % cfg.CodingMatPath - path to mat file with coding info % cfg.EventsPerTrial - double, defaults depends on CodingAppVersion % cfg.roi - roi table with sessions audio sync information % cfg.audio_chanel - string indicating audio channel (optinal) % cfg.CodingAppVersion - char, defines format expected for CodingMatrix % accepted values are: % >'U01_v1': UO1 coding before July 2018 % >'U01_v2'(default): UO1 coding after July 2018. % Contains structured coding of errors % >'pilot': for coding of pilot data (DBS2000 series) % cfg.session_id - integer, session id number for warnings and % session_id column of output table % cfg.diary_filename - str, name of file to save all output, including % warnings. Defaults to empty % cfg.timetol_consolidate - double: consolidation time tolerance. Defaults to 1e-3s % this time tolerance relates to the sync consolidation process. % extrinsic time tolerance (between samples of different strams) % cfg.praat - bool: if true, audio files are opened in praat for visual % inspections % cfg.AudioCoord = time coordinates of audio file. If empty, calculated % from roi % % returns annot table with one row per trial (syllable triplet) % Todo: take sync table as input, read audio files, use them to sync the % Audio variable of the mat and, with that, get the times in master % coordinates. % if nargin ~= 1 error('Use as bml_coding2annot(cfg)'); end CodingMatPath = bml_getopt_single(cfg,'CodingMatPath'); assert(~isempty(CodingMatPath),'cfg.CodingMatPath required in single argument call'); load(CodingMatPath,'CodingMatrix'); load(CodingMatPath,'EventTimes'); load(CodingMatPath,'SkipEvents'); load(CodingMatPath,'WordList'); load(CodingMatPath,'Afs'); roi = bml_getopt(cfg,'roi'); CodingAppVersion = bml_getopt(cfg,'CodingAppVersion','U01_v2'); AudioCoord = bml_getopt(cfg,'AudioCoord'); praat = bml_getopt(cfg,'praat',false); audio_channel = bml_getopt(cfg,'audio_channel'); session_id = bml_getopt(cfg,'session_id',nan); diary_filename = bml_getopt_single(cfg,'diary_filename',[]); timetol_cons = bml_getopt(cfg,'timetol_consolidate',1e-3); if ~isempty(diary_filename) diary(diary_filename); end if ~isnan(session_id) fprintf('\n - Extracting coding from session %i - \n\n ',session_id) end if isempty(AudioCoord) || praat %loading sychronized audio to get the time-mapping %roi = bml_sync_consolidate(roi); cfg1=[]; cfg1.roi = roi; cfg1.match_labels = false; %allowing for audio files with different labels cfg1.timetol_consolidate = timetol_cons; sync_audio = bml_load_continuous(cfg1); if ~isempty(audio_channel) cfg1=[]; cfg1.channel = audio_channel; cfg1.trackcallinfo = false; cfg1.showcallinfo = 'no'; sync_audio = ft_selectdata(cfg1,sync_audio); end % unwarping to facilitate correlation with coding_audio loadedAudioCoord = bml_raw2coord(sync_audio); sync_audio_time = sync_audio.time; sync_audio.time{1} = (1:length(sync_audio.time{1}))./sync_audio.fsample; %loading coding audio cfg1=[]; cfg1.CodingMatPath = CodingMatPath; coding_audio = bml_coding2raw(cfg1); if isempty(AudioCoord) AudioCoord = loadedAudioCoord; fprintf('Calculating alignment between coding and roi audio\n'); cfg1=[]; cfg1.method='lpf'; assert(sync_audio.fsample == Afs, 'roi''s Fs=%f should be equivalent to Coding Audio Afs=%f',sync_audio.fsample,Afs); [coding_audio_dt, max_corr] = bml_timealign(cfg1, sync_audio, coding_audio); AudioCoord.s1 = AudioCoord.s1 - round(coding_audio_dt*Afs); AudioCoord.s2 = AudioCoord.s2 - round(coding_audio_dt*Afs); if max_corr < 0.95 fprintf('Warning: max_cor = %f should be near 1. Check in Praat if alignment is correct.\n', max_corr) end end if praat sync_audio.time = sync_audio_time; %setting sync time coding_audio.time{1} = bml_idx2time(AudioCoord, 1:length(coding_audio.time{1})); bml_praat(sync_audio, bml_conform_to(sync_audio,coding_audio)); end end annot=table(); if ismember(CodingAppVersion,{'U01_v2'}) % CodingApp version July 2018 ============= EventsPerTrial = bml_getopt(cfg,'EventsPerTrial',3); N_trials = size(CodingMatrix,2); if SkipEvents + N_trials * EventsPerTrial > length(EventTimes) fprintf('Warning: Less EventTimes than expected based on CodingMatrix.\n'); N_trials = floor((length(EventTimes) - SkipEvents)/EventsPerTrial); end for i=1:N_trials id=i; trial_id = id; data_integrity = true; %initial trial time in Audio seconds ti = EventTimes(SkipEvents + i * EventsPerTrial); tf_idx = SkipEvents + i * EventsPerTrial + 1; if tf_idx <= length(EventTimes) tf = EventTimes(tf_idx); else tf = ti + 5; end %CodingMatrix row 1: Phonetic code in latex phonetic_code=CodingMatrix(1,i); if isempty(phonetic_code)|| strcmp(phonetic_code,{' '}) || strcmp(phonetic_code,{''}) phonetic_code = {nan(1)}; end %CodingMatrix row 2: Syllable errors - deprecated % err_syl1=CodingMatrix{2,i}(1); % err_syl2=CodingMatrix{2,i}(2); % err_syl3=CodingMatrix{2,i}(3); %CodingMatrix row 3: Syl onset time onset_syl=bml_strnumcell2ordvec(CodingMatrix{3,i}); %in Audio seconds empty_syl = isempty(onset_syl); if length(onset_syl) ~= 3 %if ~empty_syl || ~ismissing(phonetic_code{1}) if ~empty_syl | ~ismissing(phonetic_code{1}) fprintf('Warning[01] number of syllable onsets is different from 3 in trial %i of session %i \n',trial_id,session_id) data_integrity = false; end onset_syl = default_nan3(onset_syl); end syl1_onset=bml_idx2time(AudioCoord,(onset_syl(1)+ti)*Afs); %in sfm syl2_onset=bml_idx2time(AudioCoord,(onset_syl(2)+ti)*Afs); %in sfm syl3_onset=bml_idx2time(AudioCoord,(onset_syl(3)+ti)*Afs); %in sfm if ~isnan(syl1_onset) && ~iscellstr(phonetic_code) fprintf('Warning[02] phonetic coding is missing but syllable onsets are present in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end %CodingMatrix row 4: Syl offset time offset_syl = default_nan(bml_strnumcell2ordvec(CodingMatrix{4,i})); %in Audio seconds offset_syl_complete = nan(1,length(onset_syl)); if ~empty_syl for j=1:length(onset_syl) if j<length(onset_syl) && ~isnan(onset_syl(j+1)) curr_syl_offset = offset_syl(offset_syl > onset_syl(j) & offset_syl <= onset_syl(j+1)); else %last syl curr_syl_offset = offset_syl(offset_syl > onset_syl(j)); end if length(curr_syl_offset)>1 fprintf('Warning[05] syllable %i has more than one offset in trial %i of session %i\n',j,trial_id,session_id) data_integrity = false; offset_syl_complete(j) = curr_syl_offset(1); elseif length(curr_syl_offset)==1 offset_syl_complete(j) = curr_syl_offset(1); else %no current syl offset if j < length(onset_syl) offset_syl_complete(j) = onset_syl(j+1); elseif ~isnan(onset_syl(j)) %last syl onset fprintf('Warning[04] last syllable has no offset in trial %i of session %i\n',trial_id,session_id) data_integrity = false; offset_syl_complete(j) = nan; end end end else %empty syl if ~all(ismissing(offset_syl)) fprintf('Warning[03] syllable offsets are present but no syllable onsets are given in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end offset_syl_complete = nan(1,length(onset_syl)); end syl1_offset=bml_idx2time(AudioCoord,(offset_syl_complete(1)+ti) * Afs);%in sfm syl2_offset=bml_idx2time(AudioCoord,(offset_syl_complete(2)+ti) * Afs);%in sfm syl3_offset=bml_idx2time(AudioCoord,(offset_syl_complete(3)+ti) * Afs);%in sfm %CodingMatrix row 5: Vowel onset time onset_vowel=bml_strnumcell2ordvec(CodingMatrix{5,i}); %in Audio seconds onset_vowel_complete = nan(1,length(onset_syl)); if ~empty_syl %checking for vowel onsets outside syllables if isectopic(onset_vowel,onset_syl,offset_syl_complete) fprintf('Warning[08] vowel onset(s) outside syllable in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end %assigning vowel onsets to syllables for j=1:length(onset_syl) curr_onset_vowel = onset_vowel(onset_vowel >= onset_syl(j) & onset_vowel < offset_syl_complete(j)); if length(curr_onset_vowel)>1 fprintf('Warning[06] syllable %i has more than one vowel onset in trial %i of session %i\n',j,trial_id,session_id) data_integrity = false; onset_vowel_complete(j) = curr_onset_vowel(1); elseif length(curr_onset_vowel)==1 onset_vowel_complete(j) = curr_onset_vowel(1); else %no current vowel onset, assuming syl onset for vowel onset_vowel_complete(j) = onset_syl(j); end end else %empty syl if ~all(ismissing(onset_vowel)) fprintf('Warning[07] vowel onset(s) are present but no syllable onsets are given in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end onset_vowel_complete = nan(1,length(onset_syl)); end syl1_vowel_onset=bml_idx2time(AudioCoord,(onset_vowel_complete(1)+ti) * Afs); syl2_vowel_onset=bml_idx2time(AudioCoord,(onset_vowel_complete(2)+ti) * Afs); syl3_vowel_onset=bml_idx2time(AudioCoord,(onset_vowel_complete(3)+ti) * Afs); %CodingMatrix row 6: Vowel offsets offset_vowel = bml_strnumcell2ordvec(CodingMatrix{6,i}); %in Audio seconds offset_vowel_complete = nan(1,length(onset_syl)); if ~empty_syl %checking for vowel offsets outside syllables if isectopic(offset_vowel,onset_syl,offset_syl_complete) fprintf('Warning[11] vowel offset(s) outside syllable in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end %assigning vowel offsets to syllables for j=1:length(onset_syl) curr_offset_vowel = offset_vowel(offset_vowel > onset_syl(j) & offset_vowel <= offset_syl_complete(j)); if length(curr_offset_vowel)>1 fprintf('Warning[09] syllable %i has more than one vowel offset in trial %i of session %i\n',j,trial_id,session_id) data_integrity = false; offset_vowel_complete(j) = curr_offset_vowel(1); elseif length(curr_offset_vowel)==1 offset_vowel_complete(j) = curr_offset_vowel(1); else %no current vowel onset, assuming syl onset for vowel offset_vowel_complete(j) = offset_syl_complete(j); end end else %empty syl if ~all(ismissing(offset_vowel)) fprintf('Warning[10] vowel offset(s) are present but no syllable onsets are given in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end offset_vowel_complete = nan(1,length(onset_syl)); end syl1_vowel_offset=bml_idx2time(AudioCoord,(offset_vowel_complete(1)+ti) * Afs);%in sfm syl2_vowel_offset=bml_idx2time(AudioCoord,(offset_vowel_complete(2)+ti) * Afs);%in sfm syl3_vowel_offset=bml_idx2time(AudioCoord,(offset_vowel_complete(3)+ti) * Afs);%in sfm %CodingMatrix row 7: Preword onset times nontask1_pre_onset = default_nan(bml_strnumcell2ordvec(CodingMatrix{7,i})); %in Audio seconds if length(nontask1_pre_onset) > 1 fprintf('Warning[12] more than one Pre onset time given in trial %i of session %i\n',trial_id,session_id) data_integrity = false; nontask1_pre_onset = nontask1_pre_onset(1); end if ~isnan(nontask1_pre_onset) && nontask1_pre_onset >= onset_syl(1) fprintf('Warning[13] Pre event onset after first syllable onset in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end nontask1_pre_onset = bml_idx2time(AudioCoord,(nontask1_pre_onset+ti) * Afs); %CodingMatrix row 8: Preword offset times nontask1_pre_offset = default_nan(bml_strnumcell2ordvec(CodingMatrix{8,i})); %in Audio seconds if ~isnan(nontask1_pre_offset) || length(nontask1_pre_offset) > 1 fprintf('Warning[14] Pre event offset(s) present when none expected in trial %i of session %i\n',trial_id,session_id) data_integrity = false; nontask1_pre_offset = nontask1_pre_offset(1); else %asigning Pre offse to first syl onset nontask1_pre_offset = onset_syl(1); end nontask1_pre_offset = bml_idx2time(AudioCoord,(nontask1_pre_offset+ti) * Afs); %CodingMatrix row 9: Post word onset times nontask2_post_onset = default_nan(bml_strnumcell2ordvec(CodingMatrix{9,i})); %in Audio seconds if ~isnan(nontask2_post_onset) || length(nontask2_post_onset) > 1 fprintf('Warning[15] Post event onset(s) present when none expected in trial %i of session %i\n',trial_id,session_id) data_integrity = false; nontask2_post_onset = nontask2_post_onset(1); else %asigning post onset to last syl offset nontask2_post_onset = offset_syl_complete(end); end nontask2_post_onset = bml_idx2time(AudioCoord,(nontask2_post_onset+ti) * Afs); %CodingMatrix row 10: Post word offset times nontask2_post_offset = default_nan(bml_strnumcell2ordvec(CodingMatrix{10,i})); %in Audio seconds if length(nontask2_post_offset) > 1 fprintf('Warning[16] more than one Post event offset time given in trial %i of session %i\n',trial_id,session_id) data_integrity = false; nontask2_post_offset = nontask2_post_offset(1); end if ~isnan(nontask2_post_offset) && nontask2_post_offset <= offset_syl_complete(end) fprintf('Warning[17] Post event offset before last syllable offset in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end nontask2_post_offset = bml_idx2time(AudioCoord,(nontask2_post_offset+ti) * Afs); %CodingMatrix row 11: Other onset times nontask345_other_onset = default_nan3(bml_strnumcell2ordvec(CodingMatrix{11,i})); if length(nontask345_other_onset) ~= 3 fprintf('Warning[18] more than 3 ''Other events'' onsets present in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end %CodingMatrix row 12: Other offset times nontask345_other_offset = default_nan3(bml_strnumcell2ordvec(CodingMatrix{12,i})); if length(nontask345_other_offset) ~= 3 fprintf('Warning[19] more than 3 ''Other events'' offsets present in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end if (~isnan(nontask345_other_offset(1)) && isnan(nontask345_other_onset(1))) || ... (~isnan(nontask345_other_offset(2)) && isnan(nontask345_other_onset(2))) || ... (~isnan(nontask345_other_offset(3)) && isnan(nontask345_other_onset(3))) fprintf('Warning[20] Other event offset has no corresponding onset in trial %i of session %i\n',trial_id,session_id) data_integrity = false; end for j=1:3 if ~isnan(nontask345_other_onset(j)) && ... isectopic(nontask345_other_onset(j),onset_syl,offset_syl_complete) && ... isnan(nontask345_other_offset(j)) fprintf('Warning[21] Other event onset %i outside syllables has no corresponding offset in trial %i of session %i\n',j,trial_id,session_id) data_integrity = false; end end %transforming to global time coords of other nontask events nontask345_other_onset = bml_idx2time(AudioCoord,(nontask345_other_onset+ti) * Afs); nontask3_other_onset = nontask345_other_onset(1); nontask4_other_onset = nontask345_other_onset(2); nontask5_other_onset = nontask345_other_onset(3); nontask345_other_offset = bml_idx2time(AudioCoord,(nontask345_other_offset+ti) * Afs); nontask3_other_offset = nontask345_other_offset(1); nontask4_other_offset = nontask345_other_offset(2); nontask5_other_offset = nontask345_other_offset(3); %CodingMatrix row 13: Note for current trial row13=CodingMatrix{13,i}; if ~iscell(row13) || ~(size(row13,1)==2 && size(row13,2)==1) fprintf('Warning[22] CodingMatrix format of non-task event description is invalid in trial %i of session %i\n',trial_id,session_id) data_integrity = false; comment = {'row13 invalid'}; nontask1_pre_type={nan}; nontask2_post_type={nan}; nontask3_other_type={nan}; nontask4_other_type={nan}; nontask5_other_type={nan}; else comment = default_str(row13(1,1)); %mapping non-task codes to strings nt_code = [1, 2, 3, 4, 5, 6]; nt_str = {'none', 'beeping-constant', 'OR-noise', 'provider-speech', 'patient-speech', 'patient-non-speech'}; if length(row13{2,1}) < 5 row13{2,1}=[row13{2,1} ones(1,5-length(row13{2,1}))]; end nontask1_pre_type=bml_map(row13{2,1}(1),nt_code,nt_str); nontask2_post_type=bml_map(row13{2,1}(2),nt_code,nt_str); nontask3_other_type=bml_map(row13{2,1}(3),nt_code,nt_str); nontask4_other_type=bml_map(row13{2,1}(4),nt_code,nt_str); nontask5_other_type=bml_map(row13{2,1}(5),nt_code,nt_str); end %CodingMatrix row 14: Stressors binary row14=CodingMatrix{14,i}; if ~isnumeric(row14) || iscell(row14) || ~(size(row14,1)==5 && size(row14,2)==3) fprintf('Warning[23] CodingMatrix format of speech-specific annotations are invalid in trial %i of session %i\n',trial_id,session_id) syl1_stress={nan}; syl2_stress={nan}; syl3_stress={nan}; syl1_consonant_accuracy={nan}; syl2_consonant_accuracy={nan}; syl3_consonant_accuracy={nan}; syl1_vowel_accuracy={nan}; syl2_vowel_accuracy={nan}; syl3_vowel_accuracy={nan}; syl1_consonant_disorder={nan}; syl2_consonant_disorder={nan}; syl3_consonant_disorder={nan}; syl1_vowel_disorder={nan}; syl2_vowel_disorder={nan}; syl3_vowel_disorder={nan}; else stressor_code = [0,1]; stressor_str = {'not-stressed', 'stressed'}; syl1_stress = bml_map(row14(1,1),stressor_code,stressor_str); syl2_stress = bml_map(row14(1,2),stressor_code,stressor_str); syl3_stress = bml_map(row14(1,3),stressor_code,stressor_str); accuracy_code = [0,1]; accuracy_str = {'accurate', 'inaccurate'}; syl1_consonant_accuracy = bml_map(row14(2,1),accuracy_code,accuracy_str); syl2_consonant_accuracy = bml_map(row14(2,2),accuracy_code,accuracy_str); syl3_consonant_accuracy = bml_map(row14(2,3),accuracy_code,accuracy_str); syl1_vowel_accuracy = bml_map(row14(3,1),accuracy_code,accuracy_str); syl2_vowel_accuracy = bml_map(row14(3,2),accuracy_code,accuracy_str); syl3_vowel_accuracy = bml_map(row14(3,3),accuracy_code,accuracy_str); disorder_code = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; disorder_str = {'none', 'missing', 'distorted', 'imprecise', 'spirantization', 'dysfluency', 'creaky', 'tremor', 'breathy', 'hoarse-harsh', 'voice-break','strain'}; syl1_consonant_disorder = bml_map(row14(4,1),disorder_code,disorder_str); syl2_consonant_disorder = bml_map(row14(4,2),disorder_code,disorder_str); syl3_consonant_disorder = bml_map(row14(4,3),disorder_code,disorder_str); syl1_vowel_disorder = bml_map(row14(5,1),disorder_code,disorder_str); syl2_vowel_disorder = bml_map(row14(5,2),disorder_code,disorder_str); syl3_vowel_disorder = bml_map(row14(5,3),disorder_code,disorder_str); end cue_triplet = WordList(i); starts = bml_idx2time(AudioCoord, ti * Afs); ends = bml_idx2time(AudioCoord, tf * Afs); annot = [annot; table(id, starts, ends, session_id, trial_id, ... cue_triplet, phonetic_code,... syl1_onset, syl1_offset, syl1_vowel_onset, syl1_vowel_offset, syl1_stress,... syl1_consonant_accuracy, syl1_consonant_disorder, syl1_vowel_accuracy, syl1_vowel_disorder, ... syl2_onset, syl2_offset, syl2_vowel_onset, syl2_vowel_offset, syl2_stress,... syl2_consonant_accuracy, syl2_consonant_disorder, syl2_vowel_accuracy, syl2_vowel_disorder, ... syl3_onset, syl3_offset, syl3_vowel_onset, syl3_vowel_offset, syl3_stress,... syl3_consonant_accuracy, syl3_consonant_disorder, syl3_vowel_accuracy, syl3_vowel_disorder, ... nontask1_pre_onset, nontask1_pre_offset, nontask1_pre_type, ... nontask2_post_onset, nontask2_post_offset, nontask2_post_type, ... nontask3_other_onset, nontask3_other_offset, nontask3_other_type, ... nontask4_other_onset, nontask4_other_offset, nontask4_other_type, ... nontask5_other_onset, nontask5_other_offset, nontask5_other_type, ... comment, data_integrity)]; end elseif ismember(CodingAppVersion,{'U01_v1'}) %================================== EventsPerTrial = bml_getopt(cfg,'EventsPerTrial',3); N_trials = size(CodingMatrix,2); if SkipEvents + N_trials * EventsPerTrial > length(EventTimes) warning("Less EventTimes than expected based on CodingMatrix."); N_trials = floor((length(EventTimes) - SkipEvents)/EventsPerTrial); end for i=1:N_trials id=i; %initial trial time in Audio seconds ti = EventTimes(SkipEvents + i * EventsPerTrial); %CodingMatrix row 1: Phonetic code in latex phoneticCode=CodingMatrix(1,i); %CodingMatrix row 2: Syllable errors err_syl1=CodingMatrix{2,i}(1); err_syl2=CodingMatrix{2,i}(2); err_syl3=CodingMatrix{2,i}(3); %CodingMatrix row 3: Syl onset time onset_syl=bml_strnumcell2ordvec(CodingMatrix{3,i}); %in Audio seconds if size(onset_syl,2) < 3 onset_syl = [onset_syl, nan(1,3-size(onset_syl,2))]; end onset_syl1=bml_idx2time(AudioCoord,(onset_syl(1)+ti)*Afs); %in sfm onset_syl2=bml_idx2time(AudioCoord,(onset_syl(2)+ti)*Afs); %in sfm onset_syl3=bml_idx2time(AudioCoord,(onset_syl(3)+ti)*Afs); %in sfm %CodingMatrix row 4: Syl offset time offset_syl = bml_strnumcell2ordvec(CodingMatrix{4,i}); %in Audio seconds if isempty(offset_syl) offset_syl = nan; end %completing missing offsets if length(offset_syl)==length(onset_syl) offset_syl_complete = offset_syl; offset_syl_coded = ones(1,length(offset_syl_complete)); else offset_syl_complete = zeros(1,length(onset_syl)); offset_syl_coded = zeros(1,length(onset_syl)); onset_syl_inf = [onset_syl inf]; j=1; %offset_syl counter for k=1:(length(onset_syl)) if j <= length(offset_syl) if offset_syl(j) <= onset_syl_inf(k+1) offset_syl_complete(k) = offset_syl(j); offset_syl_coded(k) = 1; j = j + 1; else offset_syl_complete(k) = onset_syl_inf(k+1); offset_syl_coded(k) = 0; end else offset_syl_complete(k) = NaN; offset_syl_coded(k) = 0; warning('Inconsistent syl offset times in trial %i',i) end end end offset_syl1=bml_idx2time(AudioCoord,(offset_syl_complete(1)+ti) * Afs);%in sfm offset_syl2=bml_idx2time(AudioCoord,(offset_syl_complete(2)+ti) * Afs);%in sfm offset_syl3=bml_idx2time(AudioCoord,(offset_syl_complete(3)+ti) * Afs);%in sfm offset_coded_syl1=offset_syl_coded(1); offset_coded_syl2=offset_syl_coded(2); offset_coded_syl3=offset_syl_coded(3); %CodingMatrix row 5: Vowel onset time onset_vowel=bml_strnumcell2ordvec(CodingMatrix{5,i}); %in Audio seconds if size(onset_vowel,2) < 3 onset_vowel = [onset_vowel, nan(1,3-size(onset_vowel,2))]; end onset_vowel1=bml_idx2time(AudioCoord,(onset_vowel(1)+ti) * Afs); onset_vowel2=bml_idx2time(AudioCoord,(onset_vowel(2)+ti) * Afs); onset_vowel3=bml_idx2time(AudioCoord,(onset_vowel(3)+ti) * Afs); %CodingMatrix row 6: Vowel offsets, not coded %CodingMatrix row 7: Preword onset times %CodingMatrix row 8: Preword offset times %CodingMatrix row 9: Post word onset times %CodingMatrix row 10: Post word offset times %CodingMatrix row 11: Other onset times %CodingMatrix row 12: Other offset times %CodingMatrix row 13: Note for current trial comment=CodingMatrix(13,i); %CodingMatrix row 14: Stressors binary word_triplet = WordList(i); starts = bml_idx2time(AudioCoord,(min(onset_syl)+ti) * Afs); ends = bml_idx2time(AudioCoord,(max(offset_syl)+ti) * Afs); annot = [annot; table(id, starts, ends, phoneticCode, err_syl1, err_syl2, err_syl3,... onset_syl1, offset_syl1, onset_syl2, offset_syl2, onset_syl3, offset_syl3,... onset_vowel1, onset_vowel2, onset_vowel3,... offset_coded_syl1, offset_coded_syl2, offset_coded_syl3, word_triplet, comment)]; end elseif ismember(CodingAppVersion,{'pilot'}) %================================== EventsPerTrial = bml_getopt(cfg,'EventsPerTrial',4); N_trials = size(CodingMatrix,2); if SkipEvents + N_trials * EventsPerTrial > length(EventTimes) warning("Less EventTimes than expected based on CodingMatrix."); N_trials = floor((length(EventTimes) - SkipEvents)/EventsPerTrial); end for i=1:N_trials id=i; ti = EventTimes(SkipEvents + i * EventsPerTrial); %CodingMatrix row 1. phonetic code in LaTex separated by '/'. phoneticCode = default_str(CodingMatrix(1,i)); %CodingMatrix row 2. 1st Consonant errors err_cons1 = CodingMatrix(2,i); %CodingMatrix row 3. Vowel errors err_vowel = CodingMatrix(3,i); %CodingMatrix row 4. 2nd Consonant error err_cons2 = CodingMatrix(4,i); %CodingMatrix row 5. Word onset time onset_word=bml_idx2time(AudioCoord,(default_nan(CodingMatrix{5,i}) + ti) * Afs); %CodingMatrix row 6. Word offset time offset_word=bml_idx2time(AudioCoord,(default_nan(CodingMatrix{6,i}) + ti) * Afs); %CodingMatrix row 7. 1 if actual task presentation was revealed unveil=default_int(CodingMatrix{7,i}); %CodingMatrix row 8. Notes for current trial comment=CodingMatrix(8,i); %CodingMatrix row 9. Onset of vowel onset_vowel=bml_idx2time(AudioCoord,(default_nan(CodingMatrix{9,i}) + ti) * Afs); %CodingMatrix row 10. Offset of vowel offset_vowel=bml_idx2time(AudioCoord,(default_nan(CodingMatrix{10,i}) + ti) * Afs); word = WordList(i); starts = onset_word; ends = offset_word; annot = [annot; table(id, starts, ends, phoneticCode,... err_cons1, err_vowel, err_cons2, onset_word, offset_word, ... unveil, comment, onset_vowel, offset_vowel, word)]; end else error('unknown CodingAppVersion') end annot = bml_annot_table(annot); annot.trial_id = annot.id; if ~isempty(diary_filename) diary off; end end %%%%%%%%%%%%%%%%%%%%%%%%% %%% Private functions %%% %%%%%%%%%%%%%%%%%%%%%%%%% function default = default_str(input) if isempty(input) default = {''}; else default = input; end end function default = default_int(input) if isempty(input) default = 0; else default = input; end end function default = default_nan(input) if isempty(input) default = nan; else default = input; end end function default = default_nan3(input) %defualt_nan3 ensures array has at least three columns, filling up with %nans where required %Function definition using padarray of Image Processing Toolbox %default = padarray(input,[isempty(input),max([0,3-size(input,2)])],nan,'post'); if isempty(input) default = nan(1,3); else padcoln = max([0,3-size(input,2)]); default = [input nan(size(input,1),padcoln)]; end end function ise = isectopic(t,syl_onset,syl_offset) for j=1:length(t) if ~isnan(t(j)) ise = true; for k=1:length(syl_onset) if ~isnan(syl_onset(k)) && ~isnan(syl_offset(k)) && t(j) >= syl_onset(k) && t(j) <= syl_offset(k) ise = false; end end if ise return end end end ise = false; end
github
paultimothymooney/Data-Projects-master
fret_correct.m
.m
Data-Projects-master/Random/MATLAB/Useful scripts from Hoffman Lab/fret_correct.m
8,355
utf_8
b531c86da0d93dc0ee87aad35423d58e
function fret_correct(aexp,dexp,fexp,abtfn,dbtfn,varargin) % outputs = fret_correct(af,df,fr,abtfn,dbtfn,params) % outputs = fret_correct(af,df,fr,abtfn,dbtfn,baf,bdf,bfr,params) % PURPOSE: A program to remove the intensity in a set of FRET images due to % bleed-throughs or cross-talks. Can do linear or non-linear bleedthroughs % and cross-talks. Linear bleed-throughs assume that these percentages are % constant as a function of brightness. Non-linear bleed-throughs do not. % If all four corrections are used, the corrections scheme becomes a % non-linear set of coupled equations. In this case, Newton's method is % used to solve the set of equations. This is not fully validated and % probably should have some sort of regularization to help enure that the % solution is a global minimum and not a local one % Non-linear corrections are done by linearly interpolating the correction % curves. % Background subtraction is handled one of two ways. If background levels % are included, then these images are averaged and subtracted from the % single and double labeled images. These are called bsff images. If % background images are not included, then the background (most likely % pixel in the picture) is subtracted from the image. This will not account % for variations in illumination. These images are named bs. %-------------------------------------------------------------------------- % Created 9/5/12 by Katheryn Rothenberg % Updated 9/14/12 by Wes Maloney - Translated original body of all_cor, % all_cor_func, deunder, norm_fret, align_images subfunctions % Updated 9/25/12 by Katheryn Rothenberg - Translated original body of main % function. Debugged and running except for final .tif writing. % Updated 11/27/12 by Katheryn Rothenberg - Edited the method of saving % .tif images from imwrite to using the Tiff class and fixed the % check for linear or nonlinear correction % Updated 11/29/12 by Katheryn Rothenberg - Removed the spline_intrp % subfunction and replaced with a call to the cubic spline function. % This resulted in final images with very little variation from the % test images while using the test bleed through files. Also, added % the sourcefolder and dest folder fields to the params structure. % Updated 06/17/14 by Katheryn Rothenberg - cut out all non-linear % calculations and considerations of cross-talk and dealing with % background images. %-------------------------------------------------------------------------- % INPUTS: % inputs that are required to run the function are as follows: % af - base name for the acceptor channel images of a double labeled sample % df - base name for the donor channel images of a double labeled sample % fr - base name to find the FRET channel images of a double labeled sample % abtfn - specifies acceptor bleed-through into the FRET channel, either % number or file % dbtfn - specifies donor bleed-through into the FRET channel, either % number or file % params will be a structure containing a field for each of the following % parameters: % sourcefolder - specifies the folder containing all the images being % analyzed % destfolder - specifies the destination folder for the output files and % images % ocimg - if set, the program will write out the images % bit - specifies the bit of the image % imin - the minimum intensity to allow into the output images, if either % acceptor or donor image is below this intensity, it will be zeroed in % output images % outname - manually specifies output name % double_norm - normalize to the intensity of the corrected acceptor and % donor images % donor_norm - normalize to the intensity of the corrected donor images %-------------------------------------------------------------------------- % OUTPUTS: % If ocimg is set, program writes out background subtracted version of the % data images as well as a corrected FRET, and a normalized FRET image. % Corrected FRET images are labeled c. and the normalized images are % normalized to the acceptor and entitled cna. %-------------------------------------------------------------------------- param = varargin{end}; if ~isfield(param,'bit') param.bit = 16; end param.bin = 1.0; af = file_search(aexp,param.sourcefolder); df = file_search(dexp,param.sourcefolder); fr = file_search(fexp,param.sourcefolder); % Check images found if isempty(af) warning(['No Acceptor Images found, searched using: ',aexp]) end if isempty(df) warning(['No Donor Images, searched using: ',dexp]) end if isempty(fr) warning(['No FRET Images, searched using: ', fexp]) end % Check number of images if length(af)~=length(df) warning('Number of Donor and Acceptor Images Not the Same') end if length(af)~=length(fr) warning('Number of FRET and Acceptor Images Not the Same') end if length(df)~=length(fr) warning('Number of Donor and FRET Images Not the Same') end abt = double(abtfn{1}); dbt = double(dbtfn{1}); for i = 1:length(df) % Get fluorescent images axam = double(imread(fullfile(param.sourcefolder,af{i}))); dxdm = double(imread(fullfile(param.sourcefolder,df{i}))); dxam = double(imread(fullfile(param.sourcefolder,fr{i}))); [axam, dxdm, dxam] = deover(axam,dxdm,dxam,param.bit); if isfield(param,'imin') [axam, dxdm, dxam] = deunder(axam,dxdm,dxam,param.imin); end % Following supplemental material of Chen, Puhl et al BJ Lett 2006 iaa = axam; idd = dxdm; fc = dxam-abt.*iaa-dbt.*idd; if ~isfield(param,'leave_neg') iaa(iaa<0) = 0; idd(idd<0) = 0; fc(fc<0) = 0; end nafc = norm_fret(fc,iaa); if isfield(param,'outname') nfrn = ['_' param.outname fr{i}]; ndfn = ['_' param.outname df{i}]; nafn = ['_' param.outname af{i}]; else nfrn = ['_' fr{i}]; ndfn = ['_' df{i}]; nafn = ['_' af{i}]; end target_folder = fileparts([pwd '/' param.destfolder '/c' nfrn]); if (not(exist(target_folder,'dir'))) mkdir(target_folder); end imwrite2tif(fc,[],fullfile(pwd,param.destfolder,['c' nfrn]),'single') target_folder = fileparts([pwd '/' param.destfolder '/cna' nfrn]); if (not(exist(target_folder,'dir'))) mkdir(target_folder); end imwrite2tif(nafc,[],fullfile(pwd,param.destfolder,['cna' nfrn]),'single') if param.donor_norm ndfc = norm_fret(fc,idd); imwrite2tif(ndfc,fullfile(pwd,param.destfolder,['cnd' nfrn]),'single') end if param.double_norm nandfc = norm_fret(fc,iaa,idd); imwrite2tif(nandfc,fullfile(pwd,param.destfolder,['cnand' nfrn]),'single') end if param.ocimg target_folder = fileparts([pwd '/' param.destfolder '/bsd' ndfn]); if (not(exist(target_folder,'dir'))) mkdir(target_folder); end imwrite2tif(idd,[],fullfile(pwd,param.destfolder,['bsd' ndfn]),'single') target_folder = fileparts([pwd '/' param.destfolder '/bsa' nafn]); if (not(exist(target_folder,'dir'))) mkdir(target_folder); end imwrite2tif(iaa,[],fullfile(pwd,param.destfolder,['bsa' nafn]),'single') end end end %-------------------------------------------------------------------------- % SUBFUNCTIONS: function ftemp = norm_fret(f,n,varargin) n_params = nargin; if n_params== 2 ftemp=f; ntemp=n; wnz=find(n ~= 0); wz =find(n == 0); if ~isempty(wnz) ftemp(wnz)=ftemp(wnz)./ntemp(wnz); end if ~isempty(wz) ftemp(wz)=0; end elseif n_params == 3 ftemp=f; ntemp=n; ntemp2=n2; wnz=find(n ~= 0 & n2 ~= 0); ftemp(wnz)=ftemp(wnz)./(ntemp(wnz).*ntemp2(wnz)); ftemp(n == 0)=0; ftemp(n2 == 0)=0; end end function [a,b,c] = deunder(a,b,c,thres) % Identify pixels less than a certain value. If any of the pixels in a % single image is less than the threshold, the pixel will be set to zero in % all images w=find(a < thres(1) | b < thres(2) | c < thres(3)); if ~isempty(w) a(w)=0; b(w)=0; c(w)=0; end end
github
paultimothymooney/Data-Projects-master
fret_bledth.m
.m
Data-Projects-master/Random/MATLAB/Useful scripts from Hoffman Lab/fret_bledth.m
15,227
utf_8
3d1b0ad59971ac2997ba11373997cc29
function [abt,dbt] = fret_bledth(doa,dod,dof,varargin) % files = fret_bledth(doaf,dodf,dofr,param) % files = fret_bledth(doaf,dodf,dofr,baf,bdf,brd,param) % files = fret_bledth(doaf,dodf,dofr,baf,bdf,brd,aoaf,aodf,aofr,param) % PURPOSE: Calculate the bleed-throughs and cross-talk associated with FRET % imaging. Can do linear or non-linear bleedthroughs and cross-talks. % Bleed-throughs are defined as either fluorophore bleeding into the FRET % channel and cross-talk is defined as one fluorophore crossing over into % another's channel. Linear bleed-throughs assume that these percentages % are constant as a function of brightness. Non-linear bleed-throughs do % not. In this program, images of single labeled samples and backgrounds % are read in and the percentages that the fluorophore emit in each channel % are calculated. Files representing the non-linear bleed-throughs are % written out and linear estimates are printed to the screen. % Background subtraction is handled one of two ways. If background images % are included then these images are averaged and subtracted from the % single and double labeled images. %-------------------------------------------------------------------------- % Created 9/5/12 by Katheryn Rothenberg % Updated 9/12/12 by Wes Maloney - Translated original body of lister % subfunction % Updated 9/14/12 by Wes Maloney - Translated original body of smooth_table % and fit_samp subfunctions % Updated 9/14/12 by Katheryn Rothenberg - Translated original body of main % function with adjustments to file loading % Updated 9/20/12 by Katheryn Rothenberg - Debugged and functioning % Updated 11/6/12 by Katheryn Rothenberg - Fixed a bug in the fit_samp % function with calculation of the mean while binning the data % Updated 11/9/12 by Katheryn Rothenberg - Adjusted image reading, output % plot matches sample data plot, any further changes will be a new % version %-------------------------------------------------------------------------- % INPUTS: Filenames must be passed in either a group of 3, 6, or 9. The % last input will be a structure with parameters. % If you input three filenames, the program will calculate the bleedthrough % assuming it is a set of donor only images. If it is really a set of % acceptor images, switch the position of the donor and acceptor channel. % doaf - base name for donor only acceptor channel image files % dodf - base name for donor only donor channel image files % dofr - base name for donor only FRET channel image files % If you input six filenames, the program assumes you have given it a three % channel set of donor only and background images and will calculate the % bleedthrough of the donor images with background flat-fielding. Use the % no background keyword if images are actually a set of three channel % images for the donor and acceptor % baf - base name for background images from the acceptor channel % bdf - base name for background images from the donor channel % brd - base name for background images from the FRET channel % If you input nine filenames (RECOMMENDED), the program will calculate % cross-talks and bleedthroughs for all channels and perform flat-fielding % calculations. % aoaf - base name for acceptor only acceptor channel image files % aodf - base name for acceptor only donor channel image files % aofr - base name for acceptor only FRET channel image files % params will be a structure containing a field for each of the following % parameters: % sourcefolder - specifies the folder containing all the images being % analyzed % destfolder - specifies the destination folder for the output files and % images % nobkg - to get naming right if you don't have background images % bit - specifies bit of the image % dthres - threshold in the donor only donor channel image (only pixels % above this intensity are used in the calculation % athres - threshold in the acceptor only acceptor channel image % outname - to specify the name of the non-linear correction files % width - set the number of points over which the non-linear correction % curves should be smoothed. Large values cause errors at intensity extrema % ocimg - set to output the images % npnts - sets the number of points in the smoothed curve % avg - will average results over block size given, useful if some % brightness regions are not sufficiently covered % pf - set to write out files with only prefix names %-------------------------------------------------------------------------- % initialize/get variables param = varargin{end}; if ~isfield(param,'athres') param.athres = 1; end if ~isfield(param,'dthres') param.dthres = 1; end if ~isfield(param,'bit') param.bit = 12; end if ~isfield(param,'width') param.width = 1500; end if ~isfield(param,'npnts') param.npnts = 1000; end if ~isfield(param,'avg') param.avg = 1; end param.npnts = double(param.npnts); daflag = 0; nps = nargin-1; param.bin = 1; doaf = file_search(doa,param.sourcefolder); dodf = file_search(dod,param.sourcefolder); dofr = file_search(dof,param.sourcefolder); if param.nobkgd && nps > 3 aoaf = file_search(varargin{1},param.sourcefolder); aodf = file_search(varargin{2},param.sourcefolder); aofr = file_search(varargin{3},param.sourcefolder); end % load files filecell = {'doafn','dodfn','dofrn','bafn','bdfn','bfrn','aoafn','aodfn','aofrn'}; filenames = {doaf,dodf,dofr}; ndoa = length(doaf); ndod = length(dodf); ndof = length(dofr); if param.nobkgd && nps > 3 filenames{4} = aoaf; filenames{5} = aodf; filenames{6} = aofr; naoa = length(aoaf); end for i = 1:3 for j = 1:ndoa eval(sprintf('%s{j} = double(imread(fullfile(''%s'',''%s'')));',... filecell{i},param.sourcefolder,filenames{i}{j})); end end % do background averages if ~param.nobkgd && nps >= 6 for i = 1:3 % read in 4-6 as background for j = 1:length(varargin{1}) eval(sprintf('%s{j} = double(imread(''%s''));',filecell{i+3},filenames{i+3}{j})); end end tot = 0; tot2 = 0; tot3 = 0; nba = length(varargin{1}); nbd = length(varargin{2}); nbf = length(varargin{3}); for i=1:nba tot = tot+bafn{i}; tot2 = tot2+bdfn{i}; tot3 = tot3+bfrn{i}; end axamb = tot/nba; dxdmb = tot2/nbd; dxamb = tot3/nbf; elseif nps >= 6 && param.nobkgd for i = 1:3 % read in 4-6 as ao for j = 1:length(aoaf) eval(sprintf('%s{j} = double(imread(fullfile(''%s'',''%s'')));',... filecell{i+6},param.sourcefolder,filenames{i+3}{j})) end end daflag = 1; end if nps == 9 for i = 1:3 % read in 7-9 as ao for j = 1:length(varargin{4}) eval(sprintf('%s{j} = double(imread(''%s''));',filecell{i+6},filenames{i+6}{j})) end end daflag = 1; end doaxam = cell(1,ndoa); dodxam = cell(1,ndoa); dodxdm = cell(1,ndoa); for i=1:ndoa [doaxam{i}, dodxdm{i}, dodxam{i}] = deover(doafn{i},dodfn{i},dofrn{i},param.bit); if nps >= 6 && ~param.nobkgd dodxdm{i} = bs_ff(dodxdm{i},dxdmb,param); dodxam{i} = bs_ff(dodxam{i},dxamb,param); doaxam{i} = bs_ff(doaxam{i},axamb,param); else dodxdm{i} = bs_ff(dodxdm{i},param); dodxam{i} = bs_ff(dodxam{i},param); doaxam{i} = bs_ff(doaxam{i},param); end % get the mask wdo = find(dodxdm{i} > param.dthres); if i ==1 ddd = lister(dodxdm{i},wdo,i); dda = lister(dodxam{i},wdo,i); daa = lister(doaxam{i},wdo,i); else ddd = lister(dodxdm{i},wdo,i,ddd); dda = lister(dodxam{i},wdo,i,dda); daa = lister(doaxam{i},wdo,i,daa); end % Structure for tiff writing % write files if requested if param.ocimg if param.nobkgd imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bs' dodfn{i}]),'single') imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bs' doafn{i}]),'single') imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bs' dofrn{i}]),'single') else imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bsff' dodfn{i}]),'single') imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bsff' doafn{i}]),'single') imwrite2tif(dodxdm,[],fullfile(pwd,param.destfolder,['bsff' dofrn{i}]),'single') end end end aoaxam = cell(1,naoa); aodxam = cell(1,naoa); aodxdm = cell(1,naoa); if daflag for i = 1:length(aoaxam) % do flatfielding and background subtraction [aoaxam{i},aodxdm{i},aodxam{i}] = deover(aoafn{i},aodfn{i},aofrn{i},param.bit); if nps == 9 && ~param.nobkgd aodxdm{i} = bs_ff(aodxdm{i},dxdmb,param); aodxam{i} = bs_ff(aodxam{i},dxamb,param); aoaxam{i} = bs_ff(aoaxam{i},axamb,param); else aodxdm{i} = bs_ff(aodxdm{i},param); aodxam{i} = bs_ff(aodxam{i},param); aoaxam{i} = bs_ff(aoaxam{i},param); end % get the mast wao = find(aoaxam{i} > param.athres); if i ==1 aaa = lister(aoaxam{i},wao,i); ada = lister(aodxam{i},wao,i); add = lister(aodxdm{i},wao,i); else aaa = lister(aoaxam{i},wao,i,aaa); ada = lister(aodxam{i},wao,i,ada); add = lister(aodxdm{i},wao,i,add); end if param.ocimg if param.nobkgd imwrite2tif(aodxdm,[],fullfile(pwd,param.destfolder,['bs' aodfn{i}]),'single') imwrite2tif(aoaxdm,[],fullfile(pwd,param.destfolder,['bs' aoafn{i}]),'single') imwrite2tif(aodxam,[],fullfile(pwd,param.destfolder,['bs' aofrn{i}]),'single') else imwrite2tif(aodxdm,[],fullfile(pwd,param.destfolder,['bsff' aodfn{i}]),'single') imwrite2tif(aoaxdm,[],fullfile(pwd,param.destfolder,['bsff' aodfn{i}]),'single') imwrite2tif(aodxam,[],fullfile(pwd,param.destfolder,['bsff' aodfn{i}]),'single') end end end else ada = [0 0]; aaa = [0 0]; add = [0 0]; end [ldbt,mddd,mdda] = fit_samp(ddd,dda,param.avg); [labt,maaa,mada] = fit_samp(aaa,ada,param.avg); [ldct,mddd,mdaa] = fit_samp(ddd,daa,param.avg); [lact,maaa,madd] = fit_samp(aaa,add,param.avg); xmax = max([mddd , maaa]); plot(mddd,mdda./mddd,'o') % donor bleed-through axis([0 xmax 0 1.2]) hold on plot(maaa,mada./maaa,'s') % acceptor bleed-through plot(mddd,mdaa./mddd,'m^') % donor cross-talk plot(maaa,madd./maaa,'mx') % acceptor cross-talk plot([0 2^param.bit],[ldbt(1) ldbt(1)],'r') plot([0 2^param.bit],[labt(1) labt(1)],'r') plot([0 2^param.bit],[ldct(1) ldct(1)],'r') plot([0 2^param.bit],[lact(1) lact(1)],'r') if max(mddd) > 0 && max(mdda) > 0 nldbt = smooth_table(mddd,mdda,param.width,param.npnts); else nldbt = zeros(5,2); end if max(maaa) > 0 && max(mada) > 0 nlabt = smooth_table(maaa,mada,param.width,param.npnts); else nlabt = zeros(5,2); end if max(mddd) > 0 && max(mdaa) > 0 nldct = smooth_table(mddd,mdaa,param.width,param.npnts); else nldct = zeros(5,2); end if max(maaa) > 0 && max(madd) > 0 nlact = smooth_table(maaa,madd,param.width,param.npnts); else nlact = zeros(5,2); end plot(nldbt(:,1),nldbt(:,2),'g',nlabt(:,1),nlabt(:,2),'g',nldct(:,1),nldct(:,2),'g',... nlact(:,1),nlact(:,2),'g') if nps <= 6 && ~daflag fprintf('The bleed-through in the FRET channel is: %.2f\n',ldbt(1)) fprintf('The cross-talk into the non-FRET channel is: %.2f\n', ldct(1)) end if daflag fprintf('The donor bleed-through into the FRET channel is: %.2f\n',ldbt(1)) dbt = ldbt(1); fprintf('The acceptor bleed-through into the FRET channel is: %.2f\n',labt(1)) abt = labt(1); fprintf('The donor crosstalk into acceptor channel is: %.2f\n',ldct(1)) fprintf('The acceptor crosstalk into donor channel is: %.2f\n',lact(1)) end if ~isfield(param,'pf') save(fullfile(param.destfolder,'nlabt.dat'),'nlabt','-ascii') save(fullfile(param.destfolder,'nldbt.dat'),'nldbt','-ascii') save(fullfile(param.destfolder,'nlact.dat'),'nlact','-ascii') save(fullfile(param.destfolder,'nldct.dat'),'nldct','-ascii') else if ~isfield(param,'outname') param.outname = ' '; nele = length(param.pf); if nele >= 1 save(fullfile(pwd,param.destfodler,[param.pf(1) '_' param.outname]),'nldbt','-ascii') end if nele >= 2 save(fullfile(pwd,param.destfodler,[param.pf(2) '_' param.outname]),'nldct','-ascii') end if nele >= 3 save(fullfile(pwd,param.destfodler,[param.pf(3) '_' param.outname]),'nlabt','-ascii') end if nele >= 4 save(fullfile(pwd,param.destfodler,[param.pf(4) '_' param.outname]),'nlact','-ascii') end end end end %-------------------------------------------------------------------------- % SUBFUNCTIONS function list = lister(img,w,i,list) % change the data structure from images type (1024x1024) to list type % (npixels), also removes zeroes. This means w must be the same in all % calls if min(w) > -1 if i > 1 list=[list;img(w)]; else list=img(w); end else if i == 1 list=[0,0]; end end end function [res,xm,ym] = fit_samp(x,y,avg) % program to optionally bit, fit, and smooth data if sum(x+y) > 0 %This is just a quick way to bin by size avg x2=round(x./avg); [un,s] = unique(x2); % xm = x2(s).*avg; % ym = y(s); s = []; for i = 1:numel(un) s = [s; find(un(i) == x2)]; end x2 = x2(s)*avg; y2 = y(s); [trash,u]=unique(x2); nele=length(u); xm=zeros(1,nele); ym=zeros(1,nele); for i=1:nele if i == 1 n=u(1); if n >= 3 xm(i)=mean(x2(1:u(1))); ym(i)=mean(y2(1:u(1))); end if n == 1 xm(1)=x2(1); ym(1)=y2(1); end if n == 2 xm(i)=sum(x2(1:2))/double(2); ym(i)=sum(y2(1:2))/double(2); end else n=u(i)-(u(i-1)+1); xm(i)=mean(x2(u(i-1)+1:u(i))); ym(i)=mean(y2(u(i-1)+1:u(i))); end end res=polyfit(xm,ym,1); else res=[0,0]; xm=res; ym=res; end end function res = smooth_table(tx,ty,width,npnts) % program to smooth data [x,i]=sort(tx); y=ty(i); w=find(x ~= 0 & y ~= 0); x=x(w); y=y(w); f=y./x; [spx,spf] = spline_p_k(x,f); sf = smooth(spf,width); nele=length(sf); del=(nele/npnts); if del >= 1 vec=floor((1:npnts)*del); res = [spx(vec) ;sf(vec)']'; else end end
github
26hzhang/OptimizedImageEnhance-master
Sift.m
.m
OptimizedImageEnhance-master/matlab/Sift.m
25,130
utf_8
8801fad8ac6769b01edbd9b10d2cea9c
function [frames,descriptors,gss,dogss]=Sift(I,varargin) % SIFT Extract SIFT features % [FRAMES,DESCR]=SIFT(I) extracts the SIFT frames FRAMES and their % descriptors DESCR from the image I. % % The image I must be gray-scale, of storage class DOUBLE and % ranging in [0,1]. % % FRAMES is a 4xK matrix storing one SIFT frame per column. Its % format is: % FRAMES(1:2,k) center (X,Y) of the frame k, % FRAMES(3,k) scale SIGMA of the frame k, % FRAMES(4,k) orientation THETA of the frame k. % Note that the X,Y center coordinates are (0,0) based, contrary to % the standard MATLAB convention that uses (1,1) as the top-left % image coordiante. The plotting function PLOTSIFTFRAME() and % PLOTSIFTDESCRIPTOR() automatically shift the keypoints to the % default (1,1) reference. % % DESCR is a DxK matrix stores one descriptor per columm (usually % D=128). % % [FRAMES,DESCR,GSS,DOGSS]=SIFT(...) returns the Gaussian and % Difference of Gaussians scale spaces computed by the algorithm. % % The function accepts the following option-value pairs: % % Verbosity - Verbosity level [{0},1] % 0 = quiet, 1 = print detailed progress report % % BoundaryPoint - Remove frames on the image boundaries [0,{1}] % Remove points whose descriptor intersects the boundary. % % NumOctaves - Number of octaves [1,2,...] % Number of octaves of the Gaussian scale space. By default it is % computed to cover all possible feature sizes. % % FirstOctave - Index of the first octave [...,-1,{0},+1,...] % Setting the parameter to -1 has the effect of doubling the image % before computing the scale space. % % NumLevels - [1,2,...] % Number of scale levels within each octave. % % Sigma0 - Base smoothing [pixels] % Smoothing of the level 0 of octave 0 of the scale space. By % default it is set to be equivalent to the value 1.6 of [1]. % Since however 1.6 is the smoothing of the level -1 and Simga0 % of the level 0, the actual value is NOT 1.6. % % SigmaN - Nominal smoothing [pixels, {0.5}] % Nominal smoothing of the input image. % % Threshold - Strenght threshold [>= 0, {0.01}] % Maxima of the DOG scale space [1] below this threshold are % ignored. Smaller values accept more features. % % EdgeThreshold - Localization threshold [>= 0, {10}] % Feature which have flattness score [1] above this threshold are % ignored. Bigger values accept more features. % % Magnif - Descriptor window magnification % See SIFTDESCRIPTOR(). % % NumSpatialBins - Number of spatial bins [2,{4},6,...] % See SIFTDESCRIPTOR(). % % NumOrientbins - Number of orientation bins [1,2,...,{8},...] % See SIFTDESCRIPTOR(). % % See also GAUSSIANSS(), DIFFSS(), PLOTSIFTFRAME(), PLOTSIFTDESCRIPTOR(), % SIFTDESCRIPTOR(), SIFTMATCH(). [M,N,C] = size(I); % Lowe's equivalents choices(default values) S=3; omin= 0;%-1; O = 4;%floor(log2(min(M,N)))-omin-3; sigma0=1.6*2^(1/S); sigman=0.5; thresh = 0.2 / S / 2;%0.04/S/2; r = 18;%10; NBP = 4; NBO = 8; magnif = 3.0; discard_boundary_points = 1; verb = 0; if nargin > 1 for k=1:2:length(varargin) switch lower(varargin{k}) case 'numoctaves' O = varargin{k+1}; case 'firstoctave' omin = varargin{k+1}; case 'numlevels' S = varargin{k+1}; case 'sigma0' sigma0 = varargin{k+1}; case 'sigman' sigman = varargin{k+1}; case 'threshold' thresh = varargin{k+1}; case 'edgethreshold' r = varargin{k+1}; case 'boundarypoint' discard_boundary_points = varargin{k+1}; case 'numspatialbins' NBP = varargin{k+1}; case 'numorientbins' NBO = varargin{k+1}; case 'magnif' magnif = varargin{k+1}; case 'verbosity' verb = varargin{k+1} ; otherwise error(['Unknown parameter ''' varargin{k} '''.']); end end end % The image I must be gray-scale, of storage class DOUBLE and ranging in [0,1]. if C > 1 error('I should be a grayscale image') ; end frames = []; descriptors = []; % -------------------------------------------------------------------- % SIFT Detector and Descriptor % -------------------------------------------------------------------- % compute the Gaussian scale space of image I, that is, construct the % Gaussian Pyramid if verb>0 fprintf('SIFT: computing scale space...'); tic; end gss = gaussianss(I,sigman,O,S,omin,-1,S+1,sigma0); if verb>0 fprintf('(%.3f s gss; ',toc); tic; end % compute the Difference of scale space, that is, construct the DoG Pyramid dogss = diffss(gss); if verb > 0 fprintf('%.3f s dogss) done\n',toc); end if verb > 0 fprintf('\nSIFT scale space parameters [PropertyName in brackets]\n'); fprintf(' sigman [SigmaN] : %f\n', sigman); fprintf(' sigma0 [Sigma0] : %f\n', dogss.sigma0); fprintf(' O [NumOctaves] : %d\n', dogss.O); fprintf(' S [NumLevels] : %d\n', dogss.S); fprintf(' omin [FirstOctave] : %d\n', dogss.omin); fprintf(' smin : %d\n', dogss.smin); fprintf(' smax : %d\n', dogss.smax); fprintf('\nSIFT detector parameters\n') fprintf(' thersh [Threshold] : %e\n', thresh); fprintf(' r [EdgeThreshold] : %.3f\n', r); fprintf('\nSIFT descriptor parameters\n') fprintf(' magnif [Magnif] : %.3f\n', magnif); fprintf(' NBP [NumSpatialBins]: %d\n', NBP); fprintf(' NBO [NumOrientBins] : %d\n', NBO); end for o=1:gss.O if verb > 0 fprintf('\nSIFT: processing octave %d\n', o-1+omin); tic; end % Local maxima of the DOG octave % The 80% tricks discards early very weak points before refinement. oframes1 = siftlocalmax( dogss.octave{o}, 0.8*thresh, dogss.smin ); oframes = [oframes1 , siftlocalmax( - dogss.octave{o}, 0.8*thresh, dogss.smin)]; if verb > 0 fprintf('SIFT: %d initial points (%.3f s)\n',size(oframes,2),toc);tic; end if size(oframes, 2) == 0 continue; end % Remove points too close to the boundary if discard_boundary_points rad = magnif * gss.sigma0 * 2.^(oframes(3,:)/gss.S) * NBP / 2 ; sel=find(oframes(1,:)-rad >= 1 & oframes(1,:)+rad <= size(gss.octave{o},2) & ... oframes(2,:)-rad >= 1 & oframes(2,:)+rad <= size(gss.octave{o},1)); oframes=oframes(:,sel); if verb > 0 fprintf('SIFT: %d away from boundary\n', size(oframes,2)); tic; end end % Refine the location, threshold strength and remove points on edges oframes = siftrefinemx(oframes, dogss.octave{o}, dogss.smin, thresh, r); if verb > 0 fprintf('SIFT: %d refined (%.3f s)\n', size(oframes,2),toc); tic; end % Compute the orientations oframes = siftormx(oframes, gss.octave{o}, gss.S, gss.smin, gss.sigma0 ); % Store frames x = 2^(o-1+gss.omin) * oframes(1,:); y = 2^(o-1+gss.omin) * oframes(2,:); sigma = 2^(o-1+gss.omin) * gss.sigma0 * 2.^(oframes(3,:)/gss.S); frames = [frames, [x(:)'; y(:)'; sigma(:)'; oframes(4,:)]]; % Descriptors if verb > 0 fprintf('\nSIFT: computing descriptors...'); tic; end sh = siftdescriptor(gss.octave{o}, oframes, gss.sigma0, gss.S, gss.smin, ... 'Magnif', magnif, 'NumSpatialBins', NBP, 'NumOrientBins', NBO); descriptors = [descriptors, sh]; if verb > 0 fprintf('done (%.3f s)\n',toc); end end function SS = gaussianss(I,sigman,O,S,omin,smin,smax,sigma0) % GAUSSIANSS % SS = GAUSSIANSS(I,SIGMAN,O,S,OMIN,SMIN,SMAX,SIGMA0) returns the % Gaussian scale space of image I. Image I is assumed to be % pre-smoothed at level SIGMAN. O,S,OMIN,SMIN,SMAX,SIGMA0 are the % parameters of the scale space %Scale Space Multiplicative Step k k = 2^(1/S); if nargin<7 sigma0=1.6*k; end if omin<0 for o=1:-omin I=doubleSize(I); end elseif omin>0 for o=1:-omin I=halveSize(I); end end [M,N] = size(I); %size of image dsigma0 = sigma0*sqrt(1-1/k^2); %scale step factor so=-smin+1; %index offset % Scale space structure SS.O = O; SS.S = S; SS.sigma0 = sigma0; SS.omin = omin; SS.smin = smin; SS.smax = smax; %First octave % The first level of the first octave has scale index (o,s) = % (omin,smin) and scale coordinate % sigma(omin,smin) = sigma0 2^omin k^smin % The input image I is at nominal scale sigman. Thus in order to get % the first level of the pyramid we need to apply a smoothing of % sqrt( (sigma0 2^omin k^smin)^2 - sigman^2 ). % As we have pre-scaled the image omin octaves (up or down, % depending on the sign of omin), we need to correct this value % by dividing by 2^omin, getting % sqrt( (sigma0 k^smin)^2 - (sigman/2^omin)^2 ) SS.octave{1} = zeros(M,N,smax-smin+1); SS.octave{1}(:,:,1) = smooth(I,sqrt((sigma0*k^smin)^2 -(sigman/2^omin)^2)); for s=smin+1:smax % Here we go from (omin,s-1) to (omin,s). The extra smoothing % standard deviation is % (sigma0 2^omin 2^(s/S) )^2 - (simga0 2^omin 2^(s/S-1/S) )^2 % Aftred dividing by 2^omin (to take into account the fact % that the image has been pre-scaled omin octaves), the % standard deviation of the smoothing kernel is % dsigma = sigma0 k^s sqrt(1-1/k^2) dsigma = k^s * dsigma0; SS.octave{1}(:,:,s+so) = smooth( squeeze(SS.octave{1}(:,:,s-1+so)) ,dsigma); end %Other octaves for o=2:O % We need to initialize the first level of octave (o,smin) from % the closest possible level of the previous octave. A level (o,s) % in this octave corrsponds to the level (o-1,s+S) in the previous % octave. In particular, the level (o,smin) correspnds to % (o-1,smin+S). However (o-1,smin+S) might not be among the levels % (o-1,smin), ..., (o-1,smax) that we have previously computed. % The closest pick is % / smin+S if smin+S <= smax % (o-1,sbest) , sbest = | % \ smax if smin+S > smax % The amount of extra smoothing we need to apply is then given by % ( sigma0 2^o 2^(smin/S) )^2 - ( sigma0 2^o 2^(sbest/S - 1) )^2 % As usual, we divide by 2^o to cancel out the effect of the % downsampling and we get % ( sigma 0 k^smin )^2 - ( sigma0 2^o k^(sbest - S) )^2 sbest = min(smin+S,smax); TMP = halvesize( squeeze(SS.octave{o-1}(:,:,sbest+so)) ); sigma_next = sigma0*k^smin; sigma_prev = sigma0*k^(sbest-S); if (sigma_next>sigma_prev) sig=sqrt(sigma_next^2-sigma_prev^2); TMP= smooth( TMP,sig); end [M,N] = size(TMP); SS.octave{o} = zeros(M,N,smax-smin+1); SS.octave{o}(:,:,1) = TMP; for s=smin+1:smax % The other levels are determined as above for the first octave. dsigma = k^s * dsigma0; SS.octave{o}(:,:,s+so) = smooth( squeeze(SS.octave{o}(:,:,s-1+so)) ,dsigma); end end % ------------------------------------------------------------------------- % Auxiliary functions % ------------------------------------------------------------------------- function J = halvesize(I) J=I(1:2:end,1:2:end); function J = doubleSize(I) [M,N]=size(I) ; J = zeros(2*M,2*N) ; J(1:2:end,1:2:end) = I ; J(2:2:end-1,2:2:end-1) = 0.25*I(1:end-1,1:end-1) + 0.25*I(2:end,1:end-1) + ... 0.25*I(1:end-1,2:end) + 0.25*I(2:end,2:end) ; J(2:2:end-1,1:2:end) = 0.5*I(1:end-1,:) + 0.5*I(2:end,:) ; J(1:2:end,2:2:end-1) = 0.5*I(:,1:end-1) + 0.5*I(:,2:end) ; function J = smooth(I,s) %filter h=fspecial('gaussian',ceil(4*s),s); %convolution J=imfilter(I,h); return; function dss = diffss(ss) % DIFFSS Difference of scale space % DSS=DIFFSS(SS) returns a scale space DSS obtained by subtracting % consecutive levels of the scale space SS. % % In SIFT, this function is used to compute the difference of % Gaussian scale space from the Gaussian scale space of an image. dss.smin = ss.smin; dss.smax = ss.smax-1; dss.omin =ss.omin; dss.O = ss.O; dss.S = ss.S; dss.sigma0 = ss.sigma0; for o=1:dss.O % Can be done at once, but it turns out to be faster in this way [M,N,S] = size(ss.octave{o}); dss.octave{o} = zeros(M,N,S-1); for s=1:S-1 dss.octave{o}(:,:,s) = ss.octave{o}(:,:,s+1) - ss.octave{o}(:,:,s); end end function J = siftlocalmax(octave, thresh,smin) [N,M,S]=size(octave); nb=1; k=0.0002; %for each point of this scale space, we look for extrama bigger than thresh J = []; for s=2:S-1 for j=20:M-20 for i=20:N-20 a=octave(i,j,s); if a>thresh+k ... && a>octave(i-1,j-1,s-1)+k && a>octave(i-1,j,s-1)+k && a>octave(i-1,j+1,s-1)+k ... && a>octave(i,j-1,s-1)+k && a>octave(i,j+1,s-1)+k && a>octave(i+1,j-1,s-1)+k ... && a>octave(i+1,j,s-1)+k && a>octave(i+1,j+1,s-1)+k && a>octave(i-1,j-1,s)+k ... && a>octave(i-1,j,s)+k && a>octave(i-1,j+1,s)+k && a>octave(i,j-1,s)+k ... && a>octave(i,j+1,s)+k && a>octave(i+1,j-1,s)+k && a>octave(i+1,j,s)+k ... && a>octave(i+1,j+1,s)+k && a>octave(i-1,j-1,s+1)+k && a>octave(i-1,j,s+1)+k ... && a>octave(i-1,j+1,s+1)+k && a>octave(i,j-1,s+1)+k && a>octave(i,j+1,s+1)+k ... && a>octave(i+1,j-1,s+1)+k && a>octave(i+1,j,s+1)+k && a>octave(i+1,j+1,s+1)+k J(1,nb)=j-1; J(2,nb)=i-1; J(3,nb)=s+smin-1; nb=nb+1; end end end end function J=siftrefinemx(oframes,octave,smin,thres,r) [M,N,S]=size(octave); [L,K]=size(oframes); comp=1; for p = 1:K b=zeros(1,3) ; A=oframes(:,p); x=A(1)+1; y=A(2)+1; s=A(3)+1-smin; %Local maxima extracted from the DOG have coordinates 1<=x<=N-2, 1<=y<=M-2 % and 1<=s-mins<=S-2. This is also the range of the points that we can refine. if(x < 2 || x > N-1 || y < 2 || y > M-1 || s < 2 || s > S-1) continue ; end val=octave(y,x,s); Dx=0;Dy=0;Ds=0;Dxx=0;Dyy=0;Dss=0;Dxy=0;Dxs=0;Dys=0 ; dx = 0 ; dy = 0 ; for iter = 1:5 A = zeros(3,3) ; x = x + dx ; y = y + dy ; if (x < 2 || x > N-1 || y < 2 || y > M-1 ) break ; end % Compute the gradient. Dx = 0.5 * (octave(y,x+1,s) - octave(y,x-1,s)); Dy = 0.5 * (octave(y+1,x,s) - octave(y-1,x,s)) ; Ds = 0.5 * (octave(y,x,s+1) - octave(y,x,s-1)) ; % Compute the Hessian. Dxx = (octave(y,x+1,s) + octave(y,x-1,s) - 2.0 * octave(y,x,s)) ; Dyy = (octave(y+1,x,s) + octave(y-1,x,s) - 2.0 * octave(y,x,s)) ; Dss = (octave(y,x,s+1) + octave(y,x,s-1) - 2.0 * octave(y,x,s)) ; Dys = 0.25 * ( octave(y+1,x,s+1) + octave(y-1,x,s-1) - octave(y-1,x,s+1) - octave(y+1,x,s-1) ) ; Dxy = 0.25 * ( octave(y+1,x+1,s) + octave(y-1,x-1,s) - octave(y-1,x+1,s) - octave(y+1,x-1,s) ) ; Dxs = 0.25 * ( octave(y,x+1,s+1) + octave(y,x-1,s-1) - octave(y,x-1,s+1) - octave(y,x+1,s-1) ) ; % Solve linear system. A(1,1) = Dxx ; A(2,2) = Dyy ; A(3,3) = Dss ; A(1,2) = Dxy ; A(1,3) = Dxs ; A(2,3) = Dys ; A(2,1) = Dxy ; A(3,1) = Dxs ; A(3,2) = Dys ; b(1) = - Dx ; b(2) = - Dy ; b(3) = - Ds ; c=b*inv(A); % If the translation of the keypoint is big, move the keypoint and re-iterate the computation. Otherwise we are all set. if (c(1) > 0.6 && x < N-2 ) if (c(1) < -0.6 && x > 1) dx=0; else dx=1; end else if (c(1) < -0.6 && x > 1) dx=-1; else dx=0; end end if (c(2) > 0.6 && y < N-2 ) if (c(2) < -0.6 && y > 1) dy=0; else dy=1; end else if (c(2) < -0.6 && y > 1) dy=-1; else dy=0; end end if( dx == 0 && dy == 0 ) break ; end end %we keep the value only of it verify the conditions val = val + 0.5 * (Dx * c(1) + Dy * c(2) + Ds * c(3)) ; score = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ; xn = x + c(1) ; yn = y + c(2) ; sn = s + c(3) ; if (abs(val) > thres) && ... (score < (r+1)*(r+1)/r) && ... (score >= 0) && ... (abs(c(1)) < 1.5) && ... (abs(c(2)) < 1.5) && ... (abs(c(3)) < 1.5) && ... (xn >= 0) && ... (xn <= M-1) && ... (yn >= 0) && ... (yn <= N-1) && ... (sn >= 0) && ... (sn <= S-1) J(1,comp)=xn-1; J(2,comp)=yn-1; J(3,comp)=sn-1+smin; comp=comp+1; end end return function oframes = siftormx(oframes, octave, S, smin, sigma0 ) % this function computes the major orientation of the keypoint (oframes). % Note that there can be multiple major orientations. In that case, the % SIFT keys will be duplicated for each major orientation % Author: Yantao Zheng. Nov 2006. For Project of CS5240 frames = []; win_factor = 1.5 ; NBINS = 36; histo = zeros(1, NBINS); [M, N, s_num] = size(octave); % M is the height of image, N is the width of image; num_level is the number of scale level of the octave key_num = size(oframes, 2); magnitudes = zeros(M, N, s_num); angles = zeros(M, N, s_num); % compute image gradients for si = 1: s_num img = octave(:,:,si); dx_filter = [-0.5 0 0.5]; dy_filter = dx_filter'; gradient_x = imfilter(img, dx_filter); gradient_y = imfilter(img, dy_filter); magnitudes(:,:,si) =sqrt( gradient_x.^2 + gradient_y.^2); angles(:,:,si) = mod(atan(gradient_y ./ (eps + gradient_x)) + 2*pi, 2*pi); end % round off the cooridnates and x = oframes(1,:); y = oframes(2,:) ; s = oframes(3,:); x_round = floor(oframes(1,:) + 0.5); y_round = floor(oframes(2,:) + 0.5); scales = floor(oframes(3,:) + 0.5) - smin; for p=1:key_num s = scales(p); xp= x_round(p); yp= y_round(p); sigmaw = win_factor * sigma0 * 2^(double (s / S)) ; W = floor(3.0* sigmaw); for xs = xp - max(W, xp-1): min((N - 2), xp + W) for ys = yp - max(W, yp-1) : min((M-2), yp + W) dx = (xs - x(p)); dy = (ys - y(p)); if dx^2 + dy^2 <= W^2 % the points are within the circle wincoef = exp(-(dx^2 + dy^2)/(2*sigmaw^2)); bin = round( NBINS * angles(ys, xs, s+ 1)/(2*pi) + 0.5); histo(bin) = histo(bin) + wincoef * magnitudes(ys, xs, s+ 1); end end end theta_max = max(histo); theta_indx = find(histo> 0.8 * theta_max); for i = 1: size(theta_indx, 2) theta = 2*pi * theta_indx(i) / NBINS; frames = [frames, [x(p) y(p) s theta]']; end end oframes = frames; function descriptors = siftdescriptor(octave, oframes, sigma0, S, smin, varargin) % gaussian scale space of an octave % frames containing keypoint coordinates and scale, and orientation % base sigma value % level of scales in the octave for k=1:2:length(varargin) switch lower(varargin{k}) case 'magnif' magnif = varargin{k+1} ; case 'numspatialbins' NBP = varargin{k+1} ; case 'numorientbins' NBO = varargin{k+1} ; otherwise error(['Unknown parameter ' varargin{k} '.']) ; end end num_spacialBins = NBP; num_orientBins = NBO; key_num = size(oframes, 2); % compute the image gradients [M, N, s_num] = size(octave); % M is the height of image, N is the width of image; num_level is the number of scale level of the octave descriptors = []; magnitudes = zeros(M, N, s_num); angles = zeros(M, N, s_num); % compute image gradients for si = 1: s_num img = octave(:,:,si); dx_filter = [-0.5 0 0.5]; dy_filter = dx_filter'; gradient_x = imfilter(img, dx_filter); gradient_y = imfilter(img, dy_filter); magnitudes(:,:,si) =sqrt( gradient_x.^2 + gradient_y.^2); % if sum( gradient_x == 0) > 0 % fprintf('00'); % end angles(:,:,si) = mod(atan(gradient_y ./ (eps + gradient_x)) + 2*pi, 2*pi); end x = oframes(1,:); y = oframes(2,:); s = oframes(3,:); % round off x_round = floor(oframes(1,:) + 0.5); y_round = floor(oframes(2,:) + 0.5); scales = floor(oframes(3,:) + 0.5) - smin; for p = 1: key_num s = scales(p); xp= x_round(p); yp= y_round(p); theta0 = oframes(4,p); sinth0 = sin(theta0) ; costh0 = cos(theta0) ; sigma = sigma0 * 2^(double (s / S)) ; SBP = magnif * sigma; %W = floor( sqrt(2.0) * SBP * (NBP + 1) / 2.0 + 0.5); W = floor( 0.8 * SBP * (NBP + 1) / 2.0 + 0.5); descriptor = zeros(NBP, NBP, NBO); % within the big square, select the pixels with the circle and put into % the histogram. no need to do rotation which is very expensive for dxi = max(-W, 1-xp): min(W, N -2 - xp) for dyi = max(-W, 1-yp) : min(+W, M-2-yp) mag = magnitudes(yp + dyi, xp + dxi, s); % the gradient magnitude at current point(yp + dyi, xp + dxi) angle = angles(yp + dyi, xp + dxi, s) ; % the gradient angle at current point(yp + dyi, xp + dxi) angle = mod(-angle + theta0, 2*pi); % adjust the angle with the major orientation of the keypoint and mod it with 2*pi dx = double(xp + dxi - x(p)); % x(p) is the exact keypoint location (floating number). dx is the relative location of the current pixel with respect to the keypoint dy = double(yp + dyi - y(p)); % dy is the relative location of the current pixel with respect to the keypoint nx = ( costh0 * dx + sinth0 * dy) / SBP ; % nx is the normalized location after rotation (dx, dy) with the major orientation angle. this tells which x-axis spatial bin the pixel falls in ny = (-sinth0 * dx + costh0 * dy) / SBP ; nt = NBO * angle / (2* pi) ; wsigma = NBP/2 ; wincoef = exp(-(nx*nx + ny*ny)/(2.0 * wsigma * wsigma)) ; binx = floor( nx - 0.5 ) ; biny = floor( ny - 0.5 ) ; bint = floor( nt ); rbinx = nx - (binx+0.5) ; rbiny = ny - (biny+0.5) ; rbint = nt - bint ; for(dbinx = 0:1) for(dbiny = 0:1) for(dbint = 0:1) % if condition limits the samples within the square % width W. binx+dbinx is the rotated x-coordinate. % therefore the sampling square is effectively a % rotated one if( binx+dbinx >= -(NBP/2) && ... binx+dbinx < (NBP/2) && ... biny+dbiny >= -(NBP/2) && ... biny+dbiny < (NBP/2) && isnan(bint) == 0) weight = wincoef * mag * abs(1 - dbinx - rbinx) ... * abs(1 - dbiny - rbiny) ... * abs(1 - dbint - rbint) ; descriptor(binx+dbinx + NBP/2 + 1, biny+dbiny + NBP/2+ 1, mod((bint+dbint),NBO)+1) = ... descriptor(binx+dbinx + NBP/2+ 1, biny+dbiny + NBP/2+ 1, mod((bint+dbint),NBO)+1 ) + weight ; end end end end end end descriptor = reshape(descriptor, 1, NBP * NBP * NBO); descriptor = descriptor ./ norm(descriptor); %Truncate at 0.2 indx = find(descriptor > 0.2); descriptor(indx) = 0.2; descriptor = descriptor ./ norm(descriptor); descriptors = [descriptors, descriptor']; end
github
26hzhang/OptimizedImageEnhance-master
bilateralFilter.m
.m
OptimizedImageEnhance-master/matlab/bilateralFilter.m
6,703
utf_8
a76d6aab0840ad8b7e6e749526f36660
% % output = bilateralFilter( data, edge, ... % edgeMin, edgeMax, ... % sigmaSpatial, sigmaRange, ... % samplingSpatial, samplingRange ) % % Bilateral and Cross-Bilateral Filter using the Bilateral Grid. % % Bilaterally filters the image 'data' using the edges in the image 'edge'. % If 'data' == 'edge', then it the standard bilateral filter. % Otherwise, it is the 'cross' or 'joint' bilateral filter. % For convenience, you can also pass in [] for 'edge' for the normal % bilateral filter. % % Note that for the cross bilateral filter, data does not need to be % defined everywhere. Undefined values can be set to 'NaN'. However, edge % *does* need to be defined everywhere. % % data and edge should be of the greyscale, double-precision floating point % matrices of the same size (i.e. they should be [ height x width ]) % % data is the only required argument % % edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data' % for the normal bilateral filter) and is useful when the input is in a % range that's not between 0 and 1. For instance, if you are filtering the % L channel of an image that ranges between 0 and 100, set edgeMin to 0 and % edgeMax to 100. % % edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge(:)). % This is probably *not* what you want, since the input may not span the % entire range. % % sigmaSpatial and sigmaRange specifies the standard deviation of the space % and range gaussians, respectively. % sigmaSpatial defaults to min( width, height ) / 16 % sigmaRange defaults to ( edgeMax - edgeMin ) / 10. % % samplingSpatial and samplingRange specifies the amount of downsampling % used for the approximation. Higher values use less memory but are also % less accurate. The default and recommended values are: % % samplingSpatial = sigmaSpatial % samplingRange = sigmaRange % function output = bilateralFilter( data, edge, edgeMin, edgeMax,... sigmaSpatial, sigmaRange, samplingSpatial, samplingRange ) if( ndims( data ) > 2 ), error( 'data must be a greyscale image with size [ height, width ]' ); end if( ~isa( data, 'double' ) ), error( 'data must be of class "double"' ); end if ~exist( 'edge', 'var' ), edge = data; elseif isempty( edge ), edge = data; end if( ndims( edge ) > 2 ), error( 'edge must be a greyscale image with size [ height, width ]' ); end if( ~isa( edge, 'double' ) ), error( 'edge must be of class "double"' ); end inputHeight = size( data, 1 ); inputWidth = size( data, 2 ); if ~exist( 'edgeMin', 'var' ), edgeMin = min( edge( : ) ); %warning( 'edgeMin not set! Defaulting to: %f\n', edgeMin ); end if ~exist( 'edgeMax', 'var' ), edgeMax = max( edge( : ) ); %warning( 'edgeMax not set! Defaulting to: %f\n', edgeMax ); end edgeDelta = edgeMax - edgeMin; if ~exist( 'sigmaSpatial', 'var' ), sigmaSpatial = min( inputWidth, inputHeight ) / 16; %fprintf( 'Using default sigmaSpatial of: %f\n', sigmaSpatial ); end if ~exist( 'sigmaRange', 'var' ), sigmaRange = 0.1 * edgeDelta; %fprintf( 'Using default sigmaRange of: %f\n', sigmaRange ); end if ~exist( 'samplingSpatial', 'var' ), samplingSpatial = sigmaSpatial; end if ~exist( 'samplingRange', 'var' ), samplingRange = sigmaRange; end if size( data ) ~= size( edge ), error( 'data and edge must be of the same size' ); end % parameters derivedSigmaSpatial = sigmaSpatial / samplingSpatial; derivedSigmaRange = sigmaRange / samplingRange; paddingXY = floor( 2 * derivedSigmaSpatial ) + 1; paddingZ = floor( 2 * derivedSigmaRange ) + 1; % allocate 3D grid downsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial )... + 1 + 2 * paddingXY; downsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial )... + 1 + 2 * paddingXY; downsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ; gridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth ); gridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth ); % compute downsampled indices [ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); % ii = % 0 0 0 0 0 % 1 1 1 1 1 % 2 2 2 2 2 % jj = % 0 1 2 3 4 % 0 1 2 3 4 % 0 1 2 3 4 % so when iterating over ii( k ), jj( k ) % get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first) di = round( ii / samplingSpatial ) + paddingXY + 1; dj = round( jj / samplingSpatial ) + paddingXY + 1; dz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1; % perform scatter (there's probably a faster way than this) % normally would do downsampledWeights( di, dj, dk ) = 1, but we have to % perform a summation to do box downsampling for k = 1 : numel( dz ), dataZ = data( k ); % traverses the image column wise, same as di( k ) if ~isnan( dataZ ), dik = di( k ); djk = dj( k ); dzk = dz( k ); gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ; gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1; end end % make gaussian kernel kernelWidth = 2 * derivedSigmaSpatial + 1; kernelHeight = kernelWidth; kernelDepth = 2 * derivedSigmaRange + 1; halfKernelWidth = floor( kernelWidth / 2 ); halfKernelHeight = floor( kernelHeight / 2 ); halfKernelDepth = floor( kernelDepth / 2 ); [gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1,... 0 : kernelHeight - 1, 0 : kernelDepth - 1 ); gridX = gridX - halfKernelWidth; gridY = gridY - halfKernelHeight; gridZ = gridZ - halfKernelDepth; gridRSquared = ( gridX .* gridX + gridY .* gridY ) /... ( derivedSigmaSpatial * derivedSigmaSpatial ) +... ( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange ); kernel = exp( -0.5 * gridRSquared ); % convolve blurredGridData = convn( gridData, kernel, 'same' ); blurredGridWeights = convn( gridWeights, kernel, 'same' ); % divide % avoid divide by 0, won't read there anyway blurredGridWeights( blurredGridWeights == 0 ) = -2; normalizedBlurredGrid = blurredGridData ./ blurredGridWeights; % put 0s where it's undefined normalizedBlurredGrid( blurredGridWeights < -1 ) = 0; % for debugging % blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back % upsample % meshgrid does x, then y, so output arguments need to be reversed [ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); % no rounding di = ( ii / samplingSpatial ) + paddingXY + 1; dj = ( jj / samplingSpatial ) + paddingXY + 1; dz = ( edge - edgeMin ) / samplingRange + paddingZ + 1; % interpn takes rows, then cols, etc % i.e. size(v,1), then size(v,2), ... output = interpn( normalizedBlurredGrid, di, dj, dz );
github
damien911224/theWorldInSafety-master
extractOpticalFlow_gpu.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow_cpu/matlab/extractOpticalFlow_gpu.m
1,645
utf_8
e184fc7aad7743036e394d6b08ba37f9
function [] = extractOpticalFlow_gpu(index, device_id, type) % path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/'; % if type ==0 % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_farn_gpu_step_2/'; % elseif type ==1 % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_tvl1_gpu_step_2/'; % else % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_brox_gpu_step_2/'; % end path1 = '/nfs/lmwang/lmwang/Data/HMDB51/hmdb51_org/'; if type ==0 path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_farn_gpu/'; elseif type ==1 path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_tvl1_gpu/'; else path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_brox_gpu/'; end folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20 -t %d -d %d -s %d',... file1,file2,file3,file4,type,device_id,1); system(cmd); end i end end
github
damien911224/theWorldInSafety-master
extracOpticalFlow.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow_cpu/matlab/extracOpticalFlow.m
1,034
utf_8
87c098785c996cfa862cd7e84742994e
function [] = extracOpticalFlow(index) path1 = '/home/lmwang/data/UCF/ucf101_org/'; path2 = '/home/lmwang/data/UCF/ucf101_warp_flow_img/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
damien911224/theWorldInSafety-master
extractOpticalFlow.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow_cpu/matlab/extractOpticalFlow.m
1,042
utf_8
e73edca68bee408e232e58e19e2aae1b
function [] = extractOpticalFlow(index) path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/'; path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_TV/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
damien911224/theWorldInSafety-master
classification_demo.m
.m
theWorldInSafety-master/actionRecognition/lib/caffe-action/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
damien911224/theWorldInSafety-master
extractOpticalFlow_gpu.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow/matlab/extractOpticalFlow_gpu.m
1,645
utf_8
e184fc7aad7743036e394d6b08ba37f9
function [] = extractOpticalFlow_gpu(index, device_id, type) % path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/'; % if type ==0 % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_farn_gpu_step_2/'; % elseif type ==1 % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_tvl1_gpu_step_2/'; % else % path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_brox_gpu_step_2/'; % end path1 = '/nfs/lmwang/lmwang/Data/HMDB51/hmdb51_org/'; if type ==0 path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_farn_gpu/'; elseif type ==1 path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_tvl1_gpu/'; else path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_brox_gpu/'; end folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20 -t %d -d %d -s %d',... file1,file2,file3,file4,type,device_id,1); system(cmd); end i end end
github
damien911224/theWorldInSafety-master
extracOpticalFlow.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow/matlab/extracOpticalFlow.m
1,034
utf_8
87c098785c996cfa862cd7e84742994e
function [] = extracOpticalFlow(index) path1 = '/home/lmwang/data/UCF/ucf101_org/'; path2 = '/home/lmwang/data/UCF/ucf101_warp_flow_img/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
damien911224/theWorldInSafety-master
extractOpticalFlow.m
.m
theWorldInSafety-master/actionRecognition/lib/dense_flow/matlab/extractOpticalFlow.m
1,042
utf_8
e73edca68bee408e232e58e19e2aae1b
function [] = extractOpticalFlow(index) path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/'; path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_TV/'; folderlist = dir(path1); foldername = {folderlist(:).name}; foldername = setdiff(foldername,{'.','..'}); for i = index if ~exist([path2,foldername{i}],'dir') mkdir([path2,foldername{i}]); end filelist = dir([path1,foldername{i},'/*.avi']); for j = 1:length(filelist) if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir') mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]); end file1 = [path1,foldername{i},'/',filelist(j).name]; file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x']; file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y']; file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i']; cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4); system(cmd); end i end end
github
dabamos/openadms-server-master
api.m
.m
openadms-server-master/examples/clients/octave/api.m
1,685
utf_8
96ec2c25505068abb0665ba993068e3d
################################################################################ # OpenADMS Server API Access Example ################################################################################ # Run inside the command window: # >> source("api.m"); # >> source("profile.m"); # >> data = get_json(host, user, password, pid, nid, sensor, target, from, to); # >> [x, y] = get_values(data, 'temperature'); # >> plot_values(x, y, "Temperature", "Time", "Temperature [°C]"); ################################################################################ # Add JSONLab library. addpath('./jsonlab'); # Retrieves JSON object from OpenADMS Server instance. function x = get_json(host, user, password, pid, nid, sensor, target, from, to) api = strcat("https://", user, ":", password, "@", host, "/api/v1/projects/", pid, "/nodes/", nid, "/sensors/", sensor, "/targets/", target, "/observations/?start=", from, "&end=", to); printf("Loading observations from 'https://%s/' ...\n", host); x = loadjson(urlread(api)); endfunction # Returns timestamps and values of given `name` from input `json`. function [x, y] = get_values(json, name) x = nan(length(json)); y = nan(length(json)); for i = 1:length(json) # Convert ISO 8601 to serial. Strip everything beyond the seconds. x(i) = datenum(substr(json{i}.data.timestamp, 1, 19), "yyyy-mm-ddTHH:MM:SS"); y(i) = getfield(json{i}.data.responseSets, name).value; endfor endfunction # Plots timestamps and values. function plot_values(x, y, t, xl, yl) plot(x, y); xlabel(xl); ylabel(yl); title(t); datetick("x"); grid(); endfunction
github
nsdesai/dynamic_clamp-master
DC.m
.m
dynamic_clamp-master/matlab_alternative/DC.m
3,479
utf_8
ff97efa3d0178044850c872645730cf4
% Matlab script to communicate with the Teensy 3.6 when it is in dynamic % clamp mode. % % Calling DC without arguments opens the GUI and initializes all the % numbers at 0.0. % % The GUI calls the subfunctions by passing arguments. % % Last modified 06/11/17. function [] = DC(varargin) if (nargin==0) % initialize openfig('DC.fig','reuse'); initializeteensy('COM3') % replace COM3 with the name of % the USB port to which the Teensy % is connected zero; else % feval switchyard if (nargout) [varargout{1:nargout}] = feval(varargin{:}); %#ok<NASGU> else feval(varargin{:}); end end % ------------------------------------------------------------------------- function [] = initializeteensy(portName) global teensy teensy = serial(portName,'BaudRate',115200,'ByteOrder','littleEndian'); fopen(teensy); % ------------------------------------------------------------------------- function [] = upload() global teensy g_shunt = get(findobj('Tag','g_shunt'),'Value'); g_HCN = get(findobj('Tag','g_HCN'),'Value'); g_Na = get(findobj('Tag','g_Na'),'Value'); m_OU_exc = get(findobj('Tag','m_OU_exc'),'Value'); D_OU_exc = get(findobj('Tag','D_OU_exc'),'Value'); m_OU_inh = get(findobj('Tag','m_OU_inh'),'Value'); D_OU_inh = get(findobj('Tag','D_OU_inh'),'Value'); g_EPSC = get(findobj('Tag','g_EPSC'),'Value'); out = [g_shunt; g_HCN; g_Na; m_OU_exc; D_OU_exc; m_OU_inh; D_OU_inh; g_EPSC]; out = typecast(single(out),'uint8'); fwrite(teensy,out); % ------------------------------------------------------------------------- function [] = zero() set(findobj('Tag','g_shunt'),'Value',0); set(findobj('Tag','g_HCN'),'Value',0); set(findobj('Tag','g_Na'),'Value',0); set(findobj('Tag','m_OU_exc'),'Value',0); set(findobj('Tag','D_OU_exc'),'Value',0); set(findobj('Tag','m_OU_inh'),'Value',0); set(findobj('Tag','D_OU_inh'),'Value',0); set(findobj('Tag','g_EPSC'),'Value',0); getnumbers upload % ------------------------------------------------------------------------- function [] = getnumbers() g_shunt = get(findobj('Tag','g_shunt'),'Value'); g_HCN = get(findobj('Tag','g_HCN'),'Value'); g_Na = get(findobj('Tag','g_Na'),'Value'); m_OU_exc = get(findobj('Tag','m_OU_exc'),'Value'); D_OU_exc = get(findobj('Tag','D_OU_exc'),'Value'); m_OU_inh = get(findobj('Tag','m_OU_inh'),'Value'); D_OU_inh = get(findobj('Tag','D_OU_inh'),'Value'); g_EPSC = get(findobj('Tag','g_EPSC'),'Value'); set(findobj('Tag','g_shunt_Num'),'String',num2str(g_shunt,'%0.2f')) set(findobj('Tag','g_HCN_Num'),'String',num2str(g_HCN,'%0.2f')) set(findobj('Tag','g_Na_Num'),'String',num2str(g_Na,'%0.2f')) set(findobj('Tag','m_OU_exc_Num'),'String',num2str(m_OU_exc,'%0.2f')) set(findobj('Tag','D_OU_exc_Num'),'String',num2str(D_OU_exc,'%0.2f')) set(findobj('Tag','m_OU_inh_Num'),'String',num2str(m_OU_inh,'%0.2f')) set(findobj('Tag','D_OU_inh_Num'),'String',num2str(D_OU_inh,'%0.2f')) set(findobj('Tag','g_EPSC_Num'),'String',num2str(g_EPSC,'%0.2f')) % ------------------------------------------------------------------------- function [] = closedcfigure %#ok<*DEFNU> global teensy delete(findobj('Tag','DC_figure')) fclose(teensy); delete(teensy) clear teensy
github
mribri999/MRSignalsSeqs-master
lin.m
.m
MRSignalsSeqs-master/Lecture-Examples/lin.m
291
utf_8
0b4623bc8e1b70a0bca534fc35e56d28
% This function linearizes a matrix (m) of any dimension (eg M=m(:)). % If an index vector (ind) is given then the the ind entries of m(:) are % returned. % % SYNTAX: m=lin(m); % m=lin(m,ind); % % DBE 12/22/03 function m=lin(m,ind); m=m(:); if nargin==2 m=m(ind); end return
github
mribri999/MRSignalsSeqs-master
rot3d.m
.m
MRSignalsSeqs-master/Lecture-Examples/rot3d.m
280
utf_8
ddd58619ab5636f2789e146fd9e9a07e
% This function simply activates the camer toolbar and allows 3D rotation % % Uses: cameratoolbar('SetMode','orbit','SetCoordSys','none'); % % DBE 12/29/02 function rot3d cameratoolbar('Show'); cameratoolbar('SetMode','orbit'); cameratoolbar('SetCoordSys','none'); return
github
mribri999/MRSignalsSeqs-master
csens2d.m
.m
MRSignalsSeqs-master/Matlab/csens2d.m
942
utf_8
bb28eb1175ba75749a0a6c9d861be532
% % function [ncs,cs] = csens2d(klow) % % Function calculates 2D coil sensitivities from an array klow, % that is a calibration region (ie mostly zero except near the % center. % % INPUT: % klow = Nx x Ny x Nc matrix % % OUTPUT: % ncs = coil sensitivities, normalized by RMS % cs = coil sensitivities, raw % cmrms = RMS of sensitivities function [ncs,cs,cmrms] = csens2d(klow) sz = size(klow); nc = sz(3); cs = fftshift(fft(fftshift(klow,1),[],1),1); % FFT x cs = fftshift(fft(fftshift(cs,2),[],2),2); % FFT y cmrms = sqrt( sum( conj(cs).*cs , 3) ); % RMS of maps, coil dimension meancm = mean(cmrms(:)); % -- Normalize % -- If RMS is 0, replace values in channel 1 f = find(cmrms(:)==0); cs = reshape(cs,sz(1)*sz(2),nc); % Npix x Nc cmrms(f)=meancm/100; cs(f,:) = meancm/10000; % Small values in background ncs = cs ./ (cmrms(:)*ones(1,nc)); % Normalized matrix ncs = reshape(ncs,sz); cs = reshape(cs,sz);
github
mribri999/MRSignalsSeqs-master
plotgradinfo.m
.m
MRSignalsSeqs-master/Matlab/plotgradinfo.m
3,718
utf_8
52ec061fe9e274ac50b1fd0f861894e2
% % function [k,g,s,m1,m2,t,v]=plotgradinfo(g,T,k0) % % Function makes a nice plot given a 2D gradient waveform. % % INPUT: % g gradient (G/cm) = gx + i*gy, or Nx2, Nx3 or Nx4. % T sample period (s) % k0 initial condition for k-space. % % OUTPUT: % k k-space trajectory (cm^(-1)) % g gradient (G/cm) % s slew rate trajectory (G/cm/s) % m1 first moment trajectory (s/cm) % m2 second moment trajectory (s^2/cm) % % B.Hargreaves, Aug 2002. % % =============== CVS Log Messages ========================== % This file is maintained in CVS version control. % % $Log: plotgradinfo.m,v $ % Revision 1.7 2003/09/16 16:45:03 brian % Added ability to plot acquisition interval. % % Revision 1.6 2003/09/03 18:42:32 brian % Added a comment. Voltage to 2nd moment. % % Revision 1.5 2002/10/14 15:59:36 brian % Added calculation/plot of voltage. % % Revision 1.4 2002/09/05 18:35:44 bah % Separted into calculation and plot parts. % % Revision 1.3 2002/09/05 17:45:31 bah % Plots and returns first and second moments now too. % % Revision 1.2 2002/09/04 01:20:17 bah % Fixed scaling of slew, and other bugs. % % Revision 1.1 2002/09/03 23:08:20 bah % Added to CVS. % % % =========================================================== function [k,g,s,m1,m2,t,v]=plotgradinfo(g,T,k0) if (nargin < 2) T = .000004; end; if (nargin < 3) k0 = 0; end; gamma = 4258; sg=size(g); if ((sg(2)==1) & ~isreal(g)) g = [real(g) imag(g)]; end; [k,g,s,m1,m2,t,v]=calcgradinfo(g,T,k0); sg=size(g); ng=sg(2); if (ng > 3) acq = g(:,4); g = g(:,1:3); k = k(:,1:3); s = s(:,1:3); m1 = m1(:,1:3); m2 = m2(:,1:3); v = v(:,1:3); sg=size(g); ng=sg(2); else acq=[]; end; pls={'g--','r--','b--','k:'}; pls{ng+1}='k:'; M=2; N=3; clf; if (ng>=2) subplot(M,N,1); if (max(size(acq))>0) mxk = sqrt(max(acq'.*sum((k(:,1:2))'.*(k(:,1:2))'))); xsq = cos(2*pi*[0:30]/30)*mxk; ysq = sin(2*pi*[0:30]/30)*mxk; h=patch(xsq,ysq,.8*[1 1 1]); set(h,'EdgeColor',.8*[1 1 1]); hold on; end; plot(k(:,1),k(:,2),'b-'); xlabel('k_x'); ylabel('k_y'); title('K-space Trajectory'); grid on; a = axis; axis(max(abs(a))*[-1 1 -1 1]); end; subplot(M,N,2); doplot(t*1000,k,'k',pls,acq); xlabel('time(ms)'); ylabel('K-space (cm^{-1})'); title('K-space vs time'); subplot(M,N,3); doplot(t*1000,g,'g',pls,acq); xlabel('time(ms)'); ylabel('Gradient (G/cm)'); title('Gradient vs time'); subplot(M,N,4); doplot(t*1000,s,'slew',pls,acq); xlabel('time(ms)'); ylabel('Slew Rate (G/cm/s)'); title('Slew Rates vs time'); if (M*N>=5) subplot(M,N,5); doplot(t*1000,m1,'m1',pls,acq); xlabel('time(ms)'); ylabel('First Moment (s/cm)'); title('First Moment vs time'); end; if (0==0) % Plot second moment if (M*N>=6) subplot(M,N,6); doplot(t*1000,m2,'m2',pls,acq); xlabel('time(ms)'); ylabel('Second Moment (s^2/cm)'); title('Second Moment vs time'); end; else % Plot coil voltage. if (M*N>=6) subplot(M,N,6); doplot(t*1000,v,'voltage',pls,acq); xlabel('time(ms)'); ylabel('Voltage (V)'); title('Coil Voltage vs time'); end; end; function doplot(x,y,labs,col,acq) axl={'x','y','z'}; ss = size(y); if (min(size(acq))>0) mina = min(find(acq > 0)); maxa = max(find(acq > 0)); xsq = [x(mina) x(maxa) x(maxa) x(mina)]; ysq = 1.1*sqrt(max(abs(sum(y'.*y'))))*[-1 -1 1 1]; patchc = .8*[1 1 1]; end; hold off; if (min(size(acq))>0) h=patch(xsq,ysq,patchc); set(h,'EdgeColor',patchc); hold on; end; for q=1:ss(2) plot(x,y(:,q),col{q}); hold on; leg{q} = sprintf('%s_%s',labs,axl{q}); end; if (ss(2)>1) ab = sqrt(sum(y.'.*y.')).'; plot(x,ab,col{ss(2)+1}); leg{ss(2)+1}=sprintf('|%s|',labs); end; hold off; legend(leg); grid on;
github
mribri999/MRSignalsSeqs-master
epg_gradecho.m
.m
MRSignalsSeqs-master/Matlab/epg_gradecho.m
3,862
utf_8
60eaf73a6815f16315b3249214cc1cda
% function [s,phasediag,FZ] = epg_gradecho(flipangle,T1,T2,TR,TE,rfdphase,rfdphaseinc,gspoil,dfreq,N) % % EPG simulation of any gradient-echo sequence: % (a) balanced SSFP % (b) gradient spoiling % (c) reversed gradient spoiling % (d) RF spoiling % (e) Perfect spoiling % % INPUT: % flipangle = flip angle in radians [pi/6 radians] % T1,T2 = relaxation times, ms [1000,200 ms] % TR = repetition time, ms [10ms] % TE = echo time (RF to signal), ms [5ms] % rfdphase = amount to increment RF phase per TR, radians [pi radians] % rfdphaseinc = amount to increment rfdphase, per TR, radians [0 rad] % gspoil = 0 to apply no spoiler, 1,-1 spoiler after,before TE [0] % dfreq = off-resonance frequency (Hz) [0Hz] % N = number of repetitions to steady state [200] % % NOTE SETTINGS FOR SEQUENCES: % SEQUENCE rfdphase rfdphaseinc gspoil % --===--------------------------------------------------------------- % (a) bSSFP any (shifts profile) 0 0 % (b) Grad-spoiled anything 0 1 % (c) Rev.Grad-spoiled anything 0 -1 % (d) RF Spoiled anything pi/180*117 1 % (e) Perfect spoiling anything 0 or any 100 % % All states are kept, for demo purposes, though this % is not really necessary. % % OUTPUT: % s = signal % phasediag = display-able phase diagram % FZ = record of all states (3xNxN) function [s,phasediag,FZ] = epg_gradecho(flipangle,T1,T2,TR,TE,rfdphase,rfdphaseinc,gspoil,dfreq,N) if (nargin < 1) flipangle = pi/6; end; if (nargin < 2) T1 = 1000; end; % ms if (nargin < 3) T2 = 200; end; %ms if (nargin < 4) TR = 10; end; % ms if (nargin < 5) TE = 5; end; % ms if (nargin < 6) rfdphase = pi; end; % radians if (nargin < 7) rfdphaseinc = 0; end; % radians if (nargin < 8) gspoil = 0; end; if (nargin < 9) dfreq = 0; end; if (nargin < 10) N=200; end; % -- Initialization P = zeros(3,N); % Allocate all known states, 1 per echo. P(3,1)=1; % Initial condition/equilibrium. FZ = zeros(3,N,N); % Store all states. Pstore = zeros(2*N,N); % Store F,F* states, with 2 gradients per echo Zstore = zeros(N,N); % Store Z states, with 2 gradients per echo s = zeros(1,N); % Allocate signal vector to store. rfphase = 0; % Register to store. for n=1:N % Repeat over N TRs. *START/END at TE!!* P = epg_grelax(P,T1,T2,TR-TE,0,0,0,1); % Relaxation TE to TR P = epg_zrot(P,2*pi*dfreq*(TR-TE)/1000); % Off-resonance precession TE to TR if (gspoil ==1) P = epg_grad(P,1); end; % Gradient spoiler at end of TR if (gspoil==100) P = diag([0 0 1])*P; end;% Zero-out transverse states at TR P = epg_rf(P,flipangle,rfphase); % RF excitation P = epg_grelax(P,T1,T2,TE,0,0,0,1); % Relaxation 0 to TE P = epg_zrot(P,2*pi*dfreq*(TE)/1000); % Off-resonance precession 0 to TE. if (gspoil < 0) P = epg_grad(P,1); end; % Gradient spoiler before TE % -- Store Signals and update RF phase s(1,n) = P(1,1)*exp(-i*rfphase); % Store signal, demodulated by RF phase rfphase = rfphase+rfdphase; % Increment the phase rfdphase = rfdphase + rfdphaseinc; % Increment the increment... Pstore(N:2*N-1,n) = P(2,:).'; % Put in negative states Pstore(1:N,n) = flipud(P(1,:).'); % Put in positive, overwrite center. Zstore(:,n) = P(3,:).'; FZ(:,:,n) = P; % Store in state matrix format end; set(0,'defaultAxesFontSize',14); % Default font sizes set(0, 'DefaultLineLineWidth', 2); % Default line width plotstate = cat(1,Pstore,Zstore); subplot(1,2,1); plot([1:N]*TR,abs(s)); lplot('Evolution Time','Signal',' Signal vs TR time'); subplot(1,2,2); dispim(plotstate,0,0.2); xlabel('Echo'); ylabel('F(top) and Z(bottom) States'); title('F and Z states vs time'); phasediag = plotstate;
github
mribri999/MRSignalsSeqs-master
epg_gradspoil.m
.m
MRSignalsSeqs-master/Matlab/epg_gradspoil.m
1,596
utf_8
e3198d6aadc9e77ccb34e81b1a38966b
% function [s,phasediag,P] = epg_gradspoil(flipangle,N,T1,T2,TR) % % EPG Simulation of Gradient-spoiled sequence. % % flipangle = flip angle (radians) % N = number of TRs % T1,T2,TR = relaxation times and TR % % All states are kept, for demo purposes, though this % is not really necessary. function [s,phasediag,P] = epg_gradspoil(flipangle,N,T1,T2,TR) if (nargin < 1) flipangle = pi/6; end; if (nargin < 2) N=100; end; if (nargin < 3) T1 = 1; end; % sec if (nargin < 4) T2 = 0.1; end; % sec if (nargin < 5) TR = 0.01; end; % sec P = zeros(3,N); % Allocate all known states, 1 per echo. P(3,1)=1; % Initial condition/equilibrium. Pstore = zeros(2*N,N); % Store F,F* states, with 2 gradients per echo Zstore = zeros(N,N); % Store Z states, with 2 gradients per echo s = zeros(1,N); % Allocate signal vector to store. for n=1:N P = epg_rf(P,flipangle,pi/2); % RF excitation s(n) = P(1,1); % Signal is F0 state. P = epg_grelax(P,T1,T2,TR,1,0,1,1); % Gradient spoiler, relaxation Pstore(N:2*N-1,n) = P(2,:).'; % Put in negative states Pstore(1:N,n) = flipud(P(1,:).'); % Put in positive, overwrite center. Zstore(:,n) = P(3,:).'; end; set(0,'defaultAxesFontSize',14); % Default font sizes set(0, 'DefaultLineLineWidth', 2); % Default line width plotstate = cat(1,Pstore,Zstore); subplot(1,2,1); plot([1:N]*TR,abs(s)); lplot('Evolution Time','Signal','Gradient-Spoiled Signal vs TR time'); subplot(1,2,2); dispim(plotstate,0,0.2); xlabel('Echo'); ylabel('F(top) and Z(bottom) States'); title('F and Z states vs time'); phasediag = plotstate;
github
mribri999/MRSignalsSeqs-master
yrot.m
.m
MRSignalsSeqs-master/Matlab/yrot.m
532
utf_8
3c88674a611fed2de10652231470c9dd
% function [M] = yrot(angle) % % Function returns the rotation matrix M such that % y = Mx rotates a 1x3 cartesian vector about the y axis % by angle degrees, using a left-handed rotation. % % ======================== CVS Log Messages ======================== % $Log: yrot.m,v $ % Revision 1.2 2002/03/28 00:50:12 bah % Added log to source file % % % % ================================================================== function [M] = yrot(angle) c = cos(pi*angle/180); s = sin(pi*angle/180); M = [c 0 -s; 0 1 0; s 0 c];
github
mribri999/MRSignalsSeqs-master
gridmat.m
.m
MRSignalsSeqs-master/Matlab/gridmat.m
3,644
utf_8
afcd86ff08365e331425ce6448d70c75
% % Function [dat] = gridmat(ksp,kdat,dcf,gridsize) % % function performs gridding in Matlab. This is designed to % be a teaching function, and is not necessarily fast(!), but % reasonable for 2D gridding. % % INPUT: % ksp = k-space locations, kx+i*ky, normalized to |k|<=0.5, 1/pixel. % dat = complex data samples at k-space locations. % dcf = density compensation factors at k-space locations. % gridsize = size of grid (default is 256) % % OUTPUT: % dat = matrix of gridded data samples % % Many parameters come from Jackson 1991 here. % B.Hargreaves - October 2014. function [dat] = gridmat(ksp,kdat,dcf,gridsize) ksp=ksp(:); % Translate to 1D vector in case this is 2D dcf=dcf(:); kdat=kdat(:); kwid = 3; % Convolution kernel width kbbeta = 4.2; % Kaiser-bessel Beta % -- Allocate grid to accumulate data padgridsize = gridsize+4*kwid; % Padded grid to avoid errors padgrid = zeros(padgridsize,padgridsize); % Padded grid. % -- Sample Density correction kdat = kdat .* dcf; % Density correct (Simple!). % -- Use a lookup-table for grid kernel dr = 0.01; r = [0:dr:2*kwid]; % input to kaiser-bessel kerntab = kb(r,kwid,kbbeta); % kaiser-bessel function % -- Scale kspace points to grid units kxi = real(ksp)*(gridsize-1)+padgridsize/2; % Scale kx to grid units kyi = imag(ksp)*(gridsize-1)+padgridsize/2; % Scale ky to grid units % -- Round to nearest grid point ikxi = round(kxi); % Closest integer ikyi = round(kyi); % Closest integer % -- Make a small matrix, that completely encompasses the grid points % within the convolution kernel around a k-space sample -- sgridext = ceil(kwid/2)+1; % Size of small grid around sample [smaty,smatx] = meshgrid([-sgridext :sgridext ],[-sgridext :sgridext ]); sgrid = 0*smatx; % allocate % -- Go through k-space samples to do convolution for p = 1:length(ksp) %tt = sprintf('Gridding sample %d of %d',p,length(ksp)); %disp(tt); gridx = smatx + ikxi(p); % grid of 'closest' integer pts gridy = smaty + ikyi(p); % same in y % -- Distance index (array), to use for kernel lookup % Just calculating kernel value between ksp(p) and every point % in this small grid. dist = round(sqrt((gridx - kxi(p)).^2 + (gridy -kyi(p)).^2)/dr)+1; sgrid(:) = kdat(p) * kerntab(dist(:)); % Convolve sample w/ kernel % -- Add the 'small-grid' into the padded grid padgrid(ikxi(p)-sgridext:ikxi(p)+sgridext,ikyi(p)- ... sgridext:ikyi(p)+sgridext) = padgrid(ikxi(p)-sgridext: ... ikxi(p)+sgridext,ikyi(p)-sgridext:ikyi(p)+sgridext) + sgrid; end; % -- Extract the main grid from the padded grid. dat = padgrid(2*kwid+1:2*kwid+gridsize, 2*kwid+1:2*kwid+gridsize); % Kaiser-bessel Kernel % % function y = kb(u,w,beta) % % Computes the Kaiser-Bessel function used for gridding, namely % % y = f(u,w,beta) = I0 [ beta*sqrt(1-(2u/w)^2) ]/w % % where I0 is the zero-order modified Bessel function % of the first kind. % % INPUT: % u = vector of k-space locations for calculation. % w = width parameter - see Jackson et al. % beta = beta parameter - see Jackson et al. % % OUTPUT: % y = vector of Kaiser-Bessel values. % % SEE ALSO: % kbk2x.m % B. Hargreaves Oct, 2003. function y = kb(u,w,beta) if (nargin < 3) error('Not enough arguments -- 3 arguments required. '); end; if (length(w) > 1) error('w should be a single scalar value.'); end; y = 0*u; % Allocate space. uz = find(abs(u)< w/2); % Indices where u<w/2. if (length(uz) > 0) % Calculate y at indices uz. x = beta*sqrt(1-(2*u(uz)/w).^2); % Argument - see Jackson '91. y(uz) = besseli(0,x)./w; end; y = real(y); % Force to be real.
github
mribri999/MRSignalsSeqs-master
zrot.m
.m
MRSignalsSeqs-master/Matlab/zrot.m
530
utf_8
14f6f75ae9fdf7b82c76961f50fef6e7
% function [M] = zrot(angle) % % Function returns the rotation matrix M such that % y = Mx rotates a 1x3 cartesian vector about the z axis % by angle degrees, using a left-handed rotaton. % % ======================== CVS Log Messages ======================== % $Log: zrot.m,v $ % Revision 1.2 2002/03/28 00:50:12 bah % Added log to source file % % % % ================================================================== function [M] = zrot(angle) c = cos(pi*angle/180); s = sin(pi*angle/180); M = [c s 0; -s c 0; 0 0 1];
github
mribri999/MRSignalsSeqs-master
Rad229_fig_style.m
.m
MRSignalsSeqs-master/Matlab/Rad229_fig_style.m
3,234
utf_8
aae76bd3f690c606f3af2c0411448294
% This function makes some stylistic figure adjustments. % % SYNTAX: PAM_fig_style(handle,aspect,style,invert) % % EXAMPLE: PAM_fig_style(gcf,'rect',[],0); % % [email protected] (March 2021) for Rad229 function Rad229_fig_style(handle,aspect,style,invert) %% Define the defaults... if nargin<1, handle=gcf; end if nargin<2, aspect='rect'; end if nargin<3, style ='PSD'; end % Default is for a pulse sequence diagram (RF, Gx, Gy, Gz) if nargin<4, invert=0; end switch aspect case 'rect' width=6.5; height=4; case 'square' width=4; height=4; case 'tall' width=4; height=6.5; case 'wide' width=6.5; height=2; otherwise width=6.5; height=4; end if invert==0 bg_color =[0.9 0.9 0.9]; txt_color=[0.0 0.0 0.0]; else bg_color =[0.0 0.0 0.0]; txt_color=[0.9 0.9 0.9]; end font_name='Helvetica'; font_size=10; % format{1}='%6.1f'; % format{2}='%6.1f'; % format{3}='%6.1f'; format{1}='%6.1e'; format{2}='%6.1f'; format{3}='%6.1e'; %% Define the FIGURE properties set(handle,'Units','inches'); pos=get(handle,'position'); set(handle,'Position',[pos(1) pos(2) width height],... 'PaperSize',[width height],'PaperPosition',[0 0 width height],... 'InvertHardCopy','Off','MenuBar','None','Color',bg_color); cameratoolbar('hide'); txt=findobj(handle,'Type','text'); for n=1:numel(txt) % set(txt(n),'Color',[1 1 1],'FontSize',font_size); set(txt(n),'Color',txt_color,'FontSize',font_size); end %% Define the AXES properties a=findobj(handle,'Type','Axes'); txt=[]; lab=[]; ind=1; for n=1:length(a) % Adjust the font for each axis % set(a(n),'FontName',font_name,'FontSize',font_size,'FontWeight','Bold','Color',bg_color); set(a(n),'FontName',font_name,'FontSize',font_size,'Color',bg_color); set(a(n),'XColor',txt_color, 'YColor',txt_color,'ZColor',txt_color); % Collect the handles for each TEXT or LABEL object within the axis txt=[txt; findobj(a(n),'type','text')]; lab(ind)=get(a(n),'XLabel'); ind=ind+1; lab(ind)=get(a(n),'YLabel'); ind=ind+1; lab(ind)=get(a(n),'ZLabel'); ind=ind+1; lab(ind)=get(a(n),'Title'); ind=ind+1; if isfield(get(a(n)),'XTickLabel'), set(a(n),'XTickLabel',num2str(get(a(n),'XTick')',format{1}),'FontSize',font_size); end if isfield(get(a(n)),'YTickLabel'), set(a(n),'YTickLabel',num2str(get(a(n),'YTick')',format{2}),'FontSize',font_size); end if isfield(get(a(n)),'ZTickLabel'), set(a(n),'ZTickLabel',num2str(get(a(n),'ZTick')',format{3}),'FontSize',font_size); end if strcmp(style,'PSD') if n>1, set(a(n),'XTickLabel',[]); end % Turn off xlabels for RF, Gx, and Gy end end %% Set the defaults for the Labels and Titles for n=1:length(txt) % set(txt(n),'FontName',font_name,'FontSize',font_size,'FontWeight','Bold','Color',txt_color); set(txt(n),'FontName',font_name,'FontSize',font_size,'Color',txt_color); end for n=1:length(lab) % set(lab(n),'FontName',font_name,'FontSize',1.25*font_size,'FontWeight','Bold','Color',txt_color); set(lab(n),'FontName',font_name,'FontSize',1.25*font_size,'Color',txt_color); end % % If there are a lot of labels, then rotate them for legibility % if length(get(a(1),'XTickLabel'))>5 % set(gca,'XTickLabelRotation',45); % end return
github
mribri999/MRSignalsSeqs-master
mc2mr.m
.m
MRSignalsSeqs-master/Matlab/mc2mr.m
644
utf_8
be31adafa98db265334c4f2d3167b16d
% % function Mr = mc2mr(Mc) % % Transform magnetization of the % complex form [mx+i*my; mx-i*my; mz]. % to the rectilinear form [mx;my;mz]. to % INPUT: % 3xN array of rectilinear magnetization [mx;my;mz] % % OUTPUT: % 3xN array of complex magnetization [mx+i*my; mx-i*my; mz] % function Mr = mc2mr(Mc) % -- Check input is 3xN, add rows if not. sz = size(Mc); if (sz(1)~=3) error('Mc should have 3 rows'); end; T = [1,1,0;-i,i,0;0,0,2]/2; % Transformation Mr = T*Mc; % -- Alternative method %Mr = 0*Mc; % Allocate %Mr(1,:) = real((Mc(1,:)+Mc(2,:))/2); % 1st row %Mr(2,:) = imag((Mc(1,:)-Mc(2,:))/2); % 2nd row %Mr(3,:) = Mc(3,:);
github
mribri999/MRSignalsSeqs-master
dispangle.m
.m
MRSignalsSeqs-master/Matlab/dispangle.m
195
utf_8
40c4589aceb98b70dbc698989c7958d7
% % function dispangle(arr) % % Function displays the angle of the complex data % on a scale of black=-pi to white=pi. % function dispangle(arr) angarr = angle(arr)+pi; dispim(angarr,0,2*pi);
github
mribri999/MRSignalsSeqs-master
Rad229_Slice_Select_Demo.m
.m
MRSignalsSeqs-master/Matlab/Rad229_Slice_Select_Demo.m
6,903
utf_8
13d0c7ac57bccd934e9d43c4d9b1911a
%% Rad229_Slice_Select_Demo – Demonstrate designing both the RF pulse and gradient for slice selection. % % SYNTAX - [acq, sys, Gx, Gy, Gz, RF] = Rad229_Slice_Select_Demo(acq, RF); % % INPUTS - acq.dz = 10.0e-3; % Slice thickness [m] % % RF.alpha = 90; % RF flip angle [degrees] % RF.TBW = 6; % Time*bandwidth product [unitless] (relates to quality of RF pulse) % RF.dur = 2.5e-3; % RF pulse duration [seconds] % RF.apod = 0.46; % apod = 0 is non-apodized, apod = 0.5 is 'Hanning windowed', apod<0.5 is 'Hamming windowed' % % OUTPUTS – acq - A structure of the defined acquisition parameters. % sys - A structure of the defined MRI system parameters. % Gx - A structure with the Gx gradient parameters. % Gy - A structure with the Gy gradient parameters. % Gz - A structure with the Gz gradient parameters. % RF - A structure with the RF gradient parameters. % % [email protected] (March 2021) for Rad229 %% These questions can be used to further explore the code and concepts. Use the default settings as a starting point. % RF Questions: % 1.1) What is the highest possible flip angle without a B1 warning? % % 1.2) What is the highest possible TBW without a B1 warning? % % 1.3) A 180' pulse exceeds B1,max. What adjustments can be made to enable a 180'? % % 1.4) Design the shortest possible TBW = 8 refocusing pulse that doesn't exceed B1,max. % % 1.5) [Advanced] Make a plot of B1,max and Gz,max as a function of flip angle for the shortest % duration RF pulse. Use flip angles from 5 to 180 degrees. All pulses should be within ALL % default hardware limits. What do you observe about the shape of the curve and the hardware % limits encountered? % % Gradient Questions: % 2.1) What is the thinnest slice you can excite without a gradient warning? % % 2.2) What adjustments can be made to enable exciting a 0.1mm slice? % % 2.3) [Advanced] Demonstrate the effectiveness of the post-excitation refocusing gradient. % % 2.4) [Advanced] What is the thinnest slice you can excite with a 10' flip angle % 2ms TBW=6 RF pulse (within hardware limits)? What is the shortest duration you can % make this pulse? % % Slice Selection Questions % 3.1) [Advanced] Compare the slice profiles for a 2ms TBW=4 and TBW=16 RF pulse. What differences % do you observe? % % 3.2) [Advanced] Plot the slice profile with and without apodization. % What differences do you observe? % % Non-1H Imaging Questions (sys.gamma_bar=10.7084e6 [Hz/T]): % 4.1) What happens if the default pulse is used to excite 13C? Why? % % 4.2) What else needs to change about the RF pulse to excite 13C? % % 4.3) [Advanced] Design an TBW=10 RF pulse to refocus 13C for a 10mm slice within hardware % limits. If you were to build an MRI system for 13C imaging would you prefer an increase % in G_max or B1_max? Why? function [acq, sys, Gx, Gy, Gz, RF] = Rad229_Slice_Select_Demo(acq, RF) %% Define MRI system constants sys = Rad229_MRI_sys_config; % sys.gamma_bar=10.7084e6; % Gyromagnetic ratio for 11C %% Define the RF pulse to excite a slice if nargin == 0 acq.dz = 10.0e-3; % Slice thickness [m] RF.alpha = 90; % RF flip angle [degrees] RF.TBW = 6; % Time*bandwidth product [unitless] (relates to quality of RF pulse) RF.dur = 2.5e-3; % RF pulse duration [seconds] RF.apod = 0.46; % apod = 0 is non-apodized, apod = 0.5 is 'Hanning windowed', apod<0.5 is 'Hamming windowed' end % Parameters calculated from the INPUTS RF.BW = RF.TBW ./ RF.dur; % RF bandwidth [Hz] RF.N = ceil( RF.dur / sys.dt ); % Number of points in the pulse RF.t = linspace( -1, 1, RF.N )'; % Normalized time vector (duration is 1) %% Design the RF pulse (waveform) RF.apod_fxn = ( 1 - RF.apod ) + RF.apod * cos( pi * RF.t ); % RF pulse apodization function RF.B1 = sinc( RF.t * RF.TBW / 2 ) .* RF.apod_fxn; % Apodized (windowed) RF SINC pulse RF.B1 = RF.B1 ./ sum( RF.B1 ); % Normalize to unit area RF.B1 = ( RF.alpha * pi/180 ) * RF.B1 / ( 2 * pi * sys.gamma_bar * sys.dt); % Scale for flip angle and real amplitude if max( RF.B1 ) > sys.B1max, warning('RF.B1 exceeds sys.B1max'); end %% Design the gradient to excite a slice Gz.G_amp = RF.BW / ( sys.gamma_bar * acq.dz ); % Gradient amplitude [T/m] if max(Gz.G_amp)>sys.G_max, warning('Gz.G_amp exceeds sys.G_max'); end Gz.G_plat = Gz.G_amp * ones( size( RF.B1 ) ); % Gradient amplitude [T/m] Gz.dG = sys.S_max * sys.dt; % Slice-select gradient incremental gradient step [T/m] Gz.G_ramp = ( 0 : Gz.dG : Gz.G_amp )'; % Readout gradient ramp [T/m] % if max(Gz.G_ramp) ~= Gz.G_amp, warning('Gz.G_ramp does not reach target value of Gz.G_amp'); end Gz.t_ramp = sys.dt * numel(Gz.G_ramp); % Gz.t_ramp = sys.G_max / sys.S_max; % Ramp time [s] % if ~isinteger(Gz.t_ramp / sys.dt), warning('Gz.t_ramp is NOT an integer number of sys.dt!'); end Gz.G = [0; Gz.G_ramp; Gz.G_plat; flipud(Gz.G_ramp)]; %% Design the post-excitation slice-select refocusing gradient (SSRG) Gz.M0 = sum( Gz.G * sys.dt ); % The SSRG needs to have half this area [T*s/m] Gz.G_ssrg_amp = -sys.G_max; % The SSRG should use the maximum hardware to be fast [T/m] Gz.G_ssrg_ramp_time = sys.G_max ./ sys.S_max; % The SSRG should ramp as fast as possible Gz.t_ssrg = ( ( Gz.M0 / 2 ) - 2 * (0.5) * Gz.G_ssrg_ramp_time * abs(Gz.G_ssrg_amp) ) / abs( Gz.G_ssrg_amp ); % Duration of pre-phasing gradient plateau [s] % The SSGR gradient needs half the moment, the plateau duration needs to account for moments from the two ramps too. tmp = 0 : sys.dt : Gz.t_ssrg; % Refocusing gradient gradient time vector [s] Gz.G_ssrg_ramp = ( 0 : -Gz.dG : Gz.G_ssrg_amp )'; % Refocusing gradient ramp waveform [T/m] Gz.G_ssrg_plat = ones( size(tmp') ) * Gz.G_ssrg_amp; % Refocusing gradient plateau waveforms [T/m] % tmp_M0 = 2 * sum( [ Gz.G_ssrg_ramp; Gz.G_ssrg_plat; flipud(Gz.G_ssrg_ramp) ] * sys.dt ) %% Composite the RF and Gradient waveforms and plot them Gz.G = [0; Gz.G_ramp; Gz.G_plat; flipud(Gz.G_ramp); Gz.G_ssrg_ramp; Gz.G_ssrg_plat; flipud(Gz.G_ssrg_ramp); 0]; % Gradient amplitude [T/m] % Timing corrections needed to center RF pulse delay = zeros( length( Gz.G_ramp ), 1 ); % Delay RF start to end of gradient ramp pad = zeros( length( [Gz.G_ssrg_ramp; Gz.G_ssrg_plat; Gz.G_ssrg_ramp; Gz.G_ramp] ), 1 ); RF.B1 = [0; delay; RF.B1; pad; 0]; % B1 amplitude [T] Gx.G = zeros ( size ( Gz.G ) ); % Gradient amplitude [T/m] Gy.G = zeros ( size ( Gz.G ) ); % Gradient amplitude [T/m] %% Plot the final waveforms % Rad229_PSD_fig(1e6*RF.B1, Gx.G, Gy.G, Gz.G, sys.dt); return
github
mribri999/MRSignalsSeqs-master
ksquare.m
.m
MRSignalsSeqs-master/Matlab/ksquare.m
1,379
utf_8
efb55f2285247497b43ce655a8c5a1d2
% function kdata = ksquare(center,swidth,kloc,tsamp,df) % % Function generates k-space data for a square % with given center location (cm) and swidth length (cm) % at the given k-space locations, with the given sampling period % and off-resonance (Hz) % % INPUT: % center,swidth = describes square, in cm % center can be a list for more squares % kloc = array of kx+i*ky, Nsamples x Ninterleaves (cm^-1) % tsamp = time between points (resets each interleaf) (sec) % df = off-resonance (Hz) % OUTPUT: % Data samples, same size as kloc % function kdata = ksquare(center,swidth,kloc,tsamp,df) if (nargin < 5) df = 0; end; % on resonance if (nargin < 4) tsamp = 0.000004; end; % 4us if (nargin < 3) [kx,ky] = meshgrid([-128:127]/128*5,[-128:127]/128*5); kloc = kx+i*ky; end; if (nargin < 2) swidth = 1.9; end; if (nargin < 1) center = 0; end; % -- Define data with a sinc sdata = swidth*sinc(swidth*real(kloc)).*sinc(swidth*imag(kloc)); kdata = 0*sdata; % -- Add linear phase for shift of center for q=1:length(center) thisk = exp(i*2*pi*real(center(q))*real(kloc)).*sdata; thisk = exp(i*2*pi*imag(center(q))*imag(kloc)).*thisk; kdata = kdata + thisk; end; % -- Add linear phase for off-resonance. if (nargin > 4) ph = exp(2*i*pi*tsamp*[1:size(kloc,1)]*df); % phase due to off-resonance. kdata = diag(ph)*kdata; % off-res induced phase end;
github
mribri999/MRSignalsSeqs-master
mr2mc.m
.m
MRSignalsSeqs-master/Matlab/mr2mc.m
732
utf_8
7dec1eae20e3c60b49c89281c763e1aa
% % function Mc = mr2mc(Mr) % % Transform magnetization of the form [mx;my;mz] to % complex form [mx+i*my; mx-i*my; mz]. % % INPUT: % 3xN array of rectilinear magnetization [mx;my;mz] % (if 1xN or 2xN, will zero-pad) % % OUTPUT: % 3xN array of complex magnetization [mx+i*my; mx-i*my; mz] % function Mc = mr2mc(Mr) % -- Check input is 3xN, add rows if not. sz = size(Mr); if (sz(1)~=3) Mr(3,1)=0; Mr=Mr(1:3,:); disp('mr2mc.m: Warning input is not 3 rows - zero-filling and cropping'); end; T = [1,i,0;1,-i,0;0,0,1]; % Transformation Mr to Mc Mc = T*Mr; % -- Alternative method Mc = 0*Mr; % Allocate Mc(1,:) = Mr(1,:)+i*Mr(2,:); % 1st row Mc(2,:) = Mr(1,:)-i*Mr(2,:); % 2nd row Mc(3,:) = Mr(3,:); % mz is the same.
github
mribri999/MRSignalsSeqs-master
bssfp.m
.m
MRSignalsSeqs-master/Matlab/bssfp.m
507
utf_8
96744d0b445a59428b227ad9fc71605f
% function s = bssfp(a,TR,TE,T1,T2,df) % % Calculate the bSSFP signal as a function of parameters % % a = flip angle in degrees % Times in ms, df in Hz function s = bssfp(flip,TR,TE,T1,T2,df) E1 = exp(-TR/T1); E2 = exp(-TR/T2); flip = flip*pi/180; phi = 2*pi*df*TR/1000; % Precession over TR (rad) sf = sin(flip); cf = cos(flip); a = -(1-E1)*E2*sf; b = (1-E1)*sf; c = E2*(E1-1)*(1+cf); d = 1-E1*cf-(E1-cf)*E2^2; s0 = (a*exp(i*phi)+b) / (c*cos(phi)+d); s = s0*exp(-TE/T2)*exp(-i*phi*(TE/TR));
github
mribri999/MRSignalsSeqs-master
nift.m
.m
MRSignalsSeqs-master/Matlab/nift.m
247
utf_8
b42635fa9b515225c2f86820ee575a50
% function im = nift(dat) % % Function does a centered, normalized inverse 2DFT of the data: % % im = ifftshift(ifft2(ifftshift(dat))) * sqrt(length(dat(:))); function im = nft(dat) im = ifftshift(ifft2(ifftshift(dat))) * sqrt(length(dat(:)));
github
mribri999/MRSignalsSeqs-master
whirl.m
.m
MRSignalsSeqs-master/Matlab/whirl.m
4,577
utf_8
259921edea3503ca1aeec88927628fc4
% % function [g] = whirl(N,res,fov) % % Function designs a WHIRL trajectory, as presented by J. Pipe. % WHIRL should be slightly faster than spiral and TWIRL, as the % maximum gradient amplitude is reached more quickly. % % INPUT: % N = # interleaves. % res = resolution in cm (NOT mm). % fov = field-of-view in cm. % dT = Sampling time (default=.000004s) % % OUTPUT: % g = gradient waveform. % % % % B. Hargreaves, Oct 2002. % % Note 1: % This is sensitive to dT, which bothers me. Sampling % at higher rates, seems to work, so we use an oversampling % factor here of 8. % See James Pipe, MRM 42(4):714-720, October 1999. % % % =============== CVS Log Messages ========================== % This file is maintained in CVS version control. % % $Log: whirl.m,v $ % Revision 1.2 2003/02/11 19:41:55 brian % Added a bunch of signal simulation files. % Not quite sure what the changes to other % files were here. % % Revision 1.1 2002/10/07 22:20:45 brian % WHIRL: Winding Hybrid Interleaved Lines. % % % =========================================================== function [g,g1,g2,g3] = whirl(N,res,fov,Ts) if (nargin < 4) Ts=.000004; end; upsamp=16; % Upsample during design. gmax = 3.9; % Max grad amp, G/cm. S = 14500; % Max slew rate, G/cm/s dT = Ts/upsamp; % Sampling rate, seconds kmax = .5/res; % maximum k-space radius. gamma = 4258; % gamma, in rads/G. delta = N/2/pi/fov; % delta, as defined in Pipe. r1 = 1/sqrt(5)*delta; % r1, end-radius of stage 1 as in Pipe. r2 = 3/sqrt(5)*delta; % r2, end-radius of stage 2 as in Pipe. tt = sprintf('Delta = %g cm^(-1)',delta); disp(tt); % =========================== Stage 1 ============================ Gc = sqrt(2*S*r1/gamma); % Pipe, eq. 26. g = [0:S*dT:Gc].'; % Define g during ramp. k = cumsum(g)*gamma*dT; % Define k during ramp. ng = length(g); % Number of points in ramp. ng1=ng; tt=sprintf('End stage 1: G = %g G/cm and kr= %g cm^(-1)',max(abs(g(:))),max(abs(k))); disp(tt); % =========================== Stage 2 ============================ % --- G, r, kk and phi for stages 2 and 3, with values at end of stage 1. G = g(end); % G(t) as defined in Pipe. r = k(end); % r(t), k-space radius as defined in Pipe. kk = k(end); % kk is just the current value of k(t) in Pipe paper. phi = 0; % phi(t) as defined in Pipe. % --- Pre-allocate memory to speed up the loop ---- maxng = 10000*upsamp; g(maxng)=0; k(maxng)=0; Grec=g; Grec(10000)=0; phirec = 0*Grec; % --- Circular bridge between trajectories ---- % % G(t) is constant. phi'(t) is constant. % done=0; dphi = S/abs(G)*dT; % Pipe, eq. 15. We use the G that we got to in % Stage 1 which should be less than, % but approach the Gc in Pipe. while (r < r2) ng = ng+1; % update # gradient points. phi = phi+dphi; % update phi. g(ng) = G*exp(i*phi); % update g(t). kk = kk+g(ng)*dT*gamma; % update k k(ng) = kk; % record k(t). r = abs(kk); % update k-space radius. end; ng2=ng; tt=sprintf('End stage 2: G = %g G/cm and kr= %g cm^(-1)',max(abs(g(:))),max(abs(k))); disp(tt); % =========================== Stage 3 ============================ dG=0; %maxng = ng; % STOP, if testing!! while (r<kmax) & (ng < maxng) % G'(t) and phi'(t) are defined in terms of each other, % so we'll take a guess at r and G in the middle of the % sample interval, extrapolating from the last sample. Gapp=G; % approx. G in center. r=abs(k(ng) + gamma*g(ng)*dT/2); % approx. r in center (using k and G). ng = ng+1; % update # gradient points. % dphi = phi'(t)*dT dphi = gamma*Gapp/sqrt(r^2-delta^2)*dT; % Pipe, eq. 14. dG = sqrt(S^2-(dphi/dT*Gapp)^2)*dT; % Pipe, eq. 27. G = G+dG; % update G if (G>=gmax) G=gmax; % constrain G. dG=0; % for approx. G above. end; phi = phi+dphi; % update phi. g(ng) = G*exp(i*phi); % update g(t). Pipe Eq 2 kk = kk+g(ng)*dT*gamma; % update k k(ng) = kk; % record k(t). r = abs(kk); % update k-space radius. if (ng >= maxng) tt=sprintf('Maximum number of points, %d, reached.',maxng); disp(tt); end; end; ng3=ng; % ======================== Finished! ============================ k = k(1:upsamp:ng); g = g(1:upsamp:ng); t = [1:length(g)].'*Ts; g1=g(1:round(ng1/upsamp)); g2=g(round(ng1/upsamp)+1:round(ng2/upsamp)); g3=g(round(ng2/upsamp)+1:length(g)); % ------ Plot, for testing. ----------- if (1==1) figure(1); plotgradinfo(g(:),Ts); figure(2); for q=1:N plot(k*exp(2*pi*i*q/N)); hold on; end; hold off; axis equal; title('K-space trajectory...'); end;
github
mribri999/MRSignalsSeqs-master
xrot.m
.m
MRSignalsSeqs-master/Matlab/xrot.m
531
utf_8
fc2b5f31aff687cb23ec7bf18b369dbb
% function [M] = xrot(angle) % % Function returns the rotation matrix M such that % y = Mx rotates a 1x3 cartesian vector about the x axis % by angle degrees, using a left-handed rotation. % % ======================== CVS Log Messages ======================== % $Log: xrot.m,v $ % Revision 1.2 2002/03/28 00:50:12 bah % Added log to source file % % % % ================================================================== function [M] = xrot(angle) c = cos(pi*angle/180); s = sin(pi*angle/180); M = [1 0 0; 0 c s; 0 -s c];
github
mribri999/MRSignalsSeqs-master
grid_phantom.m
.m
MRSignalsSeqs-master/Matlab/grid_phantom.m
1,342
utf_8
c49a29850f1fa9463b4ce8f67569a6a6
% This function creates a simple grid-pattern phantom. % % SYNTAX - grid_im = grid_phantom(imsize) % % INPUT - imsize - integer that defines square matrix size % % OUTPUT - grid_im - Image of a circular phantom with a grid pattern % % Original code creation by Michael Loecher. [email protected] (April 2020 for Rad229) function grid_im = grid_phantom(imsize) if nargin == 0, imsize = 256; end phantom_rad = 0.46; phantom_mag = 0.9; comb_os = 20; comb_cutoff = -.8; % Makes initial comb function, between -1 and 1, smaller is thinner lines blur_mod = 5; grid_freq = 20; % How many lines in the total image (this will get cropped) grid_crop = 0.5; % Crop radius of grid (>0.5 = no crop) im_background = zeros(imsize); [XX, YY] = meshgrid( 1 : imsize , 1 : imsize); XX = (XX - imsize / 2.0) / imsize; YY = (YY - imsize / 2.0) / imsize; RR = sqrt(XX.^2 + YY.^2); im_background(RR < phantom_rad) = phantom_mag; Ncomb = imsize*comb_os; cos_comb = cos(2.0*pi.*grid_freq.*linspace(-0.5, 0.5, Ncomb)); comb = ones(1, Ncomb); comb(cos_comb < comb_cutoff) = 0.0; comb = smoothdata(comb,'gaussian',blur_mod*comb_os); comb = comb(1:comb_os:end); comb = comb'*comb; grid_mod = comb; grid_mod(abs(XX) > grid_crop) = 1.0; grid_mod(abs(YY) > grid_crop) = 1.0; grid_im = im_background.*grid_mod; end
github
mribri999/MRSignalsSeqs-master
get_stim.m
.m
MRSignalsSeqs-master/Matlab/get_stim.m
1,229
utf_8
d421c1a26df13cf49d1e908f84edaba7
% GET_STIM Summary of this function goes here % % Reference: "Peripheral Nerve Stimulation-Optimal GradientWaveform Design" % Rolf F. Schulte1 and Ralph Noeske % https://onlinelibrary.wiley.com/doi/epdf/10.1002/mrm.25440 % % Detailed explanation goes here... % % [email protected] (March 2020) for Rad229 % [email protected] (March 2021) for Rad229 - Minor updates function stim_out = get_stim( G, dt ) %% Define the PNS model coefficients L_grad = 0.333; % Effective gradient coil length [m] (sometimes called alpha) r = 20.0; % Rheobase [T/s] {gradient coild specific} % r = 23.4; c = 334e-6; % Chronaxie time [s] {gradient coild specific} Smin = r / L_grad; % Threshold at which 50% of people are stimulated %% coeff = zeros( numel(G) , 1); for i = 1:(numel(G)) coeff(i) = ( c / ((c + dt * ( numel(G) - 1 ) - dt * ( i - 1 ) ) ^ 2.0 ) / Smin ); end stim_out = zeros(numel(G), 1); for j = 1:(numel(G)-2) % fprintf('%d \n', j); ss = 0; for i = 1:(j+1) % fprintf('%d %d %d %d %d\n', j, (numel(G)-1), i, (j+1), numel(coeff)-j+i-1); % fprintf('-----\n'); ss = ss + coeff( numel(coeff)-j+i-1 ) * (G(i+1)-G(i)); end stim_out(j) = ss; end end
github
mribri999/MRSignalsSeqs-master
epg_spins2FZ.m
.m
MRSignalsSeqs-master/Matlab/epg_spins2FZ.m
1,065
utf_8
1e07562d41c0a6e336e15c251927765f
%function [FpFmZ] = epg_spins2FZ(M,trim) % % Function converts a 3xQ array of vectors to EPG states F+,F- and Z, % with Q representing the dimension across a voxel. Note that it % is not realistic to have more than floor(Q/2)+1 states, since M % is real-valued and the F states can be complex. % % INPUT: % M = [Mx My Mz].' representing magnetization vectors. % trim = threshold to trim, 0 for none (default = 0.01) % % OUTPUT: % FpFmZ = F,Z states, 3xQ vector where there are Q states, % where rows represent F+, F- and Z states starting at 0. % function [FpFmZ] = epg_spins2FZ(M,trim) if (size(M,1)~=3) error('EPG state must be 3xQ vector'); end; if (nargin < 2) trim=0.01; end; Q = size(M,2); % -- The following are Eqs. 2-4 from Wiegel 2010: Fp = fft(M(1,:)+i*M(2,:)); % FFT to get F+ states. Fm = fft(M(1,:)-i*M(2,:)); % FFT to get F- states. Z = fft(M(3,:)); % FFT to get Z. FpFmZ = [Fp;Fm;Z]; % Combine into 3xQ matrix FpFmZ = FpFmZ(:,1:floor(Q/2)+1); % Cut off redundant states. FpFmZ = epg_trim([FpFmZ],trim); % Trim near-zero states.
github
mribri999/MRSignalsSeqs-master
nft.m
.m
MRSignalsSeqs-master/Matlab/nft.m
230
utf_8
5fe423f4805f1a08b5eaf72ee8b204d1
% function im = nft(dat) % % Function does a centered, normalized 2DFT of the data: % % im = fftshift(fft2(fftshift(dat)))/sqrt(length(dat(:))); function im = nft(dat) im = fftshift(fft2(fftshift(dat))) / sqrt(length(dat(:)));
github
mribri999/MRSignalsSeqs-master
epg_grad.m
.m
MRSignalsSeqs-master/Matlab/epg_grad.m
874
utf_8
39dd6f49ede899ea6a221825e7914cf9
% %function [FpFmZ] = epg_grad(FpFmZ,noadd) % Propagate EPG states through a "unit" gradient. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % noadd = 1 to NOT add any higher-order states - assume % that they just go to zero. Be careful - this % speeds up simulations, but may compromise accuracy! % % OUTPUT: % Updated FpFmZ state. % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. function [FpFmZ] = epg_grad(FpFmZ,noadd) if (nargin < 2) noadd=0; end; % Add by default. % Gradient does not affect the Z states. if (noadd==0) FpFmZ = [FpFmZ [0;0;0]]; % Add higher dephased state. end; FpFmZ(1,:) = circshift(FpFmZ(1,:),[0 1]); % Shift Fp states. FpFmZ(2,:) = circshift(FpFmZ(2,:),[0 -1]); % Shift Fm states. FpFmZ(2,end)=0; % Zero highest Fm state. FpFmZ(1,1) = conj(FpFmZ(2,1)); % Fill in lowest Fp state.
github
mribri999/MRSignalsSeqs-master
relax.m
.m
MRSignalsSeqs-master/Matlab/relax.m
498
utf_8
03fa5fcf79e37d4cd0722187418b6749
% % function [A,B] = relax(T,T1,T2,combine) % % Function returns A matrix and B vector for % relaxation over time T, with relaxation times T1 and T2, % such that m' = A*m+B where m and m' are the magnetization before % and after the relaxation. % % If combine==1 and one output, then output is [A B] (3x4) % % function [A,B] = relax(T,T1,T2,combine) E1 = exp(-T/T1); E2 = exp(-T/T2); A = diag([E2 E2 E1]); B = [0;0;1-E1]; if ((nargin > 3) && (nargout < 2) && (combine==1)) A = [A B]; end;
github
mribri999/MRSignalsSeqs-master
Rad229_MRI_sys_config.m
.m
MRSignalsSeqs-master/Matlab/Rad229_MRI_sys_config.m
1,873
utf_8
7b0d7a24f8a88c08915cfcc5172a5a0d
%% This function defines some default parameters and constants for an MRI system. % The MRI hardware is designed to be whimpy. This is helpful to better see the gradient % waveforms and to make the gradient waveform timing a little easier, thereby avoiding % some timing errors (maybe). % % [email protected] (March 2021) for Rad229 function sys = Rad229_MRI_sys_config %% Default Parameters (don't change these!): % These are the default parameters that should be used to define and/or % reset the system. They are chosen specifically to help with making % certain phenomena more apparent. % % sys.B0 = 3.0; sys.B0_units = 'T'; % Main (B0) field strength [T] % sys.B1max = 25e-6; sys.B1max_units = 'T'; % RF (B1) maximum field strength [T] % sys.G_max = 10e-3; sys.G_max_unts = 'T/m'; % Gradient maximum [T/m] % sys.S_max = 100; sys.S_max_units = 'T/m/s'; % Slewrate maximum [T/m/s] % sys.dt = 10e-6; sys.dt_units = 's'; % Waveform time steps (i.e. "raster time") [s] % sys.gamma_bar=42.577478518e6; sys.gamma_bar_units = 'Hz/T'; % 1H gyromagnetic ratio [Hz/T] %% Define the MRI system configuration sys.B0 = 3.0; sys.B0_units = 'T'; % Main (B0) field strength [T] sys.B1max = 25e-6; sys.B1max_units = 'T'; % RF (B1) maximum field strength [T] sys.G_max = 10e-3; sys.G_max_unts = 'T/m'; % Gradient maximum [T/m] sys.S_max = 100; sys.S_max_units = 'T/m/s'; % Slewrate maximum [T/m/s] sys.dt = 10e-6; sys.dt_units = 's'; % Waveform time steps (i.e. "raster time") [s] sys.gamma_bar=42.577478518e6; sys.gamma_bar_units = 'Hz/T'; % 1H gyromagnetic ratio [Hz/T] % sys.gamma_bar=10.7084e6; sys.gamma_bar_units = 'Hz/T'; % 13C gyromagnetic ratio [Hz/T]
github
mribri999/MRSignalsSeqs-master
epg_stim.m
.m
MRSignalsSeqs-master/Matlab/epg_stim.m
574
utf_8
41fc7a7ad9cfaa2413f950131fccd64c
%function [S,P] = epg_stim(flips) % % Function uses EPG simulation to quickly calculate % the signal from a stimulated echo sequence defined % as % flip - gradient - flip - gradient ... flip - gradient % % Relaxation is neglected, and flip angles (vector) are in degrees % % Example Try: fplot('abs(epg_stim([x x x]))',[0,120]); % function [S,P] = epg_stim_calc(flips) P = [0 0 1]'; % Equilibrium for k=1:length(flips) P = epg_rf(P,flips(k)*pi/180,pi/2); % RF pulse P = epg_grelax(P,1,.2,0,1,0,1); % Gradient end; S = P(1,1); % Return signal from F0
github
mribri999/MRSignalsSeqs-master
plotc.m
.m
MRSignalsSeqs-master/Matlab/plotc.m
474
utf_8
ab1bc5ee7fc1584f5431e2b9f109ec3b
% plotc(x,y) % % plots the complex vector y as a function of x. % plots real (blue --) ,imag (red :) and magnitude (yellow -). % returns the row as a vector. function plotc(x,y); if (nargin <2) y = x; x = 1:max(size(y)); % color... plot(x,real(y),'b--',x,imag(y),'r:',x,abs(y),'y-'); plot(x,real(y),'b--',x,imag(y),'r:',x,abs(y),'k-'); else % color... plot(x,real(y),'b--',x,imag(y),'r:',x,abs(y),'y-'); plot(x,real(y),'b--',x,imag(y),'r:',x,abs(y),'k-'); end;
github
mribri999/MRSignalsSeqs-master
epg_show_grelax.m
.m
MRSignalsSeqs-master/Matlab/epg_show_grelax.m
1,639
utf_8
6ba59e021fa637fec91e98bce725d7ca
%function [FpFmZ] = epg_show_grelax(FpFmZ,noadd,T1,T2,T,Nanim,showtwists,shiftfs) % % Propagate EPG states through a "unit" gradient, with relaxation % and animate. % NOTE: This is a bit contrived, as the magnetization is not % really all in F0 (say) as it dephases. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % noadd = 1 to NOT add any higher-order states - assume % that they just go to zero. Be careful - this % speeds up simulations, but may compromise accuracy! % T1,T2 = Relaxation times (same as T) % T = Time interval (same as T1,T2) % Nanim = Number of frames % showtwists = 1 to show twist, 0 to have all spins from origin % % OUTPUT: % Updated FpFmZ state. % % SEE ALSO: % epg_grad % % B.Hargreaves. % function [FpFmZ] = epg_show_grelax(FpFmZ,noadd,T1,T2,T,Nanim,showtwists,shiftfs) if (nargin < 1 || length(FpFmZ)<1) FpFmZ = [.3 .5 ;.3 .5 ; .2 .2 ]; end; if (nargin < 2 || length(noadd)<1) noadd=0; end; % Add by default. if (nargin < 3 || length(T1)<1) T1 = 1; end; if (nargin < 4 || length(T2)<1) T2 = 0.2; end; if (nargin < 5 || length(T)<1) T = .2; end; if (nargin < 6 || length(Nanim)<1) Nanim=48; end; if (nargin < 7 || length(showtwists)<1) showtwists=0; end; if (nargin < 8 || length(shiftfs)<1) shiftfs=0; end; [m,n] = size(FpFmZ); if (m<3) FpFmZ(3,1)=0; end; % -- Added for animation... FZ = FpFmZ; for k=1:Nanim FZ = epg_relax(FZ,T1,T2,T/Nanim); epg_show(FZ(1:m,:),k/Nanim,[],[],showtwists,shiftfs); drawnow; end; % -- Actually DO epg_grad and relaxation! FpFmZ = epg_grad(FpFmZ,noadd); FpFmZ = epg_relax(FpFmZ,T1,T2,T);
github
mribri999/MRSignalsSeqs-master
absplit.m
.m
MRSignalsSeqs-master/Matlab/absplit.m
480
utf_8
a41abadf15aa5b974cd5558744fbe139
% function [Ai,Bi] = absplit(n,A,B) % % Function 'splits' a propagation A,B into sub-matrices so that % n 'propagations' of M'=Ai*M+Bi is the same as M'=A*M+B. % % This is useful for animating an operation, where you want % to split it into many frames. See abanim.m % function [Ai,Bi] = absplit(n,A,B) if (nargin < 3) B=[0;0;0]; end; Ai = A^(1/n); % Multiplications are just nth root Aprop = inv(eye(3)-Ai)* (eye(3)-Ai^n); % Series formula for sum A^k Bi = inv(Aprop)*B;
github
mribri999/MRSignalsSeqs-master
Rad229_Phase_Encode_Demo.m
.m
MRSignalsSeqs-master/Matlab/Rad229_Phase_Encode_Demo.m
5,438
utf_8
e3b51110b8110bc45a5626b8874afec5
%% Rad229_Phase_Encode_Demo – Demonstrate phase encode gradient design for imaging. % % Recall, dy = FOVy / Ny . In general, the user can usually pick FOVy and Ny on the scanner. % dky = 1 / FOVy = gamma_bar * dG * t_PE . The k-space step size defines the FOV. % % Note: See code for variable definitions and units % % SYNTAX - [acq, sys, Gx, Gy, Gz, RF] = Rad229_Phase_Encode_Demo(acq) % % INPUTS - acq.FOVy = 100e-3; % Field-of-view along y-direction [m] % acq.Ny = 33; % Number of pixels to discretize FOVy [#] % acq.y_pos = linspace(-acq.FOVy/2, acq.FOVy/2, acq.Ny); % Define the pixel locations [m] % % OUTPUTS – acq - A structure of the defined acquisition parameters. % sys - A structure of the defined MRI system parameters. % Gx - A structure with the Gx gradient parameters. % Gy - A structure with the Gy gradient parameters. % Gz - A structure with the Gz gradient parameters. % RF - A structure with the RF gradient parameters. % % [email protected] (March 2021) for Rad229 %% These questions can be used to further explore the code and concepts. % Phase Encode Questions: % 1) How many cycles are there across the FOV when using the maximum phase encoding gradient? % Does this satisfy Nyquist? % % 2) How many cycles per pixel? Decrease the resolution and answer the same questions. Discuss. % % 3) What happens to the duration of the phase encoding gradients for higher resolution imaging? % % 4) [Advanced] Why are the phase encoding gradient timing warnings important? If there is a % warning, then what would be the artifact? What causes the possible timing error? % % 5) [Advanced] Incorporate a FOV shift in the PE direction. Hint: See Bernstein p. 264 function [acq, sys, Gx, Gy, Gz, RF] = Rad229_Phase_Encode_Demo(acq) %% Define MRI system constants sys = Rad229_MRI_sys_config; %% Define Phase Encoding Variables - Most scanners are configured for the user to select the FOV and % matrix size for encoding, which then defines the spatial resolution. if nargin == 0 acq.FOVy = 100e-3; % Field-of-view along y-direction [m] acq.Ny = 33; % Number of pixels to discretize FOVy [#] % acq.Ny = 65; % Number of pixels to discretize FOVy [#] acq.y_pos = linspace(-acq.FOVy/2, acq.FOVy/2, acq.Ny); % Define the pixel locations [m] end acq.dy = acq.FOVy / acq.Ny; % Pixel dimension along y-direction [m] %% Design the phase encode gradients Gy.dky = 1 / acq.FOVy; % Spatial frequency increment [cycle/m] Gy.ky_max = ( (acq.Ny-1) / 2 ) * Gy.dky; % Maximum phase encode spatial frequency [cycle/m] % Phase encode gradient timing [ramp, then plateau] Gy.t_ramp = sys.G_max / sys.S_max; % Ramp time [s] % if ~isinteger(Gy.t_ramp / sys.dt), warning('Gy.t_ramp integer number of sys.dt!'); end % Recall, k = gamma_bar * G * t Gy.t_plat = ( Gy.ky_max / (sys.gamma_bar * sys.G_max) ) - Gy.t_ramp; % Plateau time [s] % if ~isinteger(Gy.t_plat / sys.dt), warning('Gy.t_plat integer number of sys.dt!'); end if Gy.t_plat<0, error('Gy.t_plat is NEGATIVE!'); end % Phase encode gradient waveform design Gy.dG = Gy.dky / (sys.gamma_bar * (Gy.t_ramp + Gy.t_plat) ); % Gradient amplitude increment [T/m] Gy.G_steps = -sys.G_max : Gy.dG : sys.G_max; % Phase encode gradient amplitudes [T/m] tmp = 0 : sys.dt : Gy.t_plat; % Phase encode gradient time vector [s] Gy.G_plat = ones( size(tmp') ) * Gy.G_steps; % Phase encode plateau waveforms [T/m] % Design each phase encoding step for n = 1 : acq.Ny m = Gy.t_ramp / sys.dt; % Number of raster steps along phase encode ramp grad_step = abs( Gy.G_steps(n) / m ) + eps; % Phase encode gradient increment (unique for each PE step) Gy.G_ramp(:,n) = sign(Gy.G_steps(n)) * ( 0 : grad_step : abs( Gy.G_steps(n) ) ); % Design the precise gradient raster amplitudes (bookkeeping to get sign right) end % Composite the first ramp, plateau, and last ramp Gy.G = [Gy.G_ramp; Gy.G_plat; flipud(Gy.G_ramp) ]; %% Plot the waveforms and visualize the encoding per FOV and per pixel % Define a subset of PE steps to examine (cubic sampling looks good...) m = (acq.Ny-1) / 2; % PE_IND = unique(round(m * ( linspace(-m, m, 7) ).^3 / (m^3) + (m+1) ) ); % Overly complicated... PE_IND = 1 : 4 : acq.Ny; % Used during plotting to show a subset of PE steps % Define the RF and gradient waveforms RF.B1 = zeros( size(Gy.G , 1) , 1 ); Gx.G = zeros( size(Gy.G , 1) , 1 ); Gy.G = Gy.G; Gz.G = zeros( size(Gy.G , 1) , 1 ); % Make a nice figure Rad229_PSD_fig(1e6*RF.B1, Gz.G, Gy.G(:,PE_IND), Gx.G, sys.dt); %% What do the phase encode gradients do to the phase of the transverse magnetization in each pixel? pix = interp(acq.y_pos,10); % Upsample the positions used to sample the encoding (makes visualization a bit better) figure; hold on; IND = 1; for k = PE_IND phase = (2*pi) * sys.gamma_bar * sum( Gy.G(:,k) * sys.dt ) * pix; % Bulk magnetization phase depends on gradient area and position subplot(length(PE_IND),1,IND); hold on; q = plot([acq.y_pos(1:10:end); acq.y_pos(1:10:end)],[-1 1],'k'); set(q,'LineWidth',2); % Plot some reference position lines p = plot(pix,sin(phase)); set(p,'LineWidth',3); axis tight; if IND == 1, title('Phase Encode Gradient Induced Phase Across FOV'); end if IND == length(PE_IND), xlabel('Field Of View [m]'); end IND=IND+1; end return
github
mribri999/MRSignalsSeqs-master
bvalue.m
.m
MRSignalsSeqs-master/Matlab/bvalue.m
467
utf_8
f0f548fec405864d56b70c8b0ac13788
% % Function b = bvalue(gradwave,T) % % Function calculates the b value of a gradient waveform. % If there is a 180 pulse, then flip the gradient sign on one % side or another! % % Input: % gradwave = waveform, in mT/m % T = sampling period in seconds % % Output: % b = b value in s/mm^2 % function b = bvalue(gradwave,T) gamma = 2*pi*42.58; % rad * Hz/T intg = cumsum(gradwave)*T; % mT/m*s b = gamma^2 * sum( intg.^2) * T; % rad^2 /T^2 * (mT^2 / m^2) s
github
mribri999/MRSignalsSeqs-master
epg_show_grad.m
.m
MRSignalsSeqs-master/Matlab/epg_show_grad.m
1,108
utf_8
9c25c01ccb827fd97c1a569a7de1f490
%function [FpFmZ] = epg_show_grad(FpFmZ,noadd,Nanim,showtwists) % % Propagate EPG states through a "unit" gradient, and animate as it % goes. NOTE: This is a bit contrived, as the magnetization is not % really all in F0 (say) as it dephases. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % noadd = 1 to NOT add any higher-order states - assume % that they just go to zero. Be careful - this % speeds up simulations, but may compromise accuracy! % Nanim = Number of frames % showtwists = 1 to show twist, 0 to have all spins from origin % % OUTPUT: % Updated FpFmZ state. % % SEE ALSO: % epg_grad % % B.Hargreaves. % function [FpFmZ] = epg_show_grad(FpFmZ,noadd,Nanim,showtwists) if (nargin < 2) noadd=0; end; % Add by default. if (nargin < 3 || length(Nanim)<1) Nanim=32; end; if (nargin < 4 || length(showtwists)<1) showtwists=0; end; % -- Added for animation... Nanim=16; % Animation frames for k=1:Nanim epg_show(FpFmZ,k/Nanim,[],[],showtwists); drawnow; end; % -- Actually DO epg_grad! FpFmZ = epg_grad(FpFmZ,noadd); epg_show(FpFmZ); drawnow;
github
mribri999/MRSignalsSeqs-master
Rad229_Conventional_FlowEncode.m
.m
MRSignalsSeqs-master/Matlab/Rad229_Conventional_FlowEncode.m
2,718
utf_8
ef61334ada6f73e181cb69c3838efbc3
%% Rad229_Conventional_FlowEncode – Demonstrate designing a flow-compensated gradient waveform. % % Based, in part, on this paper: % % Encoding strategies for three-direction phasecontrast MR imaging of flow. % Pelc NJ, Bernstein MA, Shimakawa A, Glover GH. J Magn Reson Imaging 1991;1(4):405-413. % % SYNTAX - [G_FE, DeltaM1, M0_FE, M1_FE, t_FE] = Rad229_Conventional_FlowEncode(params) % % INPUTS - params % % OUTPUTS – G_FE % etc. % % [email protected] (March 2020) for Rad229 % [email protected] (March 2021) for Rad229 - Minor updates function [G_FE, DeltaM1, M0_FE, M1_FE, t_FE] = Rad229_Conventional_FlowEncode(params) % GAM = 2*pi*42.57e6; % rad/(s*T) % M1 needed for flow encoding Venc % DeltaM1 = pi/(GAM*params.VENC); % T/m x s^2 DeltaM1 = pi/(2 * pi * params.gamma_bar * params.VENC); % T/m x s^2 % Moments at end of slice select M0S = params.M0S(1,end); M1S = params.M1S(1,end); % Now solve for the next two lobes as presented in: % Pelc NJ, Bernstein MA, Shimakawa A, Glover GH. Encoding strategies for three-direction phasecontrast MR imaging of flow. J Magn Reson Imaging 1991;1(4):405-413. % But we add an additional search over risetime (r) to allow for % waveforms with triangle lobes % Maximum risetime [s] rmax = params.gmax/params.smax; % r = risetime in [s] for r = 1e-06:2e-06:rmax h = r*params.smax; % gradient strength [T/m] M02 = abs(-h*r+sqrt((h*r)^2+2*(h*r*M0S + M0S^2 + 2*h*(M1S+DeltaM1))))/2; % Area of the second lobe (see above paper for derivation) [T/m x s] M01 = M0S + M02; % Area of the first lobe (see above paper for derivation) [T/m x s] w1 = abs(M01)/h + r; % Duration of first lobe [s] w2 = abs(M02)/h + r; % Duration of second lobe [s] r_ = (ceil(r/params.dt)); % risetime in 'dt' units w1_ = (ceil(w1/params.dt)); % Duration of first lobe in 'dt' units w2_ = (ceil(w2/params.dt)); % Duration of second lobe in 'dt' units % We stop this loop if the flattop time is less than one 'dt' unit (triangle lobe) if (w1_-2*r_ <= 1) || (w2_-2*r_ <= 1) break end end % Build the flow compensated bipolar G = horzcat(linspace(0,-h,r_),linspace(-h,-h,w1_-2*r_),linspace(-h,0,r_),linspace(h/r_,h,r_-1),linspace(h,h,w2_-2*r_),linspace(h,0,r_)); % Output waveform in [T/m] G_FE = horzcat(params.G_ss,G); % Compute final gradient moments t_vec = 0 : params.dt : ( length( G_FE ) - 1 ) * params.dt; M0_FE = cumsum( ( G_FE .* params.dt ) , 2 ); % [T/m x s] M1_FE = cumsum( ( G_FE .* t_vec * params.dt ) , 2); % [T/m x s^2] % Define a time vector t_FE = ( 0 : (length(G_FE)-1) ) * params.dt; return
github
mribri999/MRSignalsSeqs-master
epg_show.m
.m
MRSignalsSeqs-master/Matlab/epg_show.m
4,171
utf_8
4dd86bc75767ad354554469883b69b0d
%function epg_show(FZ,frac,scale,Nspins,showtwists,shiftfs,simpleaxes) % % Show all (n+1) EPG states in 3x(n+1) plot % % FZ = 3xn column vector of F+,F- and Z. % frac = fraction of twist, if animating. % scale = axis scale [-scale scale] defaults to 1. % Nspins = number of spins, defaults to 24 % showtwists = 0 (all spins start at 0) or 1 (variation to show twists) % simpleaxis = 0 (full axes) or 1 for simple, no grid axes% % Run with no arguments for an example. % % Use arrow3D for prettier plots! function epg_show(FZ,frac,scale,Nspins,showtwists,shiftfs,simpleaxes) if (nargin < 1 || length(FZ)<1) FZ = [.3 0.5; 0.3 0.25; 0.2 0.2]; end; if (nargin < 2 || length(frac)<1) frac = 0; end; if (nargin < 3 || length(scale)<1) scale = 1; end; if (nargin < 4 || length(Nspins)<1) Nspins = 23; end; if (nargin < 5 || length(showtwists)<1) showtwists=0; end; if (nargin < 6 || length(shiftfs)<1) shiftfs=1; end; if (nargin < 7 || length(simpleaxes)<1) simpleaxes=1; end; [m,n] = size(FZ); % # subplots = size of FZ matrix. if (m<3) FZ(3,1)=0; end; % -- Add 3rd row if not given if (length(FZ(:)) < 4) shiftfs=0; end; % No shifting F states if only 0 order clf; % -- Clear figure for mm = 1:m % -- Rows (F+,F-,Z) for nn=1:n % -- Order (n) h=subplotaxis(m,n,nn+(mm-1)*n); % -- Do plotting for given basis function Q = 0*FZ; Q(mm,nn)=FZ(mm,nn); % Just 1 basis at a time % -- Setup Titles if (mm==1) tt = sprintf('F{^+_%d} = %0.2f + %0.2f',nn-1,real(sum(Q(:))), ... imag(sum(Q(:)))); end; if (mm==2) tt = sprintf('F{^-_%d} = %0.2f + %0.2f',nn-1,real(sum(Q(:))), ... imag(sum(Q(:)))); end; if (mm==3) tt = sprintf('Z_{%d} = %0.2f + %0.2f',nn-1,real(sum(Q(:))), ... imag(sum(Q(:)))); end; if (mm==2) && (nn==1) Q=FZ; tt='3D View'; end; % All states in F0* position % -- Plot this state if (showtwists==0 || (mm==2 && nn==1)) % Don't twist 3D plot epg_showstate(Q,frac,scale,Nspins); else voxvar = 1; % -- Variation along mz for F states if (mm==3) voxvar = 2; end; % -- Variation along mx for Z states (easier) epg_showstate(Q,frac,scale,Nspins,voxvar); end; title(tt); % -- Show F states from above. if (showtwists==0 && mm==1) view(0,90); end; if ((showtwists==0 && mm==2) && (nn>1)) view(0,90); end; % Temporary! %if (mm==2 && nn==1) axis(4*[-1 1 -1 1 -1 1]); end; % -- Put simple axes lines instad of grid/white area if (simpleaxes==1) hold on; axis off; plot3([-1 1],[0 0],[0 0]); % x axis plot3([0 0],[-1 1 ],[0 0]); % y axis plot3([0 0],[0 0],[-1 1]); % z axis text(scale,0,0,'M_x'); text(0,scale,0,'M_y'); % Mx, My labels if (mm>2 || (mm==2 && nn==1)) text(0,0,scale,'M_z'); end; % Mz Labels hold off; end; end; end; setprops; % -- Remaining code to shift states if animating - probably ignore! if (shiftfs==1) for mm = 1:m % -- Rows (F+,F-,Z) for nn=1:n % -- Order (n) h=subplotaxis(m,n,nn+(mm-1)*n); sposx(mm,nn)=h.Position(1); sposy(mm,nn)=h.Position(2); end; end; dx = sposx(1,2)-sposx(1,1); % -- Position between adjacent F's on plot dy = sposy(2,1)-sposy(1,1); % -- Position between rows on plot. sposx(1,:) = sposx(1,:)+frac*dx; sposx(2,:) = sposx(2,:)-frac*dx; sposy(2,2) = sposy(2,2)-frac*dy; % F(-1) gets shifted left AND up. for nn=1:n mm=1; nnp = n-nn+1; % Reverse order for 1st row h=subplotaxis(m,n,nnp+(mm-1)*n); hpos = h.Position; set(h,'Position',[sposx(mm,nnp) sposy(mm,nnp) hpos(3:4)]); end; for nn=1:n mm=2; nnp = nn; % Increasing order for 2nd row h=subplotaxis(m,n,nnp+(mm-1)*n); hpos = h.Position; if (nn>1) set(h,'Position',[sposx(mm,nnp) sposy(mm,nnp) hpos(3:4)]); end; end; end; % -- Save frame if animating. if (exist('epg_saveframe')) epg_saveframe; % Save frame, if globals 'framenum' and 'filestem' exist end; function h=subplotaxis(m,n,q) % Function calles subplot or subaxis (if it exists), returning the handle. % subaxis is a more efficient (dense) arrangment of subplots - see Mathworks % for download. if (exist('subaxis')) h=subaxis(m,n,q); else h=subplot(m,n,q); end;
github
mribri999/MRSignalsSeqs-master
epg_show_relax.m
.m
MRSignalsSeqs-master/Matlab/epg_show_relax.m
1,078
utf_8
e4bb021805481aace14a6a3cb18a3a4a
%function [FpFmZ] = epg_show_relax(FpFmZ,T1,T2,T,Nanim,showtwists) % % Propagate EPG states through relaxation given by T1,T2,T % plotting frames. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % T1,T2 = Relaxation times (same as T) % T = Time interval (same as T1,T2) % Nanim = Number of frames % showtwists = 1 to show twist, 0 to have all spins from origin % % OUTPUT: % FpFmZ = Updated FpFmZ state. % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. % function [FpFmZ] = epg_show_relax(FpFmZ,T1,T2,T,Nanim,showtwists) if (nargin < 1 || length(FpFmZ)<1) FpFmZ = [.3 .5 .25;.3 .5 .25; .2 .2 .2]; end; if (nargin < 2 || length(T1)<1) T1 = 1; end; if (nargin < 3 || length(T2)<1) T2 = 0.2; end; if (nargin < 4 || length(T)<1) T = 1; end; if (nargin < 5 || length(Nanim)<1) Nanim=16; end; if (nargin < 6 || length(showtwists)<1) showtwists=0; end; T = T/Nanim; % -- Animate. for k=1:Nanim FpFmZ = epg_relax(FpFmZ,T1,T2,T); epg_show(FpFmZ,[],[],[],showtwists); drawnow; end;
github
mribri999/MRSignalsSeqs-master
time2freq.m
.m
MRSignalsSeqs-master/Matlab/time2freq.m
365
utf_8
07e6fbd7bb7f88c4e51f1989bcefc7b2
% function f = time2freq(t) % % Function converts a time array to the corresponding frequency % points such that the (shifted) FFT of an array at times t leads % to frequency points f. % % Example: time2freq([-5:4]) = [-.5:0.1:0.4] % function f = time2freq(t) dt = t(2)-t(1); df = 1/ (length(t))/dt; np = length(t); f = [-ceil((np-1)/2):floor((np-1)/2)]*df;
github
mribri999/MRSignalsSeqs-master
calc_spherical_harmonics.m
.m
MRSignalsSeqs-master/Matlab/calc_spherical_harmonics.m
1,699
utf_8
31db11c485a21aaafb0f6275a035a408
% This function computes the the spherical harmonic coefficients that are % specific to a scanner and used to compute the non-linear gradient induced % displacement distortion. % % SYNTAX - B = calc_spherical_harmonics(Alpha, Beta, X, Y, Z, R0) % % INPUTS - Alpha - Coefficient for the cosine terms % Beta - Coefficient for the sine terms % X - X-position at which to compute the harmonic [1 x m] % Y - Y-position at which to compute the harmonic [1 x m] % Z - Z-position at which to compute the harmonic [1 x m] % R0 - Scaling factor % % OUTPUTS - B - Spherical harmonic values at (X,Y,Z) [1 x m] % % Original code creation by Michael Loecher. [email protected] (April 2020 for Rad229) function B = calc_spherical_harmonics(Alpha, Beta, X, Y, Z, R0) % Calculate displacement field from spherical harmonic coefficients nmax = size( Alpha , 1 ) - 1; % Convert to spherical coordinates R = sqrt( X.^2 + Y.^2 + Z.^2); R_eps = R + .0001; Theta = acos( Z ./ R_eps ); Phi = atan2( Y ./ R_eps , X ./ R_eps ); % Evaluate the Legendre polynomial with normalization B = 0; for n = 0 : nmax P = gradient_nonlin_legendre(n,cos(Theta)); F = ( R / R0 ) .^ n; for m = 0 : n F2 = Alpha( n + 1 , m + 1 ) * cos( m * Phi ) + Beta( n + 1 , m + 1) * sin( m * Phi ); B = B + F .* P( m + 1 , : ) .* F2; end end return function P = gradient_nonlin_legendre( n , X ) % Calculate the Legendre polynomial with normalization P = legendre(n,X); for m = 1 : n normfact = (-1) ^ m * sqrt( (2 * n + 1) * factorial( n - m ) / ( 2 * factorial(n + m) ) ); P( m + 1 , : ) = normfact * P( m + 1 , : ); end return
github
mribri999/MRSignalsSeqs-master
abanim.m
.m
MRSignalsSeqs-master/Matlab/abanim.m
409
utf_8
1052c1b376c2c5e9e11075063db7dde7
% % function M = abanim(M,n,A,B) % % Animate a propagation of the form M'=A*M+B, where % A and B are assumed to be rotations and relaxation that occur % continuously across the animation interval. % function M = abanim(M,n,A,B) if (nargin < 4) B=[0;0;0]; end; [Ai,Bi] = absplit(n,A,B); % Split operation into n frames for k=1:n M = Ai*M + Bi; % Propagate plotm(M); % Display drawnow; % Show end;
github
mribri999/MRSignalsSeqs-master
senseweights.m
.m
MRSignalsSeqs-master/Matlab/senseweights.m
1,123
utf_8
ed1edffe9e99b42f82638f7f074d6ef7
% % function [W,gfact,imnoise] = senseweights(sens,Psi) % % Function calculates the SENSE weights at a pixel given % input sensitivities and covariance matrix. A reduction % factor R can be assumed from the shape of the sens matrix. % The number of coils Nc is determined by the size of sens. If Psi % is omitted it is assumed to be the identity matrix. % % INPUT: % sens = Nc x R matrix of coil sensitivites % Psi = Nc x Nc noise covariance matrix. % % OUTPUT: % W = coil combination weights - R x Nc % gfact = gfactor (1xR vector including each aliased pixel) % imnoise = image noise covariance matrix (RxR) % function [W,gfact,imnoise] = senseweights(sens,Psi) [Nc,R] = size(sens); % -- Get #coils and reduction factor if nargin < 2 Psi = eye(Nc); end; % Default to perfectly uncorrelated noise % -- invPsi = inv(Psi); % Calculate inverse once CiPsiC = sens'*invPsi*sens; % Calculate jsut once iCiPsiC = inv(CiPsiC); % Calculate just once W = iCiPsiC * sens'*invPsi; % SENSE weights imnoise = iCiPsiC; % Image noise covariance gfact = sqrt(diag(imnoise).* diag(inv(imnoise))); % Elementwise prod.
github
mribri999/MRSignalsSeqs-master
epg_animgrad.m
.m
MRSignalsSeqs-master/Matlab/epg_animgrad.m
464
utf_8
49f9c207af0dadbe2a458095ffc05f97
function FZ = epg_animgrad(FZ,N,scale) %function FZ = epg_animgrad(FZ,N,scale) % % Animate an EPG state to the next F state. % % N = #spins % scale = axis scale multiplier % if (nargin < 2) N = 24; end; if (nargin < 3) scale = 1; end; Nf = 20; for p=1:Nf epg_showstate(FZ,p/Nf,scale,N); drawnow; pause(0.05); if (exist('epg_saveframe')) epg_saveframe; % Save frame, if globals 'framenum' and 'filestem' exist end; end; FZ = epg_grad(FZ);
github
mribri999/MRSignalsSeqs-master
mag.m
.m
MRSignalsSeqs-master/Matlab/mag.m
436
utf_8
2fb6a38305d2b59296e48d46098f7491
% This function finds the magnitude of a vector of any length or of a % matrix along a given dimension (1 or 2) % % SYNTAX: mag=mag(vector,dim); % mag=mag(vector); % If a vector % % DBE 01/25/00 function mag=mag(vector,dim) % len=length(vector); if nargin==1 dim=find(min(size(vector))==size(vector)); end if size(vector,1)==1 dim=2; elseif size(vector,2)==1 dim=1; end mag= sqrt(sum(vector.^2,dim)); return;
github
mribri999/MRSignalsSeqs-master
epg_cpmg.m
.m
MRSignalsSeqs-master/Matlab/epg_cpmg.m
2,518
utf_8
2b2df3aaccdfcc424ec6f2a6ee47f8ef
% function [s,phasediag,P] = epg_cpmg(flipangle,etl,T1,T2,esp) % % EPG Simulation of CPMG sequence. First flip angle % is 90 about y axis, and others by default are about % x-axis (make flipangle complex to change that). % % flipangle = refocusing flip angle or list (radians) % etl = echo train length, if single flipangle is to be repeated. % T1,T2,esp = relaxation times and echo spacing (arb. units). % % Note that if refoc flip angle is constant, less than pi, and etl > 1 the % first refocusing flip angle is the average of 90 and the desired % refocusing flip angle, as proposed by Hennig. % % All states are kept, for demo purposes, though this % is not really necessary. function [s,phasediag,P] = epg_cpmg(flipangle,etl,T1,T2,esp) if (nargin < 1) flipangle = pi*ones(1,12); end; % -- Default parameters: ETL = length(flipangle) if (nargin < 2 || length(etl)==0) etl = length(flipangle); end; if (length(flipangle)==1) && (etl > 1) && (abs(flipangle)<pi) % -- 1st flip reduced trick (Hennig) flipangle(2)=flipangle(1); flipangle(1)=(pi+abs(flipangle(2)))/2/abs(flipangle(2)) * flipangle(2); end; if (etl > length(flipangle)) flipangle(end+1:etl) = flipangle(end); end; if (nargin < 3) T1 = 1; end; % sec if (nargin < 4) T2 = 0.1; end; % sec if (nargin < 5) esp = 0.01; end; % sec P = zeros(3,2*etl); % Allocate all known states, 2 per echo. P(3,1)=1; % Initial condition/equilibrium. Pstore = zeros(4*etl,etl); % Store F,F* states, with 2 gradients per echo Zstore = zeros(2*etl,etl); % Store Z states, with 2 gradients per echo % -- 90 excitation P = epg_rf(P,pi/2,pi/2); % Do 90 tip. s = zeros(1,etl); % Allocate signal vector to store. for ech=1:etl P = epg_grelax(P,T1,T2,esp/2,1,0,1,1); % -- Left crusher P = epg_rf(P,abs(flipangle(ech)),angle(flipangle(ech))); % -- Refoc. RF P = epg_grelax(P,T1,T2,esp/2,1,0,1,1); % -- Right crusher s(ech) = P(1,1); % Signal is F0 state. Pstore(2*etl:4*etl-1,ech) = P(2,:).'; % Put in negative states Pstore(1:2*etl,ech) = flipud(P(1,:).'); % Put in positive, overwrite center. Zstore(:,ech) = P(3,:).'; end; set(0,'defaultAxesFontSize',14); % Default font sizes set(0, 'DefaultLineLineWidth', 2); % Default line width plotstate = cat(1,Pstore,Zstore); subplot(1,2,1); plot([1:etl]*esp,abs(s)); lplot('Echo Time','Signal','CPMG: Signal vs Echo Time'); subplot(1,2,2); dispim(plotstate); xlabel('Echo'); ylabel('F(top) and Z(bottom) States'); title('F and Z states vs time'); phasediag = plotstate;
github
mribri999/MRSignalsSeqs-master
epg_rf.m
.m
MRSignalsSeqs-master/Matlab/epg_rf.m
1,121
utf_8
9a45c7686a8396fcff76dbd9aa18a2be
% %function [FpFmZ,RR] = epg_rf(FpFmZ,alpha,phi) % Propagate EPG states through an RF rotation of % alpha, with phase phi (both radians). % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % % OUTPUT: % FpFmZ = Updated FpFmZ state. % RR = RF rotation matrix (3x3). % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. % function [FpFmZ,RR] = epg_rf(FpFmZ,alpha,phi) if (nargin < 1) FpFmZ = [0;0;1]; end; % Default is M=M0 if (nargin < 2) alpha = pi/2; end; % Default is pi/2 if (nargin < 3) phi = 0; tt = sprintf('epg_rf defaulting to M0 with alpha=%g, phi=%g',alpha,phi); disp(tt); end; % Default is pi/2 % -- From Weigel at al, JMR 205(2010)276-285, Eq. 8. if (nargin < 3) phi = pi/2; end; if length(FpFmZ)<3 FpFmZ = [0;0;1]; end; if (abs(alpha)>2*pi) warning('epg_rf: Flip angle should be in radians!'); end; RR = [(cos(alpha/2))^2 exp(2*i*phi)*(sin(alpha/2))^2 -i*exp(i*phi)*sin(alpha); exp(-2*i*phi)*(sin(alpha/2))^2 (cos(alpha/2))^2 i*exp(-i*phi)*sin(alpha); -i/2*exp(-i*phi)*sin(alpha) i/2*exp(i*phi)*sin(alpha) cos(alpha)]; FpFmZ = RR * FpFmZ;
github
mribri999/MRSignalsSeqs-master
design_symmetric_gradients.m
.m
MRSignalsSeqs-master/Matlab/design_symmetric_gradients.m
8,333
utf_8
edaf1e6b9780a887e95b4b9b17ea4656
function [TE,G,b] = design_symmetric_gradients(bvalue_target,T_ECHO,T_90,G_Max,MMT) % Returns the TE for symmetric DWI waveforms with a specified b-value and % sequence timing parameters. The waveforms used are: MONOPOLAR, BIPOLAR % and MODIFIED BIPOLAR (Stoeck CT, von Deuster C, Genet M, Atkinson D, Kozerke % S. Second-order motion-compensated spin echo diffusion % tensor imaging of the human heart. MRM. 2015.) % % INPUTS: G_Max - Max gradient amplitude [T/m] % bvalue_target- Desired b-value [s/mm2] % T_ECHO - EPI time to Echo [ms] % T_90 - Start time of diffusion encoding [ms] % MMT - Desired waveform moments % - 0 - M0= 0 - MONO % - 1 - M0M1 = 0 - BIPOLAR % - 2 - M0M1M2 = 0 - MODIFIED BIPOLAR % % OUTPUTS: TE - TE of resultant waveform [ms] % G - Diffusion encoding waveform [T/m] % b - b-value of encoding waveform [s/mm2] % % Magnetic Resonance Research Labs (http://mrrl.ucla.edu) % Department of Radiological Sciences % University of California, Los Angeles % Eric Aliotta ([email protected]) % Holden Wu ([email protected]) % Daniel Ennis ([email protected]) % December 16, 2015 epsilon = 1.5; % gradient ramp time RFgap = 4.3; % 180 pulse duration epsilon = floor(epsilon*10)/10; % define monopolar waveform if MMT == 0 gap = RFgap; N = 4*epsilon + gap + 2*T_ECHO+T_90; % starting point for total duration T = 0.1; % scale time in ms b = 0; % update waveform until the b-value is large enough while(b<bvalue_target*0.995) N = N+T; time = N; lambda = (time - 4*epsilon - gap - 2*T_ECHO)/2; lambda = round(lambda/T); grad = trapTransform([lambda,lambda],G_Max,floor(epsilon/T),1,floor((T_ECHO-T_90+gap)/T),1); n = length(grad); C=tril(ones(n)); C2 = C'*C; GAMMA = 42580; INV = ones(n,1); INV(floor((n+T_ECHO)/2):end) = -1; Ts = T*(1e-3); b = (GAMMA*2*pi)^2*(grad.*INV*Ts)'*(C2*(grad.*INV*Ts))*Ts; tINV = ceil(lambda + floor((T_ECHO-T_90+gap)/T) + 2*epsilon/T - 0.5*gap/T); TEh1 = T_ECHO/T + length(grad(tINV:end)); TEh2 = tINV; TE = 2*max(TEh1,TEh2)*T; G = grad; end end % define bipolar waveform (M1=0) if MMT == 1 L = 1; % starting point T = 0.1; % scale time in ms b = 0; % update waveform until the b-value is large enough while(b<bvalue_target*0.995) L = L+T; % duration of each bipolar lobe lambda = L; LAMBDA = lambda; LAMBDA = round(LAMBDA/T); lambda = round(lambda/T); % gap b/w gradients is just the RF duration gap = RFgap; % take trapezoid durations and create G(t) vector grad = trapTransform([lambda,-LAMBDA,LAMBDA,-lambda],G_Max,round(epsilon/T),1,round(gap/T),2); % legnth of waveform n = length(grad); % vector for b-value integration C=tril(ones(n)); C2 = C'*C; % Gyromagnetic ratio GAMMA = 42580; % refocusing pulse time tINV = floor(n/2); % vector to invert magnetization (+1 before 180, -1 after 180) INV = ones(n,1); INV(floor(tINV):end) = -1; % time increment in seconds Ts = T*(1e-3); % test b-value b = (GAMMA*2*pi)^2*(grad.*INV*Ts)'*(C2*(grad.*INV*Ts))*Ts; % pre 180 contribution to TE TEh1 = 0.5*RFgap/T + lambda + LAMBDA + 4*epsilon/T + T_ECHO/T; % post 180 contribution to TE TEh2 = 0.5*RFgap/T + lambda + LAMBDA + 4*epsilon/T + T_90/T; % Final TE TE = 2*max(TEh1,TEh2)*T + 2 + 2; %additional 4ms for spoilers. % final gradient waveform G = grad; end end % define modified bipolar (M1=M2 = 0) waveform if MMT == 2 L = 1; % starting point T = 0.1; % scale in ms b = 0; % update waveform until the b-value is large enough while(b<bvalue_target*0.995) L = L+T; % first trap duration lambda = L; lambda = round(lambda/T); % second trap duration LAMBDA = 2*lambda + epsilon; LAMBDA = round(LAMBDA/T); % time between first and second sets of gradients gap = 2*epsilon + lambda; % take trapezoid durations and create G(t) vector grad = trapTransform([lambda,-LAMBDA,-LAMBDA,lambda],G_Max,round(epsilon/T),1,round(gap/T),2); % legnth of waveform n = length(grad); % vector for b-value integration C=tril(ones(n)); C2 = C'*C; % Gyromagnetic ratio GAMMA = 42580; % refocusing pulse time tINV = n/2 + round(gap/T) - round(RFgap/T); % vector to invert magnetization (+1 before 180, -1 after 180) INV = ones(n,1); INV(floor(tINV):end) = -1; % time increment in seconds Ts = T*(1e-3); % test b-value b = (GAMMA*2*pi)^2*(grad.*INV*Ts)'*(C2*(grad.*INV*Ts))*Ts; % pre 180 contribution to TE TEh1 = 0.5*RFgap/T + lambda + LAMBDA + 4*epsilon/T + T_ECHO/T; % post 180 contribution to TE TEh2 = -0.5*RFgap/T + lambda + LAMBDA + 4*epsilon/T + T_90/T + gap/T; % final TE TE = 2*max(TEh1,TEh2)*T; % final gradient waveform G = grad; end end end function g = trapTransform(f,G0,SR,tFact,gap,gpos) % gradient waveform from trapezoidal reduction % define waveform in terms of gradient duration and sign assuming % G = Gmax % % input: f -- row of numbers indicating the duration of each gradient lobe % in ms. Must correspond to an integer number of timepoints % G0 -- Gmax. All lobes assumed to be at Gmax % SR -- Slew duration (normalized to unit size) (default- 1) % tFact -- Temporal resolution subsampling (default- 1) % gap-- Gap duration an RF pulse [units] (default 0) % gpos- Position of gap (list the number of f entry to put the gap % AFTER (default floor(num entries/2) % % output: g -- fully represented gradient waveform if nargin<2 G0 = 0.074; end if nargin<3 SR = 1; end if nargin<4 tFact = 1; end if nargin<5 gap = 0; end if nargin<6 gpos = floor(length(f)/2); end if tFact == 1e-3 tFact = 1; fprintf('Assuming T = 1ms, subsample of 1 used!! \n'); end if min(abs(f)) < 1 fprintf('ERROR - Need to allow time for slewing!!!\n'); return; end %g = G0*ones( (sum(abs(f))+gap )*tFact,1); g = G0*ones( (sum(abs(f)) + gap + 2*numel(f)*SR - (numel(f)-1) )*tFact,1); count = 1; for j=1:length(f) PLAT = abs(f(j)); if j == gpos tnow = count; % ramp up g(tnow:tnow+SR-1) = g(tnow:tnow+SR-1).*(0:1/SR:1-1/SR)'*(f(j)/PLAT); %g(count+1:count+1+SR) = g(count+1:count+1+SR).*(0:1/SR:1)'*(f(j)/PLAT); tnow = tnow + SR; % plateau g(tnow:tnow+PLAT*tFact-1) = g(tnow:tnow+PLAT*tFact-1)*f(j)/PLAT; %g(count+2+SR:count+PLAT*tFact-SR+1) = g(count+2+SR:count+PLAT*tFact-SR+1)*f(j)/PLAT; tnow = tnow + PLAT*tFact; % ramp down g(tnow:tnow+SR-1) = g(tnow:tnow+SR-1).*(1-(1/SR:1/SR:1))'*(f(j)/PLAT); count = tnow + SR-1; g(count+1:count+gap*tFact) = g(count+1:count+gap*tFact)*0; count = count + gap*tFact; else tnow = count; % ramp up g(tnow:tnow+SR-1) = g(tnow:tnow+SR-1).*(0:1/SR:1-1/SR)'*(f(j)/PLAT); %g(count+1:count+1+SR) = g(count+1:count+1+SR).*(0:1/SR:1)'*(f(j)/PLAT); tnow = tnow + SR; % plateau g(tnow:tnow+PLAT*tFact-1) = g(tnow:tnow+PLAT*tFact-1)*f(j)/PLAT; %g(count+2+SR:count+PLAT*tFact-SR+1) = g(count+2+SR:count+PLAT*tFact-SR+1)*f(j)/PLAT; tnow = tnow + PLAT*tFact; % ramp down g(tnow:tnow+SR-1) = g(tnow:tnow+SR-1).*(1-(1/SR:1/SR:1))'*(f(j)/PLAT); count = tnow + SR-1; % ramp up % g(count+1:count+1+SR) = g(count+1:count+1+SR).*(0:1/SR:1)'*(f(j)/PLAT); % % plateau % g(count+1+SR:count+PLAT*tFact-SR) = g(count+1+SR:count+PLAT*tFact-SR)*f(j)/PLAT; % % ramp down % g(count+PLAT*tFact-SR:count+PLAT*tFact) = g(count+PLAT*tFact-SR:count+PLAT*tFact).*(1-(0:1/SR:1))'*(f(j)/PLAT); % %count = count + PLAT*tFact; end end end
github
mribri999/MRSignalsSeqs-master
vds.m
.m
MRSignalsSeqs-master/Matlab/vds.m
10,710
utf_8
53e86b9243ff4d9736f898b64a4fff7b
% % function [k,g,s,time,r,theta] = vds(smax,gmax,T,N,Fcoeff,rmax,z) % % % VARIABLE DENSITY SPIRAL GENERATION: % ---------------------------------- % % Function generates variable density spiral which traces % out the trajectory % % k(t) = r(t) exp(i*q(t)), [1] % % Where q is the same as theta... % r and q are chosen to satisfy: % % 1) Maximum gradient amplitudes and slew rates. % 2) Maximum gradient due to FOV, where FOV can % vary with k-space radius r/rmax, as % % FOV(r) = Sum Fcoeff(k)*(r/rmax)^(k-1) [2] % % % INPUTS: % ------- % smax = maximum slew rate G/cm/s % gmax = maximum gradient G/cm (limited by Gmax or FOV) % T = sampling period (s) for gradient AND acquisition. % N = number of interleaves. % Fcoeff = FOV coefficients with respect to r - see above. % rmax= value of k-space radius at which to stop (cm^-1). % rmax = 1/(2*resolution); % z = R/L for gradient coil, to include voltage model. This % tends to speed up gradient design slightly. % % % OUTPUTS: % -------- % k = k-space trajectory (kx+iky) in cm-1. % g = gradient waveform (Gx+iGy) in G/cm. % s = derivative of g (Sx+iSy) in G/cm/s. % time = time points corresponding to above (s). % r = k-space radius vs time (used to design spiral) % theta = atan2(ky,kx) = k-space angle vs time. % % % METHODS: % -------- % Let r1 and r2 be the first derivatives of r in [1]. % Let q1 and q2 be the first derivatives of theta in [1]. % Also, r0 = r, and q0 = theta - sometimes both are used. % F = F(r) defined by Fcoeff. % % Differentiating [1], we can get G = a(r0,r1,q0,q1,F) % and differentiating again, we get S = b(r0,r1,r2,q0,q1,q2,F) % % (functions a() and b() are reasonably easy to obtain.) % % FOV limits put a constraint between r and q: % % dr/dq = N/(2*pi*F) [3] % % We can use [3] and the chain rule to give % % q1 = 2*pi*F/N * r1 [4] % % and % % q2 = 2*pi/N*dF/dr*r1^2 + 2*pi*F/N*r2 [5] % % % % Now using [4] and [5], we can substitute for q1 and q2 % in functions a() and b(), giving % % G = c(r0,r1,F) % and S = d(r0,r1,r2,F,dF/dr) % % % Using the fact that the spiral should be either limited % by amplitude (Gradient or FOV limit) or slew rate, we can % solve % |c(r0,r1,F)| = |Gmax| [6] % % analytically for r1, or % % |d(r0,r1,r2,F,dF/dr)| = |Smax| [7] % % analytically for r2. % % [7] is a quadratic equation in r2. The smaller of the % roots is taken, and the real part of the root is used to % avoid possible numeric errors - the roots should be real % always. % % The choice of whether or not to use [6] or [7], and the % solving for r2 or r1 is done by findq2r2 - in this .m file. % % Once the second derivative of theta(q) or r is obtained, % it can be integrated to give q1 and r1, and then integrated % again to give q and r. The gradient waveforms follow from % q and r. % % Brian Hargreaves -- Sept 2000. % % See Brian's journal, Vol 6, P.24. % % % See also: vds2.m, vdsmex.m, vds.c % % =============== CVS Log Messages ========================== % $Log: vds.m,v $ % Revision 1.5 2004/04/27 18:08:44 brian % Revision 1.6 2007-02-23 18:30:19 brian % * Included LR-circuit model for increased slewing. % * NOTE: There is a bug in the substititution of % q1 with r1, in that the dr/dt term should % include dFOV/dr. This is confusing, but should % be a relatively easy fix that stabilizes the % algorithm for quickly-changing density functions. % % Revision 1.5 2004/04/27 18:08:44 brian % Changed FOV to a polynomial of unlimited length, % and hopefully changed all comments accordingly. % Also moved sub-functions into vds.m so that % no other .m files are needed. % % Revision 1.4 2003/09/16 02:55:52 brian % minor edits % % Revision 1.3 2002/11/18 05:36:02 brian % Rounds lengths to a multiple of 4 to avoid % frame size issues later on. % % Revision 1.2 2002/11/18 05:32:19 brian % minor edits % % Revision 1.1 2002/03/28 01:03:20 bah % Added to CVS % % % =========================================================== function [k,g,s,time,r,theta] = vds(smax,gmax,T,N,Fcoeff,rmax,z) if (nargin < 7) z=0; end; disp('vds.m'); gamma = 4258; oversamp = 8; % Keep this even. To = T/oversamp; % To is the period with oversampling. q0 = 0; q1 = 0; theta = zeros(1,10000); r = zeros(1,10000); r0 = 0; r1 = 0; time = zeros(1,10000); t = 0; count = 1; theta = zeros(1,1000000); r = zeros(1,1000000); time = zeros(1,1000000); while r0 < rmax [q2,r2] = findq2r2(smax,gmax,r0,r1,To,T,N,Fcoeff,rmax,z); % Integrate for r, r', theta and theta' q1 = q1 + q2*To; q0 = q0 + q1*To; t = t + To; r1 = r1 + r2*To; r0 = r0 + r1*To; % Store. count = count+1; theta(count) = q0; r(count) = r0; time(count) = t; if (rem(count,100)==0) tt = sprintf('%d points, |k|=%f',count,r0); disp(tt); end; end; r = r(oversamp/2:oversamp:count); theta = theta(oversamp/2:oversamp:count); time = time(oversamp/2:oversamp:count); % Keep the length a multiple of 4, to save pain...! % ltheta = 4*floor(length(theta)/4); r=r(1:ltheta); theta=theta(1:ltheta); time=time(1:ltheta); % % Plot. % %x = alpha*theta .* cos(theta); %y = alpha*theta .* sin(theta); %plot(x,y); %title('k-space trajectory.'); k = r.*exp(i*theta); g = 1/gamma*([k 0]-[0 k])/T; g = g(1:length(k)); s = ([g 0]-[0 g])/T; s = s(1:length(k)); % ========= Plot gradients and slew rates. ========== tp= time(1:10:end); gp = g(1:10:end); % Plotting undersamples kp = k(1:10:end); sp= s(1:10:end); subplot(2,2,1); plot(real(kp),imag(kp)); lplot('kx (cm^{-1})','ky (cm^{-1})','ky vs kx'); axis('square'); subplot(2,2,2); plot(tp,real(kp),'c-',tp,imag(kp),'g-'); %,tp,abs(kp),'k-'); lplot('Time (s)','k (cm^{-1})','k-space vs Time'); subplot(2,2,3); plot(tp,real(gp),'c-',tp,imag(gp),'g-'); %,tp,abs(gp),'k-'); lplot('Time (s)','g (G/cm)','Gradient vs Time'); subplot(2,2,4); plot(tp,real(sp),'c-',tp,imag(sp),'g-',tp,abs(sp),'k-'); lplot('Time (s)','s (G/cm/s)','Slew-Rate vs Time'); if (exist('setprops')) setprops; end; return; % % function [q2,r2] = q2r2(smax,gmax,r,r1,T,Ts,N,F) % % VARIABLE DENSITY SPIRAL DESIGN ITERATION % ---------------------------------------- % Calculates the second derivative of r and q (theta), % the slew-limited or FOV-limited % r(t) and q(t) waveforms such that % % k(t) = r(t) exp(i*q(t)) % % Where the FOV is a function of k-space radius (r) % % FOV = Fcoeff(1) + Fcoeff(2)*r/rmax + Fcoeff(3)*(r/rmax)^2 + ... ; % % F(1) in cm. % F(2) in cm^2. % F(3) in cm^3. % . % . % . % % The method used is described in vds.m % % INPUT: % ----- % smax = Maximum slew rate in G/cm/s. % gmax = Maximum gradient amplitdue in G. % r = Current value of r. % r1 = Current value of r', first derivative of r wrt time. % T = Gradient sample rate. % Ts = Data sampling rate. % N = Number of spiral interleaves. % F is described above. % % =============== CVS Log Messages ========================== % This file is maintained in CVS version control. % % $Log: vds.m,v $ % Revision 1.5 2004/04/27 18:08:44 brian % Changed FOV to a polynomial of unlimited length, % and hopefully changed all comments accordingly. % Also moved sub-functions into vds.m so that % no other .m files are needed. % % Revision 1.2 2003/05/29 23:02:21 brian % minor edits % % Revision 1.1 2002/03/28 01:03:20 bah % Added to CVS % % % =========================================================== function [q2,r2] = findq2r2(smax,gmax,r,r1,T,Ts,N,Fcoeff,rmax,z) gamma = 4258; % Hz/G smax = smax + z*gmax; F = 0; % FOV function value for this r. dFdr = 0; % dFOV/dr for this value of r. for rind = 1:length(Fcoeff) F = F+Fcoeff(rind)*(r/rmax)^(rind-1); if (rind>1) dFdr = dFdr + (rind-1)*Fcoeff(rind)*(r/rmax)^(rind-2)/rmax; end; end; GmaxFOV = 1/gamma /F/Ts; % FOV limit on G Gmax = min(GmaxFOV,gmax); % maxr1 = sqrt((gamma*Gmax)^2 / (1+(2*pi*F*r/N)^2)); if (r1 > maxr1) % Grad amplitude limited. Here we % just run r upward as much as we can without % going over the max gradient. r2 = (maxr1-r1)/T; %tt = sprintf('Grad-limited r=%5.2f, r1=%f',r,r1); %disp(tt); else twopiFoN = 2*pi*F/N; twopiFoN2 = twopiFoN^2; % A,B,C are coefficents of the equation which equates % the slew rate calculated from r,r1,r2 with the % maximum gradient slew rate. % % A*r2*r2 + B*r2 + C = 0 % % A,B,C are in terms of F,dF/dr,r,r1, N and smax. % A = 1+twopiFoN2*r*r; B = 2*twopiFoN2*r*r1*r1 + 2*twopiFoN2/F*dFdr*r*r*r1*r1 + 2*z*r1 + 2*twopiFoN2*r1*r;; C1 = twopiFoN2^2*r*r*r1^4 + 4*twopiFoN2*r1^4 + (2*pi/N*dFdr)^2*r*r*r1^4 + 4*twopiFoN2/F*dFdr*r*r1^4 - (gamma)^2*smax^2; C2 = z*(z*r1^2 + z*twopiFoN2*r1^2 + 2*twopiFoN2*r1^3*r + 2*twopiFoN2/F*dFdr*r1^3*r); C = C1+C2; %A = 1+twopiFoN2*r*r; %B = 2*twopiFoN2*r*r1*r1 + 2*twopiFoN2/F*dFdr*r*r*r1*r1; %C = twopiFoN2^2*r*r*r1^4 + 4*twopiFoN2*r1^4 + (2*pi/N*dFdr)^2*r*r*r1^4 + 4*twopiFoN2/F*dFdr*r*r1^4 - (gamma)^2*smax^2; [rts] = qdf(A,B,C); % qdf = Quadratic Formula Solution. r2 = real(rts(1)); % Use bigger root. The justification % for this is not entirely clear, but % in practice it seems to work, and % does NOT work with the other root. % Calculate resulting slew rate and print an error % message if it is too large. slew = 1/gamma*(r2-twopiFoN2*r*r1^2 + i*twopiFoN*(2*r1^2 + r*r2 + dFdr/F*r*r1^2)); %tt = sprintf('Slew-limited r=%5.2d SR=%f G/cm/s',r,abs(slew)); %disp(tt); sr = abs(slew)/smax; if (abs(slew)/smax > 1.01) tt = sprintf('Slew violation, slew = %d, smax = %d, sr=%f, r=%f, r1=%f',round(abs(slew)),round(smax),sr,r,r1); disp(tt); end; end; % Calculate q2 from other pararmeters. q2 = 2*pi/N*dFdr*r1^2 + 2*pi*F/N*r2; % function [r1,r2] = qdf(a,b,c) % % Outputs quadratic roots of ax^2+bx+c = 0. % % =============== CVS Log Messages ========================== % This file is maintained in CVS version control. % % $Log: vds.m,v $ % Revision 1.6 2007-02-23 18:30:19 brian % * Included LR-circuit model for increased slewing. % * NOTE: There is a bug in the substititution of % q1 with r1, in that the dr/dt term should % include dFOV/dr. This is confusing, but should % be a relatively easy fix that stabilizes the % algorithm for quickly-changing density functions. % % Revision 1.5 2004/04/27 18:08:44 brian % Changed FOV to a polynomial of unlimited length, % and hopefully changed all comments accordingly. % Also moved sub-functions into vds.m so that % no other .m files are needed. % % Revision 1.1 2002/03/28 01:27:46 bah % Added to CVS % % % =========================================================== function [roots] = qdf(a,b,c) d = b^2 - 4*a*c; roots(1) = (-b + sqrt(d))/(2*a); roots(2) = (-b - sqrt(d))/(2*a);
github
mribri999/MRSignalsSeqs-master
dispim.m
.m
MRSignalsSeqs-master/Matlab/dispim.m
765
utf_8
8084246dbda9eb28bb4312282cfbaeb8
% dispim(im,[low,high]) % displays magnitude version of image im (complex array) % % im = 2D image array (real or complex, magnitude displayed) % low = black level, high = white level. % Omit low,high for autoscaling. % % =========================================================== function [low,high] = dispim(im,low,high) im = squeeze((im)); if (nargin < 2) low = 0; end; if (nargin < 3) immax = max(abs(im(:))); imstd = std(abs(im(:))); high = immax-.5*imstd; end; % display image scale= 256/(high-low); offset = scale*low; % set colormap for 256 gray levels c = colormap; if (sum(abs(std(c')))>0.01) % Only change colormap if it is not gray. a=[1 1 1]/256; b=[1:256]; c=(a'*b)'; colormap(c); end; image(abs(im)*scale-offset); axis('square');
github
mribri999/MRSignalsSeqs-master
epg_show_rf.m
.m
MRSignalsSeqs-master/Matlab/epg_show_rf.m
1,713
utf_8
aab5f333732230eeda7211ef9fc956d8
%function [FpFmZ,RR] = epg_show_rf(FpFmZ,alpha,phi,Nanim,showtwists) % % Propagate EPG states through an RF rotation of % alpha, with phase phi (both radians), plotting frames. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % alpha, phi = flip angle and phase. % Nanim = Number of frames % showtwists = 1 to show twist, 0 to have all spins from origin % % OUTPUT: % FpFmZ = Updated FpFmZ state. % RR = RF rotation matrix (3x3). % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. % function [FpFmZ,RR] = epg_show_rf(FpFmZ,alpha,phi,Nanim,showtwists) if (nargin < 1 || length(FpFmZ)<1) FpFmZ = [0;0;1]; end; if (nargin < 3 || length(phi)<1) phi = pi/2; end; if (nargin < 2 || length(alpha)<1) alpha = pi/2; end; if (nargin < 4 || length(Nanim)<1) Nanim=32; end; if (nargin < 5 || length(showtwists)<1) showtwists=0; end; [m,n] = size(FpFmZ); if (m<3) FpFmZ(3,1)=0; end; % -- From Weigel at al, JMR 205(2010)276-285, Eq. 8. if (abs(alpha)>2*pi) warning('epg_rf: Flip angle should be in radians!'); end; RR = [(cos(alpha/2))^2 exp(2*i*phi)*(sin(alpha/2))^2 -i*exp(i*phi)*sin(alpha); exp(-2*i*phi)*(sin(alpha/2))^2 (cos(alpha/2))^2 i*exp(-i*phi)*sin(alpha); -i/2*exp(-i*phi)*sin(alpha) i/2*exp(i*phi)*sin(alpha) cos(alpha)]; alpha = alpha/Nanim; RRa = [(cos(alpha/2))^2 exp(2*i*phi)*(sin(alpha/2))^2 -i*exp(i*phi)*sin(alpha); exp(-2*i*phi)*(sin(alpha/2))^2 (cos(alpha/2))^2 i*exp(-i*phi)*sin(alpha); -i/2*exp(-i*phi)*sin(alpha) i/2*exp(i*phi)*sin(alpha) cos(alpha)]; FZ = FpFmZ; % -- Animate. for k=1:Nanim FZ = RRa * FZ; epg_show(FZ(1:m,:),[],[],[],showtwists); drawnow; end; FpFmZ = RR * FpFmZ;
github
mribri999/MRSignalsSeqs-master
zpadcrop.m
.m
MRSignalsSeqs-master/Matlab/zpadcrop.m
904
utf_8
c5421c7fd1276b9c7436c3f476b371dd
% function newim = zpadcrop(im,newsize) % % Function zero pads or crops an image to the new % size in x and y, keeping the image centered. % function newim = zpadcrop(im,newsize) sz = [size(im)]; if (length(sz)==2) sz = [sz 1]; end; % Make 3D at least. newim = zeros(newsize); if (length(newsize) < length(sz)) % Copy extra dimensions from original newsize(length(newsize)+1:length(sz))= sz(length(newsize)+1:end); else % Crop extra dimensions in new size newsize = newsize(1:length(sz)); end; cz = floor(sz/2)+1; % Central point. ncz= floor(newsize/2)+1; % New central point minsz = min([sz; newsize]); % minimum of sizes % -- Start and end indices newst = ncz-floor(minsz/2); newen = ncz+ceil(minsz/2)-1; oldst = cz-floor(minsz/2); olden = cz+ceil(minsz/2)-1; newim(newst(1):newen(1),newst(2):newen(2),newst(3):newen(3)) = im(oldst(1):olden(1),oldst(2):olden(2),oldst(3):olden(3));
github
mribri999/MRSignalsSeqs-master
adiabatic.m
.m
MRSignalsSeqs-master/Matlab/adiabatic.m
1,666
utf_8
8b021ffd7cb6660a379759a6669d7422
% % function [b1,freq,phase] = adiabatic(peakb1,bw,beta,T,Ts,blochsim) % % Function designs a Silver-Hoult adiabatic pulse with % peakb1 = max B1 in Gauss. % bw = bandwidth in Hz % beta = S-H beta (in Hz) % T = duration in seconds % Ts = sample period in seconds % blochsim = 1 to simulate pulse. % % Run with no arguments for a sample. % function [b1,freq,phase] = adiabatic(peakb1,bw,beta,T,Ts,blochsim) if (nargin < 1) peakb1=0.2; end; if (nargin < 2) bw = 2000; end; if (nargin < 3) beta = 1000; end; if (nargin < 4) T = 0.010; end; if (nargin < 5) Ts = 0.00001; end; if (nargin < 6) blochsim=0; end; T = 2*round(T/Ts/2)*Ts; N = T/Ts; t = [Ts:Ts:T] - round(N/2)*Ts; % Time from -T/2 to T/2. b1 = peakb1 * sech(beta*t); freq = bw/2 * tanh(beta*t); phase = cumsum(freq)*2*pi*Ts; phase = phase-phase(round(N/2)); % Zero phase half-way. phase = mod(phase+pi,2*pi)-pi; % Limit to [-pi,pi]; if (blochsim) t = t-t(1); % Start t at 0 for plots. figure(1); tt = sprintf('Adiabatic Silver-Hoult Pulse (Beta = %g Hz)',beta); subplot(3,1,1); plot(t,b1); xlabel('Time(s)'), ylabel('B1(G)'); title(tt); subplot(3,1,2); plot(t,phase); xlabel('Time(s)'), ylabel('Phase(rad)'); subplot(3,1,3); plot(t,freq); xlabel('Time(s)'), ylabel('Freq(Hz)'); if (exist('bloch')) gr = 0*b1; tp = Ts; t1 = .6; t2=.1; df = [-3*bw:bw/20:3*bw]; dp = 0; mode = 0; [mx,my,mz] = bloch(b1.*exp(i*phase),gr,tp,t1,t2,df,dp,mode); figure(2); plot(df,mx,'b--',df,my,'g--',df,mz,'r-'); xlabel('Freq (Hz)'); ylabel('Magnetization'); legend('Mx','My','Mz'); grid; else disp('bloch.m not found. No Bloch simulation.'); end; end;
github
mribri999/MRSignalsSeqs-master
gaussian2d.m
.m
MRSignalsSeqs-master/Matlab/gaussian2d.m
480
utf_8
c77cd444e9874db3a899cd743b7f3d3c
% function im = gaussian2d(size,mean,sigma) % % Function generates a gaussian image with the above parameters. % Mean and sigma can be vectors if different in x and y, or it % is the same. function im = gaussian2d(sz,mn,sig); if (length(sz) < 2) sz = [sz sz]; end; im = zeros(sz(2),sz(1)); if (length(mn)<2) mn = [mn mn]; end; if (length(sig)<2) sig = [sig sig]; end; x = 1:sz(1); gx = gaussian(x,mn(1),sig(1)); y = [1:sz(2)]'; gy = gaussian(y,mn(2),sig(2)); im = gy*gx;
github
mribri999/MRSignalsSeqs-master
cropim.m
.m
MRSignalsSeqs-master/Matlab/cropim.m
467
utf_8
a41647bfa4391a46758c0d2aba2f9324
% Function [cim] = cropim(im,sx,sy) % % Crops image to sx x sy. % If sy is omitted, sy=sx. % If sx is omitted, sx=size(1)/2. % If sx or sy is < 1, then fractional % function [cim] = cropim(im,sx,sy) sz = size(im); if (nargin < 2) sx = floor(sz(1)/2); end; if (nargin < 3) sy = sx; end; if (sx<1) sx=sz(1)*sx; end; % If fractional if (sy<1) sy=sz(1)*sy; end; stx = floor(sz(2)/2-sx/2)+1; sty = floor(sz(1)/2-sy/2)+1; cim = im( sty:sty+sy-1, stx:stx+sx-1 );
github
mribri999/MRSignalsSeqs-master
epg_showstate.m
.m
MRSignalsSeqs-master/Matlab/epg_showstate.m
4,770
utf_8
4458c0eef9b87faf31ff67541300168a
function epg_showstate(FZ,frac,scale,Nspins,voxelvar,simpleaxes) %function epg_showstate(FZ,frac,scale,Nspins,voxelvar,simpleaxes) % % Show an EPG representation in a single 3D plot. % (Zero-out other states if just wanting to show 1 basis function. % % FZ = 3x1 column vector of F+,F- and Z. % frac = fraction of twist, if animating. % scale = axis scaling [-scale scale] defaults to 1. % Nspins = #spins to show, default = 23. % voxelvar = origin of spin vectors (0=center, 1=along mz, 2=along mx) % % Get arrow3D to make these look nicer! % See epg_show and epg_showorder % if (nargin < 4 || length(Nspins)<1) Nspins = 23; end; myc = mycolors(Nspins); if (nargin < 1 || length(FZ)<1) FZ = [.75;.25;-.433i]; end; if (nargin < 2 || length(frac)<1) frac = 0; end; if (nargin < 3 || length(scale)<1) scale = 1; end; if (nargin < 4 || length(Nspins)<1) Nspins = 23; end; if (nargin < 5 || length(voxelvar)<1) voxelvar=0; end; if (nargin < 6 || length(simpleaxes)<1) simpleaxes=0; end; % -- Get vectors to plot M = epg_FZ2spins(FZ,Nspins,frac)*Nspins; % -- Figure out spin origins (twist vs all at 0 etc) if (voxelvar==0) spinorig = 0*M; % -- All at origin (most common) else spinrange = ([1:Nspins]-.5)/Nspins-.5; % voxel dimension spinrange = 2*spinrange; % fill plots if (voxelvar==1) spinorig = [zeros(2,Nspins); spinrange]; % Variation along mz else spinorig = [spinrange; zeros(2,Nspins)]; % Variation along mx (for Z_n) end; end; % -- Plot vectors. hold off; for k=1:Nspins if (exist('arrow3D')) %arrow3D(spinorig(:,k),M(:,k),myc(k,:),0.8,0.03*scale); % Pre 2021 arrow3D if (max(abs(M(:,k))) > 0.01) % -- new arrow3D doesn't like zero-length vectors arrow3D(spinorig(:,k),M(:,k),myc(k,:),0.8); end; else Mplot = M+spinorig; % Add origin, s h = plot3([spinorig(1,k) Mplot(1,k)],[spinorig(2,k) Mplot(2,k)],[spinorig(3,k) Mplot(3,k)]); set(h,'LineWidth',3); set(h,'Color',myc(k,:)); view(37,30); hold on; grid on; end; end; axis(scale*[-1 1 -1 1 -1 1]); if (voxelvar == 0) xlab='M_x'; ylab='M_y'; zlab='M_z'; end; if (voxelvar == 1) xlab='M_x'; ylab='M_y'; zlab='Voxel Dir (z) x2'; end; if (voxelvar ==2 ) xlab='Voxel Dir (z)'; ylab=' '; zlab='M_z'; end; % Apply labels xlabel(xlab); ylabel(ylab); zlabel(zlab); if (simpleaxes==1) hold on; axis off; plot3([-1 1],[0 0],[0 0]); % x axis plot3([0 0],[-1 1 ],[0 0]); % y axis plot3([0 0],[0 0],[-1 1]); % z axis text(scale,0,0,xlab); text(0,scale,0,ylab); % Mx, My labels text(0,0,scale,zlab); hold off; end; axis square; lighting phong; camlight right; function c = mycolors(n) cc = [ 0 0 0.5625 0 0 0.6250 0 0 0.6875 0 0 0.7500 0 0 0.8125 0 0 0.8750 0 0 0.9375 0 0 1.0000 0 0.0625 1.0000 0 0.1250 1.0000 0 0.1875 1.0000 0 0.2500 1.0000 0 0.3125 1.0000 0 0.3750 1.0000 0 0.4375 1.0000 0 0.5000 1.0000 0 0.5625 1.0000 0 0.6250 1.0000 0 0.6875 1.0000 0 0.7500 1.0000 0 0.8125 1.0000 0 0.8750 1.0000 0 0.9375 1.0000 0 1.0000 1.0000 0.0625 1.0000 0.9375 0.1250 1.0000 0.8750 0.1875 1.0000 0.8125 0.2500 1.0000 0.7500 0.3125 1.0000 0.6875 0.3750 1.0000 0.6250 0.4375 1.0000 0.5625 0.5000 1.0000 0.5000 0.5625 1.0000 0.4375 0.6250 1.0000 0.3750 0.6875 1.0000 0.3125 0.7500 1.0000 0.2500 0.8125 1.0000 0.1875 0.8750 1.0000 0.1250 0.9375 1.0000 0.0625 1.0000 1.0000 0 1.0000 0.9375 0 1.0000 0.8750 0 1.0000 0.8125 0 1.0000 0.7500 0 1.0000 0.6875 0 1.0000 0.6250 0 1.0000 0.5625 0 1.0000 0.5000 0 1.0000 0.4375 0 1.0000 0.3750 0 1.0000 0.3125 0 1.0000 0.2500 0 1.0000 0.1875 0 1.0000 0.1250 0 1.0000 0.0625 0 1.0000 0 0 0.9375 0 0 0.8750 0 0 0.8125 0 0 0.7500 0 0 0.6875 0 0 0.6250 0 0 0.5625 0 0 0.5000 0 0]; sz = size(cc); cind = round(([1:n]/(n+1))*sz(1)); c = cc(cind,:);
github
mribri999/MRSignalsSeqs-master
epg_relax.m
.m
MRSignalsSeqs-master/Matlab/epg_relax.m
848
utf_8
865ca72ddc8b060332d46233d3e4b573
%function [FpFmZ,EE] = epg_relax(FpFmZ,T1,T2,T) % % Propagate EPG states through a period of relaxation over % an interval T. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % T1,T2 = Relaxation times (same as T) % T = Time interval (same as T1,T2) % % OUTPUT: % FpFmZ = updated F+, F- and Z states. % EE = decay matrix, 3x3 = diag([E2 E2 E1]); % % SEE ALSO: % epg_grad, epg_rf % % B.Hargreaves. function [FpFmZ,EE] = epg_gt(FpFmZ,T1,T2,T) if(T1 < 0 || T2 < 0 || T < 0) warning('negative values for time') end E2 = exp(-T/T2); E1 = exp(-T/T1); EE = diag([E2 E2 E1]); % Decay of states due to relaxation alone. RR = [1-E1]; % Mz Recovery, affects only Z0 state, as % recovered magnetization is not dephased. FpFmZ = EE * FpFmZ; % Apply Relaxation FpFmZ(3,1) = FpFmZ(3,1)+RR; % Recovery
github
mribri999/MRSignalsSeqs-master
Rad229_MRI_Phantom.m
.m
MRSignalsSeqs-master/Matlab/Rad229_MRI_Phantom.m
1,927
utf_8
e1453e3b131e8433928e0bb9fab86e50
%% Rad229_MRI_Phantom – Create an object with MRI related properties. % % SYNTAX - [ P , M ] = Rad229_MRI_Phantom(acq) % % INPUTS - acq is a structure that needs to contain acq.Nx (number of % pixels defining the *square* phantom matrix size. % % OUTPUTS - P - Is the phantom object matrix [acq.Nx x acq.Nx] % M - A 3D logical mask matrix. Each layer is an object in the phantom. % % [email protected] (April 2021) for Rad229 function [ P , M ] = Rad229_MRI_Phantom(acq) if nargin == 0 acq.Nx = 128; % Matrix is NxN (then padded later to accomodate motion) end %% Use the default "modified shepp-logan" phantom parameters and define "tissue" parameters [ P , E ] = phantom( 'modified shepp-logan' , acq.Nx ); % Create a default phantom %% Create a separate object for each feature for n = 1 : size( E , 1 ) tmp = phantom( [ 1 E( n , 2 : end ) ] , acq.Nx ); % Force each mask intensity to be ONE M( : , : , n ) = tmp ~= 0; % Logical mask for each object in phantom (objects may overlap) end % Parse the background and define some "white-matter" (bulk of phantom) and a "skull" (outer ring of "tissue") Q( : , : , 1 ) = ~M( : , : , 1 ) & ~M( : , : , 2 ); % Background Q( : , : , 2 ) = M( : , : , 1 ) & M( : , : , 2 ); % White-matter Q( : , : , 3 ) = M( : , : , 1 ) & ~M( : , : , 2 ); % "Skull" or "fat" M = cat( 3 , Q , M( : , : , 3 : end ) ); M( : , : , 2 ) =~ ( sum( M , 3 ) > 1 ) & Q( : , : , 2 ); % This makes the "white matter" only everywhere around the ROIs (no overlap) return %% NOT IMPLEMENTED YET... % obj.Nx = % obj.pd(n). % obj.T1(n). % obj.T2(n). % obj.fat(n). % obj.off(n). % obj.T2s(n). % obj.obj(n) = % obj.tissue(n) = %% Assign tissue parameters to each feature % T1_fat=260; % T2_fat=85; % PD_fat=1.0; % % T1_WM=790; % T2_WM=92; % PD_WM=0.9; % % T1_CSF=2400; % T2_CSF=180; % PD_CSF=1.0; % % T1_HEM=400; % T2_HEM=50; % PD_HEM=0.75;
github
mribri999/MRSignalsSeqs-master
homodyneshow.m
.m
MRSignalsSeqs-master/Matlab/homodyneshow.m
1,512
utf_8
205063c142e65166d21bf63a960bb495
% Function imhd = homodyneshow(im,w) % % Function does a homodyne reconstruction on % data for a complex image im, with merge filter % width w (even) and displays stages. % function imhd = homodyneshow(im,w) if (nargin < 2) w=16; end; % Get image size [m,n] = size(im); % Low-pass filter % lpf = zeros(m,1); lpf( floor(m/2)-w/2: floor(m/2)+w/2-1 ) = 1; % LPF of 1s in center. % Merging filter mf = cumsum(lpf); % Ramp merge filter mf = 2*mf/max(mf(:)); % Scale from 0 to 2. subplot(3,3,1); plot(lpf); lplot('ky','LPF','a) LPF Magnitude'); subplot(3,3,2); plot(mf); lplot('ky','Merging Filter','b) Merge Filter'); setprops; % Low-res Phase Estimate % ksp = ifftshift(ifft2(ifftshift(im))); klp = diag(lpf)*ksp; imlp= ft(klp); % Low-Res image subplot(3,3,4); dispim(imlp); axis off; title('c) Low-Res Image'); subplot(3,3,5); dispangle(imlp); axis off; title('d) Phase'); %% f) Phase estimate khf = diag(mf)*ksp; % Half kspace imhf = ft(khf); % Half Fourier Image (zero filled) subplot(3,3,7); dispim(imhf); axis off; title('e) Zero-Filled Image'); subplot(3,3,8); dispangle(imhf); axis off; title('f) Phase'); phest = angle(imlp); imhd = imhf.*exp(-i*phest); % Homodyne recon Image imhd = imhd * (mean(abs(im(:)))/mean(abs(real(imhd(:))))); % Normalize subplot(3,3,3); [l,h] = dispim(real(im)); axis off; title(' Original Image'); subplot(3,3,6); dispim(real(imhd)); axis off; title(' Final Image'); subplot(3,3,9); dispim(real(imhd)-abs(im),l,h); axis off; title('Difference Image');
github
mribri999/MRSignalsSeqs-master
magphase.m
.m
MRSignalsSeqs-master/Matlab/magphase.m
382
utf_8
4b1fc6a38d193b9710db763156ee0158
% % function magphase(x,arr) % % Function plots in two subplots the magnitude and % phase of a complex-valued signal. % function magphase(x,arr) if (nargin < 2) arr = x; x = 1:length(arr); end; mg = abs(arr); ph = angle(arr); subplot(2,1,1); plot(x,mg); ylabel('Magnitude'); subplot(2,1,2); plot(x,ph/pi); ylabel('Phase/\pi'); a = axis; axis([a(1) a(2) -1 1]); grid on;
github
mribri999/MRSignalsSeqs-master
vecdcf.m
.m
MRSignalsSeqs-master/Matlab/vecdcf.m
1,811
utf_8
35f82890de93bea5905a12f0b6065577
% function [dcf,k] = vecdcf(g,k [,N,res,FOV]) % % Calculate the Density Correction Factors for % a given spiral trajectory using the vector approach % used by Craig Meyer (MRM, 1992) % % INPUT: % g = gradient (Gx + i*Gy) % k = k-space (kx + i*ky) % % % OUTPUT: % dcf = list of density compensation factors % % % NOTES: % if k is omitted, it is calculated from g. % If k is 1x1, it is assumed to be the % #of sample points. % % =============== CVS Log Messages ========================== % This file is maintained in CVS version control. % % $Log: vecdcf.m,v $ % Revision 1.1 2003/08/28 20:27:01 brian % Added. % % Revision 1.1 2002/04/25 21:58:20 bah % Added to CVS. % % % =========================================================== function [dcf,k] = vecdcf(g,k,N,res,FOV) % ========== Fix Gradient if Nx2 ============ sg = size(g); if (sg(2)==2) % Gradient vector is Nx2 g = g(:,1)+i*g(:,2); end; % ========== Calculate k-space from gradients ============ if ((nargin < 2) | (length(k)==0)) % If only g is given. k = cumint(g,0.5); k = k*0.5/max(abs(k(:))); end; if (max(size(k))==1) Nsamps = k; k = cumint(g(1:Nsamps),0.5); k = k*0.5/max(abs(k(:))); end; Nsamps = length(k); % ========== Calculate Density Corr Factors using Vector Approach ===== g3 = [real(g(:)) imag(g(:)) 0*g(:)]'; k3 = [real(k(:)) imag(k(:)) 0*k(:)]'; dcf = 0*k; for m=1:Nsamps dcf(m) = norm(cross(g3(:,m),k3(:,m))); if (abs(k(m)) > 0) dcf(m) = dcf(m)/abs(k(m)); else dcf(m) = 0; end; end; % =========== IF N, res, FOV given, replicate for N interleaves === dcf = dcf(:); k = k(:); if (nargin > 2) dcfall = zeros(length(dcf),N); kall = zeros(length(dcf),N); for p=1:N ph=exp(i*2*pi*(p-1)/N); kall(:,p)=k*ph; dcfall(:,p)=dcf; end; dcf=dcfall; k = kall * FOV/res/256; end;
github
mribri999/MRSignalsSeqs-master
epg_grelax.m
.m
MRSignalsSeqs-master/Matlab/epg_grelax.m
2,622
utf_8
dc7d9df2a831bffc54fc2da5f6058dab
%function [FpFmZ,EE,BV] = epg_grelax(FpFmZ,T1,T2,T,kg,D,Gon,noadd) % % Propagate EPG states through a period of relaxation, and % diffusion over an interval T, with or without a gradient. % Leave last 3 blank to exclude diffusion effects. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % T1,T2 = Relaxation times (s) % T = Time interval (s) % (Optional inputs follow) % kg = k-space traversal due to gradient (rad/m) for diffusion % D = Diffusion coefficient (m^2/s) % Gon = 0 if no gradient on, 1 if gradient on % (gradient will advance states at the end.) % noadd=1 to not add higher-order states - see epg_grad.m % % OUTPUT: % FpFmZ = updated F+, F- and Z states. % EE = decay matrix, 3x3 = diag([E2 E2 E1]); % BV = b-value matrix, 3xN (see FpFmZ) of attenuations. % % SEE ALSO: % epg_grad, epg_rf % % B.Hargreaves. function [FpFmZ,EE,BV] = epg_grelax(FpFmZ,T1,T2,T,kg,D,Gon,noadd) if (nargin < 5) kg = 0; D = 0; end; % Default ignore diffusion if (nargin < 8) noadd=0; end; % Default is to add states. if (nargin < 7) Gon = 1; end; % Default is Gon. if (nargin > 1) % Skip relaxation if only one argument E2 = exp(-T/T2); E1 = exp(-T/T1); EE = diag([E2 E2 E1]); % Decay of states due to relaxation alone. RR = [1-E1]; % Mz Recovery, affects only Z0 state, as % recovered magnetization is not dephased. FpFmZ = EE * FpFmZ; % Apply Relaxation FpFmZ(3,1) = FpFmZ(3,1)+RR; % Recovery ( here applied before diffusion, % but could be after or split.) end; if (nargin > 4) % Model Diffusion Effects Findex = 0:length(FpFmZ(1,:))-1; % index of states, 0...N-1 bvalZ = ((Findex)*kg).^2*T; % diffusion for Z states, assumes that % the Z-state has to be refocused, so % this models "time between gradients" % For F states, the following models the additional diffusion time % (Findex) and the fact that the state will change if the gradient is % on (0.5*Gon), then the additional diffusion *during* the gradient, % ... Gon*kg^2/12 term. bvalp = ((( Findex+.5*Gon)*kg).^2+Gon*kg^2/12)*T; % for F+ states bvalm = (((-Findex+.5*Gon)*kg).^2+Gon*kg^2/12)*T; % for F- states FpFmZ(1,:) = FpFmZ(1,:) .* exp(-bvalp*D); % diffusion on F+ states FpFmZ(2,:) = FpFmZ(2,:) .* exp(-bvalm*D); % diffusion on F- states FpFmZ(3,:) = FpFmZ(3,:) .* exp(-bvalZ*D); % diffusion of Z states. BV = [bvalp; bvalm; bvalZ]; % For output. end; if (Gon==1) if (kg >= 0) FpFmZ = epg_grad(FpFmZ,noadd); % Advance states. else FpFmZ = epg_mgrad(FpFmZ,noadd); % Advance states by negative gradient. end; end;
github
mribri999/MRSignalsSeqs-master
lplot.m
.m
MRSignalsSeqs-master/Matlab/lplot.m
406
utf_8
507fa16138e49993eeb9d94975ed5ccd
% Function lplot(xlab,ylab,tit,ax,grid); % % Label a figure, turn on grid, and set properties % function lplot(xlab,ylab,tit,ax) if (nargin >0) && (length(xlab)>0) xlabel(xlab); end; if (nargin >1) && (length(ylab)>0) ylabel(ylab); end; if (nargin >2) && (length(tit)>0) title(tit); end; if (nargin >3) && (length(ax)>3) axis(ax); end; if (nargin <5) || (grid==1) grid on; end; setprops;
github
mribri999/MRSignalsSeqs-master
ft.m
.m
MRSignalsSeqs-master/Matlab/ft.m
172
utf_8
3de787c860ab4b960b481aa3ead77652
% function im = ft(dat) % % Function does a centered 2DFT of the data: % % im = fftshift(fft2(fftshift(dat))); function im = ft(dat) im = fftshift(fft2(fftshift(dat)));
github
mribri999/MRSignalsSeqs-master
Rad229_Conventional_FlowComp.m
.m
MRSignalsSeqs-master/Matlab/Rad229_Conventional_FlowComp.m
3,236
utf_8
f5785538f1bc291dd9a9505ecef0be9d
%% Rad229_Conventional_FlowComp – Demonstrate designing a flow-compensated gradient waveform. % % Based, in part, on this paper: % % Encoding strategies for three-direction phasecontrast MR imaging of flow. % Pelc NJ, Bernstein MA, Shimakawa A, Glover GH. J Magn Reson Imaging 1991;1(4):405-413. % % SYNTAX - [G_FC, M0S, M1S, t_ss, G_ss, M0_FC, M1_FC] = Rad229_Conventional_FlowComp(params) % % INPUTS - params % % OUTPUTS – G_FC % M0S % M1S % t_ss % G_ss % M0_FC % M1_FC % % [email protected] (March 2020) for Rad229 % [email protected] (March 2021) for Rad229 - Minor updates function [G_FC, M0S, M1S, t_ss, G_ss, M0_FC, M1_FC, t_FC] = Rad229_Conventional_FlowComp(params) % Build the slice select gradient Gss_plat = linspace( params.g_ss , params.g_ss , ceil( params.p_ss / params.dt ) ); % Gss_down = linspace( params.g_ss , params.g_ss / 10 , 10 ); Gss_down = linspace( params.g_ss , 0 , 10 ); G_ss = [ Gss_plat Gss_down ]; t_ss = length(G_ss) * params.dt; t_vec = 0 : params.dt : (length(G_ss)-1)*params.dt; % Get moments of the slice select that we need to compensate M0S = cumsum( (G_ss .* params.dt) , 2); % [T/m x s] M1S = cumsum( (G_ss .* t_vec * params.dt) , 2); % [T/m x s^2] % Moments at end of slice select M0S_ = M0S( 1 , end ); M1S_ = M1S( 1 , end ); % Now solve for the next two lobes as presented in: % Encoding strategies for three-direction phasecontrast MR imaging of flow. % Pelc NJ, Bernstein MA, Shimakawa A, Glover GH. J Magn Reson Imaging 1991;1(4):405-413. % But we add an additional search over risetime (r) to allow for waveforms with triangle lobes. % Maximum riseitme [s] rmax = params.gmax/params.smax; % r = risetime in [s] for r = 1e-06 : 1e-06 : rmax r_ = (ceil(r/params.dt)); % risetime in 'dt' units h = r*params.smax; % gradient strength [T/m] M02 = (-h*r+sqrt((h*r)^2+2*(h*r*M0S_ + M0S_^2 + 2*h*M1S_)))/2; % Area of the second lobe (see above paper for derivation) [T/m x s] M01 = M02 + M0S_; % Area of the first lobe (see above paper for derivation) [T/m x s] w1 = M01/h + r; % Duration of first lobe [s] w2 = M02/h + r; % Duration of second lobe [s] w1_ = (ceil(w1/params.dt)); % Duration of first lobe in 'dt' units w2_ = (ceil(w2/params.dt)); % Duration of first lobe in 'dt' units % Signed amplitudes [T/m] h1 = -h; h2 = h; % We stop this loop if the flattop time is less than one 'dt' unit (triangle lobe) if (w1_-2*r_ <= 1) || (w2_-2*r_ <= 1) h1 = M01/(r_-w1_)*100; h2 = -M02/(r_-w2_)*100; break end end % Build the flow compensated bipolar G = horzcat(linspace(0,h1,r_),linspace(h1,h1,w1_-2*r_),linspace(h1,h2,2*r_),linspace(h2,h2,w2_-2*r_),linspace(h2,0,r_)); % Output waveform in [T/m] G_FC = horzcat(G_ss,G); % Compute final gradient moments t_vec = 0 : params.dt : ( length( G_FC ) - 1 ) * params.dt; M0_FC = cumsum( ( G_FC .* params.dt ) , 2 ); % [T/m x s] M1_FC = cumsum( ( G_FC .* t_vec * params.dt ) , 2); % [T/m x s^2] % Define a time vector t_FC = ( 0 : (length(G_FC)-1) ) * params.dt; end
github
mribri999/MRSignalsSeqs-master
epg_mgrad.m
.m
MRSignalsSeqs-master/Matlab/epg_mgrad.m
939
utf_8
e79c2b413cb65a6eb82cbd8f75a426d8
% %function [FpFmZ] = epg_mgrad(FpFmZ,noadd) % Propagate EPG states through a *NEGATIVE* "unit" gradient. % (States move the opposite direction to epg_grad!) % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % noadd = 1 to NOT add any higher-order states - assume % that they just go to zero. Be careful - this % speeds up simulations, but may compromise accuracy! % % OUTPUT: % Updated FpFmZ state. % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. function [FpFmZ] = epg_mgrad(FpFmZ,noadd) if (nargin < 2) noadd=0; end; % Add by default. % Gradient does not affect the Z states. if (noadd==0) FpFmZ = [FpFmZ [0;0;0]]; % Add higher dephased state. end; FpFmZ(2,:) = circshift(FpFmZ(2,:),[0 1]); % Shift Fm states. FpFmZ(1,:) = circshift(FpFmZ(1,:),[0 -1]); % Shift Fp states. FpFmZ(1,end)=0; % Zero highest Fp state. FpFmZ(2,1) = conj(FpFmZ(1,1)); % Fill in lowest Fm state.
github
mribri999/MRSignalsSeqs-master
epg_FZ2spins.m
.m
MRSignalsSeqs-master/Matlab/epg_FZ2spins.m
1,952
utf_8
70c6102373f20b409e7ebbe080b33238
%function [M] = epg_FZ2spins(FpFmZ, N, frac) % % Function returns a 3xN array of magnetization vectors [Mx My Mz].' % that is represented by the EPG state FpFmZ. Note that the % magnetization assumes that a "voxel" is divided into N states, % as is necessary to make the conversion. N must be at least % as large as twice the number of F+ states minus one. % % INPUT: % FpFmZ = F,Z states, 3xQ vector where there are Q states, % where rows represent F+, F- and Z states starting at 0. % N = number of spins used to represent the states. Default % is minimum. % frac = (optional) fraction of state to increment/decrement % so if frac=1, this is equivalent to first passing % FpFmZ through epg_grad(). This is mostly just % to make plots. % % OUTPUT: % M = [Mx My Mz].' representing magnetization vectors. % function [M] = epg_FZ2spins(FpFmZ,N,frac) if (nargin < 3) frac=0; end; % -- Don't include fractional rotation if (size(FpFmZ,1)~=3) error('EPG state must be 3xQ vector'); end; Ns = size(FpFmZ,2); % Number of EPG states (N should be 2*Q-1 or more) if (nargin < 2) N = 2*Ns-1; end; % Minimum value for N. if (N < 2*Ns-1) warning('Number of spins should be at least double number of states minus 1'); end; % -- Use a matrix for FFT to support arbitrary N. % This is because we are going from a discrete set of % coefficients to a "continuous" distribution of Mx,My,Mz x = [0:N-1]/N-0.5; % Fraction of a cycle for spins locations. ph = exp(i*2*pi*x.'*([-(Ns-1):(Ns-1)]+frac)); % Phasors for Fourier Xform % Note: frac = 0 usually! Fstates = [fliplr(conj(FpFmZ(2,2:end))) FpFmZ(1,:)]; % Stretched out % Vector of Fp (-n,n) Mxy = ph * Fstates.'; % 1D Fourier Transform to Mxy. ph = exp(i*2*pi*x.'*[0:Ns-1]); % Phasors for Mz transform FpFmZ(3,1)=FpFmZ(3,1)/2; % Account for discretization Mz = 2*real(ph*FpFmZ(3,:).'); % Transform to Mz M = [real(Mxy) imag(Mxy) Mz].'/N; % Form output vector.
github
mribri999/MRSignalsSeqs-master
epg_zrot.m
.m
MRSignalsSeqs-master/Matlab/epg_zrot.m
483
utf_8
83073de8b2328d733399d898a026f8f4
%function [FpFmZ] = epg_zrot(FpFmZ,rotangle) % % Rotate spin state about Mz axis by rotangle radians. % % INPUT: % FpFmZ = 3xN vector of F+, F- and Z states. % rotangle = angle by which to rotate (radians) % % OUTPUT: % Updated FpFmZ state. % % SEE ALSO: % epg_grad, epg_grelax % % B.Hargreaves. % function [FpFmZ] = epg_zrot(FpFmZ,rotangle) if (nargin < 2) rotangle = 0; end; phasor = exp(i*rotangle); FpFmZ = diag([phasor conj(phasor) 1]) * FpFmZ;
github
mribri999/MRSignalsSeqs-master
mingrad.m
.m
MRSignalsSeqs-master/Matlab/mingrad.m
1,339
utf_8
3f15db389b0c2af9df7ca0ed8ad106ee
% % function [g,t] = mingrad(area,Gmax,Smax,dt) % % Function calculates the fastest gradient waveform % to achieve the given area in k-space, and returns % it, along with a time array. % % INPUT: % area = desired k-space area in cm^(-1) % Gmax = maximum gradient (mT/m) [50]; % Smax = maximum slew (mT/m/ms) [200]; % dt = time step in ms [.004]; % % OUTPUT: % g = gradient waveform (mT/m); % t = time array (ms); % function [g,t] = mingrad(area,Gmax,Smax,dt) area = area*100; % Convert cm(-1) to m(-1) if (nargin < 2) Gmax = 50; end; % mT/m if (nargin < 3) Smax = 200; end; % mT/m/ms if (nargin < 4) dt = 0.004; end; % ms % 2 cases - triangle or trapezoid. % gamma = 42.58; % kHz/mT gamma = 40; % kHz/mT % Area of largest triangle Atri = gamma * (Gmax^2/Smax); % 1/2 base * height if (area <= Atri) % Area = (tramp)^2*Smax tramp = sqrt(area/gamma/Smax); % Ramp time (ms) Nramp = ceil(tramp/dt); % #pts on ramp g = [1:Nramp]*Smax*dt; % Generate ramp g = [g fliplr(g)]; else tramp = (Gmax/Smax); % Ramp time (ms) Nramp = ceil(tramp/dt); % #pts on ramp gramp = [1:Nramp]/Nramp*Gmax; Nplat = ceil(area/gamma/Gmax/dt - Gmax/Smax/dt); g = [gramp Gmax*ones(1,Nplat) fliplr(gramp)]; end; t = [1:length(g)]*dt; % Generate time array g = g * (area/gamma)/(sum(g)*dt); % Correct for rounding.
github
mribri999/MRSignalsSeqs-master
ghist.m
.m
MRSignalsSeqs-master/Matlab/ghist.m
1,314
utf_8
3305eccce75e3e6a42f1b0230f828e03
% % Function ghist(data,gmean,gsig,nbins,gtitle,gleg1,gleg2) % % Function makes is histogram of a signal, and superimposes % a gaussian fit. % % INPUT: % data = signal to make histogram for. % gmean = estimate for gaussian fit, mean [default=mean(data)] % gsig = estimate for gaussian fit, sigma [default=std(data)] % nbins = number of bins % gtitle = plot title % gleg1 = legend top line (describe data) % gleg2 = legend second line (describe gaussian) % function ghist(data,gmean,gsig,bins,gtitle,gleg1,gleg2) N = length(data(:)); if nargin < 2 || length(gmean)==0 gmean = mean(data); end; if nargin < 3 || length(gsig)==0 gsig = std(data); end; if nargin < 4 || length(bins)==0 nbins=100; bins = 4*gsig*[-1:2/(nbins-1):1]; % Histogram bins end; if nargin < 5 || length(gtitle)==0 gtitle='Data and Gaussian'; end; if nargin < 6 || length(gleg1)==0 gleg1 = 'Data'; end; if nargin < 7 || length(gleg2)==0 gleg2 = 'Gaussian Fit'; end; hold off; histogram(data(:),bins); % Plot Histogram lplot('Signal','Likelihood',gtitle,[min(bins),max(bins),0,10*sqrt(N)]); hold on; gscale = N/length(bins)/1.5; %gscale = N/length(bins)/sqrt(sqrt(bsigma)); % Scaling plot(bins,gscale*gaussian(bins,gmean,gsig),'r-'); % Plot normal distribution. legend(gleg1,gleg2); hold off; grid on;
github
mribri999/MRSignalsSeqs-master
gaussian.m
.m
MRSignalsSeqs-master/Matlab/gaussian.m
262
utf_8
822d6349afc30f0f984cb8aa020e2619
% Function y = gaussian(x,mn,sig) % % Function generates the gaussian distribution output y % based on x and the mean (mn) and sigma (sig). x can be a % number or array. % function y = gaussian(x,mn,sig) y = exp(-(x-mn).^2 / (2*sig^2)) / (sqrt(2*pi)*sig);
github
mribri999/MRSignalsSeqs-master
calcgradinfo.m
.m
MRSignalsSeqs-master/Matlab/calcgradinfo.m
1,595
utf_8
e888e10d970046f47949765dcd3ecee4
% % function [k,g,s,m1,m2,t,v]=calcgradinfo(g,T,k0,R,L,eta) % % Function calculates gradient information % % INPUT: % g gradient (G/cm) = gx + i*gy % T sample period (s) % k0 initial condition for k-space. % R coil resistance (ohms, default =.35) % L coil inductance (H, default = .0014) % eta coil efficiency (G/cm/A, default = 1/56) % % OUTPUT: % k k-space trajectory (cm^(-1)) % g gradient (G/cm) % s slew rate trajectory (G/cm/s) % m1 first moment trajectory (s/cm) % m2 second moment trajectory (s^2/cm) % t vector of time points (s) % v voltage across coil. % % B.Hargreaves, Aug 2002. % % =============== CVS Log Messages ========================== % $Log: calcgradinfo.m,v $ % Revision 1.4 2002/10/14 15:59:36 brian % Added calculation/plot of voltage. % % Revision 1.3 2002/09/26 21:16:39 bah % Fixed m2 calculation % % Revision 1.2 2002/09/16 22:35:51 bah % now supports Nx2 g % % Revision 1.1 2002/09/05 18:35:43 bah % Separted into calculation and plot parts. % % % =========================================================== function [k,g,s,m1,m2,t,v]=calcgradinfo(g,T,k0,R,L,eta) if (nargin < 2) T = .000004; end; if (nargin < 3) k0 = 0; end; if (nargin < 4) R = .35; end; if (nargin < 5) L = .0014; end; if (nargin < 6) eta = 1/56; end; gamma = 4258; s = size(g); lg = max(size(g)); k = k0 + cumsum(g)*gamma*T; t = ([1:length(g)]-.5)*T; t = t'; s = size(g); tt = t*ones(1,s(2)); s = [g; g(lg,:)]-[0*g(1,:); g]; sz=size(s); s = s(2:sz(1),:)/T; m1 = cumsum(g.*tt)*gamma*T; m2 = cumsum(g.*(tt.*tt+T^2/12))*gamma*T; v = (1/eta)*(L*s+R*g);
github
mribri999/MRSignalsSeqs-master
Rad229_Fourier_Encoding.m
.m
MRSignalsSeqs-master/Matlab/Rad229_Fourier_Encoding.m
4,185
utf_8
47fce21ee336430db323a1896cd391cf
%% Rad229_Fourier_Encoding demonstrates some Fourier sampling functions % % SYNTAX - [acq, F] = Rad229_Fourier_Encoding(acq); % % INPUTS - acq.FOVx = 210e-3; % Field-of-view along y-direction [m] % acq.Nx = 21; % Number of pixels to discretize FOVy [#] % % acq.FOVy = 150e-3; % Field-of-view along y-direction [m] % acq.Ny = 15; % Number of pixels to discretize FOVy [#] % % acq.n_kx = 0; % Fourier kx-sampling point to show (=0 is middle of k-space) % % acq.n_ky = 4; % Fourier ky-sampling point to show (=0 is middle of k-space) % % acq.upsamp = 5; % Upsampling factor for visualizing patterns % % OUTPUTS - acq - Acquisition parameter structure % F - Fourier encoding pattern % % [email protected] (March 2021) for Rad229 %% These questions can be used to further explore the code and concepts. % % 1) Set acq.n_kx = 3 and acq.n_ky = 0. How many phase cycles do you see along the frequency encode direction? % % 2) Set acq.n_kx = 0 and acq.n_ky = 4. How many phase cycles do you see along the phase encode direction? % % 3) Set acq.n_kx = 2 and acq.n_ky = 5. How many phase cycles do you see along the phase and frequency encode direction? % % 4) If you set acq.n_kx = k_x,max and acq.n_ky = k_y,max does this satisfy Nyquist sampling? Explain. % % 4) [Advanced] Revise the code to compute the applied phase and frequency encoding gradients, then dkx and dky. % % 5) [Advanced] Use this code to estimate the Fourier coefficients for an object, then use the FFT % to recover an image of the object. % % 6) [Advanced] Use this code to demonstrate field-of-view aliasing and compressed-sensing artifacts. function [acq, F] = Rad229_Fourier_Encoding(acq) %% Define MRI system constants sys = Rad229_MRI_sys_config; %% Define acquisition parameters if nargin == 0 acq.FOVx = 210e-3; % Field-of-view along y-direction [m] acq.Nx = 21; % Number of pixels to discretize FOVy [#] % acq.RBW = 32e3; % Receiver pixel bandwidth magnitude [Hz] acq.FOVy = 150e-3; % Field-of-view along y-direction [m] acq.Ny = 15; % Number of pixels to discretize FOVy [#] acq.n_kx = 0; acq.n_ky = 4; acq.upsamp = 5; % Upsampling factor for visualizing patterns end %% Check the index is within range if abs(acq.n_kx) > ( (acq.Nx - 1) / 2 ), warning('acq.n_kx will exceed kx_max.'); end if abs(acq.n_ky) > ( (acq.Ny - 1) / 2 ), warning('acq.n_ky will exceed ky_max.'); end %% Calculate some spatial parameters acq.x_pos = linspace(-acq.FOVx/2, acq.FOVx/2, acq.upsamp * acq.Nx); % Define the pixel locations [m] acq.y_pos = linspace(-acq.FOVy/2, acq.FOVy/2, acq.upsamp * acq.Ny); % Define the pixel locations [m] [acq.X, acq.Y] = ndgrid(acq.x_pos, acq.y_pos); % Define a grid of pixel positions [m] %% Calculate the delta k-space steps acq.dkx = 1 / acq.FOVx; % Spatial frequency increment [cycle/m] acq.dky = 1 / acq.FOVy; % Spatial frequency increment [cycle/m] %% Compute the Fourier sampling functions F = exp( -1i * 2 * pi * (acq.n_kx * acq.dkx * acq.X + acq.n_ky * acq.dky * acq.Y) ); % Fourier sampling functions %% Display the sampling function f = figure; hold on; s = surf(acq.X, acq.Y, angle(F)); view(0,90); set(s,'EdgeColor','None'); colorbar; caxis([-pi pi]); title('angle(F)'); axis image xy; set(gca, 'FontSize', 24); %% Compute the applied gradient % acq.dx = acq.FOVx / acq.Nx; % Pixel dimension along y-direction [m] % acq.dy = acq.FOVy / acq.Ny; % Pixel dimension along y-direction [m] % Gx.G_plat_amp = ( 2 * acq.RBW ) / ( sys.gamma_bar * acq.FOVx ); % Readout gradient plateau amplitude [T/m] % Gy.G_plat_amp = ( 2 * acq.RBW ) / ( sys.gamma_bar * acq.FOVy ); % Readout gradient plateau amplitude [T/m] % Note - This assume the phase encode step takes as long as a readout step % Compute dkx and dky from the applied gradients % acq.dkx = sys.gamma_bar * Gx.G_plat_amp * ( 1 / (2 * acq.RBW) ); % kx-space component [1/m] % acq.dky = sys.gamma_bar * Gy.G_plat_amp * ( 1 / (2 * acq.RBW) ); % ky-space component [1/m]
github
mribri999/MRSignalsSeqs-master
epg_animrf.m
.m
MRSignalsSeqs-master/Matlab/epg_animrf.m
554
utf_8
6cfb79f3aa674888de66015188f2e9a1
function FZ = epg_animrf(FZ,flip,phase,N,scale,showorder) % % Animate an EPG state through an RF pulse % if (nargin < 4) N = 24; end; if (nargin < 5) scale = 1; end; if (nargin < 6) showorder=-1; end; Nf = 20; for p=0:Nf if (showorder==-1) epg_showstate(FZ,0,scale,N); else epg_showorder(FZ(:,showorder+1),showorder,0); end; if (p<Nf) FZ = epg_rf(FZ,flip/Nf,phase); end; drawnow; pause(0.05); if (exist('epg_saveframe')) epg_saveframe; % Save frame, if globals 'framenum' and 'filestem' exist end; end;
github
mribri999/MRSignalsSeqs-master
throt.m
.m
MRSignalsSeqs-master/Matlab/throt.m
814
utf_8
834e1e36edf884f08695802d4e400f4b
% function [M] = throt(alpha,phi) % % Function returns the rotation matrix M such that % y = Mx rotates a 1x3 cartesian vector about the axis % defined by y=x*tan(phi), by alpha degrees. % The rotation is left-handed. % % phi is in degrees too. % % See also: tprot % % ======================== CVS Log Messages ======================== % $Log: throt.m,v $ % Revision 1.2 2002/03/28 00:50:11 bah % Added log to source file % % % % ================================================================== function [M] = throt(alpha,phi) ca = cos(pi/180*alpha); % cosine of tip alpha sa = sin(pi/180*alpha); % sine of tip cp = cos(pi/180*phi ); % cosine of phi sp = sin(pi/180*phi ); % sine of phi M = [cp*cp+sp*sp*ca cp*sp*(1-ca) -sp*sa; cp*sp-sp*cp*ca sp*sp+cp*cp*ca cp*sa; sa*sp -sa*cp ca];
github
mribri999/MRSignalsSeqs-master
lfphase.m
.m
MRSignalsSeqs-master/Matlab/lfphase.m
500
utf_8
c789ff17af4c8d63fb446a7b994b3231
% % Function ph = lfphase(m,n,w) % % Function generates a low-resolution phase function, by % FFT of random coefficients. % % 2*w+1 = width of non-zero Fourier coefficients. function ph = lfphase(m,n,w) if (nargin < 2) n=m; end; if (nargin < 3) w=4; end; arr = zeros(m,n); arr(floor(m/2-w):floor(m/2+w) ,floor(n/2-w):floor(n/2+w)) = randn(2*w+1,2*w+1); ang=fftshift(fft2(fftshift(arr))); % Angle ang= real(ang); ang= 2*pi*(ang-min(ang(:))) / (max(ang(:))-min(ang(:))) -pi; ph = exp(i*ang);
github
mribri999/MRSignalsSeqs-master
corrnoise.m
.m
MRSignalsSeqs-master/Matlab/corrnoise.m
1,031
utf_8
d0ce1f985ee5934dccd09c7d2843ae45
% Function [nc,Rout] = corrnoise(mn,R,n) % % Function generates correlated noise, where % R can be complex. % % INPUT: % mn = mean of noise (default to 0) % R = noise covariance matrix % n = number of samples % % OUTPUT: % nc = mxn array of noise samples, where m is dimension of R % Rout = covariance of samples (check!) % Taken from https://www.mathworks.com/matlabcentral/fileexchange/21156-correlated-gaussian-noise function [nc,Rout] = corrnoise(mn,R,n) if (nargin < 3) n = 100; end; if (nargin < 2) || (size(R,1)<1) R = [1 0.1 0.2*i; 0.1 0.8 0.3; -0.2*i 0.3 0.95]; %R = [1 0.1 0.2; 0.1 0.8 0.3; 0.2 0.3 0.95]; end; if (nargin < 1) || (length(mn)<1) mn = zeros(size(R,1),1); end; nvect = randn(size(R,1),n); % Noise vector % symmetrize matrix R R = 0.5 * (R + R'); % Force correlation matrix to be symmetric. R [v,d] = eig(R); % Eigen decompolstion. if (any(diag(d) <=0)) error('R must be positive definite'); end; w = v*sqrt(d); nc = w*nvect; if (nargout > 1) Rout = (nc * nc')/n; end;
github
mribri999/MRSignalsSeqs-master
calc_harmonics.m
.m
MRSignalsSeqs-master/Matlab/calc_harmonics.m
1,077
utf_8
73ca3d9e0c073bab404e7a6bb16a8799
%**************************************************************************% function B = calc_harmonics(Alpha, Beta, X, Y, Z, R0) %MRIS_GRADIENT_NONLIN__SIEMENS_B calculate displacement field from Siemens's coefficients nmax = size(Alpha,1)-1; % convert to spherical coordinates R = sqrt(X.^2+Y.^2+Z.^2); R_eps = R + .0001; Theta = acos(Z./R_eps); Phi = atan2(Y./R_eps,X./R_eps); % evaluate the Legendre polynomial (using Siemens's normalization) B = 0; for n = 0:nmax P = mris_gradient_nonlin__siemens_legendre(n,cos(Theta)); F = (R/R0).^n; for m = 0:n F2 = Alpha(n+1,m+1)*cos(m*Phi)+Beta(n+1,m+1)*sin(m*Phi); B = B+F.*P(m+1,:).*F2; end end end %**************************************************************************% function P = mris_gradient_nonlin__siemens_legendre(n,X) %MRIS_GRADIENT_NONLIN__SIEMENS_LEGENDRE normalize Legendre polynomial with Siemens's convention P = legendre(n,X); for m=1:n normfact = (-1)^m*sqrt((2*n+1)*factorial(n-m)/(2*factorial(n+m))); P(m+1,:) = normfact*P(m+1,:); end end
github
mribri999/MRSignalsSeqs-master
nlegend.m
.m
MRSignalsSeqs-master/Matlab/nlegend.m
489
utf_8
ff232770257e189028cd6d741fc4f7fc
% Function nlegend(a,fmt); % % Make a legend from the numbers in an array a. % Default is to use %d, but if fmt is defined, use it instead. % % Example if a=[1.2 3.4] and fmt='b=%g' then this will % effectively do legend('b=1.2','b=3.4') % % Note that you have to make sure length(a) does not exceed the % number of plot traces! % function nlegend(a,fmt) if (nargin < 2) fmt = '%d'; end; allstr = {}; for k=1:length(a) tt = sprintf(fmt,a(k)); allstr{k} = tt; end; legend(allstr);
github
mribri999/MRSignalsSeqs-master
epg_rfspoil.m
.m
MRSignalsSeqs-master/Matlab/epg_rfspoil.m
1,959
utf_8
79e6603fe80cc62bf57047fa33f68c55
% function [s,phasediag,P] = epg_rfspoil(flipangle,phinc,N,T1,T2,TR) % % EPG Simulation of RF-spoiled sequence. % % flipangle = flip angle (radians) % phinc = phase increment (radians); % N = number of TRs % T1,T2,TR = relaxation times and TR % % All states are kept, for demo purposes, though this % is not really necessary. NOTE: if phinc=0, this should give % the same result as epg_gradspoil.m function [s,phasediag,P] = epg_rfspoil(flipangle,phinc,N,T1,T2,TR) if (nargin < 1) flipangle = pi/6; end; if (nargin < 2) phinc = 117/180*pi; end; if (nargin < 3) N=100; end; if (nargin < 4) T1 = 1; end; % sec if (nargin < 5) T2 = 0.1; end; % sec if (nargin < 6) TR = 0.01; end; % sec P = zeros(3,N); % Allocate all known states, 1 per echo. P(3,1)=1; % Initial condition/equilibrium. Pstore = zeros(2*N,N); % Store F,F* states, with 2 gradients per echo Zstore = zeros(N,N); % Store Z states, with 2 gradients per echo s = zeros(1,N); % Allocate signal vector to store. phaseinc = 0; % No phase increment to start (arbitrary) rfphase = 0; % Register to store. for n=1:N P = epg_grelax(P,T1,T2,TR,1,0,1,1); % Gradient spoiler (before RF, save sig) P = epg_rf(P,flipangle,rfphase); % RF excitation s(n) = P(1,1); % Signal is F0 state. rfphase = rfphase+phaseinc; % Increment the phase phaseinc = phaseinc+phinc; % Increment the increment... Pstore(N:2*N-1,n) = P(2,:).'; % Put in negative states Pstore(1:N,n) = flipud(P(1,:).'); % Put in positive, overwrite center. Zstore(:,n) = P(3,:).'; end; set(0,'defaultAxesFontSize',14); % Default font sizes set(0, 'DefaultLineLineWidth', 2); % Default line width plotstate = cat(1,Pstore,Zstore); subplot(1,2,1); plot([1:N]*TR,abs(s)); lplot('Evolution Time','Signal','RF-Spoiled Signal vs TR time'); subplot(1,2,2); dispim(plotstate,0,0.2); xlabel('Echo'); ylabel('F(top) and Z(bottom) States'); title('F and Z states vs time'); phasediag = plotstate;
github
mribri999/MRSignalsSeqs-master
abprop.m
.m
MRSignalsSeqs-master/Matlab/abprop.m
1,670
utf_8
6ebd17e34985c6d45e06bb9ba5f19a41
% % function [A,B,mss] = abprop(A1,B1,A2,B2,A3,B3,...) % % Function 'propagates' matrices A and B to give overall A,B % such that m' = A*m+B. The Ai,Bi are applied in order, ie A1,B1 % are the first applied to m, then A2,B2 and so on. % % If mss is provided, the steady-state is calculated - in which case % the A1,B1 list should start right after the point where it is desired % to calculate mss. % % If an Ai is 3x4, then it is assumed to be [Ai Bi] % % If a Bi vector is omitted (the next argument is 3x3 or 3x4, % it is assumed to be zero. % function [A,B,mss] = abprop(varargin) A=eye(3); B=[0;0;0]; % Start with identity mss = []; % Default argcount=1; while (argcount <= nargin) Ai = varargin{argcount}; argcount = argcount+1; if (size(Ai) == [3 3]) % If next argument is 3x1, that's Bi, % otherwise (not 3x1 or end) Bi=0. if (argcount <= nargin) Bi = varargin{argcount}; if (size(Bi)==[3 1]) argcount = argcount+1; else Bi = [0;0;0]; % Wrong size for Bi, so ignore next argument end; else Bi = [0;0;0]; end; end; if (size(Ai) == [3 4]) % -- If 3x4, then of form [Ai Bi] Bi = Ai(:,4); Ai = Ai(:,1:3); end; % -- If Ai is not 3x4 or 3x3 then force an error. if (size(Ai,1)~=3) || (size(Ai,2)~=3) tt = sprintf('Argument %d should be 3x3 or 3x4',2*count-1); error(tt); end; %disp('Propagating...'); % -- Display for testing %disp ([ Ai Bi]); A = Ai*A; B = Ai*B+Bi; end; if (nargout>2) % -- Try to calculate Steady-State Mag. if (rank(eye(3)-A)<3) warning('No Unique Steady-State - mss will be []'); else mss = inv(eye(3)-A)*B; end; end;
github
mribri999/MRSignalsSeqs-master
Rad229_plot_style.m
.m
MRSignalsSeqs-master/Matlab/Rad229_plot_style.m
1,679
utf_8
ba46ff910ca044a190b2bffe39dfc3e1
% This function defines a color palette for plots and can also be used to % fetch the default colors for other uses (e.g. colormap_style.m). % % color = Rad229_plot_style(p) % % [email protected] (March 2021) for Rad229 function color = Rad229_plot_style(p) % Color Pallette - In a preferred order... if nargin==0 || numel(p)==3 % Permute the colors differently under the assumption that three plots is for Mx, My, Mz color_sat(1,:)=[1.0 0.0 0.0]; % Red color_sat(2,:)=[0.0 1.0 0.0]; % Green color_sat(3,:)=[0.0 0.0 1.0]; % Blue color_sat(4,:)=[1.0 0.5 0.0]; % Orange color_sat(5,:)=[1.0 1.0 0.0]; % Yellow color_sat(6,:)=[0.5 0.0 1.0]; % Purple color_sat(7,:)=[0.0 1.0 1.0]; % Cyan elseif numel(p)>3 % Permute the colors differently under the assumption that three plots is for B1, Gx, Gy, Gz color_sat(1,:)=[1.0 0.5 0.0]; % Orange color_sat(2,:)=[1.0 0.0 0.0]; % Red color_sat(3,:)=[0.0 1.0 0.0]; % Green color_sat(4,:)=[0.0 0.0 1.0]; % Blue color_sat(5,:)=[1.0 1.0 0.0]; % Yellow color_sat(6,:)=[0.5 0.0 1.0]; % Purple color_sat(7,:)=[0.0 1.0 1.0]; % Cyan else error('Input argument (number of plot handles) was incorrect.'); end HSV=rgb2hsv(color_sat); HSV(:,2)=0.50; % Reduce the saturation HSV(:,3)=0.80; % Reduce the brightness color=hsv2rgb(HSV); % Normalized for luminance M=repmat(mag(color,2),[1 3]); color=color./M; % Set the colors, if a PLOT handle was passed if nargin>0 for n=1:numel(p) % if isfield(p(n),'LineWidth'), set(p(n),'LineWidth',3); end % if isfield(p(n),'Color'), set(p(n),'Color',color(n,:)); end set(p(n),'LineWidth',3); set(p(n),'Color',color(n,:)); end end return
github
mribri999/MRSignalsSeqs-master
smart_subplot.m
.m
MRSignalsSeqs-master/Matlab/smart_subplot.m
2,247
utf_8
20f330ec355fb3bf46ad98d6aba64f08
% This function simply places the subplot axes with % better positioning than the default call to SUBPLOT. % The axis handle is returned as 'h'. % % SYNTAX : h=smart_subplot(m,n,p[,gap,lm,bm]) % % INPUTS : m - Number of rows % n - Number of columns % p - Plot number (raster order) % gap - Gap between plots in normalized units [DEFAULT=0.05] % lm - Left margin in normalized units [DEFAULT=0.0] % bm - Bottom margin in normalized units [DEFAULT=0.0] % % OUTPUTS: h - vector of handles for each of the subplot axes % % DBE 09/18/03 function h=smart_subplot(m,n,p,gap,left_margin,bot_margin) if nargin<3 error('Insufficient number of input arguments.'); end if p>m*n error('Requested subplot # (p) was beyond range of m*n.'); end % c_gap=0.05; c_gap=0.00; if nargin<4 | isempty(gap), gap=0.05; end if nargin<5 | isempty(left_margin), left_margin=0; end if nargin<6 | isempty(bot_margin), bot_margin=0; end % if nargin==3 % gap=0.1/min([m n]); % if gap>0.1, gap=0.1; end % end % The indices are used such that the produce the *same* order as SUBPLOT [j,i]=ind2sub([n m],p); width =((1-left_margin)-c_gap-gap*(n+1))/n; height=((1-bot_margin)-gap*(m+1))/m; left =(j-(1-c_gap))*(gap+width)+gap+left_margin; bottom=1-(i*(gap+height)); % [left bottom width height] h=axes('position',[left bottom width height]); % set(gca,'color',[1 1 1],'FontWeight','Bold','XColor',[1 1 1],'YColor',[1 1 1],'FontSize',15); return % function h=smart_subplot(m,n,p,gap) % % if nargin<3 % error('Insufficient number of input arguments.'); % end % % if p>m*n % error('Requested subplot # (p) was beyond range of m*n.'); % end % % % if nargin==3 % % gap=0.1/min([m n]); % % if gap>0.1, gap=0.1; end % % end % % % The indices are used such that the produce the *same* order as SUBPLOT % [j,i]=ind2sub([n m],p); % % width =(1-gap*(n+1))/n; % height=(1-gap*(m+1))/m; % left =(j-1)*(gap+width)+gap; % bottom=1-(i*(gap+height)); % % h=subplot('position',[left bottom width height]); % set(gca,'color',[1 1 1],'FontWeight','Bold','XColor',[1 1 1],'YColor',[1 1 1],'FontSize',15); % % return
github
mribri999/MRSignalsSeqs-master
Rad229_MRI_Resolution_Phantom.m
.m
MRSignalsSeqs-master/Matlab/Rad229_MRI_Resolution_Phantom.m
1,484
utf_8
e91f07df8677c8b2b20b80be55b4e0fe
%% Rad229_MRI_Resolution_Phantom – Create a resolution phantom with some noise. % % SYNTAX - [ P , M ] = Rad229_MRI_Resolution_Phantom( acq , obj ) % % INPUTS - acq is a structure that needs to contain acq.Nx (number of % pixels defining the *square* phantom matrix size. % % - obj is a structure that needs to contain a obj.obj.T2star vector % of FIVE T2-star values in seconds. % % OUTPUTS - P - Is the phantom object matrix [acq.Nx x acq.Nx] with assigned T2-star values % % [email protected] (April 2021) for Rad229 function P = Rad229_MRI_Resolution_Phantom( acq , obj ) if nargin == 0 acq.Nx = 128; % Matrix will be NxN obj.T2star = [10e-3 25e-3 50e-3 100e-3 1000e-3]; % Range of T2-star values [s] end P = zeros(acq.Nx); C0 = 16 : 2 : acq.Nx; C1 = 16 : 2 : acq.Nx; % Fine line spacing R0 = 9 : 24 : acq.Nx; R1 = 25 : 24 : acq.Nx; % for c = 1 : 5 for r = 1 : 5 P( R0(r) : R1(r) , C0(c) : C1(c) ) = obj.T2star(r); end end C0 = 48 : 4 : acq.Nx; C1 = 49 : 4 : acq.Nx; % Medium line spacing R0 = 9 : 24 : acq.Nx; R1 = 25 : 24 : acq.Nx; for c = 1 : 5 for r = 1 : 5 P( R0(r) : R1(r) , C0(c) : C1(c)) = obj.T2star(r); end end C0 = 88 : 8 : acq.Nx; C1 = 91 : 8 : acq.Nx; % Coarse line spacing R0 = 9 : 24 : acq.Nx; R1 = 25 : 24 : acq.Nx; for c=1:5 for r=1:5 P( R0(r) : R1(r) , C0(c) : C1(c) ) = obj.T2star(r); end end P=P'; % Want the resolution elements parallel to phase encode direction return
github
mribri999/MRSignalsSeqs-master
psf2d.m
.m
MRSignalsSeqs-master/Matlab/psf2d.m
1,681
utf_8
fa922acc74050bf5dcaa222ab5a86e1a
% function im = psf2d(ksp,oversamp,timemode) % % Function calculates and plots the point-spread function for % a given 1D or 2D k-space. % % INPUT: % ksp = k-space sample points (can be weighted if desired) % oversamp = oversampling of PSF (to smooth). Default 16 % timemode = 1 for ksp to be k x time % % OUTPUT: % im = 2D PSF (can be plotted) % plots of PSF. function im = psf2d(ksp,oversamp,timemode) if (nargin < 1) ksp = ones(256,256); end; if (nargin < 2) oversamp=16; end; if (nargin < 3) timemode=0; end; kplot=ksp; if (timemode==1) ksp = ifftshift(ifft(ifftshift(ksp,2),[],2),2); % FFT to interpolate end; [y,x] = size(ksp); ki = ksp; ki(oversamp*y,oversamp*x)=0; ki = circshift(ki,round((oversamp/2-0.5)*[y x])); im = ft(ki); % 2DFT im = im/max(abs(im(:))); % Normalize subplot(2,2,1); dispim(kplot); title('k-space'); axis off; subplot(2,2,2); dispim(cropim(kplot,16)); title('Central k-space'); axis off; subplot(2,2,3); dispim(log(1+abs(im))); title('PSF Image (log scale)'); axis off; subplot(2,2,4); npix=8; tt = sprintf('Central PSF %d x %d pixels',npix,npix); cim = cropim(im,npix*oversamp); dispim(cim); title(tt); hold on; axis off; h=plot([1:npix*oversamp],npix*oversamp/2*(1-abs(cim(4*oversamp+1,:))),'c--'); set(h,'LineWidth',2'); h=plot(npix*oversamp/2*(1+abs(cim(:,4*oversamp+1))),[1:npix*oversamp],'y--'); set(h,'LineWidth',2'); % -- Plot 'axis' plot([1:npix*oversamp],npix/2*oversamp*ones(npix*oversamp),'k-'); plot([1:npix*oversamp],npix/2*oversamp*ones(npix*oversamp),'w--'); plot(npix/2*oversamp*ones(npix*oversamp), [1:npix*oversamp], 'k-'); plot(npix/2*oversamp*ones(npix*oversamp), [1:npix*oversamp], 'w--'); hold off;
github
mribri999/MRSignalsSeqs-master
ift.m
.m
MRSignalsSeqs-master/Matlab/ift.m
187
utf_8
82904e346076c3b915c46439a30bef8f
% function im = ft(dat) % % Function does a centered inverse 2DFT of the data: % % im = ifftshift(ifft2(ifftshift(dat))); function im = ift(dat) im = ifftshift(ifft2(ifftshift(dat)));
github
mribri999/MRSignalsSeqs-master
sinc.m
.m
MRSignalsSeqs-master/Matlab/sinc.m
288
utf_8
08e1ceaf2751003b3496a701b614bf09
% function y = sinc(x) % % Function returns y = sin(pi*x)/pi*x if x is non-zero, and 1 otherwise. % Works on arrays. function y = sinc(x) sz = size(x); x = x(:); y = x; % Allocate f1 = find(x==0); f2 = find(x~=0); y(f1)=1; y(f2) = sin(pi*x(f2))./(pi*x(f2)); y = reshape(y,sz);